auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected double parseDouble(String value, String description) throws InvalidStateException { try { Double numeric = Double.valueOf(value); if (numeric.isNaN()) { throw new InvalidStateException("Could not understand '" + value + "' in " + description); } return numeric.doubleValue(); } catch (NumberFormatException nfe) { throw new InvalidStateException("Could not understand '" + value + "' in " + description); } }

Target:
protected double parseDouble(String value, String description) throws InvalidStateException { try { Double numeric = Double.valueOf(value); if (numeric.isNaN()) { throw new InvalidStateException("Could not understand '" + value + "' in " + description); } return numeric; } catch (NumberFormatException nfe) { throw new InvalidStateException("Could not understand '" + value + "' in " + description); } }
Source:
public boolean equals(final Object obj) { boolean result = false; if (this == obj) { result = true; } else { if (obj instanceof RepresentationDescriptionItemImpl) { final RepresentationDescriptionItemImpl rdiObj = (RepresentationDescriptionItemImpl) obj; result = EqualityHelper.areEquals(this.representationDescription, rdiObj.representationDescription); result = this.parent.equals(rdiObj.parent); } } return result; }

Target:
public boolean equals(final Object obj) { boolean result = false; if (this == obj) { result = true; } else { if (obj instanceof RepresentationDescriptionItemImpl) { final RepresentationDescriptionItemImpl rdiObj = (RepresentationDescriptionItemImpl) obj; result = EqualityHelper.areEquals(this.representationDescription, rdiObj.representationDescription); result = result && this.parent.equals(rdiObj.parent); } } return result; }
Source:
static boolean isChoice(Term term) { return term instanceof KItem && ((KItem) term).kLabel() instanceof KLabelConstant && (((KItem) term).kLabel().toString().equals("Map:choice") || ((KItem) term).kLabel().toString().equals("Set:choice")) && ((KItem) term).kList() instanceof KList && ((KList) ((KItem) term).kList()).isConcreteCollection() && ((KList) ((KItem) term).kList()).concreteSize() == 2; }

Target:
static boolean isChoice(Term term) { return term instanceof KItem && ((KItem) term).kLabel() instanceof KLabelConstant && (((KItem) term).kLabel().toString().equals(MAP_CHOICE) || ((KItem) term).kLabel().toString().equals(SET_CHOICE)) && ((KItem) term).kList() instanceof KList && ((KList) ((KItem) term).kList()).isConcreteCollection() && ((KList) ((KItem) term).kList()).concreteSize() == 2; }
Source:
public static BloomFilterHeader toBloomFilterHeader( org.apache.parquet.column.values.bloomfilter.BloomFilter bloomFilter) { BloomFilterAlgorithm algorithm = null; BloomFilterHash hashStrategy = null; BloomFilterCompression compression = null; if (bloomFilter.getAlgorithm() == BloomFilter.Algorithm.BLOCK) { algorithm = BloomFilterAlgorithm.BLOCK(new SplitBlockAlgorithm()); } if (bloomFilter.getHashStrategy() == BloomFilter.HashStrategy.XXH64) { hashStrategy = BloomFilterHash.XXHASH(new XxHash()); } if (bloomFilter.getCompression() == BloomFilter.Compression.UNCOMPRESSED) { compression = BloomFilterCompression.UNCOMPRESSED(new Uncompressed()); } if (algorithm != null && hashStrategy != null && compression != null) { return new BloomFilterHeader(bloomFilter.getBitsetSize(), algorithm, hashStrategy, compression); } else { return null; } }

Target:
public static BloomFilterHeader toBloomFilterHeader( org.apache.parquet.column.values.bloomfilter.BloomFilter bloomFilter) { BloomFilterAlgorithm algorithm = null; BloomFilterHash hashStrategy = null; BloomFilterCompression compression = null; if (bloomFilter.getAlgorithm() == BloomFilter.Algorithm.BLOCK) { algorithm = BloomFilterAlgorithm.BLOCK(new SplitBlockAlgorithm()); } if (bloomFilter.getHashStrategy() == BloomFilter.HashStrategy.XXH64) { hashStrategy = BloomFilterHash.XXHASH(new XxHash()); } if (bloomFilter.getCompression() == BloomFilter.Compression.UNCOMPRESSED) { compression = BloomFilterCompression.UNCOMPRESSED(new Uncompressed()); } if (algorithm != null && hashStrategy != null && compression != null) { return new BloomFilterHeader(bloomFilter.getBitsetSize(), algorithm, hashStrategy, compression); } else { throw new IllegalArgumentException(String.format("Failed to build thrift structure for BloomFilterHeader," + "algorithm=%s, hash=%s, compression=%s", bloomFilter.getAlgorithm(), bloomFilter.getHashStrategy(), bloomFilter.getCompression())); } }
Source:
public List<DeviceStatus> getPillStatus(@Scope(OAuthScope.ADMINISTRATION_READ) final AccessToken accessToken, @PathParam("email") final String email) { LOGGER.debug("Fetching pill status for user = {}", email); Optional<Long> accountId = getAccountIdByEmail(email); final List<DeviceStatus> pillStatuses = new ArrayList<>(); if (!accountId.isPresent()) { LOGGER.debug("ID not found for account {}", email); throw new WebApplicationException(Response.Status.NOT_FOUND); } final ImmutableList<DeviceAccountPair> pills = deviceDAO.getPillsForAccountId(accountId.get()); for (final DeviceAccountPair pill : pills) { pillStatuses.addAll(deviceDAO.pillStatusWithBatteryLevel(pill.internalDeviceId)); } return pillStatuses; }

Target:
public List<DeviceStatus> getPillStatus(@Scope(OAuthScope.ADMINISTRATION_READ) final AccessToken accessToken, @PathParam("email") final String email) { LOGGER.debug("Fetching pill status for user = {}", email); final Optional<Long> accountId = getAccountIdByEmail(email); final List<DeviceStatus> pillStatuses = new ArrayList<>(); if (!accountId.isPresent()) { LOGGER.debug("ID not found for account {}", email); throw new WebApplicationException(Response.Status.NOT_FOUND); } final ImmutableList<DeviceAccountPair> pills = deviceDAO.getPillsForAccountId(accountId.get()); for (final DeviceAccountPair pill : pills) { pillStatuses.addAll(deviceDAO.pillStatusWithBatteryLevel(pill.internalDeviceId)); } return pillStatuses; }
Source:
public void testUGILoginFromKeytab() throws Exception { long beforeLogin = Time.now(); String principal = "foo"; File keytab = new File(workDir, "foo.keytab"); kdc.createPrincipal(keytab, principal); UserGroupInformation.loginUserFromKeytab(principal, keytab.getPath()); UserGroupInformation ugi = UserGroupInformation.getLoginUser(); Assert.assertTrue("UGI should be configured to login from keytab", ugi.isFromKeytab()); User user = getUser(ugi.getSubject()); Assert.assertNotNull(user.getLogin()); Assert.assertTrue("User last login time is not set correctly", user.getLastLogin() > beforeLogin); }

