auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private List<String> getUnixGroups(String user) throws IOException { ShellCommandExecutor executor = createGroupExecutor(user); List<String> groups; try { executor.execute(); groups = resolveFullGroupNames(executor.getOutput()); } catch (ExitCodeException e) { try { groups = resolvePartialGroupNames(user, e.getMessage(), executor.getOutput()); } catch (PartialGroupNameException pge) { LOG.warn("unable to return groups for user {}", user, pge); return new LinkedList<>(); } } catch (IOException ioe) { if (executor.isTimedOut()) { LOG.warn( "Unable to return groups for user '{}' as shell group lookup " + "command '{}' ran longer than the configured timeout limit of " + "{} seconds.", user, Arrays.asList(executor.getExecString()), timeout ); return new LinkedList<>(); } else { throw ioe; } } if (!Shell.WINDOWS) { for (int i = 1; i < groups.size(); i++) { if (groups.get(i).equals(groups.get(0))) { groups.remove(i); break; } } } return groups; }

Target:
private List<String> getUnixGroups(String user) throws IOException { ShellCommandExecutor executor = createGroupExecutor(user); List<String> groups; try { executor.execute(); groups = resolveFullGroupNames(executor.getOutput()); } catch (ExitCodeException e) { try { groups = resolvePartialGroupNames(user, e.getMessage(), executor.getOutput()); } catch (PartialGroupNameException pge) { LOG.warn("unable to return groups for user {}", user, pge); return EMPTY_GROUPS; } } catch (IOException ioe) { if (executor.isTimedOut()) { LOG.warn( "Unable to return groups for user '{}' as shell group lookup " + "command '{}' ran longer than the configured timeout limit of " + "{} seconds.", user, Joiner.on(' ').join(executor.getExecString()), timeout ); return EMPTY_GROUPS; } else { throw ioe; } } if (!Shell.WINDOWS) { for (int i = 1; i < groups.size(); i++) { if (groups.get(i).equals(groups.get(0))) { groups.remove(i); break; } } } return groups; }
Source:
public void onGitStatusChanged(String endpointId, StatusChangedEventDto statusChangedEventDto) { Status status = statusChangedEventDto.getStatus(); editorAgentProvider .get() .getOpenedEditors() .stream() .filter( editor -> editor instanceof HasVcsChangeMarkerRender && statusChangedEventDto .getProjectName() .equals(editor.getEditorInput().getFile().getLocation().segment(0))) .forEach( editor -> { EditorTab tab = multiPartStackProvider.get().getTabByPart(editor); String nodeLocation = tab.getFile().getLocation().removeFirstSegments(1).toString(); if (status.getUntracked().contains(nodeLocation)) { tab.setTitleColor(UNTRACKED.getColor()); } else if (status.getModified().contains(nodeLocation) || status.getChanged().contains(nodeLocation)) { tab.setTitleColor(MODIFIED.getColor()); } else if (status.getAdded().contains(nodeLocation)) { tab.setTitleColor(ADDED.getColor()); } else { tab.setTitleColor(NOT_MODIFIED.getColor()); } }); }

Target:
public void onGitStatusChanged(String endpointId, StatusChangedEventDto statusChangedEventDto) { Status status = statusChangedEventDto.getStatus(); editorAgentProvider .get() .getOpenedEditors() .stream() .filter( editor -> editor instanceof HasVcsChangeMarkerRender && statusChangedEventDto .getProjectName() .equals(getRootPath(editor.getEditorInput().getFile().getLocation()))) .forEach( editor -> { EditorTab tab = multiPartStackProvider.get().getTabByPart(editor); String nodeLocation = tab.getFile().getLocation().removeFirstSegments(1).toString(); if (status.getUntracked().contains(nodeLocation)) { tab.setTitleColor(UNTRACKED.getColor()); } else if (status.getModified().contains(nodeLocation) || status.getChanged().contains(nodeLocation)) { tab.setTitleColor(MODIFIED.getColor()); } else if (status.getAdded().contains(nodeLocation)) { tab.setTitleColor(ADDED.getColor()); } else { tab.setTitleColor(NOT_MODIFIED.getColor()); } }); }
Source:
public boolean isServiceDetected(InetAddress address, URI agentConfig) { LOG.debug("isServiceDetected(address=[{}], agentConfig=[{}])", address, agentConfig); try { m_connectionFactory.setBrokerURL(agentConfig.toString()); connection = m_connectionFactory.createConnection(m_user, m_password); LOG.info("connection created"); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); LOG.info("session created"); connection.start(); LOG.info("connection started"); session.close(); connection.close(); return true; } catch (Throwable t) { throw new UndeclaredThrowableException(t); } }

Target:
public boolean isServiceDetected(InetAddress address, URI agentConfig) { LOG.debug("isServiceDetected(address=[{}], agentConfig=[{}])", address, agentConfig); try { m_connectionFactory.setBrokerURL(agentConfig.toString()); m_connection = m_connectionFactory.createConnection(m_user, m_password); LOG.info("connection created"); m_session = m_connection.createSession(false, Session.AUTO_ACKNOWLEDGE); LOG.info("session created"); m_connection.start(); LOG.info("connection started"); return true; } catch (Throwable t) { throw new UndeclaredThrowableException(t); } }
Source:
public ItemIngot() { super(Form.INGOT, true, true, CollectionTools.createIndexedLookupTable(STEEL, COPPER, TIN, BRONZE, LEAD, SILVER)); setSmeltingExperience(1); }

Target:
public ItemIngot() { super(Form.INGOT, true, true, CollectionTools.createIndexedLookupTable(STEEL, COPPER, TIN, LEAD, SILVER, BRONZE)); setSmeltingExperience(1); }
Source:
public String getServerAuthenticationToken() { if (serverAuthenticationToken != null) { return serverAuthenticationToken.trim(); } return serverAuthenticationToken; }

Target:
public String getServerAuthenticationToken() { return StringUtils.trimToNull(serverAuthenticationToken); }
Source:
public final void testGetLogicalProcessorInformation() { WinNT.SYSTEM_LOGICAL_PROCESSOR_INFORMATION informationArray = Kernel32Util.getLogicalProcessorInformation(); assertTrue(informationArray >= 1); for (WinNT.SYSTEM_LOGICAL_PROCESSOR_INFORMATION information : informationArray) { } }

