auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public boolean findPom(IContainer container) { IFile file = container.getFile(new Path("pom.xml")); boolean rc = false; if (file.exists()) { try { Document xmlDocument = builder.parse(file.getContents()); String parent = xPath.compile(PARENT_NODE).evaluate(xmlDocument); if (!parent.equals("")) { rc = findPom(container.getParent()); } else { rc = true; } } catch (SAXException e) { StubbyLog.logError(e); } catch (IOException e) { StubbyLog.logError(e); } catch (XPathExpressionException e) { StubbyLog.logError(e); } catch (CoreException e) { StubbyLog.logError(e); } } return rc; }

Target:
public boolean findPom(IContainer container) { if (container.getProject() == null) return false; IFile file = container.getFile(new Path("pom.xml")); boolean rc = false; if (file.exists()) { try { Document xmlDocument = builder.parse(file.getContents()); String parent = xPath.compile(PARENT_NODE).evaluate(xmlDocument); if (!parent.equals("")) { rc = findPom(container.getParent()); } else { rc = true; } } catch (SAXException e) { StubbyLog.logError(e); } catch (IOException e) { StubbyLog.logError(e); } catch (XPathExpressionException e) { StubbyLog.logError(e); } catch (CoreException e) { StubbyLog.logError(e); } } return rc; }
Source:
public void leaveNode(Tree tree) { if (tree instanceof IterationStatementTree) { decrementLoopLevelinScope(); } else { scope.pop(); } }

Target:
public void leaveNode(Tree tree) { if (tree.is(CheckUtils.iterationStatementsArray())) { decrementLoopLevelinScope(); } else { scope.pop(); } }
Source:
public static PeerToPeerReviewArtifact getOrCreatePeerReview(ReviewBlockType reviewBlockType, AtsTestUtilState relatedToState, SkynetTransaction transaction) throws OseeCoreException { ensureLoaded(); try { if (peerRevArt == null) { peerRevArt = PeerToPeerReviewManager.createNewPeerToPeerReview( AtsWorkDefinitionService.get().getDefaultPeerToPeerWorkflowDefinition(), teamArt, AtsTestUtil.class.getSimpleName() + " Test Peer Review", relatedToState.getName(), transaction); } } catch (Exception ex) { throw new OseeWrappedException(ex); } return peerRevArt; }

Target:
public static PeerToPeerReviewArtifact getOrCreatePeerReview(ReviewBlockType reviewBlockType, AtsTestUtilState relatedToState, SkynetTransaction transaction) throws OseeCoreException { ensureLoaded(); try { if (peerRevArt == null) { peerRevArt = PeerToPeerReviewManager.createNewPeerToPeerReview( AtsWorkDefinitionService.get().getDefaultPeerToPeerWorkflowDefinition(), teamArt, AtsTestUtil.class.getSimpleName() + " Test Peer Review", relatedToState.getName(), transaction); } } catch (OseeCoreException ex) { throw new OseeWrappedException(ex); } return peerRevArt; }
Source:
public void testRegenerateKeys() throws Exception { server.enqueue(jsonResponse("/storageaccountkeys.json")); final StorageAccountApi storageAPI = api.getStorageAccountApi(resourceGroup); assertEquals(storageAPI.regenerateKeys("TESTSTORAGE", "key1"), StorageServiceKeys.create( "bndO7lydwDkMo4Y0mFvmfLyi2f9aZY7bwfAVWoJWv4mOVK6E9c/exLnFsSm/NMWgifLCfxC/c6QBTbdEvWUA7w==", "/jMLLT3kKqY4K+cUtJTbh7pCBdvG9EMKJxUvaJJAf6W6aUiZe1A1ulXHcibrqRVA2RJE0oUeXQGXLYJ2l85L7A==")); assertSent(server, "POST", "/subscriptions/" + subsriptionId + "/resourcegroups/" + resourceGroup + "/providers/Microsoft.Storage/storageAccounts/TESTSTORAGE/regenerateKey?api-version=2015-06-15"); }

Target:
public void testRegenerateKeys() throws Exception { server.enqueue(jsonResponse("/storageaccountkeys.json")); final StorageAccountApi storageAPI = api.getStorageAccountApi(resourceGroup); assertEquals(storageAPI.regenerateKeys("TESTSTORAGE", "key1"), StorageServiceKeys.create( "bndO7lydwDkMo4Y0mFvmfLyi2f9aZY7bwfAVWoJWv4mOVK6E9c/exLnFsSm/NMWgifLCfxC/c6QBTbdEvWUA7w==", "/jMLLT3kKqY4K+cUtJTbh7pCBdvG9EMKJxUvaJJAf6W6aUiZe1A1ulXHcibrqRVA2RJE0oUeXQGXLYJ2l85L7A==")); assertSent(server, "POST", "/subscriptions/" + subsriptionId + "/resourcegroups/" + resourceGroup + "/providers/Microsoft.Storage/storageAccounts/TESTSTORAGE/regenerateKey?api-version=2015-06-15", String.format("{\"keyName\":\"key1\"}")); }
Source:
protected void initSelectedType() { VmInterfaceType selectedNicType = VmInterfaceType.forValue(getNic().getType()); if (selectedNicType == null || !supportedVnicTypes.contains(selectedNicType)) { selectedNicType = getDeafultNicTypeByProfile(); } getNicType().setItems(supportedVnicTypes, selectedNicType); }

Target:
protected void initSelectedType() { VmInterfaceType selectedNicType = VmInterfaceType.forValue(getNic().getType()); final Collection<VmInterfaceType> vnicTypes = supportedVnicTypes == null ? new ArrayList<VmInterfaceType>() : supportedVnicTypes; if (selectedNicType == null || !vnicTypes.contains(selectedNicType)) { selectedNicType = getDeafultNicTypeByProfile(); } if (getNicType().getItems() != vnicTypes) { getNicType().setItems(vnicTypes, selectedNicType); } else { getNicType().setSelectedItem(selectedNicType); } }
Source:
public synchronized T getDataset() { return dataset; }