Target:
public void testUGILoginFromKeytab() throws Exception { long beforeLogin = Time.now(); String principal = "foo"; File keytab = new File(workDir, "foo.keytab"); kdc.createPrincipal(keytab, principal); UserGroupInformation.loginUserFromKeytab(principal, keytab.getPath()); UserGroupInformation ugi = UserGroupInformation.getLoginUser(); Assert.assertTrue("UGI should be configured to login from keytab", ugi.isFromKeytab()); User user = getUser(ugi.getSubject()); Assert.assertNotNull(user.getLogin()); Assert.assertTrue("User login time is less than before login time, " + "beforeLoginTime:" + beforeLogin + " userLoginTime:" + user.getLastLogin(), user.getLastLogin() > beforeLogin); }
Source:
protected void startProcess(ExecutorDriver driver, Task task) { if (task.process == null) { try { task.run(); redirectProcess(task.process); } catch (IOException e) { LOGGER.error("Failed to run command", e); fail(driver); } } else { LOGGER.error("Tried to start process, but process already running"); } }

Target:
protected void startProcess(ExecutorDriver driver, Task task) { if (task.process == null) { try { task.run(); redirectProcess(task.process); try { Thread.sleep(10000); task.process.exitValue(); fail(driver); } catch (InterruptedException | IllegalThreadStateException e) { LOGGER.debug("task still running after 10s"); } } catch (IOException e) { LOGGER.error("Failed to run command", e); fail(driver); } } else { LOGGER.error("Tried to start process, but process already running"); } }
Source:
private static Arguments printout(Arguments arguments) { System.out.println(Arrays.toString(arguments.get())); return arguments; }

Target:
private static Arguments printout(Arguments arguments) { if (testMode != TestMode.PLAYBACK) { System.out.println(Arrays.toString(arguments.get())); } return arguments; }
Source:
public void testContentEquals() { Bytes b1 = Bytes.of("a"); byte[] b2 = b1.toArray(); Assert.assertTrue(b1.contentEquals(b2)); byte[] b3 = Bytes.of("b").toArray(); Assert.assertFalse(b1.contentEquals(b3)); }

Target:
public void testContentEquals() { Bytes b1 = Bytes.of("a"); byte[] b2 = b1.toArray(); byte[] b3 = Bytes.of("b").toArray(); Bytes b5 = Bytes.of("qwerty"); byte[] b6 = b5.toArray(); Bytes b7 = Bytes.of(""); byte[] b8 = b7.toArray(); Assert.assertTrue(b1.contentEquals(b2)); Assert.assertTrue(b5.contentEquals(b6)); Assert.assertTrue(b7.contentEquals(b8)); Assert.assertFalse(b1.contentEquals(b3)); Assert.assertFalse(b1.contentEquals(b6)); Assert.assertFalse(b5.contentEquals(b2)); Assert.assertFalse(b1.contentEquals(b8)); Assert.assertFalse(b5.contentEquals(b8)); Assert.assertFalse(b7.contentEquals(b2)); Assert.assertFalse(b7.contentEquals(b6)); }
Source:
public void testInvalidURI() throws Exception { HttpServletRequest request = Mockito.mock(HttpServletRequest.class); Mockito.when(request.getRemoteAddr()).thenReturn(null); Mockito.when(request.getMethod()).thenReturn("GET"); Mockito.when(request.getRequestURI()).thenReturn("/InvalidURI"); Mockito.when(request.getQueryString()).thenReturn(null); HttpServletResponse response = Mockito.mock(HttpServletResponse.class); Filter filter = new HostRestrictingAuthorizationFilter(); HashMap<String, String> configs = new HashMap<String, String>() {}; configs.put(AuthenticationFilter.AUTH_TYPE, "simple"); FilterConfig fc = new DummyFilterConfig(configs); filter.init(fc); filter.doFilter(request, response, (servletRequest, servletResponse) -> {}); Mockito.verify(response, Mockito.times(1)) .sendError(Mockito.eq(HttpServletResponse.SC_NOT_FOUND), Mockito.anyString()); filter.destroy(); }

Target:
public void testInvalidURI() throws Exception { HttpServletRequest request = Mockito.mock(HttpServletRequest.class); Mockito.when(request.getMethod()).thenReturn("GET"); Mockito.when(request.getRequestURI()).thenReturn("/InvalidURI"); HttpServletResponse response = Mockito.mock(HttpServletResponse.class); Filter filter = new HostRestrictingAuthorizationFilter(); HashMap<String, String> configs = new HashMap<String, String>() {}; configs.put(AuthenticationFilter.AUTH_TYPE, "simple"); FilterConfig fc = new DummyFilterConfig(configs); filter.init(fc); filter.doFilter(request, response, (servletRequest, servletResponse) -> {}); Mockito.verify(response, Mockito.times(1)) .sendError(Mockito.eq(HttpServletResponse.SC_NOT_FOUND), Mockito.anyString()); filter.destroy(); }
Source:
public void handleUpstream( ChannelHandlerContext ctx, ChannelEvent evt) throws Exception { if (!(evt instanceof MessageEvent)) { ctx.sendUpstream(evt); return; } MessageEvent e = (MessageEvent) evt; Object originalMessage = e.getMessage(); Object decodedMessage = decode(e.getChannel(), e.getRemoteAddress(), originalMessage); onMessageEvent(e.getChannel(), e.getRemoteAddress(), originalMessage, decodedMessage); if (originalMessage == decodedMessage) { ctx.sendUpstream(evt); } else { if (decodedMessage == null) { decodedMessage = handleEmptyMessage(e.getChannel(), e.getRemoteAddress(), originalMessage); } if (decodedMessage != null) { if (decodedMessage instanceof Collection) { for (Object o : (Collection) decodedMessage) { saveOriginal(o, originalMessage); Channels.fireMessageReceived(ctx, o, e.getRemoteAddress()); } } else if (decodedMessage instanceof Map) { Iterator it = ((Map) decodedMessage).entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); List<Position> positions = (List<Position>) pair.getValue(); for (Position position : positions) { saveOriginal(position, originalMessage); Channels.fireMessageReceived(ctx, position, e.getRemoteAddress()); } } } else { saveOriginal(decodedMessage, originalMessage); Channels.fireMessageReceived(ctx, decodedMessage, e.getRemoteAddress()); } } } }