Target:
public final void testGetLogicalProcessorInformation() { WinNT.SYSTEM_LOGICAL_PROCESSOR_INFORMATION[] informationArray = Kernel32Util.getLogicalProcessorInformation(); assertTrue(informationArray.length >= 1); for (WinNT.SYSTEM_LOGICAL_PROCESSOR_INFORMATION information : informationArray) { } }
Source:
public Map<String, Region> getAllSecondLevelCacheRegions() { final Map<String, Region> allCacheRegions = new HashMap<String, Region>(); if ( settings.isQueryCacheEnabled() ) { allCacheRegions.put( updateTimestampsCache.getRegion().getName(), updateTimestampsCache.getRegion() ); allCacheRegions.put( queryCache.getRegion().getName(), queryCache.getRegion() ); } if ( settings.isQueryCacheEnabled() ) { for ( QueryCache queryCacheValue : queryCaches.values() ) { allCacheRegions.put( queryCacheValue.getRegion().getName(), queryCacheValue.getRegion() ); } } allCacheRegions.putAll( otherRegionMap ); allCacheRegions.putAll( naturalIdRegionMap ); allCacheRegions.putAll( collectionRegionMap ); allCacheRegions.putAll( entityRegionMap ); return allCacheRegions; }

Target:
public Map<String, Region> getAllSecondLevelCacheRegions() { final Map<String, Region> allCacheRegions = new HashMap<String, Region>(); if ( settings.isQueryCacheEnabled() ) { allCacheRegions.put( updateTimestampsCache.getRegion().getName(), updateTimestampsCache.getRegion() ); allCacheRegions.put( queryCache.getRegion().getName(), queryCache.getRegion() ); for ( QueryCache queryCacheValue : queryCaches.values() ) { allCacheRegions.put( queryCacheValue.getRegion().getName(), queryCacheValue.getRegion() ); } } allCacheRegions.putAll( otherRegionMap ); allCacheRegions.putAll( naturalIdRegionMap ); allCacheRegions.putAll( collectionRegionMap ); allCacheRegions.putAll( entityRegionMap ); return allCacheRegions; }
Source:
private Revision getRevision(RevCommit commit, String filePath) throws GitAPIException, IOException { List<String> commitParentsList = Stream.of(commit.getParents()) .map(RevCommit::getName) .collect(Collectors.toList()); List<Branch> commitBranchesList = getBranchesOfCommit(commit, ListMode.ALL); List<DiffCommitFile> diffCommitFilesList = getCommitDiffFiles(commit, filePath); GitUser author = getCommitAuthor(commit); GitUser committer = getCommitCommitter(commit); return newDto(Revision.class).withId(commit.getId() .getName()) .withMessage(commit.getFullMessage()) .withCommitTime((long) commit.getCommitTime() * 1000) .withCommitter(committer) .withAuthor(author) .withBranches(commitBranchesList) .withCommitParent(commitParentsList) .withDiffCommitFile(diffCommitFilesList); }

Target:
private Revision getRevision(RevCommit commit, String filePath) throws GitAPIException, IOException { List<String> commitParentsList = Stream.of(commit.getParents()) .map(RevCommit::getName) .collect(Collectors.toList()); return newDto(Revision.class).withId(commit.getId().getName()) .withMessage(commit.getFullMessage()) .withCommitTime((long) commit.getCommitTime() * 1000) .withCommitter(getCommitCommitter(commit)) .withAuthor(getCommitAuthor(commit)) .withBranches(getBranchesOfCommit(commit, ListMode.ALL)) .withCommitParent(commitParentsList) .withDiffCommitFile(getCommitDiffFiles(commit, filePath)); }
Source:
public void init() { OreDictionary.registerOre("materialRope", rope.getItem()); OreDictionary.registerOre("materialSalt", salt.getItem()); OreDictionary.registerOre("foodSalt", salt.getItem()); OreDictionary.registerOre("dustSalt", salt.getItem()); OreDictionary.registerOre("powderSalt", salt.getItem()); OreDictionary.registerOre("lumpSalt", salt.getItem()); OreDictionary.registerOre("bottleSalt", saltBottle.getItem()); OreDictionary.registerOre("bucketSalt", saltBucket.getItem()); }

Target:
public void init() { OreDictionary.registerOre("materialRope", rope.getItem()); OreDictionary.registerOre("materialSalt", salt.getItem()); OreDictionary.registerOre("foodSalt", salt.getItem()); OreDictionary.registerOre("dustSalt", salt.getItem()); OreDictionary.registerOre("lumpSalt", salt.getItem()); OreDictionary.registerOre("bottleSalt", saltBottle.getItem()); OreDictionary.registerOre("bucketSalt", saltBucket.getItem()); }
Source:
public static void onPostUploadedSnackbarHandler(final Activity activity, View snackbarAttachView, PostStore.OnPostUploaded event, final SiteModel site, final Dispatcher dispatcher) { final PostModel post = event.post; if (event.isError()) { UploadUtils.showSnackbar(snackbarAttachView, R.string.editor_draft_saved_locally); } else { boolean isDraft = PostStatus.fromPost(post) == PostStatus.DRAFT; if (isDraft) { View.OnClickListener publishPostListener = new View.OnClickListener() { @Override public void onClick(View v) { UploadUtils.publishPost(activity, post, site, dispatcher); } }; UploadUtils.showSnackbarSuccessAction(snackbarAttachView, R.string.editor_draft_saved_online, R.string.button_publish, publishPostListener); } else { int messageRes = post.isPage() ? R.string.page_published : R.string.post_published; UploadUtils.showSnackbar(snackbarAttachView, messageRes); UploadUtils.showSnackbarSuccessAction(snackbarAttachView, messageRes, R.string.button_view, new View.OnClickListener() { @Override public void onClick(View view) { ActivityLauncher.viewPostPreviewForResult(activity, site, post); } }); } } }

Target:
public static void onPostUploadedSnackbarHandler(final Activity activity, View snackbarAttachView, PostStore.OnPostUploaded event, final SiteModel site, final Dispatcher dispatcher) { final PostModel post = event.post; if (event.isError()) { UploadUtils.showSnackbar(snackbarAttachView, R.string.editor_draft_saved_locally); } else { boolean isDraft = PostStatus.fromPost(post) == PostStatus.DRAFT; if (isDraft) { View.OnClickListener publishPostListener = new View.OnClickListener() { @Override public void onClick(View v) { UploadUtils.publishPost(activity, post, site, dispatcher); } }; UploadUtils.showSnackbarSuccessAction(snackbarAttachView, R.string.editor_draft_saved_online, R.string.button_publish, publishPostListener); } else { int messageRes = post.isPage() ? R.string.page_published : R.string.post_published; UploadUtils.showSnackbar(snackbarAttachView, messageRes); UploadUtils.showSnackbarSuccessAction(snackbarAttachView, messageRes, R.string.button_view, new View.OnClickListener() { @Override public void onClick(View view) { ActivityLauncher.browsePostOrPage(activity, site, post); } }); } } }
Source:
public void shouldNotBeAllowedToAttachTwoRules() { RetentionRule rr = createManualImmediateRuleMillis(100L); file = service.attachRule(file, rr, session); try { service.attachRule(file, rr, session); fail("Sould not be abe to attach rule twice"); } catch (NuxeoException e) { } }