Target:
public T getDataset() { return dataset; }
Source:
public List<ReadOnlyRepo<T>> getStack(long tid) { String txpath = getTXPath(tid); outer: while (true) { List<String> ops; try { ops = zk.getChildren(txpath); } catch (KeeperException.NoNodeException e) { return null; } catch (KeeperException | InterruptedException e1) { throw new RuntimeException(e1); } ops = new ArrayList<String>(ops); Collections.sort(ops, Collections.reverseOrder()); ArrayList<ReadOnlyRepo<T>> dops = new ArrayList<>(); for (String child : ops) { if (child.startsWith("repo_")) { byte[] ser; try { ser = zk.getData(txpath + "/" + child, null); dops.add((ReadOnlyRepo<T>) deserialize(ser)); } catch (KeeperException.NoNodeException e) { continue outer; } catch (KeeperException | InterruptedException e) { throw new RuntimeException(e); } } } return dops; } }

Target:
public List<ReadOnlyRepo<T>> getStack(long tid) { String txpath = getTXPath(tid); outer: while (true) { List<String> ops; try { ops = zk.getChildren(txpath); } catch (KeeperException.NoNodeException e) { return Collections.emptyList(); } catch (KeeperException | InterruptedException e1) { throw new RuntimeException(e1); } ops = new ArrayList<String>(ops); Collections.sort(ops, Collections.reverseOrder()); ArrayList<ReadOnlyRepo<T>> dops = new ArrayList<>(); for (String child : ops) { if (child.startsWith("repo_")) { byte[] ser; try { ser = zk.getData(txpath + "/" + child, null); @SuppressWarnings("unchecked") ReadOnlyRepo<T> repo = (ReadOnlyRepo<T>) deserialize(ser); dops.add(repo); } catch (KeeperException.NoNodeException e) { continue outer; } catch (KeeperException | InterruptedException e) { throw new RuntimeException(e); } } } return dops; } }
Source:
private boolean isFieldAssignment(AssignmentExpressionTree tree) { ExpressionTree variableTree = tree.variable(); if (variableTree.is(Kind.IDENTIFIER)) { Symbol variableSymbol = getSemanticModel().getReference((IdentifierTree) variableTree); return variableSymbol.owner().isKind(Symbol.TYP); } return false; }

Target:
private boolean isFieldAssignment(AssignmentExpressionTree tree) { ExpressionTree variable = tree.variable(); if (variable.is(Kind.MEMBER_SELECT)) { MemberSelectExpressionTree memberSelectExpressionTree = (MemberSelectExpressionTree) variable; if (!isThis(memberSelectExpressionTree.expression())) { return false; } variable = memberSelectExpressionTree.identifier(); } if (variable.is(Kind.IDENTIFIER)) { Symbol variableSymbol = getSemanticModel().getReference((IdentifierTree) variable); return variableSymbol != null && variableSymbol.owner().isKind(Symbol.TYP); } return false; }
Source:
private Result cloneResult(Result result) { Metacard metacard = result.getMetacard(); Metacard clonedMetacard = new MetacardImpl(metacard, metacard.getMetacardType()); Result clonedResult = new ResultImpl(clonedMetacard); ((ResultImpl) clonedResult).setDistanceInMeters(result.getDistanceInMeters()); ((ResultImpl) clonedResult).setRelevanceScore(result.getRelevanceScore()); return clonedResult; }

Target:
private Result cloneResult(Result result) { Metacard metacard = result.getMetacard(); Metacard clonedMetacard = new MetacardImpl(metacard, metacard.getMetacardType()); ResultImpl clonedResult = new ResultImpl(clonedMetacard); clonedResult.setDistanceInMeters(result.getDistanceInMeters()); clonedResult.setRelevanceScore(result.getRelevanceScore()); return clonedResult; }
Source:
protected boolean isConfigured() { return generator.getNuxeoHome() .toPath() .resolve("conf") .resolve("Catalina") .resolve("localhost") .resolve(getContextName() + ".xml") .toFile() .exists(); }

Target:
protected boolean isConfigured() { Path nuxeoContext = Path.of("conf", "Catalina", "localhost", getContextName() + ".xml"); return Files.exists(generator.getNuxeoHome().toPath().resolve(nuxeoContext)); }
Source:
public TradfriCoapClient(URI uri) { super(uri); setTimeout(TIMEOUT); logger = LoggerFactory.getLogger(getClass()); commandsQueue = new LinkedBlockingQueue<>(); commandExecutorThread = new Thread(() -> { while (true) { try { PayloadCallbackPair payloadCallbackPair = TradfriCoapClient.this.commandsQueue.take(); logger.debug("Proccessing payload: {}", payloadCallbackPair.payload); if (STOP_EXECUTOR.equals(payloadCallbackPair.payload)) { break; } TradfriCoapClient.this.put(new TradfriCoapHandler(payloadCallbackPair.callback), payloadCallbackPair.payload, MediaTypeRegistry.TEXT_PLAIN); Thread.sleep(Optional.ofNullable(payloadCallbackPair.delay).orElse(DEFAULT_DELAY_MILLIS)); } catch (InterruptedException e) { logger.debug("commandExecutorThread was interrupted", e); } } }); commandExecutorThread.setDaemon(true); }

Target:
public TradfriCoapClient(URI uri) { super(uri); setTimeout(TIMEOUT); logger = LoggerFactory.getLogger(getClass()); commandsQueue = new LinkedList<>(); commandExecutor = () -> { while (true) { try { int delayTime = 0; synchronized (this.commandsQueue) { PayloadCallbackPair payloadCallbackPair = TradfriCoapClient.this.commandsQueue.poll(); if (payloadCallbackPair != null) { logger.debug("Proccessing payload: {}", payloadCallbackPair.payload); TradfriCoapClient.this.put(new TradfriCoapHandler(payloadCallbackPair.callback), payloadCallbackPair.payload, MediaTypeRegistry.TEXT_PLAIN); delayTime = Optional.ofNullable(payloadCallbackPair.delay).orElse(DEFAULT_DELAY_MILLIS); } else { return; } } Thread.sleep(delayTime); } catch (InterruptedException e) { logger.debug("commandExecutorThread was interrupted", e); } } }; job = null; }
Source:
public void testNoSuchUserException() throws DotSecurityException, NoSuchUserException, DotInvalidTokenException, SystemException, PortalException, DotDataException { UserManager userManager = getUserManagerThrowingException( new NoSuchUserException("") ); final User user = APILocator.getUserAPI().loadUserById("dotcms.org.1"); final JsonWebTokenService jsonWebTokenService = mock(JsonWebTokenService.class); final UserToken jwtBean = new UserToken(UUID.randomUUID().toString(), "dotcms.org.1", new Date(), 100000, user.getRememberMeToken()); when(jsonWebTokenService.parseToken(eq("token1"))).thenReturn(jwtBean); ResetPasswordResource resetPasswordResource = new ResetPasswordResource(userManager, responseUtil, jsonWebTokenService); Response response = resetPasswordResource.resetPassword(request, resetPasswordForm); RestUtilTest.verifyErrorResponse(response, Response.Status.BAD_REQUEST.getStatusCode(), "please-enter-a-valid-login"); }