Target:
public void handleUpstream( ChannelHandlerContext ctx, ChannelEvent evt) throws Exception { if (!(evt instanceof MessageEvent)) { ctx.sendUpstream(evt); return; } MessageEvent e = (MessageEvent) evt; Object originalMessage = e.getMessage(); Object decodedMessage = decode(e.getChannel(), e.getRemoteAddress(), originalMessage); onMessageEvent(e.getChannel(), e.getRemoteAddress(), originalMessage, decodedMessage); if (originalMessage == decodedMessage) { ctx.sendUpstream(evt); } else { if (decodedMessage == null) { decodedMessage = handleEmptyMessage(e.getChannel(), e.getRemoteAddress(), originalMessage); } if (decodedMessage != null) { if (decodedMessage instanceof Collection) { for (Object o : (Collection) decodedMessage) { saveOriginal(o, originalMessage); Channels.fireMessageReceived(ctx, o, e.getRemoteAddress()); } } else { saveOriginal(decodedMessage, originalMessage); Channels.fireMessageReceived(ctx, decodedMessage, e.getRemoteAddress()); } } } }
Source:
private void refresh(ClusterConfig clusterConfig, InstanceConfig instanceConfig, Collection<AssignableReplica> existingAssignment) { reset(); Map<String, Integer> instanceCapaity = instanceConfig.getInstanceCapacityMap(); if (instanceCapaity.isEmpty()) { instanceCapaity = clusterConfig.getDefaultInstanceCapacityMap(); } _currentCapacity.putAll(instanceCapaity); _faultZone = computeFaultZone(clusterConfig, instanceConfig); _instanceTags = new HashSet<>(instanceConfig.getTags()); _disabledPartitionsMap = instanceConfig.getDisabledPartitionsMap(); _maxCapacity = instanceCapaity; _maxPartition = clusterConfig.getMaxPartitionsPerInstance(); assignNewBatch(existingAssignment); }

Target:
private void refresh(ClusterConfig clusterConfig, InstanceConfig instanceConfig, Collection<AssignableReplica> existingAssignment) { reset(); Map<String, Integer> instanceCapacity = instanceConfig.getInstanceCapacityMap(); if (instanceCapacity.isEmpty()) { instanceCapacity = clusterConfig.getDefaultInstanceCapacityMap(); } _currentCapacity.putAll(instanceCapacity); _faultZone = computeFaultZone(clusterConfig, instanceConfig); _instanceTags = new HashSet<>(instanceConfig.getTags()); _disabledPartitionsMap = instanceConfig.getDisabledPartitionsMap(); _maxCapacity = instanceCapacity; _maxPartition = clusterConfig.getMaxPartitionsPerInstance(); assignNewBatch(existingAssignment); }
Source:
protected void onAttach() { String loaded = $(image).parent().data("loaded"); if (loaded != null) { return; } $(image).parent().css("display", "none"); $(image).parent().data("loaded", ""); Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() { @Override public void execute() { $(image).parent().first().css("display", "block"); } }); }

Target:
protected void onAttach() { String loaded = $(image).parent().data("loaded"); if (loaded != null) { return; } $(image).parent().css("display", "none").data("loaded", ""); Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() { @Override public void execute() { $(image).parent().css("display", "block"); } }); }
Source:
static void validatePartitioner(String partitioner, CassandraKeyValueServiceConfig config) { if (!(config.safetyDisabled() || config.ignorePartitionerChecks())) { Verify.verify( CassandraConstants.ALLOWED_PARTITIONERS.contains(partitioner), "Invalid partitioner. Allowed: %s, but partitioner is: %s", CassandraConstants.ALLOWED_PARTITIONERS, partitioner); } }

Target:
static void validatePartitioner(String partitioner, CassandraKeyValueServiceConfig config) { if (!config.ignorePartitionerChecks()) { Verify.verify( CassandraConstants.ALLOWED_PARTITIONERS.contains(partitioner), "Invalid partitioner. Allowed: %s, but partitioner is: %s. " + "If you fully understand how it will affect range scan performance and vnode generation, " + "you can set 'ignorePartitionerChecks' in your config.", CassandraConstants.ALLOWED_PARTITIONERS, partitioner); } }
Source:
public synchronized boolean hasChanged() { final boolean snapExist = contentFile.exists(); final long snapLastModified = snapExist ? contentFile.lastModified() : 0; final boolean snapOrigDirectory = snapExist && contentFile.isDirectory(); final long snapLength = getLength(); return exists != snapExist || lastModified != snapLastModified || directory != snapOrigDirectory || length != snapLength; }

Target:
public boolean hasChanged() { return exists != snapExist() || lastModified != snapLastModified() || directory != snapDirectory() || length != snapLength(); }
Source:
public void testGetAuthTokenInBackgroundVerifyErrorMessageBadAuth() throws IllegalAccessException, InvocationTargetException, ClassNotFoundException, NoSuchMethodException, InstantiationException, OperationCanceledException, IOException, NoSuchFieldException, AuthenticatorException { Object brokerProxy = ReflectionUtils.getInstance("com.microsoft.aad.adal.BrokerProxy"); String acctName = "testAcct123"; Object authRequest = createAuthenticationRequest("<LINK_0>", "resource", "client", "redirect", acctName.toLowerCase(Locale.US), PromptBehavior.Auto, "", UUID.randomUUID(), false); setMockProxyForErrorCheck(brokerProxy, acctName, AccountManager.ERROR_CODE_BAD_ARGUMENTS, "testErrorMessage"); try { Method m = ReflectionUtils.getTestMethod(brokerProxy, "getAuthTokenInBackground", authRequest.getClass()); AuthenticationResult result = (AuthenticationResult) m.invoke(brokerProxy, authRequest); Assert.fail("should throw"); } catch (Exception ex) { assertTrue("Exception type check", ex.getCause() instanceof AuthenticationException); assertEquals("check error code", ADALError.BROKER_AUTHENTICATOR_BAD_ARGUMENTS, ((AuthenticationException) ex.getCause()).getCode()); } }