Target:
public void shouldNotBeAllowedToAttachTwoRules() { RetentionRule rr = createManualImmediateRuleMillis(100L); file = service.attachRule(file, rr, session); try { service.attachRule(file, rr, session); fail("Should not be abe to attach rule twice"); } catch (NuxeoException e) { } }
Source:
public void run() { aclService.assertHasAccess("Insufficient privileges to restore object " + pid.getUUID(), pid, agent.getGroups(), markForDeletion); RepositoryObject repoObj = repositoryObjectLoader.getRepositoryObject(pid); if (repoObj instanceof AdminUnit) { aclService.assertHasAccess("Insufficient privileges to delete/restore admin unit " + pid.getUUID(), pid, agent.getPrincipals(), markForDeletionUnit); } if (!(repoObj instanceof ContentObject)) { throw new InvalidOperationForObjectType("Cannot perform restore on object " + pid.getUUID() + ", objects of type " + repoObj.getClass().getName() + " are not eligible."); } String updateString = createSparqlDelete(pid.getRepositoryPath(), markedForDeletion, null); sparqlUpdateService.executeUpdate(repoObj.getMetadataUri().toString(), updateString); repoObj.getPremisLog().buildEvent(Premis.Deletion) .addImplementorAgent(agent.getUsernameUri()) .addEventDetail("Item restored from deletion") .write(); }

Target:
public void run() { aclService.assertHasAccess("Insufficient privileges to restore object " + pid.getUUID(), pid, agent.getGroups(), markForDeletion); RepositoryObject repoObj = repositoryObjectLoader.getRepositoryObject(pid); if (repoObj instanceof AdminUnit) { aclService.assertHasAccess("Insufficient privileges to restore admin unit " + pid.getUUID(), pid, agent.getPrincipals(), markForDeletionUnit); } if (!(repoObj instanceof ContentObject)) { throw new InvalidOperationForObjectType("Cannot perform restore on object " + pid.getUUID() + ", objects of type " + repoObj.getClass().getName() + " are not eligible."); } String updateString = createSparqlDelete(pid.getRepositoryPath(), markedForDeletion, null); sparqlUpdateService.executeUpdate(repoObj.getMetadataUri().toString(), updateString); repoObj.getPremisLog().buildEvent(Premis.Deletion) .addImplementorAgent(agent.getUsernameUri()) .addEventDetail("Item restored from deletion") .write(); }
Source:
public DoubleMatrix2D matrixTransposeMultiplyMatrix(DoubleMatrix2D a) { ArgumentChecker.notNull(a, "a"); final int n = a.getNumberOfRows(); final int m = a.getNumberOfColumns(); DoubleMatrix2D res = new DoubleMatrix2D(m, m); double[][] data = res.getData(); double[][] aData = a.getData(); for (int i = 0; i < m; i++) { double sum = 0.0; for (int k = 0; k < n; k++) { sum += FunctionUtils.square(aData[k][i]); } data[i][i] = sum; for (int j = i + 1; j < m; j++) { sum = 0.0; for (int k = 0; k < n; k++) { sum += aData[k][i] * aData[k][j]; } data[i][j] = sum; data[j][i] = sum; } } return res; }

Target:
public DoubleMatrix2D matrixTransposeMultiplyMatrix(DoubleMatrix2D a) { ArgumentChecker.notNull(a, "a"); final int n = a.getNumberOfRows(); final int m = a.getNumberOfColumns(); DoubleMatrix2D res = new DoubleMatrix2D(m, m); double[][] data = res.getData(); double[][] aData = a.getData(); for (int i = 0; i < m; i++) { double sum = 0.0; for (int k = 0; k < n; k++) { sum += aData[k][i] * aData[k][i]; } data[i][i] = sum; for (int j = i + 1; j < m; j++) { sum = 0.0; for (int k = 0; k < n; k++) { sum += aData[k][i] * aData[k][j]; } data[i][j] = sum; data[j][i] = sum; } } return res; }
Source:
public Label findByLabelValue(String labelValue) { return uniqueResult(namedQuery("io.dockstore.webservice.core.Label.findFileFormatByValue").setParameter("labelValue", labelValue)); }

Target:
public Label findByLabelValue(String labelValue) { return uniqueResult(namedQuery("io.dockstore.webservice.core.Label.findByLabelValue").setParameter("labelValue", labelValue)); }
Source:
protected void executeMethod(String name) { try { Method method = target.getClass().getDeclaredMethod(name); method.setAccessible(true); ReflectionUtils.invokeMethod(method, target); } catch (NoSuchMethodException | SecurityException exception) { LOG.warning(exception.getMessage()); } }

Target:
protected Object executeMethod(String name) { return executeMethod(name, new Class<?>[0]); }
Source:
public void populateBroadleafValidatorMap() { String[] beanNames = applicationContext.getBeanNamesForType(BroadleafEntityValidator.class); broadLeafValidatorMap = new HashMap<>(beanNames.length); for (String beanName : beanNames) { BroadleafEntityValidator<?> formFoxValidator = applicationContext.getBean(beanName, BroadleafEntityValidator.class); Class<?> entityType = GenericTypeResolver.resolveTypeArgument(formFoxValidator.getClass(), BroadleafEntityValidator.class); if (entityType != null) { String entityClassName = entityType.getName(); LOG.info(String.format("Registering validator %s for entity type %s", formFoxValidator.getClass().getName(), entityClassName)); List<BroadleafEntityValidator<?>> registeredValidatorsForType = broadLeafValidatorMap .get(entityClassName); if (registeredValidatorsForType == null) { registeredValidatorsForType = new ArrayList<>(); broadLeafValidatorMap.put(entityClassName, registeredValidatorsForType); } registeredValidatorsForType.add(formFoxValidator); } else { LOG.warn("Could not determine entity type for " + formFoxValidator.getClass().getName()); } } }