Target:
public void testNoSuchUserException() throws DotSecurityException, NoSuchUserException, DotInvalidTokenException, DotDataException { UserManager userManager = getUserManagerThrowingException( new NoSuchUserException("") ); final JsonWebTokenService jsonWebTokenService = mock(JsonWebTokenService.class); final UserToken jwtBean = new UserToken.Builder().id(UUIDGenerator.generateUuid()) .subject(DOTCMS_ORG_1).modificationDate(new Date()).expiresDate(100000).build(); when(jsonWebTokenService.parseToken(eq("token1"))).thenReturn(jwtBean); ResetPasswordResource resetPasswordResource = new ResetPasswordResource(userManager, responseUtil, jsonWebTokenService); Response response = resetPasswordResource.resetPassword(request, resetPasswordForm); RestUtilTest.verifyErrorResponse(response, Response.Status.BAD_REQUEST.getStatusCode(), "please-enter-a-valid-login"); }
Source:
public String createPlaceholder(final String path) { if (path == null || path.length() == 0) { try { final FcrepoResponse r = getClient().post(new URI(baseUri), null, null); assertSuccess(r); return uriToPath(r.getLocation().toString()); } catch (FcrepoOperationFailedException | URISyntaxException e) { throw new RuntimeException(e); } } else if (!exists(path)) { createResource(path); return path; } else { return path; } }

Target:
public String createPlaceholder(final String path) { if (path == null || path.length() == 0) { try { final FcrepoResponse r = getClient().post(new URI(baseUri), null, null); assertSuccess(r); return uriToPath(r.getLocation().toString()); } catch (FcrepoOperationFailedException | URISyntaxException e) { throw new RuntimeException(e); } } else if (!exists(path)) { createResource(path); } return path; }
Source:
public void run() { log.info("Starting"); if (setState(State.STARTING) == null) { log.info("StreamThread already shutdown. Not running"); return; } boolean cleanRun = false; try { runLoop(); cleanRun = true; } catch (final StreamsException e) { log.error("Encountered the following Streams exception during processing, " + "this indicates an unrecoverable error and the thread is going to shutdown: ", e); throw e; } catch (final KafkaException e) { log.error("Encountered the following unexpected Kafka exception during processing, " + "this indicates an internal error and thread is going to shutdown:", e); throw e; } catch (final Exception e) { log.error("Encountered the following unexpected exception during processing " + "and the thread is going to shutdown:", e); throw e; } finally { completeShutdown(cleanRun); } }

Target:
public void run() { log.info("Starting"); if (setState(State.STARTING) == null) { log.info("StreamThread already shutdown. Not running"); return; } boolean cleanRun = false; try { runLoop(); cleanRun = true; } catch (final KafkaException e) { log.error("Encountered the following unexpected Kafka exception during processing, " + "this usually indicate Streams internal errors:", e); throw e; } catch (final Exception e) { log.error("Encountered the following error during processing:", e); throw e; } finally { completeShutdown(cleanRun); } }
Source:
private boolean executeBatch( BoltConnection connection ) { Thread currentThread = Thread.currentThread(); String originalName = currentThread.getName(); String newName = String.format( "%s [%s] ", originalName, connection.remoteAddress(), connector ); currentThread.setName( newName ); try { return connection.processNextBatch(); } finally { currentThread.setName( originalName ); } }

Target:
private boolean executeBatch( BoltConnection connection ) { Thread currentThread = Thread.currentThread(); String originalName = currentThread.getName(); String newName = String.format( "%s [%s] ", originalName, connection.remoteAddress() ); currentThread.setName( newName ); try { return connection.processNextBatch(); } finally { currentThread.setName( originalName ); } }
Source:
public boolean checkRootBySuAccess() { if (new ShellExecutor().executeCommand(SU_CHECK_COMMAND) != null) { if (Constants.DEBUG_MODE_ENABLED) { Log.d(TAG, "su command enabled"); } return true; } else { return false; } }

Target:
public boolean checkRootBySuAccess() { if (new ShellExecutor().executeCommand(SU_CHECK_COMMAND) != null) { if (Constants.DEBUG_MODE_ENABLED) { Log.d(TAG, "su command is enabled"); } return true; } else { return false; } }
Source:
public DataSchema( @JsonProperty("dataSource") String dataSource, @JsonProperty("parser") Map<String, Object> parser, @JsonProperty("metricsSpec") AggregatorFactory[] aggregators, @JsonProperty("granularitySpec") GranularitySpec granularitySpec, @JsonProperty("transformSpec") TransformSpec transformSpec, @JacksonInject ObjectMapper jsonMapper ) { this.jsonMapper = Preconditions.checkNotNull(jsonMapper, "null ObjectMapper."); this.parser = parser; this.transformSpec = transformSpec == null ? TransformSpec.NONE : transformSpec; Preconditions.checkArgument(!Strings.isNullOrEmpty(dataSource), "dataSource cannot be null or empty. Please provide a dataSource."); Preconditions.checkArgument(!dataSource.contains("/"), "dataSource cannot contain the '/' character."); Preconditions.checkArgument(!dataSource.contains("\t"), "dataSource cannot contain the '\\t' character."); Preconditions.checkArgument(!dataSource.contains("\n"), "dataSource cannot contain the '\\n' character."); Preconditions.checkArgument(!dataSource.contains("\r"), "dataSource cannot contain the '\\r' character."); this.dataSource = dataSource; if (granularitySpec == null) { log.warn("No granularitySpec has been specified. Using UniformGranularitySpec as default."); this.granularitySpec = new UniformGranularitySpec(null, null, null); } else { this.granularitySpec = granularitySpec; } if (aggregators != null && aggregators.length != 0) { Set<String> names = new HashSet<>(); for (AggregatorFactory factory : aggregators) { if (!names.add(factory.getName())) { throw new IAE("duplicate aggregators found with name [%s].", factory.getName()); } } } else if (this.granularitySpec.isRollup()) { log.warn("No metricsSpec has been specified. Are you sure this is what you want?"); } this.aggregators = aggregators == null ? new AggregatorFactory[]{} : aggregators; }