Target:
public void testGetAuthTokenInBackgroundVerifyErrorMessageBadAuth() throws IllegalAccessException, InvocationTargetException, ClassNotFoundException, NoSuchMethodException, InstantiationException, OperationCanceledException, IOException, NoSuchFieldException, AuthenticatorException { Object brokerProxy = ReflectionUtils.getInstance("com.microsoft.aad.adal.BrokerProxy"); String acctName = "testAcct123"; Object authRequest = createAuthenticationRequest("<LINK_0>", "resource", "client", "redirect", acctName.toLowerCase(Locale.US), PromptBehavior.Auto, "", UUID.randomUUID(), false); setMockProxyForErrorCheck(brokerProxy, acctName, AccountManager.ERROR_CODE_BAD_AUTHENTICATION, "testErrorMessage"); try { Method m = ReflectionUtils.getTestMethod(brokerProxy, "getAuthTokenInBackground", authRequest.getClass()); AuthenticationResult result = (AuthenticationResult) m.invoke(brokerProxy, authRequest); Assert.fail("should throw"); } catch (Exception ex) { assertTrue("Exception type check", ex.getCause() instanceof AuthenticationException); assertEquals("check error code", ADALError.BROKER_AUTHENTICATOR_BAD_AUTHENTICATION, ((AuthenticationException) ex.getCause()).getCode()); } }
Source:
private IPersonAttributesGroupDefinition getPagsGroupDefByName(String name) { Set<IPersonAttributesGroupDefinition> pagsGroups = personAttributesGroupDefinitionDao.getPersonAttributesGroupDefinitionByName(name); if (pagsGroups.size() > 1) { logger.warn("More than one PAGS group with name found.", name); } return pagsGroups.isEmpty() ? null : pagsGroups.iterator().next(); }

Target:
private IPersonAttributesGroupDefinition getPagsGroupDefByName(String name) { Set<IPersonAttributesGroupDefinition> pagsGroups = personAttributesGroupDefinitionDao.getPersonAttributesGroupDefinitionByName(name); if (pagsGroups.size() > 1) { logger.error("More than one PAGS group with name found.", name); } return pagsGroups.isEmpty() ? null : pagsGroups.iterator().next(); }
Source:
protected boolean isConnWithSameDetailsExists() { String connection = getParameters().getStorageServerConnection().getconnection(); if ((getDbFacade().getStorageServerConnectionDao().getAllForStorage(connection)).size() != 0) { return true; } return false; }

Target:
protected boolean isConnWithSameDetailsExists() { String connection = getConnection().getconnection(); return getDbFacade().getStorageServerConnectionDao().getAllForStorage(connection).size() != 0; }
Source:
public CreateTopicsResult(Map<String, KafkaFuture<TopicMetadataAndConfig>> futures) { this.futures = futures; }

Target:
protected CreateTopicsResult(Map<String, KafkaFuture<TopicMetadataAndConfig>> futures) { this.futures = futures; }
Source:
private String normalizeBranchName(String name) { String normalized = Repository .normalizeBranchName(name.replaceAll("[#$!]", "_")); if (normalized != null && normalized.length() > 30) { normalized = Repository .normalizeBranchName(normalized.substring(0, 30)); } return normalized; }

Target:
private String normalizeBranchName(String name) { String normalized = Repository .normalizeBranchName(name.replaceAll("[#$!]", " ")); if (normalized.length() > 30) { normalized = Repository .normalizeBranchName(normalized.substring(0, 30)); } return normalized; }
Source:
public static String injectContextDependentValuesForTest(String content) { Date now = new Date(); Instant nowInstant = Instant.now(); return content.replace("<!-- test.url -->", TestProperties.TEAMMATES_URL) .replace("<!-- studentmotd.url -->", Config.STUDENT_MOTD_URL) .replace("<!-- support.email -->", Config.SUPPORT_EMAIL) .replace("<!-- version -->", TestProperties.TEAMMATES_VERSION) .replace("<!-- test.student1 -->", TestProperties.TEST_STUDENT1_ACCOUNT) .replace("<!-- test.student1.truncated -->", StringHelper.truncateLongId(TestProperties.TEST_STUDENT1_ACCOUNT)) .replace("<!-- test.student2 -->", TestProperties.TEST_STUDENT2_ACCOUNT) .replace("<!-- test.student2.truncated -->", StringHelper.truncateLongId(TestProperties.TEST_STUDENT2_ACCOUNT)) .replace("<!-- test.instructor -->", TestProperties.TEST_INSTRUCTOR_ACCOUNT) .replace("<!-- test.instructor.truncated -->", StringHelper.truncateLongId(TestProperties.TEST_INSTRUCTOR_ACCOUNT)) .replace("<!-- test.admin -->", TestProperties.TEST_ADMIN_ACCOUNT) .replace("<!-- test.admin.truncated -->", StringHelper.truncateLongId(TestProperties.TEST_ADMIN_ACCOUNT)) .replace("<!-- now.datetime -->", TimeHelper.formatTime12H(TimeHelper.convertDateToLocalDateTime(now))) .replace("<!-- now.datetime.sessions -->", TimeHelper.formatDateTimeForSessions(nowInstant, ZoneId.of("UTC"))) .replace("<!-- now.datetime.iso8601utc -->", TimeHelper.formatInstantToIso8601Utc(nowInstant)) .replace("<!-- now.datetime.courses -->", TimeHelper.formatDateTimeForInstructorCoursesPage(nowInstant, ZoneId.of("UTC"))); }