Target:
public void populateBroadleafValidatorMap() { String[] beanNames = applicationContext.getBeanNamesForType(BroadleafEntityValidator.class); broadleafValidatorMap = new HashMap<>(beanNames.length); for (String beanName : beanNames) { BroadleafEntityValidator<?> broadleafValidator = applicationContext.getBean(beanName, BroadleafEntityValidator.class); Class<?> entityType = GenericTypeResolver.resolveTypeArgument(broadleafValidator.getClass(), BroadleafEntityValidator.class); if (entityType != null) { String entityClassName = entityType.getName(); LOG.info(String.format("Registering validator %s for entity type %s", broadleafValidator.getClass().getName(), entityClassName)); List<BroadleafEntityValidator<?>> registeredValidatorsForType = broadleafValidatorMap .get(entityClassName); if (registeredValidatorsForType == null) { registeredValidatorsForType = new ArrayList<>(); broadleafValidatorMap.put(entityClassName, registeredValidatorsForType); } registeredValidatorsForType.add(broadleafValidator); } else { LOG.warn("Could not determine entity type for " + broadleafValidator.getClass().getName()); } } }
Source:
public boolean apply(Game game, Ability source) { Player controller = game.getPlayer(source.getControllerId()); if (controller == null) { return false; } TargetCard target = new TargetDiscard(0, Integer.MAX_VALUE, StaticFilters.FILTER_CARD, controller.getId()); controller.choose(outcome, controller.getHand(), target, game); int numDiscarded = controller.discard(new CardsImpl(target.getTargets()), source, game).size(); return numDiscarded > 0 && new SearchLibraryPutInHandEffect(new TargetCardInLibrary( 0, numDiscarded, StaticFilters.FILTER_CARD_BASIC_LAND ), true, true).apply(game, source); }

Target:
public boolean apply(Game game, Ability source) { Player controller = game.getPlayer(source.getControllerId()); if (controller == null) { return false; } TargetCard target = new TargetDiscard(0, Integer.MAX_VALUE, StaticFilters.FILTER_CARD, controller.getId()); controller.choose(Outcome.AIDontUseIt, controller.getHand(), target, game); int numDiscarded = controller.discard(new CardsImpl(target.getTargets()), source, game).size(); new SearchLibraryPutInHandEffect(new TargetCardInLibrary( 0, numDiscarded, StaticFilters.FILTER_CARD_BASIC_LAND ), true, true).apply(game, source); return true; }
Source:
private long getMemberRecord(int memberIndex) throws CoreException { if (memberIndex >= MAX_MEMBER_COUNT) { return 0; } return getDB().getRecPtr(getMemberOffset(memberIndex)); }

Target:
private long getMemberRecord(int memberIndex) throws CoreException { return getDB().getRecPtr(getMemberOffset(memberIndex)); }
Source:
public void testTransparentTile() throws IOException, FactoryException { Layer layer = new AsyncTileLayer(service); MapContent map = new SingleLayerMapContent(layer); GTRenderer renderer = new StreamingRenderer(); renderer.setMapContent(map); ReferencedEnvelope mapBounds = service.getBounds(); double heightToWidth = mapBounds.getSpan(1) / mapBounds.getSpan(0); int imageWidth = 600; Rectangle imageBounds = new Rectangle(0, 0, imageWidth, (int) Math.round(imageWidth * heightToWidth)); map.getViewport().setScreenArea(imageBounds); map.getViewport().setBounds(mapBounds); BufferedImage image = new BufferedImage(imageBounds.width, imageBounds.height, BufferedImage.TYPE_INT_RGB); Graphics2D gr = image.createGraphics(); gr.setPaint(Color.RED); gr.fill(imageBounds); renderer.paint(gr, imageBounds, mapBounds); int argb = image.getRGB(0, 0); boolean hasAlphaChannel = image.getAlphaRaster() != null; Color c = new Color(argb, hasAlphaChannel); System.out.println(String.format("First pixel : alpha=%s red=%s green=%s blue=%s", c.getAlpha(), c.getRed(), c.getGreen(), c.getBlue())); Assert.assertEquals("Color should be RED (background)", Color.RED, c); argb = image.getRGB(69, 49); c = new Color(argb, hasAlphaChannel); System.out.println(String.format("Rendered pixel : alpha=%s red=%s green=%s blue=%s", c.getAlpha(), c.getRed(), c.getGreen(), c.getBlue())); Assert.assertEquals("Color should be black", Color.BLACK, c); argb = image.getRGB(154, 64); c = new Color(argb, hasAlphaChannel); System.out.println(String.format("Rendered pixel : alpha=%s red=%s green=%s blue=%s", c.getAlpha(), c.getRed(), c.getGreen(), c.getBlue())); Assert.assertEquals("Color should be very dark red", new Color(44, 0, 0), c); }

Target:
public void testTransparentTile() { Layer layer = new AsyncTileLayer(service); MapContent map = new SingleLayerMapContent(layer); GTRenderer renderer = new StreamingRenderer(); renderer.setMapContent(map); ReferencedEnvelope mapBounds = service.getBounds(); double heightToWidth = mapBounds.getSpan(1) / mapBounds.getSpan(0); int imageWidth = 600; Rectangle imageBounds = new Rectangle(0, 0, imageWidth, (int) Math.round(imageWidth * heightToWidth)); map.getViewport().setScreenArea(imageBounds); map.getViewport().setBounds(mapBounds); BufferedImage image = new BufferedImage(imageBounds.width, imageBounds.height, BufferedImage.TYPE_INT_RGB); Graphics2D gr = image.createGraphics(); gr.setPaint(Color.RED); gr.fill(imageBounds); renderer.paint(gr, imageBounds, mapBounds); int argb = image.getRGB(0, 0); boolean hasAlphaChannel = image.getAlphaRaster() != null; Color c = new Color(argb, hasAlphaChannel); Assert.assertEquals("Color should be RED (background)", Color.RED, c); argb = image.getRGB(69, 49); c = new Color(argb, hasAlphaChannel); Assert.assertEquals("Color should be black", Color.BLACK, c); argb = image.getRGB(154, 64); c = new Color(argb, hasAlphaChannel); Assert.assertEquals("Color should be very dark red", new Color(44, 0, 0), c); }
Source:
public void addScenario(Scenario s, Mission m) { int id; if (s.getId() == Scenario.S_DEFAULT_ID) { id = lastScenarioId + 1; lastScenarioId = id; s.setId(id); } else { id = s.getId(); } m.addScenario(s); scenarios.put(id, s); MekHQ.triggerEvent(new ScenarioNewEvent(s)); }

Target:
public void addScenario(Scenario s, Mission m) { int id; if (s.getId() == Scenario.S_DEFAULT_ID) { id = ++lastScenarioId; s.setId(id); } else { id = s.getId(); } m.addScenario(s); scenarios.put(id, s); MekHQ.triggerEvent(new ScenarioNewEvent(s)); }
Source:
public <T> boolean put(final String dataType, final long id, final T value) { final String operationId = Long.toString(operationIdCounter.getAndIncrement()); final DataOperation operation = new DataOperation(null, operationId, DataOpType.PUT, dataType, id, value); executeOperation(operation); return operation.getResult(); }