Target:
public DataSchema( @JsonProperty("dataSource") String dataSource, @JsonProperty("parser") Map<String, Object> parser, @JsonProperty("metricsSpec") AggregatorFactory[] aggregators, @JsonProperty("granularitySpec") GranularitySpec granularitySpec, @JsonProperty("transformSpec") TransformSpec transformSpec, @JacksonInject ObjectMapper jsonMapper ) { this.jsonMapper = Preconditions.checkNotNull(jsonMapper, "null ObjectMapper."); this.parser = parser; this.transformSpec = transformSpec == null ? TransformSpec.NONE : transformSpec; validateDatasourceName(dataSource); this.dataSource = dataSource; if (granularitySpec == null) { log.warn("No granularitySpec has been specified. Using UniformGranularitySpec as default."); this.granularitySpec = new UniformGranularitySpec(null, null, null); } else { this.granularitySpec = granularitySpec; } if (aggregators != null && aggregators.length != 0) { Set<String> names = new HashSet<>(); for (AggregatorFactory factory : aggregators) { if (!names.add(factory.getName())) { throw new IAE("duplicate aggregators found with name [%s].", factory.getName()); } } } else if (this.granularitySpec.isRollup()) { log.warn("No metricsSpec has been specified. Are you sure this is what you want?"); } this.aggregators = aggregators == null ? new AggregatorFactory[]{} : aggregators; }
Source:
public void appendTest() throws IOException { doAppendTest(new Appender() { @Override public void append(LogSegment segment, ByteBuffer buffer) throws IOException { int writeSize = buffer.remaining(); int written = segment.appendFrom(buffer); assertEquals("Size written did not match size of buffer provided", writeSize, written); } }); doAppendTest(new Appender() { @Override public void append(LogSegment segment, ByteBuffer buffer) throws IOException { int writeSize = buffer.remaining(); segment.appendFrom(Channels.newChannel(new ByteBufferInputStream(buffer)), writeSize); assertFalse("The buffer was not completely written", buffer.hasRemaining()); } }); doAppendTest(new Appender() { @Override public void append(LogSegment segment, ByteBuffer buffer) throws IOException { assumeTrue(Platform.isLinux()); int writeSize = buffer.remaining(); segment.appendFromDirectly(buffer.array(), 0, writeSize); } }); }

Target:
public void appendTest() throws IOException { doAppendTest(new Appender() { @Override public void append(LogSegment segment, ByteBuffer buffer) throws IOException { int writeSize = buffer.remaining(); int written = segment.appendFrom(buffer); assertEquals("Size written did not match size of buffer provided", writeSize, written); } }); doAppendTest(new Appender() { @Override public void append(LogSegment segment, ByteBuffer buffer) throws IOException { int writeSize = buffer.remaining(); segment.appendFrom(Channels.newChannel(new ByteBufferInputStream(buffer)), writeSize); assertFalse("The buffer was not completely written", buffer.hasRemaining()); } }); if (Utils.isLinux()) { doAppendTest(new Appender() { @Override public void append(LogSegment segment, ByteBuffer buffer) throws IOException { int writeSize = buffer.remaining(); segment.appendFromDirectly(buffer.array(), 0, writeSize); } }); } }
Source:
public static void main(String[] args) throws Exception { CommandLine cmdLine = new CommandLine(); OptionSet options = cmdLine.parser().parse(args); Config orgConfig = cmdLine.loadConfig(options); Config config = Util.rewriteConfig(orgConfig); LocalApplicationRunner runner = new LocalApplicationRunner(config); WikipediaApplication app = new WikipediaApplication(); runner.run(app); runner.waitForFinish(); }

Target:
public static void main(String[] args) { CommandLine cmdLine = new CommandLine(); OptionSet options = cmdLine.parser().parse(args); Config orgConfig = cmdLine.loadConfig(options); Config config = Util.rewriteConfig(orgConfig); LocalApplicationRunner runner = new LocalApplicationRunner(config); WikipediaApplication app = new WikipediaApplication(); runner.run(app); runner.waitForFinish(); }
Source:
public void testChar() throws NoConnectionsException, IOException, ProcCallException { System.out.println("STARTING test CHAR"); if (isHSQL()) return; Client client = getClient(); ClientResponse cr; VoltTable result; cr = client.callProcedure("P1.insert", 1, "Xin@VoltDB", 1, 1.0, new Timestamp(1000000000000L)); assertEquals(ClientResponse.SUCCESS, cr.getStatus()); result = client.callProcedure("CHAR", 36158, 1).getResults()[0]; assertTrue(result.advanceRow()); assertEquals("贾", result.getString(1)); result = client.callProcedure("CHAR", 37995, 1).getResults()[0]; assertTrue(result.advanceRow()); assertEquals("鑫", result.getString(1)); String voltDB = "VoltDB"; for (int i = 0; i < voltDB.length(); i++) { char ch = voltDB.charAt(i); result = client.callProcedure("CHAR", (int)ch, 1).getResults()[0]; assertTrue(result.advanceRow()); assertEquals(String.valueOf(ch), result.getString(1)); } result = client.callProcedure("CHAR", null, 1).getResults()[0]; assertTrue(result.advanceRow()); assertEquals(null, result.getString(1)); }

Target:
public void testChar() throws NoConnectionsException, IOException, ProcCallException { System.out.println("STARTING test CHAR"); if (isHSQL()) { return; } Client client = getClient(); ClientResponse cr; VoltTable result; cr = client.callProcedure("P1.insert", 1, "Xin@VoltDB", 1, 1.0, new Timestamp(1000000000000L)); assertEquals(ClientResponse.SUCCESS, cr.getStatus()); result = client.callProcedure("CHAR", 36158, 1).getResults()[0]; assertTrue(result.advanceRow()); assertEquals("贾", result.getString(1)); result = client.callProcedure("CHAR", 37995, 1).getResults()[0]; assertTrue(result.advanceRow()); assertEquals("鑫", result.getString(1)); String voltDB = "VoltDB"; for (int i = 0; i < voltDB.length(); i++) { char ch = voltDB.charAt(i); result = client.callProcedure("CHAR", (int)ch, 1).getResults()[0]; assertTrue(result.advanceRow()); assertEquals(String.valueOf(ch), result.getString(1)); } result = client.callProcedure("CHAR", null, 1).getResults()[0]; assertTrue(result.advanceRow()); assertEquals(null, result.getString(1)); }
Source:
private void saveAccessTokenToSession(AccessToken accessToken) { ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); attr.getRequest().getSession(false).setAttribute(accessToken.applicationIdUri, accessToken); }