Target:
public static String injectContextDependentValuesForTest(String content) { Instant now = Instant.now(); return content.replace("<!-- test.url -->", TestProperties.TEAMMATES_URL) .replace("<!-- studentmotd.url -->", Config.STUDENT_MOTD_URL) .replace("<!-- support.email -->", Config.SUPPORT_EMAIL) .replace("<!-- version -->", TestProperties.TEAMMATES_VERSION) .replace("<!-- test.student1 -->", TestProperties.TEST_STUDENT1_ACCOUNT) .replace("<!-- test.student1.truncated -->", StringHelper.truncateLongId(TestProperties.TEST_STUDENT1_ACCOUNT)) .replace("<!-- test.student2 -->", TestProperties.TEST_STUDENT2_ACCOUNT) .replace("<!-- test.student2.truncated -->", StringHelper.truncateLongId(TestProperties.TEST_STUDENT2_ACCOUNT)) .replace("<!-- test.instructor -->", TestProperties.TEST_INSTRUCTOR_ACCOUNT) .replace("<!-- test.instructor.truncated -->", StringHelper.truncateLongId(TestProperties.TEST_INSTRUCTOR_ACCOUNT)) .replace("<!-- test.admin -->", TestProperties.TEST_ADMIN_ACCOUNT) .replace("<!-- test.admin.truncated -->", StringHelper.truncateLongId(TestProperties.TEST_ADMIN_ACCOUNT)) .replace("<!-- now.datetime -->", TimeHelper.formatTime12H(LocalDateTime.now(ZoneId.of("UTC")))) .replace("<!-- now.datetime.sessions -->", TimeHelper.formatDateTimeForSessions(now, ZoneId.of("UTC"))) .replace("<!-- now.datetime.iso8601utc -->", TimeHelper.formatInstantToIso8601Utc(now)) .replace("<!-- now.datetime.courses -->", TimeHelper.formatDateTimeForInstructorCoursesPage(now, ZoneId.of("UTC"))); }
Source:
private void moveSegments( final DruidServer server, final Set<BalancerSegmentHolder> segments, final DruidMasterRuntimeParams params ) { String toServer = server.getName(); LoadQueuePeon toPeon = params.getLoadManagementPeons().get(toServer); for (final BalancerSegmentHolder segment : Sets.newHashSet(segments)) { String fromServer = segment.getServer().getName(); DataSegment segmentToMove = segment.getSegment(); final String segmentName = segmentToMove.getIdentifier(); if (!toPeon.getSegmentsToLoad().contains(segmentToMove) && (server.getSegment(segmentName) == null) && new ServerHolder(server, toPeon).getAvailableSize() > segmentToMove.getSize()) { log.info( "Moving [%s] from [%s] to [%s]", segmentName, fromServer, toServer ); try { master.moveSegment( fromServer, toServer, segmentToMove.getIdentifier(), new LoadPeonCallback() { @Override protected void execute() { currentlyMovingSegments.get(server.getSubType()).remove(segmentName, segment); } } ); currentlyMovingSegments.get(server.getSubType()).put(segmentName, segment); } catch (Exception e) { log.makeAlert(e, String.format("[%s] : Moving exception", segmentName)).emit(); } } else { currentlyMovingSegments.get(server.getSubType()).remove(segment); } } }

Target:
private void moveSegments( final DruidServer server, final Set<BalancerSegmentHolder> segments, final DruidMasterRuntimeParams params ) { String toServer = server.getName(); LoadQueuePeon toPeon = params.getLoadManagementPeons().get(toServer); for (final BalancerSegmentHolder segment : Sets.newHashSet(segments)) { String fromServer = segment.getServer().getName(); DataSegment segmentToMove = segment.getSegment(); final String segmentName = segmentToMove.getIdentifier(); if (!toPeon.getSegmentsToLoad().contains(segmentToMove) && (server.getSegment(segmentName) == null) && new ServerHolder(server, toPeon).getAvailableSize() > segmentToMove.getSize()) { log.info( "Moving [%s] from [%s] to [%s]", segmentName, fromServer, toServer ); try { master.moveSegment( fromServer, toServer, segmentToMove.getIdentifier(), new LoadPeonCallback() { @Override protected void execute() { Map<String, BalancerSegmentHolder> movingSegments = currentlyMovingSegments.get(server.getTier()); if (movingSegments != null) { movingSegments.remove(segmentName); } } } ); currentlyMovingSegments.get(server.getTier()).put(segmentName, segment); } catch (Exception e) { log.makeAlert(e, String.format("[%s] : Moving exception", segmentName)).emit(); } } else { currentlyMovingSegments.get(server.getTier()).remove(segment); } } }
Source:
private void navigate(@NonNull NavDestination node, @Nullable Bundle args, @Nullable NavOptions navOptions, @Nullable Navigator.Extras navigatorExtras) { boolean popped = false; if (navOptions != null) { if (navOptions.getPopUpTo() != -1) { popped = popBackStackInternal(navOptions.getPopUpTo(), navOptions.isPopUpToInclusive()); } } Navigator<NavDestination> navigator = mNavigatorProvider.getNavigator( node.getNavigatorName()); Bundle finalArgs = node.addInDefaultArgs(args); NavDestination newDest = navigator.navigate(node, finalArgs, navOptions, navigatorExtras); if (newDest != null) { ArrayDeque<NavBackStackEntry> hierarchy = new ArrayDeque<>(); NavGraph parent = newDest.getParent(); while (parent != null) { hierarchy.addFirst(new NavBackStackEntry(parent, finalArgs)); if (parent.getId() == node.getId() && !mBackStack.isEmpty()) { break; } parent = parent.getParent(); } if (!mBackStack.isEmpty() && mBackStack.getFirst().getDestination().getId() == hierarchy.getFirst().getDestination().getId()) { hierarchy.removeFirst(); } mBackStack.addAll(hierarchy); mBackStack.add(new NavBackStackEntry(newDest, newDest.addInDefaultArgs(finalArgs))); } mOnBackPressedCallback.setEnabled(getDestinationCountOnBackStack() > 1); if (popped || newDest != null) { dispatchOnDestinationChanged(); } }

Target:
private void navigate(@NonNull NavDestination node, @Nullable Bundle args, @Nullable NavOptions navOptions, @Nullable Navigator.Extras navigatorExtras) { boolean popped = false; if (navOptions != null) { if (navOptions.getPopUpTo() != -1) { popped = popBackStackInternal(navOptions.getPopUpTo(), navOptions.isPopUpToInclusive()); } } Navigator<NavDestination> navigator = mNavigatorProvider.getNavigator( node.getNavigatorName()); Bundle finalArgs = node.addInDefaultArgs(args); NavDestination newDest = navigator.navigate(node, finalArgs, navOptions, navigatorExtras); if (newDest != null) { ArrayDeque<NavBackStackEntry> hierarchy = new ArrayDeque<>(); NavGraph parent = newDest.getParent(); boolean addNextParent = parent != null; while (addNextParent) { hierarchy.addFirst(new NavBackStackEntry(parent, finalArgs)); parent = parent.getParent(); addNextParent = parent != null; if (!mBackStack.isEmpty()) { addNextParent = addNextParent && parent.getId() != node.getId(); } } if (!mBackStack.isEmpty() && parent == null) { hierarchy.removeFirst(); } mBackStack.addAll(hierarchy); mBackStack.add(new NavBackStackEntry(newDest, newDest.addInDefaultArgs(finalArgs))); } mOnBackPressedCallback.setEnabled(getDestinationCountOnBackStack() > 1); if (popped || newDest != null) { dispatchOnDestinationChanged(); } }
Source:
public void startListeners() { for ( final ListenerInfo info : config.getListeners() ) { ChannelFutureListener listener = new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if ( future.isSuccess() ) { listeners.add( future.channel() ); getLogger().log( Level.INFO, "Listening on {0}", info.getHost() ); } else { getLogger().log( Level.WARNING, "Could not bind to host " + info.getHost(), future.cause() ); } } }; new ServerBootstrap() .channel( PipelineUtils.getServerChannel() ) .option( ChannelOption.SO_REUSEADDR, true ) .childAttr( PipelineUtils.LISTENER, info ) .childHandler( PipelineUtils.SERVER_CHILD ) .childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 1024 * 1024 * 10) .childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 1024 * 1024 * 1) .group( eventLoops, workerEventLoop ) .localAddress( info.getHost() ) .bind().addListener( listener ); if ( info.isQueryEnabled() ) { ChannelFutureListener bindListener = new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if ( future.isSuccess() ) { listeners.add( future.channel() ); getLogger().log( Level.INFO, "Started query on {0}", future.channel().localAddress() ); } else { getLogger().log( Level.WARNING, "Could not bind to host " + info.getHost(), future.cause() ); } } }; new RemoteQuery( this, info ).start( PipelineUtils.getDatagramChannel(), new InetSocketAddress( info.getHost().getAddress(), info.getQueryPort() ), eventLoops, bindListener ); } } }