Target:
public <T> boolean put(final String dataType, final long id, final T value) { final String operationId = Long.toString(operationIdCounter.getAndIncrement()); final DataOperation<T> operation = new DataOperation<>(Optional.<String>empty(), operationId, DataOpType.PUT, dataType, id, Optional.of(value)); executeOperation(operation); return operation.isSuccess(); }
Source:
protected AccessTokenAuthenticationRequestFactory createInstance(ServletContext sc) throws Exception { return new DefaultAccessTokenAuthenticationRequestFactory(); }

Target:
protected AccessTokenAuthenticationRequestFactory createInstance(ServletContext sc) throws Exception { AccountStoreResolver resolver = getConfig().getInstance("stormpath.web.accountStoreResolver"); return new DefaultAccessTokenAuthenticationRequestFactory(resolver); }
Source:
protected boolean attachUserToSession() { if (!StringUtils.isEmpty(getParameters().getSessionId())) { SessionDataContainer.getInstance().setUser(getParameters().getSessionId(), getCurrentUser()); } else { if (!SessionDataContainer.getInstance().setUser(getCurrentUser())) { return failCanDoAction(VdcBllMessages.USER_CANNOT_LOGIN_SESSION_MISSING); } SessionDataContainer.getInstance().refresh(); int userSessionHardLimit = Config.<Integer> getValue(ConfigValues.UserSessionHardLimit); Date validTo = userSessionHardLimit != 0 ? DateUtils.addMinutes(new Date(), userSessionHardLimit) : null; try { Date fromExtension = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ").parse(authRecord.<String> get(AuthRecord.VALID_TO)); if (validTo != null) { validTo = validTo.compareTo(fromExtension) < 0 ? validTo : fromExtension; } else { validTo = fromExtension; } } catch (ParseException e) { log.warn("Error parsing AuthRecord.VALID_TO . Default VALID_TO value will be set on session"); } SessionDataContainer.getInstance().setHardLimit(validTo); } return true; }

Target:
protected boolean attachUserToSession() { if (!StringUtils.isEmpty(getParameters().getSessionId())) { SessionDataContainer.getInstance().setUser(getParameters().getSessionId(), getCurrentUser()); } else { if (!SessionDataContainer.getInstance().setUser(getCurrentUser())) { return failCanDoAction(VdcBllMessages.USER_CANNOT_LOGIN_SESSION_MISSING); } SessionDataContainer.getInstance().refresh(); int userSessionHardLimit = Config.<Integer> getValue(ConfigValues.UserSessionHardLimit); Date validTo = userSessionHardLimit != 0 ? DateUtils.addMinutes(new Date(), userSessionHardLimit) : null; if (authRecord.<String> get(AuthRecord.VALID_TO) != null) { try { Date fromExtension = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ").parse(authRecord.<String> get(AuthRecord.VALID_TO)); if (validTo != null) { validTo = validTo.compareTo(fromExtension) < 0 ? validTo : fromExtension; } else { validTo = fromExtension; } } catch (ParseException e) { log.warn("Error parsing AuthRecord.VALID_TO . Default VALID_TO value will be set on session"); log.debug("Exception is ", e); } } SessionDataContainer.getInstance().setHardLimit(validTo); } return true; }
Source:
private static Pattern extractPathFromFmt(String pathTransformFmt) { int refIdx = pathTransformFmt.indexOf(PATH_TRANSFORM_PATH_CATCH); String pathMatchingFragment = "(.*)"; String transformed; if (refIdx < 0) { transformed = Pattern.quote(pathTransformFmt); } else { if (refIdx == 0) { if (pathTransformFmt.length() > 2) { transformed = pathMatchingFragment + Pattern.quote(pathTransformFmt.substring(2)); } else { transformed = pathMatchingFragment; } } else { String prefix = Pattern.quote(pathTransformFmt.substring(0, refIdx)); String suffix = refIdx < pathTransformFmt.length() - 2 ? Pattern.quote(pathTransformFmt.substring(refIdx + 2)) : ""; transformed = prefix + pathMatchingFragment + suffix; } } return Pattern.compile("^" + transformed + "$"); }

Target:
private static Pattern extractPathFromFmt(String pathTransformFmt) { Matcher m = PATH_FORMAT_DECONSTRUCTION_REGEX.matcher(pathTransformFmt); if (m.matches() && m.groupCount() == 2) { String prefix = Pattern.quote(m.group(1)); String suffix = Pattern.quote(m.group(2)); return Pattern.compile("^" + prefix + "(.*)" + suffix + "$"); } else { LOGGER.warn( format( "Invalid path transformation format '%s' could not be successfully matched by the" + " deconstruction regex '%s'. Using the path transformation as is which can result in malfunctioning" + " ingresses.", pathTransformFmt, PATH_FORMAT_DECONSTRUCTION_REGEX)); return Pattern.compile(Pattern.quote(pathTransformFmt)); } }
Source:
public void nullArrayToUnmodifiableNonNullList() { Object[] array = null; assertThat(InternalQueries.unmodifiableNonNullList(array)).isEqualTo(emptyList()); }

Target:
public void nullArrayToUnmodifiableNonNullList() { Object[] array = null; assertThat(InternalQueries.unmodifiableNonNullList(array)).isSameAs(emptyList()); }
Source:
public void refreshModel() { modifiedSeveritySinceLastRun.clear(); Set<IResource> currentDirty = null; if (dirty != null) { currentDirty = new HashSet<>(); currentDirty.addAll(this.dirty); this.dirty.removeAll(currentDirty); removeFromCache(currentDirty); modifiedSeveritySinceLastRun.addAll(currentDirty); } try { for (IMarker marker : WorkbenchNavigatorPlugin.getWorkspace().getRoot().findMarkers(IMarker.PROBLEM, true, IResource.DEPTH_INFINITE)) { IResource resource = marker.getResource(); if (neverRan || currentDirty.contains(resource)) { int severity = marker.getAttribute(IMarker.SEVERITY, 0); if (severity >= 0) { propagateSeverityToCache(resource, severity); } } } neverRan = false; } catch (CoreException e) { WorkbenchNavigatorPlugin.log(e.getMessage(), new Status(IStatus.ERROR, WorkbenchNavigatorPlugin.PLUGIN_ID, e.getMessage(), e)); throw new RuntimeException(e); } catch (CancellationException e) { } }

Target:
public void refreshModel() { modifiedSeveritySinceLastRun.clear(); Set<IResource> localDirty = new HashSet<>(dirty); synchronized (this.dirty) { this.dirty.removeAll(localDirty); } removeFromCache(localDirty); modifiedSeveritySinceLastRun.addAll(localDirty); try { for (IMarker marker : WorkbenchNavigatorPlugin.getWorkspace().getRoot().findMarkers(IMarker.PROBLEM, true, IResource.DEPTH_INFINITE)) { IResource resource = marker.getResource(); if (resource != null && (neverRan || localDirty.contains(resource))) { int severity = marker.getAttribute(IMarker.SEVERITY, 0); if (severity >= 0) { propagateSeverityToCache(resource, severity); } } } neverRan = false; } catch (CoreException e) { WorkbenchNavigatorPlugin.log(e.getMessage(), new Status(IStatus.ERROR, WorkbenchNavigatorPlugin.PLUGIN_ID, e.getMessage(), e)); throw new RuntimeException(e); } catch (CancellationException e) { } }
Source:
public void analyzeSentimentWithLanguageWithOpinionMining() { textAnalyticsAsyncClient.analyzeSentiment("The hotel was dark and unclean.", "en", new AnalyzeSentimentOptions().setIncludeOpinionMining(true)) .subscribe(documentSentiment -> { List<MinedOpinion> positiveMinedOpinions = new ArrayList<>(); List<MinedOpinion> mixedMinedOpinions = new ArrayList<>(); List<MinedOpinion> negativeMinedOpinions = new ArrayList<>(); for (SentenceSentiment sentenceSentiment : documentSentiment.getSentences()) { sentenceSentiment.getMinedOpinions().forEach(minedOpinion -> { TextSentiment aspectTextSentiment = minedOpinion.getAspect().getSentiment(); if (NEGATIVE.equals(aspectTextSentiment)) { negativeMinedOpinions.add(minedOpinion); } else if (POSITIVE.equals(aspectTextSentiment)) { positiveMinedOpinions.add(minedOpinion); } else if (MIXED.equals(aspectTextSentiment)) { mixedMinedOpinions.add(minedOpinion); } }); } System.out.printf("Negative aspects count: %d%n", negativeMinedOpinions.size()); for (MinedOpinion negativeMinedOpinion : negativeMinedOpinions) { System.out.printf("\tAspect: %s%n", negativeMinedOpinion.getAspect().getText()); for (OpinionSentiment opinionSentiment : negativeMinedOpinion.getOpinions()) { System.out.printf("\t\t'%s' sentiment because of \"%s\". Is the aspect negated: %s.%n", opinionSentiment.getSentiment(), opinionSentiment.getText(), opinionSentiment.isNegated()); } } }); END: com.azure.ai.textanalytics.TextAnalyticsAsyncClient.analyzeSentiment#String-String-AnalyzeSentimentOptions }

Target:
public void analyzeSentimentWithLanguageWithOpinionMining() { textAnalyticsAsyncClient.analyzeSentiment("The hotel was dark and unclean.", "en", new AnalyzeSentimentOptions().setIncludeOpinionMining(true)) .subscribe(documentSentiment -> { for (SentenceSentiment sentenceSentiment : documentSentiment.getSentences()) { System.out.printf("\tSentence sentiment: %s%n", sentenceSentiment.getSentiment()); sentenceSentiment.getMinedOpinions().forEach(minedOpinions -> { AspectSentiment aspectSentiment = minedOpinions.getAspect(); System.out.printf("\tAspect sentiment: %s, aspect text: %s%n", aspectSentiment.getSentiment(), aspectSentiment.getText()); for (OpinionSentiment opinionSentiment : minedOpinions.getOpinions()) { System.out.printf("\t\t'%s' sentiment because of \"%s\". Is the opinion negated: %s.%n", opinionSentiment.getSentiment(), opinionSentiment.getText(), opinionSentiment.isNegated()); } }); } }); END: com.azure.ai.textanalytics.TextAnalyticsAsyncClient.analyzeSentiment#String-String-AnalyzeSentimentOptions }
Source:
public int size() { int size = cleared ? 0 : snapshot.size(); for ( Map.Entry<RowKey,AssociationOperation> op : currentState.entrySet() ) { switch ( op.getValue().getType() ) { case PUT: case PUT_NULL: if ( cleared || snapshot.get( op.getKey() ) == null ) { size++; } break; case REMOVE: if ( !cleared && snapshot.get( op.getKey() ) != null ) { size--; } break; } } return size; }

Target:
public int size() { int size = cleared ? 0 : snapshot.size(); for ( Map.Entry<RowKey,AssociationOperation> op : currentState.entrySet() ) { switch ( op.getValue().getType() ) { case PUT: case PUT_NULL: if ( cleared || !snapshot.containsKey( op.getKey() ) ) { size++; } break; case REMOVE: if ( !cleared && snapshot.containsKey( op.getKey() ) ) { size--; } break; } } return size; }
Source:
public void initialize(FlowletContext context) throws Exception { super.initialize(context); Map<String, String> args = context.getRuntimeArguments(); boolean pullDisabled = false; if (args.containsKey(ARG_TWITTER4J_DISABLED)) { if (Boolean.parseBoolean(args.get(ARG_TWITTER4J_DISABLED))) { LOG.warn("Pulling tweets is disabled via '" + ARG_TWITTER4J_DISABLED + "' runtime argument."); pullDisabled = true; } } String srcFile = null; if (args.containsKey(ARG_SOURCE_FILE)) { srcFile = args.get(ARG_SOURCE_FILE); LOG.info("Will read tweets from file: " + srcFile); } if (!pullDisabled || srcFile != null) { queue = new LinkedBlockingQueue<Tweet>(internalQueueSize); } if (!pullDisabled) { ConfigurationBuilder cb = new ConfigurationBuilder(); if (args.containsKey(ARG_TWITTER4J_OAUTH_CONSUMER_KEY)) { cb.setOAuthConsumerKey(args.get(ARG_TWITTER4J_OAUTH_CONSUMER_KEY)); } if (args.containsKey(ARG_TWITTER4J_OAUTH_CONSUMER_SECRET)) { cb.setOAuthConsumerSecret(args.get(ARG_TWITTER4J_OAUTH_CONSUMER_SECRET)); } if (args.containsKey(ARG_TWITTER4J_OAUTH_ACCESS_TOKEN)) { cb.setOAuthAccessToken(args.get(ARG_TWITTER4J_OAUTH_ACCESS_TOKEN)); } if (args.containsKey(ARG_TWITTER4J_OAUTH_ACCESS_TOKEN_SECRET)) { cb.setOAuthAccessTokenSecret(args.get(ARG_TWITTER4J_OAUTH_ACCESS_TOKEN_SECRET)); } Configuration conf = cb.build(); twitterStreamPuller = new CollectingThread(conf); twitterStreamPuller.start(); } if (srcFile != null) { fileReader = new FileReaderThread(srcFile); fileReader.start(); } }

Target:
public void initialize(FlowletContext context) throws Exception { super.initialize(context); Map<String, String> args = context.getRuntimeArguments(); boolean pullDisabled = false; if (args.containsKey(ARG_TWITTER4J_DISABLED)) { if (Boolean.parseBoolean(args.get(ARG_TWITTER4J_DISABLED))) { LOG.warn("Pulling tweets is disabled via '" + ARG_TWITTER4J_DISABLED + "' runtime argument."); pullDisabled = true; } } String srcFile = null; if (args.containsKey(ARG_SOURCE_FILE)) { srcFile = args.get(ARG_SOURCE_FILE); LOG.info("Will read tweets from file: " + srcFile); } if (!pullDisabled || srcFile != null) { queue = new LinkedBlockingQueue<Tweet>(internalQueueSize); } if (!pullDisabled) { twitterStreamPuller = createTwitterStreamPuller(args); twitterStreamPuller.start(); } if (srcFile != null) { fileReader = new FileReaderThread(srcFile); fileReader.start(); } }
Source:
private void updateDirectoryFileSelection() { directoryFileSelector.setDirectorySelected(true); if (currentResourceSelection != null) { String text; if (currentResourceSelection.size() > 1) { directoryFileSelector.setDirectorySelected(false); StringBuilder sb = new StringBuilder(); for (IResource resource : currentResourceSelection) { sb.append(resource.getLocation().toString()); sb.append(DirectoryOrFileSelector.FILE_SEPARATOR); } sb.setLength(sb.length() - DirectoryOrFileSelector.FILE_SEPARATOR.length()); text = sb.toString(); } else { IResource selected = currentResourceSelection.iterator().next(); directoryFileSelector.setDirectorySelected(selected.getType() != IResource.FILE); text = selected.getLocation().toString(); } directoryFileSelector.setText(text); } }

Target:
private void updateDirectoryFileSelection() { directoryFileSelector.setDirectorySelected(true); if (currentResourceSelection != null) { String text; if (currentResourceSelection.isEmpty()) { IResource selected = currentResourceSelection.iterator().next(); directoryFileSelector.setDirectorySelected(selected.getType() != IResource.FILE); text = selected.getLocation().toString(); } else { directoryFileSelector.setDirectorySelected(false); StringBuilder sb = new StringBuilder(); for (IResource resource : currentResourceSelection) { sb.append(resource.getLocation().toString()); sb.append(DirectoryOrFileSelector.FILE_SEPARATOR); } sb.setLength(sb.length() - DirectoryOrFileSelector.FILE_SEPARATOR.length()); text = sb.toString(); } directoryFileSelector.setText(text); } }
Source:
public ResizeRecommendationV4Response(Set<String> scaleUpHostGroups, Set<String> scaleDownHostGroups) { this.scaleUpHostGroups = scaleUpHostGroups; this.scaleDownHostGroups = scaleDownHostGroups; }

Target:
public ResizeRecommendationV4Response(Set<String> scaleUpHostGroups, Set<String> scaleDownHostGroups) { this.scaleUpHostGroups = Set.copyOf(scaleUpHostGroups); this.scaleDownHostGroups = Set.copyOf(scaleDownHostGroups); }
Source:
public EffectiveBuildSettings(String directory, String configuration, String platform) { File file = XCodeAppendBuildPhaseMojo.getBuildEnvironmentFile(directory, configuration, platform); Properties p = new Properties(); FileInputStream fis = null; try { fis = new FileInputStream(file); p.load(fis); properties = p; } catch (IOException e) { throw new IllegalStateException("Could not read build properties file", e); } finally { if (fis != null) { IOUtils.closeQuietly(fis); } } }

Target:
public EffectiveBuildSettings(String directory, String configuration, String platform) { File file = XCodeAppendBuildPhaseMojo.getBuildEnvironmentFile(directory, configuration, platform); Properties p = new Properties(); FileInputStream fis = null; try { fis = new FileInputStream(file); p.load(fis); properties = p; } catch (IOException e) { throw new IllegalStateException("Could not read build properties file", e); } finally { IOUtils.closeQuietly(fis); } }
Source:
public ReportalServlet(Props props) { this.props = props; viewerName = props.getString("viewer.name"); reportalStorageUser = props.getString("reportal.storage.user", "reportal"); itemsPerPage = props.getInt("reportal.items_per_page", 20); showNav = props.getBoolean("reportal.show.navigation", false); reportalMailTempDirectory = new File(props.getString("reportal.mail.temp.directory", "/tmp/reportal")); reportalMailTempDirectory.mkdirs(); ReportalMailCreator.reportalMailTempDirectory = reportalMailTempDirectory; List<String> allowedDomains = props.getStringList("reportal.allowed.email.domains", (List<String>) null); if (allowedDomains != null) { allowedEmailDomains = new HashSet<String>(); for (String domain : allowedDomains) { allowedEmailDomains.add(domain); } } ReportalMailCreator.outputLocation = props.getString("reportal.output.location", "/tmp/reportal"); ReportalMailCreator.outputFileSystem = props.getString("reportal.output.filesystem", "local"); ReportalMailCreator.reportalStorageUser = reportalStorageUser; webResourcesFolder = new File(new File(props.getSource()).getParentFile().getParentFile(), "web"); webResourcesFolder.mkdirs(); setResourceDirectory(webResourcesFolder); System.out.println("Reportal web resources: " + webResourcesFolder.getAbsolutePath()); }

Target:
public ReportalServlet(Props props) { this.props = props; viewerName = props.getString("viewer.name"); reportalStorageUser = props.getString("reportal.storage.user", "reportal"); itemsPerPage = props.getInt("reportal.items_per_page", 20); showNav = props.getBoolean("reportal.show.navigation", false); reportalMailTempDirectory = new File(props.getString("reportal.mail.temp.dir", "/tmp/reportal")); reportalMailTempDirectory.mkdirs(); ReportalMailCreator.reportalMailTempDirectory = reportalMailTempDirectory; List<String> allowedDomains = props.getStringList("reportal.allowed.email.domains", (List<String>) null); if (allowedDomains != null) { allowedEmailDomains = new HashSet<String>(allowedDomains); } ReportalMailCreator.outputLocation = props.getString("reportal.output.dir", "/tmp/reportal"); ReportalMailCreator.outputFileSystem = props.getString("reportal.output.filesystem", "local"); ReportalMailCreator.reportalStorageUser = reportalStorageUser; webResourcesFolder = new File(new File(props.getSource()).getParentFile().getParentFile(), "web"); webResourcesFolder.mkdirs(); setResourceDirectory(webResourcesFolder); System.out.println("Reportal web resources: " + webResourcesFolder.getAbsolutePath()); }
Source:
public void testEquality() { Exception exception = new UnsupportedQueryException("We do not support this query"); ProcessingDetails processingDetails = new ProcessingDetailsImpl("test source", exception, "warning"); ProcessingDetails identicalProcessingDetails = new ProcessingDetailsImpl("test source", exception, "warning"); assertThat(processingDetails.equals(identicalProcessingDetails), is(true)); }

Target:
public void testEquality() { Exception exception = new UnsupportedQueryException("We do not support this query"); ProcessingDetails processingDetails = new ProcessingDetailsImpl("test source", exception, "warning"); ProcessingDetails identicalProcessingDetails = new ProcessingDetailsImpl("test source", exception, "warning"); assertThat(processingDetails, is(identicalProcessingDetails)); }
Source:
private String findWsdlCommand() throws MojoExecutionException { if (!windowsModus) { return wsdlCommand; } if (wsdlExeFolderLocation != null) { return wsdlExeFolderLocation.getAbsolutePath(); } for (File sdk : findAllInstalledSDKs(DEFAULT_WSDL_PATHS)) { File bindir = new File(sdk, "bin"); File wsdlFile = new File(bindir, wsdlCommand); if (wsdlFile.exists()) { wsdlExeFolderLocation = wsdlFile; return wsdlFile.getAbsolutePath(); } } throw new MojoExecutionException("unable to find " + wsdlCommand + " in paths " + Arrays.toString(DEFAULT_WSDL_PATHS) + "\n " + "You can specify the path manually by adding the argument \n" + " -DwsdlExeFolderLocation=\"C:\\path\\to\\wsdl.exe\""); }

Target:
private String findWsdlCommand() throws MojoExecutionException { if (isLinux()) { if (isMonoCommandInstalled(wsdlCommand)) { return wsdlCommand; } throw new MojoExecutionException("The program '" + wsdlCommand + "' is currently not installed. You can install it by typing: " + "sudo apt-get install mono-devel"); } if (wsdlExeFolderLocation != null) { return wsdlExeFolderLocation.getAbsolutePath(); } for (File sdk : findAllInstalledSDKs(DEFAULT_WSDL_PATHS)) { File bindir = new File(sdk, "bin"); File wsdlFile = new File(bindir, wsdlCommand); if (wsdlFile.exists()) { wsdlExeFolderLocation = wsdlFile; return wsdlFile.getAbsolutePath(); } } throw new MojoExecutionException("unable to find " + wsdlCommand + " in paths " + Arrays.toString(DEFAULT_WSDL_PATHS) + "\n " + "You can specify the path manually by adding the argument \n" + " -DwsdlExeFolderLocation=\"C:\\path\\to\\wsdl.exe\""); }
Source:
public List<String> getWailaBody( final IPart part, final List<String> currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) { if( part instanceof PartP2PTunnel ) { NBTTagCompound nbtData = accessor.getNBTData(); if( nbtData.hasKey( TAG_P2P_STATE ) ) { int[] stateArr = nbtData.getIntArray( TAG_P2P_STATE ); if( stateArr.length == 2 ) { int state = stateArr[0]; int outputs = stateArr[1]; switch( state ) { case STATE_UNLINKED: currentToolTip.add( WailaText.P2PUnlinked.getLocal() ); break; case STATE_OUTPUT: currentToolTip.add( WailaText.P2POutput.getLocal() ); break; case STATE_INPUT: if( outputs <= 1 ) { currentToolTip.add( WailaText.P2PInputOneOutput.getLocal() ); } else { currentToolTip.add( String.format( WailaText.P2PInputManyOutputs.getLocal(), outputs ) ); } break; } } } } return currentToolTip; }

Target:
public List<String> getWailaBody( final IPart part, final List<String> currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) { if( part instanceof PartP2PTunnel ) { NBTTagCompound nbtData = accessor.getNBTData(); if( nbtData.hasKey( TAG_P2P_STATE ) ) { int[] stateArr = nbtData.getIntArray( TAG_P2P_STATE ); if( stateArr.length == 2 ) { int state = stateArr[0]; int outputs = stateArr[1]; switch( state ) { case STATE_UNLINKED: currentToolTip.add( WailaText.P2PUnlinked.getLocal() ); break; case STATE_OUTPUT: currentToolTip.add( WailaText.P2POutput.getLocal() ); break; case STATE_INPUT: currentToolTip.add( getOutputText( outputs ) ); break; } } } } return currentToolTip; }
Source:
public void applyEnrichmentTag_JsonParseEx() throws Exception { when(jsonStringParser.parseAndValidate(Mockito.anyString())).thenThrow(new IllegalArgumentException()); defaultEnrichmentTagApplier.applyEnrichmentTag(judgment, enrichmentTag); verifyNoMoreInteractions(jsonStringParser); verifyZeroInteractions(enrichmentTagValueConverter, judgmentUpdater); }

Target:
public void applyEnrichmentTag_JsonParseEx() throws Exception { when(jsonStringParser.parseAndValidate(Mockito.anyString())).thenThrow(new IllegalArgumentException()); catchException(defaultEnrichmentTagApplier).applyEnrichmentTag(judgment, enrichmentTag); assertTrue(caughtException() instanceof IllegalArgumentException); verify(jsonStringParser).parseAndValidate(enrichmentTag.getValue()); verifyZeroInteractions(enrichmentTagValueConverter, judgmentUpdater); }
Source:
@Get("/fortunes") public HttpResponse fortunes() { List<Fortune> fortunes = getFortunes(); fortunes.add(new Fortune(0, "Additional fortune added at request time.")); fortunes.sort(Comparator.comparing(Fortune::getMessage)); try { HttpHeaders headers = HttpHeaders.of(HttpStatus.OK).add( HttpHeaderNames.SERVER, "armeria").add(HttpHeaderNames.DATE, DATE_FORMATTER.format(new Date())).contentType( MediaType.HTML_UTF_8); return HttpResponse.of(headers, HttpData.ofUtf8(buildMustacheTemplate(fortunes))); } catch (Exception e) { return HttpResponse.of(HttpStatus.INTERNAL_SERVER_ERROR); } }

Target:
public HttpResponse fortunes() throws SQLException, IOException { List<Fortune> fortunes = getFortunes(); fortunes.add( new Fortune(0, "Additional fortune added at request time.")); fortunes.sort(Comparator.comparing(Fortune::getMessage)); return HttpResponse.of( HttpHeadersHelper.getHttpHeader(MediaType.HTML_UTF_8), HttpData.ofUtf8(buildMustacheTemplate(fortunes))); }