Target:
private void saveAccessTokenToSession(AccessToken accessToken) { ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); attr.getRequest().getSession(false).setAttribute(ACCESS_TOKEN + accessToken.applicationIdUri, accessToken); }
Source:
public void nearbyStationsAddress() throws Exception { nearbyStationsAddress(44826434, -0557312); }

Target:
public void nearbyStationsAddress() throws Exception { nearbyStationsAddress(44826434, -557312); }
Source:
public List<OpenRevision> getDocWithOpenRevisions(String id, Collection<String> revisions, Collection<String> attsSince, boolean pullAttachmentsInline) { Misc.checkNotNullOrEmpty(id, "id"); Misc.checkArgument(revisions.size() > 0, "Need at lease one open revision"); Map<String, Object> options = new HashMap<String, Object>(); options.put("revs", true); if (pullAttachmentsInline) { options.put("attachments", true); if (attsSince != null) { options.put("atts_since", jsonHelper.toJson(attsSince)); } } else { options.put("attachments", false); options.put("att_encoding_info", true); } options.put("open_revs", jsonHelper.toJson(revisions)); return this.getDocument(id, options, new TypeReference<List<OpenRevision>>() { }); }

Target:
public List<OpenRevision> getDocWithOpenRevisions(String id, Collection<String> revisions, Collection<String> attsSince, boolean pullAttachmentsInline) { Misc.checkNotNullOrEmpty(id, "id"); Misc.checkArgument(revisions.size() > 0, "Need at least one open revision"); Map<String, Object> options = new HashMap<String, Object>(); options.put("revs", true); if (pullAttachmentsInline) { options.put("attachments", true); if (attsSince != null) { options.put("atts_since", jsonHelper.toJson(attsSince)); } } else { options.put("attachments", false); options.put("att_encoding_info", true); } options.put("open_revs", jsonHelper.toJson(revisions)); return this.getDocument(id, options, new TypeReference<List<OpenRevision>>() { }); }
Source:
public DockerSlave provision(StreamTaskListener listener) throws IOException, Descriptor.FormException, DockerException { PrintStream logger = listener.getLogger(); logger.println("Launching " + image ); Node.Mode mode = Node.Mode.NORMAL; RetentionStrategy retentionStrategy = new CloudRetentionStrategy(idleTerminationMinutes()); List<? extends NodeProperty<?>> nodeProperties = new ArrayList(); InspectContainerResponse containerInspectResponse = provisionNew(); String containerId = containerInspectResponse.getId(); ComputerLauncher launcher = new DockerComputerLauncher(this, containerInspectResponse); String nodeDescription = "Docker Node [" + image + " on "; try { nodeDescription += getParent().getDisplayName(); } catch(Exception ex) { nodeDescription += "???"; } nodeDescription += "]"; String slaveName = containerId.substring(0,12); try { slaveName = slaveName + "@" + getParent().getDisplayName(); } catch(Exception ex) { LOGGER.warning("Error fetching name of cloud"); } return new DockerSlave(this, containerId, slaveName, nodeDescription, remoteFs, numExecutors, mode, memoryLimit, cpuShares, labelString, launcher, retentionStrategy, nodeProperties); }

Target:
public DockerSlave provision(StreamTaskListener listener) throws IOException, Descriptor.FormException, DockerException { PrintStream logger = listener.getLogger(); logger.println("Launching " + image ); Node.Mode mode = Node.Mode.NORMAL; RetentionStrategy retentionStrategy = null; if (numExecutors == 1) { retentionStrategy = new OnceRetentionStrategy(idleTerminationMinutes()); } else { retentionStrategy = new CloudRetentionStrategy(idleTerminationMinutes()); } List<? extends NodeProperty<?>> nodeProperties = new ArrayList(); InspectContainerResponse containerInspectResponse = provisionNew(); String containerId = containerInspectResponse.getId(); ComputerLauncher launcher = new DockerComputerLauncher(this, containerInspectResponse); String nodeDescription = "Docker Node [" + image + " on "; try { nodeDescription += getParent().getDisplayName(); } catch(Exception ex) { nodeDescription += "???"; } nodeDescription += "]"; String slaveName = containerId.substring(0,12); try { slaveName = slaveName + "@" + getParent().getDisplayName(); } catch(Exception ex) { LOGGER.warning("Error fetching name of cloud"); } return new DockerSlave(this, containerId, slaveName, nodeDescription, remoteFs, numExecutors, mode, memoryLimit, cpuShares, labelString, launcher, retentionStrategy, nodeProperties); }
Source:
public Renderable compile(Class<?> page, final Template template) { Renderable renderable = new Renderable() { @Override public void render(Object bound, Respond respond) { HttpServletRequest request = httpServletRequestProvider.get(); HttpServletResponse response = httpServletResponseProvider.get(); RequestDispatcher requestDispatcher = request.getRequestDispatcher(template.getName()); try { requestDispatcher.include(request, response); } catch (ServletException e) { e.printStackTrace(); throw new RuntimeException("Could not include the response for path=" + template.getName(), e); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("Could not include the response for path=" + template.getName(), e); } } @Override public <T extends Renderable> Set<T> collect(Class<T> clazz) { throw new IllegalStateException( "The collect method should not be called while rendering a JSP template."); } }; return renderable; }

Target:
public Renderable compile(Class<?> page, final Template template) { Renderable renderable = new Renderable() { @Override public void render(Object bound, Respond respond) { HttpServletRequest request = httpServletRequestProvider.get(); HttpServletResponse response = httpServletResponseProvider.get(); RequestDispatcher requestDispatcher = request.getRequestDispatcher(template.getName()); request.setAttribute("pageFlow", bound); try { requestDispatcher.include(request, response); } catch (ServletException e) { throw new RuntimeException("Could not include the JSP response for path=" + template.getName(), e); } catch (IOException e) { throw new RuntimeException("Could not include the JSP response for path=" + template.getName(), e); } } @Override public <T extends Renderable> Set<T> collect(Class<T> clazz) { throw new IllegalStateException( "The collect method should not be called while rendering a JSP template."); } }; return renderable; }
Source:
public RestRequest continueProcessing(RestRequest request, RestChannel channel) throws Exception { try { if (enabled && threadContext.getTransient(OPENSHIFT_REQUEST_CONTEXT) != null) { OpenshiftRequestContext requestContext = threadContext.getTransient(OPENSHIFT_REQUEST_CONTEXT); request = utils.modifyRequest(request, requestContext, channel); if (requestContext != OpenshiftRequestContext.EMPTY) { utils.logRequest(request); final String kbnVersion = getKibanaVersion(request); kibanaSeed.setDashboards(requestContext, kbnVersion, cdmProjectPrefix); aclManager.syncAcl(requestContext); } } } catch (Exception e) { LOGGER.error("Error handling request", e); } return request; }