Target:
public void startListeners() { for ( final ListenerInfo info : config.getListeners() ) { ChannelFutureListener listener = new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if ( future.isSuccess() ) { listeners.add( future.channel() ); getLogger().log( Level.INFO, "Listening on {0}", info.getHost() ); } else { getLogger().log( Level.WARNING, "Could not bind to host " + info.getHost(), future.cause() ); } } }; new ServerBootstrap() .channel( PipelineUtils.getServerChannel() ) .option( ChannelOption.SO_REUSEADDR, true ) .childAttr( PipelineUtils.LISTENER, info ) .childHandler( PipelineUtils.SERVER_CHILD ) .childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 1024 * 1024 * 10) .childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 1024 * 1024 * 1) .group( bossEventLoop, workerEventLoop ) .localAddress( info.getHost() ) .bind().addListener( listener ); if ( info.isQueryEnabled() ) { ChannelFutureListener bindListener = new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if ( future.isSuccess() ) { listeners.add( future.channel() ); getLogger().log( Level.INFO, "Started query on {0}", future.channel().localAddress() ); } else { getLogger().log( Level.WARNING, "Could not bind to host " + info.getHost(), future.cause() ); } } }; new RemoteQuery( this, info ).start( PipelineUtils.getDatagramChannel(), new InetSocketAddress( info.getHost().getAddress(), info.getQueryPort() ), workerEventLoop, bindListener ); } } }
Source:
protected boolean isValidConnection(StorageServerConnections conn) { StorageType storageType = conn.getstorage_type(); if (storageType == StorageType.NFS && !new NfsMountPointConstraint().isValid(conn.getconnection(), null)) { return failCanDoAction(EngineMessage.VALIDATION_STORAGE_CONNECTION_INVALID); } if (storageType == StorageType.POSIXFS && (StringUtils.isEmpty(conn.getVfsType()))) { return failCanDoAction(EngineMessage.VALIDATION_STORAGE_CONNECTION_EMPTY_VFSTYPE); } if ((storageType == StorageType.POSIXFS || storageType == StorageType.NFS) && !validate(validateMountOptions())) { return false; } if (storageType == StorageType.ISCSI) { if (StringUtils.isEmpty(conn.getiqn())) { return failCanDoAction(EngineMessage.VALIDATION_STORAGE_CONNECTION_EMPTY_IQN); } if (!isValidStorageConnectionPort(conn.getport())) { return failCanDoAction(EngineMessage.VALIDATION_STORAGE_CONNECTION_INVALID_PORT); } } if (storageType == StorageType.GLUSTERFS) { StorageConnectionValidator validator = new StorageConnectionValidator(conn); ValidationResult validionResult = validator.isGlusterfsCliPackageInstalled(getVds()); if (!validionResult.isValid()) { return failCanDoAction(validionResult.getMessage(), validionResult.getVariableReplacements().toArray(new String[validionResult.getVariableReplacements().size()])); } } if (checkIsConnectionFieldEmpty(conn)) { return false; } return true; }

Target:
protected boolean isValidConnection(StorageServerConnections conn) { StorageType storageType = conn.getstorage_type(); if (storageType == StorageType.NFS && !new NfsMountPointConstraint().isValid(conn.getconnection(), null)) { return failCanDoAction(EngineMessage.VALIDATION_STORAGE_CONNECTION_INVALID); } if (storageType == StorageType.POSIXFS && (StringUtils.isEmpty(conn.getVfsType()))) { return failCanDoAction(EngineMessage.VALIDATION_STORAGE_CONNECTION_EMPTY_VFSTYPE); } if ((storageType == StorageType.POSIXFS || storageType == StorageType.NFS) && !validate(validateMountOptions())) { return false; } if (storageType == StorageType.ISCSI) { if (StringUtils.isEmpty(conn.getiqn())) { return failCanDoAction(EngineMessage.VALIDATION_STORAGE_CONNECTION_EMPTY_IQN); } if (!isValidStorageConnectionPort(conn.getport())) { return failCanDoAction(EngineMessage.VALIDATION_STORAGE_CONNECTION_INVALID_PORT); } } if (storageType == StorageType.GLUSTERFS) { StorageConnectionValidator validator = new StorageConnectionValidator(conn); if (!validate(validator.isGlusterfsCliPackageInstalled(getVds()))) { return false; } } if (checkIsConnectionFieldEmpty(conn)) { return false; } return true; }
Source:
public void connect() throws IOException { client = getManagementClient(); ops = new Operations(client); }

Target:
public void connect() throws IOException { client = ManagementClient.online(OnlineOptions .standalone() .localDefault() .build()); ops = new Operations(client); }
Source:
public void run() { Map<String, Object> validatedNumaMap = Utils.getNumaMap(conf); Map<String, SupervisorInfo> supervisorInfoList = buildSupervisorInfo(conf, supervisor, validatedNumaMap); for (Map.Entry<String, SupervisorInfo> supervisorInfoEntry: supervisorInfoList.entrySet()) { stormClusterState.supervisorHeartbeat(supervisorInfoEntry.getKey(), supervisorInfoEntry.getValue()); } }