Target:
public RestRequest continueProcessing(RestRequest request, RestChannel channel) throws Exception { try { if (threadContext.getTransient(OPENSHIFT_REQUEST_CONTEXT) != null) { OpenshiftRequestContext requestContext = threadContext.getTransient(OPENSHIFT_REQUEST_CONTEXT); request = utils.modifyRequest(request, requestContext, channel); if (requestContext != OpenshiftRequestContext.EMPTY) { utils.logRequest(request); final String kbnVersion = getKibanaVersion(request); kibanaSeed.setDashboards(requestContext, kbnVersion, cdmProjectPrefix); aclManager.syncAcl(requestContext); } } } catch (Exception e) { LOGGER.error("Error handling request", e); } return request; }
Source:
void testDoubleSplitAndMerge() throws Exception { tokenStore.initializeTokenSegments(testSubject.getName(), 1); List<EventMessage<?>> handledEvents = new CopyOnWriteArrayList<>(); when(mockHandler.handle(any())).thenAnswer(i -> handledEvents.add(i.getArgument(0))); publishEvents(10); testSubject.start(); waitForActiveThreads(1); assertWithin( 50, TimeUnit.MILLISECONDS, () -> assertTrue(testSubject.splitSegment(0).join(), "Expected split to succeed") ); waitForActiveThreads(1); assertWithin( 50, TimeUnit.MILLISECONDS, () -> assertTrue(testSubject.splitSegment(0).join(), "Expected split to succeed") ); waitForActiveThreads(1); assertArrayEquals(new int[]{0, 1, 2}, tokenStore.fetchSegments(testSubject.getName())); publishEvents(20); waitForProcessingStatus(0, EventTrackerStatus::isCaughtUp); assertFalse(testSubject.processingStatus().get(0).isMerging()); assertTrue(testSubject.mergeSegment(0).join(), "Expected merge to succeed"); assertArrayEquals(new int[]{0, 1}, tokenStore.fetchSegments(testSubject.getName())); publishEvents(10); waitForSegmentStart(0); waitForProcessingStatus(0, est -> est.getSegment().getMask() == 1 && est.isCaughtUp()); assertTrue(testSubject.mergeSegment(0).join(), "Expected merge to succeed"); assertArrayEquals(new int[]{0}, tokenStore.fetchSegments(testSubject.getName())); assertWithin(3, TimeUnit.SECONDS, () -> assertEquals(40, handledEvents.size())); }

Target:
void testDoubleSplitAndMerge() throws Exception { tokenStore.initializeTokenSegments(testSubject.getName(), 1); List<EventMessage<?>> handledEvents = new CopyOnWriteArrayList<>(); int segmentId = 0; when(mockHandler.handle(any())).thenAnswer(i -> handledEvents.add(i.getArgument(0))); publishEvents(10); testSubject.start(); waitForActiveThreads(1); assertWithin( 50, TimeUnit.MILLISECONDS, () -> assertTrue(testSubject.splitSegment(segmentId).join(), "Expected split to succeed") ); waitForActiveThreads(1); assertWithin( 50, TimeUnit.MILLISECONDS, () -> assertTrue(testSubject.splitSegment(segmentId).join(), "Expected split to succeed") ); waitForActiveThreads(1); assertArrayEquals(new int[]{0, 1, 2}, tokenStore.fetchSegments(testSubject.getName())); publishEvents(20); waitForProcessingStatus(segmentId, EventTrackerStatus::isCaughtUp); assertFalse(testSubject.processingStatus().get(segmentId).isMerging()); assertTrue(testSubject.mergeSegment(segmentId).join(), "Expected merge to succeed"); assertArrayEquals(new int[]{0, 1}, tokenStore.fetchSegments(testSubject.getName())); publishEvents(10); waitForSegmentStart(segmentId); waitForProcessingStatus(segmentId, est -> est.getSegment().getMask() == 1 && est.isCaughtUp()); assertTrue(testSubject.mergeSegment(segmentId).join(), "Expected merge to succeed"); assertArrayEquals(new int[]{0}, tokenStore.fetchSegments(testSubject.getName())); assertWithin(3, TimeUnit.SECONDS, () -> assertEquals(40, handledEvents.size())); }
Source:
public void setWasVillager(boolean value) { villager = value; }

Target:
public void setWasVillager(boolean value) { getHolder().getData().put(VanillaData.WAS_VILLAGER, value); }
Source:
public void testCreateScalingPolicyFail() throws IOException, InterruptedException { MockWebServer server = mockOpenStackServer(); server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource("/access.json")))); server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(404).setBody(stringFromResource("/autoscale_policy_create_response.json")))); try { AutoscaleApi autoscaleApi = api(server.getUrl("/").toString(), "rackspace-autoscale", overrides); PolicyApi api = autoscaleApi.getPolicyApiForZoneAndGroup("DFW", "groupId1"); List<ScalingPolicy> scalingPolicies = Lists.newArrayList(); ScalingPolicy scalingPolicy = ScalingPolicy.builder() .cooldown(1800) .type(ScalingPolicyType.WEBHOOK) .name("scale up by one server") .targetType(ScalingPolicyTargetType.INCREMENTAL) .target("1") .build(); scalingPolicies.add(scalingPolicy); FluentIterable<ScalingPolicyResponse> scalingPolicyResponse = api.create(scalingPolicies); assertAuthentication(server); assertRequest(server.takeRequest(), "POST", "/v1.0/888888/groups/groupId1/policies", "/autoscale_policy_create_request.json"); assertTrue(scalingPolicyResponse.size() == 0); } finally { server.shutdown(); } }

Target:
public void testCreateScalingPolicyFail() throws IOException, InterruptedException { MockWebServer server = mockOpenStackServer(); server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource("/access.json")))); server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(404).setBody(stringFromResource("/autoscale_policy_create_response.json")))); try { AutoscaleApi autoscaleApi = api(server.getUrl("/").toString(), "rackspace-autoscale", overrides); PolicyApi api = autoscaleApi.getPolicyApiForZoneAndGroup("DFW", "groupId1"); List<ScalingPolicy> scalingPolicies = Lists.newArrayList(); ScalingPolicy scalingPolicy = ScalingPolicy.builder() .cooldown(1800) .type(ScalingPolicyType.WEBHOOK) .name("scale up by one server") .targetType(ScalingPolicyTargetType.INCREMENTAL) .target("1") .build(); scalingPolicies.add(scalingPolicy); FluentIterable<ScalingPolicyResponse> scalingPolicyResponse = api.create(scalingPolicies); assertAuthentication(server); assertRequest(server.takeRequest(), "POST", "/v1.0/888888/groups/groupId1/policies", "/autoscale_policy_create_request.json"); assertTrue(scalingPolicyResponse.isEmpty(), "Expected no policy response, but was: " + scalingPolicyResponse); } finally { server.shutdown(); } }
Source:
protected void multiInternal(MultiOperationRecord request, MultiCallback cb, Object ctx) throws IllegalArgumentException { RequestHeader h = new RequestHeader(); switch (request.getOpKind()) { case TRANSACTION: h.setType(ZooDefs.OpCode.multi); break; case READ: h.setType(ZooDefs.OpCode.multiRead); break; default: throw new IllegalArgumentException("Invalid kind of op"); } MultiResponse response = new MultiResponse(); cnxn.queuePacket(h, new ReplyHeader(), request, response, cb, null, null, ctx, null); }

Target:
protected void multiInternal(MultiOperationRecord request, MultiCallback cb, Object ctx) throws IllegalArgumentException { RequestHeader h = new RequestHeader(); switch (request.getOpKind()) { case TRANSACTION: h.setType(ZooDefs.OpCode.multi); break; case READ: h.setType(ZooDefs.OpCode.multiRead); break; default: throw new IllegalArgumentException("Unsupported OpKind: " + request.getOpKind()); } MultiResponse response = new MultiResponse(); cnxn.queuePacket(h, new ReplyHeader(), request, response, cb, null, null, ctx, null); }
Source:
public void testParseValidator() { String type = "parse"; Cli<?> parser = Cli.builder("validator") .withCommand(DruidJsonValidator.class) .build(); Object command = parser.parse( "validator", "-f", "simple_test_data_record_parser.json", "-r", "simple_test_data.tsv", "-t", type ); Assert.assertNotNull(command); DruidJsonValidator druidJsonValidator = (DruidJsonValidator) command; druidJsonValidator.run(); }

Target:
public void testParseValidator() { String type = "parse"; Cli<?> parser = Cli.builder("validator") .withCommand(DruidJsonValidator.class) .build(); Object command = parser.parse( "validator", "-f", "simple_test_data_record_parser.json", "-r", "simple_test_data.tsv", "-t", type ); Assert.assertNotNull(command); Writer writer = new StringWriter() { @Override public void write(String str) { super.write(str + '\n'); } }; DruidJsonValidator druidJsonValidator = (DruidJsonValidator) command; druidJsonValidator.setLogWriter(writer); druidJsonValidator.run(); String expected = "loading parse spec from resource 'simple_test_data_record_parser.json'\n" + "loading data from resource 'simple_test_data.tsv'\n" + "2014-10-20T00:00:00.000Z\tproduct_1\n"; Assert.assertEquals(expected, writer.toString()); }
Source:
static ServiceAccountCredentials fromJson( Map<String, Object> json, HttpTransportFactory transportFactory) throws IOException { String clientId = (String) json.get("client_id"); String clientEmail = (String) json.get("client_email"); String privateKeyPkcs8 = (String) json.get("private_key"); String privateKeyId = (String) json.get("private_key_id"); String projectId = (String) json.get("project_id"); String tokenServerUriStringFromCreds = (String) json.get("token_uri"); String quotaProject = (String) json.get("quota_project_id"); URI tokenServerUriFromCreds = null; try { if (tokenServerUriStringFromCreds != null) { tokenServerUriFromCreds = new URI(tokenServerUriStringFromCreds); } } catch (URISyntaxException e) { throw new IOException("Token server URI specified in 'token_uri' could not be parsed."); } if (clientId == null || clientEmail == null || privateKeyPkcs8 == null || privateKeyId == null) { throw new IOException( "Error reading service account credential from JSON, " + "expecting 'client_id', 'client_email', 'private_key' and 'private_key_id'."); } return fromPkcs8( clientId, clientEmail, privateKeyPkcs8, privateKeyId, null, transportFactory, tokenServerUriFromCreds, null, projectId, quotaProject); }

Target:
static ServiceAccountCredentials fromJson( Map<String, Object> json, HttpTransportFactory transportFactory) throws IOException { String clientId = (String) json.get("client_id"); String clientEmail = (String) json.get("client_email"); String privateKeyPkcs8 = (String) json.get("private_key"); String privateKeyId = (String) json.get("private_key_id"); String projectId = (String) json.get("project_id"); String tokenServerUriStringFromCreds = (String) json.get("token_uri"); String quotaProjectId = (String) json.get("quota_project_id"); URI tokenServerUriFromCreds = null; try { if (tokenServerUriStringFromCreds != null) { tokenServerUriFromCreds = new URI(tokenServerUriStringFromCreds); } } catch (URISyntaxException e) { throw new IOException("Token server URI specified in 'token_uri' could not be parsed."); } if (clientId == null || clientEmail == null || privateKeyPkcs8 == null || privateKeyId == null) { throw new IOException( "Error reading service account credential from JSON, " + "expecting 'client_id', 'client_email', 'private_key' and 'private_key_id'."); } return fromPkcs8( clientId, clientEmail, privateKeyPkcs8, privateKeyId, null, transportFactory, tokenServerUriFromCreds, null, projectId, quotaProjectId); }
Source:
public void onNegativeClicked(@NonNull String instanceTag) { switch (instanceTag) { case TAG_ADD_SITE_ICON_DIALOG: break; case TAG_CHANGE_SITE_ICON_DIALOG: AnalyticsTracker.track(Stat.MY_SITE_ICON_REMOVED); showSiteIconProgressBar(true); mSiteSettings.setSiteIconMediaId(0); mSiteSettings.saveSettings(); break; case TAG_QUICK_START_DIALOG: AnalyticsTracker.track(AnalyticsTracker.Stat.QUICK_START_REQUEST_NEGATIVE_TAPPED); break; default: AppLog.e(T.EDITOR, "Dialog instanceTag is not recognized"); throw new UnsupportedOperationException("Dialog instanceTag is not recognized"); } }