Target:
public void run() { Map<String, Object> validatedNumaMap = SupervisorUtils.getNumaMap(conf); Map<String, SupervisorInfo> supervisorInfoList = buildSupervisorInfo(conf, supervisor, validatedNumaMap); for (Map.Entry<String, SupervisorInfo> supervisorInfoEntry: supervisorInfoList.entrySet()) { stormClusterState.supervisorHeartbeat(supervisorInfoEntry.getKey(), supervisorInfoEntry.getValue()); } }
Source:
private void setRepo() throws FieldNotFoundException { Map trigger = Optional.ofNullable(event.getContent()) .map(content -> (Map) content.get("execution")) .map(execution -> (Map) execution.get("trigger")) .orElseThrow(FieldNotFoundException::new); if (trigger.containsKey("type") && trigger.get("type").equals("git") && trigger.get("source").equals("github")) { String repo_project = Optional.ofNullable((String) trigger.get("project")) .orElseThrow(FieldNotFoundException::new); String repo_slug = Optional.ofNullable((String) trigger.get("slug")) .orElseThrow(FieldNotFoundException::new); repo = String.format("%s/%s", repo_project, repo_slug); } else { repo = Optional.ofNullable(trigger) .map(t -> (Map) t.get("buildInfo")) .map(buildInfo -> (String) buildInfo.get("name")) .orElseThrow(FieldNotFoundException::new); } }

Target:
private void setRepo() throws FieldNotFoundException { Map trigger = Optional.ofNullable(event.getContent()) .map(content -> (Map) content.get("execution")) .map(execution -> (Map) execution.get("trigger")) .orElseThrow(FieldNotFoundException::new); if (trigger.containsKey("type") && "git".equals(trigger.get("type")) && "github".equals(trigger.get("source"))) { String repo_project = Optional.ofNullable((String) trigger.get("project")) .orElseThrow(FieldNotFoundException::new); String repo_slug = Optional.ofNullable((String) trigger.get("slug")) .orElseThrow(FieldNotFoundException::new); repo = String.format("%s/%s", repo_project, repo_slug); } else { repo = Optional.ofNullable(trigger) .map(t -> (Map) t.get("buildInfo")) .map(buildInfo -> (String) buildInfo.get("name")) .orElseThrow(FieldNotFoundException::new); } }
Source:
static void validate(Object template, String identifier) { if (!(template instanceof Map)) { return; } Map<String, ?> map = (Map<String, ?>) template; final Map<String, ?> servicesMap; if (map.containsKey("version")) { if (!map.containsKey("services")) { log.debug("Compose file has an unknown format: 'version' is set but 'services' is not defined", identifier); return; } Object services = map.get("services"); if (!(services instanceof Map)) { log.debug("Compose file has an unknown format: 'services' is not Map", identifier); return; } servicesMap = (Map<String, ?>) services; } else { servicesMap = map; } for (Map.Entry<String, ?> entry : servicesMap.entrySet()) { String serviceName = entry.getKey(); Object serviceDefinition = entry.getValue(); if (!(serviceDefinition instanceof Map)) { break; } if (((Map) serviceDefinition).containsKey("container_name")) { throw new IllegalStateException(String.format( "Compose file %s has 'container_name' property set for service '%s' but this property is not supported by Testcontainers, consider removing it", identifier, serviceName )); } } }

Target:
static void validate(Object template, String identifier) { if (!(template instanceof Map)) { return; } Map<String, ?> map = (Map<String, ?>) template; final Map<String, ?> servicesMap; if (map.containsKey("version")) { if (!map.containsKey("services")) { log.debug("Compose file has an unknown format: 'version' is set but 'services' is not defined", identifier); return; } Object services = map.get("services"); if (!(services instanceof Map)) { log.debug("Compose file has an unknown format: 'services' is not Map", identifier); return; } servicesMap = (Map<String, ?>) services; } else { servicesMap = map; } for (Map.Entry<String, ?> entry : servicesMap.entrySet()) { String serviceName = entry.getKey(); Object serviceDefinition = entry.getValue(); if (!(serviceDefinition instanceof Map)) { log.debug("Compose file has an unknown format: service '{}' is not Map", identifier, serviceName); break; } if (((Map) serviceDefinition).containsKey("container_name")) { throw new IllegalStateException(String.format( "Compose file %s has 'container_name' property set for service '%s' but this property is not supported by Testcontainers, consider removing it", identifier, serviceName )); } } }
Source:
public void close() { stmts.forEach(stmt -> { try { if (stmt != null && !stmt.isClosed()) { stmt.close(); } } catch (SQLException e) { throw new IllegalStateException(e); } }); try { if (conn != null) { conn.close(); } } catch (SQLException e) { throw new IllegalStateException(e); } }

Target:
public void close() { stmts.forEach(stmt -> cancelAndCloseSoftly(stmt)); closeSoftly(conn); }
Source:
protected void subscribeActual(Subscriber<? super T> observer) { Collection<? super K> collection; try { collection = ObjectHelper.requireNonNull(collectionSupplier.call(), "The returned Collection is null. Null values are generally not allowed in 2.x operators and sources."); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); EmptySubscription.error(ex, observer); return; } source.subscribe(new DistinctSubscriber<T, K>(observer, keySelector, collection)); }

Target:
protected void subscribeActual(Subscriber<? super T> observer) { Collection<? super K> collection; try { collection = ObjectHelper.requireNonNull(collectionSupplier.call(), "The collectionSupplier returned a null collection. Null values are generally not allowed in 2.x operators and sources."); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); EmptySubscription.error(ex, observer); return; } source.subscribe(new DistinctSubscriber<T, K>(observer, keySelector, collection)); }
Source:
public void stacksDismissibleNotification() { NotificationInformation notificationInfo = createNotificationInfo(STACK_NOTIFICATION_DISMISSIBLE, 100); given(notificationCreator.createNotification(DOWNLOAD_BATCH_STATUS)).willReturn(notificationInfo); notificationDispatcher.updateNotification(DOWNLOAD_BATCH_STATUS); InOrder inOrder = inOrder(downloadService, notificationManager); inOrder.verify(downloadService, never()).stop(true); inOrder.verify(notificationManager).notify(NOTIFICATION_TAG, notificationInfo.getId(), notificationInfo.getNotification()); inOrder.verifyNoMoreInteractions(); }

Target:
public void stacksDismissibleNotification() { NotificationInformation notificationInfo = createNotificationInfo(STACK_NOTIFICATION_DISMISSIBLE, 100); given(notificationCreator.createNotification(DOWNLOAD_BATCH_STATUS)).willReturn(notificationInfo); notificationDispatcher.updateNotification(DOWNLOAD_BATCH_STATUS); verify(downloadService, never()).stop(true); verify(notificationManager).notify(NOTIFICATION_TAG, notificationInfo.getId(), notificationInfo.getNotification()); }
Source:
public void testPrometheusJobMetrics() throws Exception { int currentNumberOfCancelled = jobServicesClient.getRequestsByStatus(Collections.singletonList(STATUS.CANCELLED.toString()), 0, 1000).size(); int currentNumberOfDone = jobServicesClient.getRequestsByStatus(Collections.singletonList(STATUS.DONE.toString()), 0, 1000).size(); Calendar tomorrow = Calendar.getInstance(); tomorrow.add(Calendar.DATE, 1); JobRequestInstance jobRequestInstanceTomorrow = createJobRequestInstance(); jobRequestInstanceTomorrow.setScheduledDate(tomorrow.getTime()); Long jobIdTomorrow = jobServicesClient.scheduleRequest(jobRequestInstanceTomorrow); jobServicesClient.cancelRequest(jobIdTomorrow); JobRequestInstance jobRequestInstanceNow = createJobRequestInstance(); Long jobIdNow = jobServicesClient.scheduleRequest(jobRequestInstanceNow); KieServerSynchronization.waitForJobToFinish(jobServicesClient, jobIdNow); assertThat(getMetrics()).contains( "kie_server_job_scheduled_total{container_id=\"\",command_name=\"" + PRINT_OUT_COMMAND + "\",}", "kie_server_job_cancelled_total{container_id=\"\",command_name=\"" + PRINT_OUT_COMMAND + "\",} " + (currentNumberOfCancelled + 1) ); }

Target:
public void testPrometheusJobMetrics() throws Exception { int currentNumberOfCancelled = jobServicesClient.getRequestsByStatus(Collections.singletonList(STATUS.CANCELLED.toString()), 0, 1000).size(); int currentNumberOfDone = jobServicesClient.getRequestsByStatus(Collections.singletonList(STATUS.DONE.toString()), 0, 1000).size(); Instant tomorrow = Instant.now().plus(1, ChronoUnit.DAYS); JobRequestInstance jobRequestInstanceTomorrow = createJobRequestInstance(); jobRequestInstanceTomorrow.setScheduledDate(Date.from(tomorrow)); Long jobIdTomorrow = jobServicesClient.scheduleRequest(jobRequestInstanceTomorrow); jobServicesClient.cancelRequest(jobIdTomorrow); JobRequestInstance jobRequestInstanceNow = createJobRequestInstance(); Long jobIdNow = jobServicesClient.scheduleRequest(jobRequestInstanceNow); KieServerSynchronization.waitForJobToFinish(jobServicesClient, jobIdNow); assertThat(getMetrics()).contains( "kie_server_job_scheduled_total{container_id=\"\",command_name=\"" + PRINT_OUT_COMMAND + "\",}", "kie_server_job_cancelled_total{container_id=\"\",command_name=\"" + PRINT_OUT_COMMAND + "\",} " + (currentNumberOfCancelled + 1) ); }
Source:
protected Provider loadProvider() { try { Properties properties = new Properties(); properties.load(getClass().getResourceAsStream("/defaults.properties")); Class<?> providerClass = Class.forName(properties.getProperty("provider")); Constructor<?> constructor = providerClass.getConstructor(); return (Provider) constructor.newInstance(); } catch (Exception e) { throw new RuntimeException("could not create provider", e); } }

Target:
protected Provider loadProvider() { try { return new GerritProvider(); } catch (Exception e) { throw new RuntimeException("could not create provider", e); } }
Source:
public List<Role> getRoles(String inode, int permissionType, String filter, int start, int limit) { Inode inodeObj = null; List<Role> roleList = null; List<Permission> permissionList = null; try { Logger.debug( PermissionAPI.class, String.format("::getRoles -> before loading inode object(%s)", inode) ); Optional<ShortyId> shortOpt = APILocator.getShortyAPI().getShorty(inode); if ( ShortType.STRUCTURE == shortOpt.get().subType ) { ContentType foundContentType = APILocator.getContentTypeAPI(APILocator.systemUser()).find(inode); if ( null != foundContentType ) { inodeObj = new StructureTransformer(foundContentType).asStructure(); } } else { inodeObj = InodeFactory.getInode(inode, Inode.class); } permissionList = getPermissions(inodeObj, true); roleList = loadRolesForPermission(permissionList, permissionType, filter); if( start < roleList.size() ) { if (limit > -1 && start + limit < roleList.size() ) { roleList = roleList.subList(start, start + limit); } else { roleList = roleList.subList(start, roleList.size()); } } } catch (Exception e) { Logger.error(this,e.getMessage(),e); } finally { if( roleList == null ) { roleList = new ArrayList<Role>(0); } } return roleList; }

Target:
public List<Role> getRoles(String inode, int permissionType, String filter, int start, int limit) { Inode inodeObj = null; List<Role> roleList = null; List<Permission> permissionList = null; try { Logger.debug( PermissionAPI.class, String.format("::getRoles -> before loading inode object(%s)", inode) ); Optional<ShortyId> shortOpt = APILocator.getShortyAPI().getShorty(inode); if ( shortOpt.isPresent() && ShortType.STRUCTURE == shortOpt.get().subType ) { ContentType foundContentType = APILocator.getContentTypeAPI(APILocator.systemUser()).find(inode); if ( null != foundContentType ) { inodeObj = new StructureTransformer(foundContentType).asStructure(); } } else { inodeObj = InodeFactory.getInode(inode, Inode.class); } permissionList = getPermissions(inodeObj, true); roleList = loadRolesForPermission(permissionList, permissionType, filter); if( start < roleList.size() ) { if (limit > -1 && start + limit < roleList.size() ) { roleList = roleList.subList(start, start + limit); } else { roleList = roleList.subList(start, roleList.size()); } } } catch (Exception e) { Logger.error(this,e.getMessage(),e); } finally { if( roleList == null ) { roleList = new ArrayList<Role>(0); } } return roleList; }
Source:
private Object invokeMethod(String type, Method method, Object o, Object... args) { try { return method.invoke(o, args); } catch (InvocationTargetException e) { if (e.getTargetException() instanceof WebApplicationException) { return ((WebApplicationException) e.getTargetException()).getResponse(); } if (type.equals(COMPENSATE)) { return ParticipantStatus.FailedToCompensate.name(); } else if (type.equals(COMPLETE)) { return ParticipantStatus.FailedToComplete.name(); } else { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } } catch (IllegalAccessException e) { throw new RuntimeException(e); } }

Target:
private Object invokeMethod(String type, Method method, Object o, Object... args) { try { return method.invoke(o, args); } catch (InvocationTargetException e) { return processThrowable(e.getTargetException(), type); } catch (IllegalAccessException e) { throw new RuntimeException(e); } }