Target:
public void onNegativeClicked(@NonNull String instanceTag) { switch (instanceTag) { case TAG_ADD_SITE_ICON_DIALOG: break; case TAG_CHANGE_SITE_ICON_DIALOG: AnalyticsTracker.track(Stat.MY_SITE_ICON_REMOVED); showSiteIconProgressBar(true); mSiteSettings.setSiteIconMediaId(0); mSiteSettings.saveSettings(); break; case TAG_QUICK_START_DIALOG: AnalyticsTracker.track(Stat.QUICK_START_REQUEST_DIALOG_NEGATIVE_TAPPED); break; default: AppLog.e(T.EDITOR, "Dialog instanceTag is not recognized"); throw new UnsupportedOperationException("Dialog instanceTag is not recognized"); } }
Source:
public ReadRowsRequest getRequest() { if (request.get().getTableName().isEmpty()) { BigtableInstanceName bigtableInstanceName = new BigtableInstanceName(getProjectId(), getInstanceId()); String fullTableName = bigtableInstanceName.toTableNameStr(getTableId()); request = StaticValueProvider.of(request.get().toBuilder().setTableName(fullTableName).build()); } return request.get(); }

Target:
public ReadRowsRequest getRequest() { return request.get(); }
Source:
public Connection getConnection() { Connection conn = null; try { conn= DriverManager.getConnection(DB_URL, USER, PASSWORD); } catch (SQLException e) { e.printStackTrace(); } return conn; }

Target:
public Connection getConnection() throws SQLException { return DriverManager.getConnection(DB_URL, USER, PASSWORD); }
Source:
public static void configureFetchNotes(RemoteConfig remoteConfig) { String notesRef = Constants.R_NOTES + "*"; List<RefSpec> fetchRefSpecs = remoteConfig.getFetchRefSpecs(); for (RefSpec refSpec : fetchRefSpecs) { if (refSpec.matchSource(notesRef)) return; } remoteConfig.addFetchRefSpec(new RefSpec(notesRef + ":" + notesRef)); }

Target:
public static void configureFetchNotes(RemoteConfig remoteConfig) { String notesRef = Constants.R_NOTES + "*"; List<RefSpec> fetchRefSpecs = remoteConfig.getFetchRefSpecs(); for (RefSpec refSpec : fetchRefSpecs) { if (refSpec.matchSource(notesRef)) { return; } } remoteConfig.addFetchRefSpec(new RefSpec(notesRef + ":" + notesRef)); }
Source:
private void updateAddtionClusterFeatureList(Set<AdditionalClusterFeature> featuresAvailable, Set<AdditionalClusterFeature> featuresEnabled) { List<AdditionalClusterFeature> features = new ArrayList<>(); List<AdditionalClusterFeature> selectedFeatures = new ArrayList<>(); for (AdditionalClusterFeature feature : featuresAvailable) { features.add(feature); if (featuresEnabled.contains(feature)) { selectedFeatures.add(feature); } } List<List<AdditionalClusterFeature>> listOfFeatures = new ArrayList<>(); listOfFeatures.add(features); getAdditionalClusterFeatures().setItems(listOfFeatures, selectedFeatures); }

Target:
private void updateAddtionClusterFeatureList(Set<AdditionalClusterFeature> featuresAvailable, Set<AdditionalClusterFeature> featuresEnabled) { List<AdditionalClusterFeature> features = new ArrayList<>(); List<AdditionalClusterFeature> selectedFeatures = new ArrayList<>(); for (AdditionalClusterFeature feature : featuresAvailable) { features.add(feature); if (featuresEnabled.contains(feature)) { selectedFeatures.add(feature); } } List<List<AdditionalClusterFeature>> clusterFeatureList = new ArrayList<>(); clusterFeatureList.add(features); getAdditionalClusterFeatures().setItems(clusterFeatureList, selectedFeatures); }
Source:
public void setUp() throws Exception { mongoConfiguration = new MongoConfiguration(); mongoConnector = new MongoConnector(mongoConfiguration); mongoConnector.connect(); mongoConnector.getDB().dropDatabase(); mongoConnector = new MongoConnector(mongoConfiguration); mongoConnector.connect(); CoreConfiguration coreConfiguration = Main.getConfiguration(null); core = new Main(coreConfiguration); }

Target:
public void setUp() throws Exception { mongoConfiguration = new MongoConfiguration(); mongoConfiguration.setNamespace("hydra-test-FullScaleIT"); mongoConnector = new MongoConnector(mongoConfiguration); mongoConnector.connect(); mongoConnector.getDB().dropDatabase(); mongoConnector = new MongoConnector(mongoConfiguration); mongoConnector.connect(); CoreConfiguration coreConfiguration = new CoreMapConfiguration(mongoConfiguration, new MapConfiguration()); core = new Main(coreConfiguration); }
Source:
protected void actionPerformed(GuiButton button) throws IOException { super.actionPerformed(button); if(button == btnPrevRecipe) { container.nextSubRecipe(-1); } else if(button == btnNextRecipe) { container.nextSubRecipe(1); } else if(button == btnSortName) { container.setSortComparator(new ComparatorName()); } else if(button == btnSortHunger) { container.setSortComparator(new ComparatorHunger(Minecraft.getMinecraft().thePlayer)); } else if(button == btnSortSaturation) { container.setSortComparator(new ComparatorSaturation(Minecraft.getMinecraft().thePlayer)); } for (GuiButton sortButton : this.sortButtons) { if (sortButton instanceof GuiButtonSortCustom && button == sortButton) { container.setSortComparator(((GuiButtonSortCustom)sortButton).getComparator()); } } }

Target:
protected void actionPerformed(GuiButton button) throws IOException { super.actionPerformed(button); if(button == btnPrevRecipe) { container.nextSubRecipe(-1); } else if(button == btnNextRecipe) { container.nextSubRecipe(1); } for (GuiButton sortButton : this.sortButtons) { if (sortButton instanceof GuiButtonSort && button == sortButton) { container.setSortComparator(((GuiButtonSort)sortButton).getComparator(Minecraft.getMinecraft().thePlayer)); } } }