auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void addMaintenanceFailedReason(List<String> failedMessages) { Guid rootCommandGuid = commandsRepository.getCommandEntity(getCommandId()).getRootCommandId(); CommandBase<T> rootCommand = commandCoordinatorUtil.retrieveCommand(rootCommandGuid); String messageToDisplay = failedMessages.get(0); rootCommand.addCustomValue("Message", messageToDisplay); auditLogDirector.log(rootCommand, AuditLogType.VDS_MAINTENANCE_FAILED_REASON, messageToDisplay); }

Target:
private void addMaintenanceFailedReason(List<String> failedMessages) { Guid rootCommandGuid = commandsRepository.getCommandEntity(getCommandId()).getRootCommandId(); CommandBase<T> rootCommand = commandCoordinatorUtil.retrieveCommand(rootCommandGuid); String messageToDisplay = failedMessages.get(0); addCustomValue("Message", messageToDisplay); auditLogDirector.log(this, AuditLogType.VDS_MAINTENANCE_FAILED_REASON, messageToDisplay); }
Source:
private void initListBoxEditors() { dataCenterEditor = new ListModelListBoxEditor<StoragePool>(new NullSafeRenderer<StoragePool>() { @Override public String renderNullSafe(StoragePool object) { return object.getName(); } }); cpuEditor = new ListModelListBoxEditor<ServerCpu>(new NullSafeRenderer<ServerCpu>() { @Override public String renderNullSafe(ServerCpu object) { return object.getCpuName(); } }); versionEditor = new ListModelListBoxEditor<Version>(new NullSafeRenderer<Version>() { @Override public String renderNullSafe(Version object) { return object.toString(); } }); architectureEditor = new ListModelListBoxEditor<ArchitectureType>(new NullSafeRenderer<ArchitectureType>() { @Override public String renderNullSafe(ArchitectureType object) { return object.toString(); } }); clusterPolicyEditor = new ListModelListBoxEditor<ClusterPolicy>(new NullSafeRenderer<ClusterPolicy>() { @Override public String renderNullSafe(ClusterPolicy object) { return object.getName(); } }); architectureEditor.setVisible(ApplicationModeHelper.isModeSupported(ApplicationMode.VirtOnly)); }

Target:
private void initListBoxEditors() { dataCenterEditor = new ListModelListBoxEditor<StoragePool>(new NullSafeRenderer<StoragePool>() { @Override public String renderNullSafe(StoragePool object) { return object.getName(); } }); cpuEditor = new ListModelListBoxEditor<ServerCpu>(new NullSafeRenderer<ServerCpu>() { @Override public String renderNullSafe(ServerCpu object) { return object.getCpuName(); } }); versionEditor = new ListModelListBoxEditor<Version>(new NullSafeRenderer<Version>() { @Override public String renderNullSafe(Version object) { return object.toString(); } }); architectureEditor = new ListModelListBoxEditor<ArchitectureType>(new NullSafeRenderer<ArchitectureType>() { @Override public String renderNullSafe(ArchitectureType object) { return object.toString(); } }); clusterPolicyEditor = new ListModelListBoxEditor<ClusterPolicy>(new NullSafeRenderer<ClusterPolicy>() { @Override public String renderNullSafe(ClusterPolicy object) { return object.getName(); } }); }
Source:
protected Map<String, Pair<String, String>> getExclusiveLocks() { Map<String, Pair<String, String>> locks = new HashMap<String, Pair<String, String>>(); locks.put(getStorageDomain().getId().toString(), LockMessagesMatchUtil.STORAGE); locks.put(getParameters().getStorageServerConnection().getconnection(), LockMessagesMatchUtil.STORAGE_CONNECTION); locks.put(oldConnection.getconnection(), LockMessagesMatchUtil.STORAGE_CONNECTION); return locks; }

Target:
protected Map<String, Pair<String, String>> getExclusiveLocks() { Map<String, Pair<String, String>> locks = new HashMap<String, Pair<String, String>>(); domains = getStorageDomainsByConnId(getParameters().getStorageServerConnection().getid()); if(!domains.isEmpty() && domains.size() == 1) { setStorageDomain(domains.get(0)); locks.put(getStorageDomain().getId().toString(), LockMessagesMatchUtil.STORAGE); } locks.put(getParameters().getStorageServerConnection().getconnection(), LockMessagesMatchUtil.STORAGE_CONNECTION); return locks; }
Source:
private Comparable convert(AttributeType entryAttributeType, Comparable entryAttributeValue, Comparable givenAttributeValue) { Class<?> entryAttributeClass = entryAttributeValue != null ? entryAttributeValue.getClass() : null; if (entryAttributeType == AttributeType.ENUM) { return entryAttributeType.getConverter().convert(givenAttributeValue); } else { if (entryAttributeClass != null && entryAttributeClass.isAssignableFrom(givenAttributeValue.getClass())) { return givenAttributeValue; } else if (entryAttributeType != null) { return entryAttributeType.getConverter().convert(givenAttributeValue); } else { TypeConverter tc = inferTypeConverter(entryAttributeClass); if (tc != null) { return tc.convert(givenAttributeValue); } throw new QueryException("Unknown attribute type: " + givenAttributeValue.getClass().getName() + " for attribute: " + attributeName); } } }

Target:
private Comparable convert(AttributeType entryAttributeType, Comparable entryAttributeValue, Comparable givenAttributeValue) { Class<?> entryAttributeClass = entryAttributeValue != null ? entryAttributeValue.getClass() : null; if (entryAttributeType == AttributeType.ENUM) { return entryAttributeType.getConverter().convert(givenAttributeValue); } else { if (entryAttributeClass != null && entryAttributeClass.isAssignableFrom(givenAttributeValue.getClass())) { return givenAttributeValue; } else if (entryAttributeType != null) { return entryAttributeType.getConverter().convert(givenAttributeValue); } else { throw new QueryException("Unknown attribute type: " + givenAttributeValue.getClass().getName() + " for attribute: " + attributeName); } } }
Source:
protected AggregateStateRecord newStorageRecord() { List<AggregateEventRecord> records = sequenceFor(id); List<Event> expectedEvents = records.stream() .map(TO_EVENT) .collect(Collectors.toList()); AggregateStateRecord record = AggregateStateRecord .newBuilder() .addAllEvent(expectedEvents) .build(); return record; }

Target:
protected AggregateStateRecord newStorageRecord() { List<AggregateEventRecord> records = sequenceFor(id); List<Event> expectedEvents = records.stream() .map(TO_EVENT) .collect(toList()); AggregateStateRecord record = AggregateStateRecord .newBuilder() .addAllEvent(expectedEvents) .build(); return record; }
Source:
public boolean read() throws IOException { if (!hasReceive()) { createNetworkReceive(); metrics.transmissionRoundTripTime.update(time.milliseconds() - sendCompleteTime); } long startTimeMs = time.milliseconds(); long bytesRead = networkReceive.getReceivedBytes().readFrom(socketChannel); long readTimeMs = time.milliseconds() - startTimeMs; logger.trace("Bytes read " + bytesRead + " from using key Time: {}", socketChannel.socket().getRemoteSocketAddress(), getConnectionId(), readTimeMs); if (bytesRead > 0) { metrics.transmissionReceiveTime.update(readTimeMs); metrics.transmissionReceiveSize.update(bytesRead); } return networkReceive.getReceivedBytes().isReadComplete(); }

Target:
public boolean read() throws IOException { if (!hasReceive()) { initializeNetworkReceive(); metrics.transmissionRoundTripTime.update(time.milliseconds() - sendCompleteTime); } long startTimeMs = time.milliseconds(); long bytesRead = networkReceive.getReceivedBytes().readFrom(socketChannel); long readTimeMs = time.milliseconds() - startTimeMs; logger.trace("Bytes read " + bytesRead + " from using key Time: {}", socketChannel.socket().getRemoteSocketAddress(), getConnectionId(), readTimeMs); if (bytesRead > 0) { metrics.transmissionReceiveTime.update(readTimeMs); metrics.transmissionReceiveSize.update(bytesRead); } return networkReceive.getReceivedBytes().isReadComplete(); }
Source:
protected Map<String, GroupInfo> createGroupInfos() { HashMap<String, GroupInfo> groupInfos = new HashMap<>(); groupInfos.put("aggregate_report_max", createMaxGroupInfo()); LatencyValueSelector valueSelector = new LatencyValueSelector(false); StaticSeriesSelector seriesSelector = new StaticSeriesSelector(); String seriesName = String.format(PERCENTILE_FORMAT, Integer.valueOf(95)); seriesSelector.setSeriesName(seriesName); groupInfos.put(PERCENTILE_PROPERTY, createPercentileGroupInfo(PERCENTILE_PROPERTY, 95, seriesName,valueSelector,seriesSelector)); return groupInfos; }

Target:
protected Map<String, GroupInfo> createGroupInfos() { HashMap<String, GroupInfo> groupInfos = new HashMap<>(); groupInfos.put("aggregate_report_max", createMaxGroupInfo()); LatencyValueSelector valueSelector = new LatencyValueSelector(false); StaticSeriesSelector seriesSelector = new StaticSeriesSelector(); String seriesName = String.format(PERCENTILE_FORMAT, Integer.valueOf(95)); seriesSelector.setSeriesName(seriesName); groupInfos.put(PERCENTILE_PROPERTY, createPercentileGroupInfo(PERCENTILE_PROPERTY, seriesName,valueSelector,seriesSelector)); return groupInfos; }
Source:
public void checkHandlingOfFactoryNames() { createFactoryFromWorkspaceWithProject(FACTORY_NAME_EXIST); openNewFactoryPage(); createFactoryPage.clickOnWorkspaceFromList(PROJECT_WS_NAME); createFactoryPage.typeFactoryName(""); createFactoryPage.waitErrorMessageNotVisible(); assertTrue(createFactoryPage.isCreateFactoryButtonEnabled()); createFactoryPage.typeFactoryName(generate("", 2)); createFactoryPage.waitErrorMessage(TOO_SHORT_NAME_MESAAGE); assertFalse(createFactoryPage.isCreateFactoryButtonEnabled()); createFactoryPage.typeFactoryName(MIN_FACTORY_NAME); createFactoryPage.waitErrorMessageNotVisible(); assertTrue(createFactoryPage.isCreateFactoryButtonEnabled()); createFactoryPage.typeFactoryName(SPECIAL_SYMBOLS_NAME); createFactoryPage.waitErrorMessage(SPECIAL_SYMBOLS_ERROR_MESSAGE); assertFalse(createFactoryPage.isCreateFactoryButtonEnabled()); createFactoryPage.typeFactoryName(generate("", 21)); createFactoryPage.waitErrorMessage(TOO_LONG_NAME_MESSAGE); assertFalse(createFactoryPage.isCreateFactoryButtonEnabled()); createFactoryPage.typeFactoryName(MAX_FACTORY_NAME); createFactoryPage.waitErrorMessageNotVisible(); assertTrue(createFactoryPage.isCreateFactoryButtonEnabled()); createFactoryPage.typeFactoryName(FACTORY_NAME_EXIST); createFactoryPage.waitErrorMessage(EXIST_NAME_ERROR_MESSAGE); assertTrue(createFactoryPage.isCreateFactoryButtonEnabled()); }

Target:
public void checkHandlingOfFactoryNames() { createFactoryFromWorkspaceWithProject(FACTORY_NAME_EXIST); openNewFactoryPage(); createFactoryPage.clickOnWorkspaceFromList(PROJECT_WS_NAME); createFactoryPage.typeFactoryName(""); createFactoryPage.waitErrorMessageNotVisible(); assertTrue(createFactoryPage.isCreateFactoryButtonEnabled()); createFactoryPage.typeFactoryName(generate("", 2)); createFactoryPage.waitErrorMessage(TOO_SHORT_NAME_MESAAGE); assertFalse(createFactoryPage.isCreateFactoryButtonEnabled()); createFactoryPage.typeFactoryName(MIN_FACTORY_NAME); createFactoryPage.waitErrorMessageNotVisible(); assertTrue(createFactoryPage.isCreateFactoryButtonEnabled()); createFactoryPage.typeFactoryName(SPECIAL_SYMBOLS_NAME); createFactoryPage.waitErrorMessage(SPECIAL_SYMBOLS_ERROR_MESSAGE); assertFalse(createFactoryPage.isCreateFactoryButtonEnabled()); createFactoryPage.typeFactoryName(generate("", 21)); createFactoryPage.waitErrorMessage(TOO_LONG_NAME_MESSAGE); assertFalse(createFactoryPage.isCreateFactoryButtonEnabled()); createFactoryPage.typeFactoryName(MAX_FACTORY_NAME); createFactoryPage.waitErrorMessageNotVisible(); assertTrue(createFactoryPage.isCreateFactoryButtonEnabled()); createFactoryPage.typeFactoryName(FACTORY_NAME_EXIST); createFactoryPage.waitErrorMessage(EXIST_NAME_ERROR_MESSAGE); assertFalse(createFactoryPage.isCreateFactoryButtonEnabled()); }
Source:
public String toString() { StringBuilder builder = new StringBuilder(50); builder.append("search type: "); builder.append(getSearchTypeValue()); builder.append(", search pattern: ["); builder.append(getSearchPattern()); builder.append("], case sensitive? "); builder.append(getCaseSensitive()); builder.append(" [from: "); builder.append(getSearchFrom()); builder.append(", max: "); builder.append(getMaxCount()); builder.append("] "); builder.append(super.toString()); return builder.toString(); }

Target:
public String toString() { StringBuilder builder = new StringBuilder(50); builder.append("search type: "); builder.append(getSearchTypeValue()); builder.append(", search pattern: ["); builder.append(getSearchPattern()); builder.append("], case sensitive: "); builder.append(getCaseSensitive()); builder.append(" [from: "); builder.append(getSearchFrom()); builder.append(", max: "); builder.append(getMaxCount()); builder.append("] "); builder.append(super.toString()); return builder.toString(); }
Source:
public static boolean isChunkUpload(Map<String, Object> args) throws RestServiceException { return getHeader(args, Headers.CHUNK_UPLOAD_SESSION, false) != null; }

Target:
public static boolean isChunkUpload(Map<String, Object> args) throws RestServiceException { return getHeader(args, Headers.CHUNK_UPLOAD, false) != null; }
Source:
private Value(String string) { ValueType t = ValueType.STRING; double d = 0; long l = 0; Object o = string; try { d = l = Long.parseLong(string); o = l; t = ValueType.LONG; } catch (NumberFormatException e) { try { o = d = Double.parseDouble(string); t = ValueType.DOUBLE; } catch (NumberFormatException e2) { } } if (string.contains(",") && t == ValueType.STRING) { t = ValueType.LIST; String[] rawValues = string.split(","); List<Value> processedValues = new ArrayList<>(rawValues.length); for (String rawValue : rawValues) { processedValues.add(new Value(rawValue.trim())); } o = processedValues; } type = t; doubleValue = d; longValue = l; objectValue = o; }

Target:
private Value(String string) { ValueType t = ValueType.STRING; double d = 0; long l = 0; Object o = string; try { d = l = Long.parseLong(string); o = l; t = ValueType.LONG; } catch (NumberFormatException e) { try { o = d = Double.parseDouble(string); t = ValueType.DOUBLE; } catch (NumberFormatException e2) { } } type = t; doubleValue = d; longValue = l; objectValue = o; }
Source:
public void visitCallExpression(CallExpressionTree tree) { ExpressionTree callee = tree.callee(); if (callee.is(Tree.Kind.IDENTIFIER_REFERENCE)) { SyntaxToken token = ((IdentifierTree)callee).identifierToken(); if ("Function".equals(token.text()) && tree.arguments() != null && ! tree.arguments().parameters().isEmpty()) { addIssue(new PreciseIssue(this, new IssueLocation(callee, callee, MESSAGE))); } } super.visitCallExpression(tree); }

Target:
public void visitCallExpression(CallExpressionTree tree) { if (isNonEmptyFunctionConstructor(tree.callee(), tree.arguments())) { addIssue(tree.callee(), MESSAGE); } super.visitCallExpression(tree); }
Source:
public boolean prepare() throws Exception { if (!prepared) { prepared = true; super.prepare(); ProjectLauncher launcher = getProjectLauncher(); if (controlPort > 0) { launcher.getRunProperties() .put(TESTER_CONTROLPORT, "" + controlPort); if (host != null) launcher.getRunProperties() .put(TESTER_HOST, "" + host); } else if (port > 0) { launcher.getRunProperties() .put(TESTER_PORT, "" + port); if (host != null) launcher.getRunProperties() .put(TESTER_HOST, "" + host); } launcher.getRunProperties() .put(TESTER_UNRESOLVED, getProject().getProperty(Constants.TESTUNRESOLVED, "true")); launcher.getRunProperties() .put(TESTER_DIR, getReportDir().getAbsolutePath()); launcher.getRunProperties() .put(TESTER_CONTINUOUS, "" + getContinuous()); if (getProject().is(Constants.RUNTRACE)) launcher.getRunProperties() .put(TESTER_TRACE, "true"); Collection<String> testnames = getTests(); if (testnames.size() > 0) { launcher.getRunProperties() .put(TESTER_NAMES, Processor.join(testnames.stream() .map(ProjectTesterImpl::maybeQuote) .collect(Collectors.toList()))); } launcher.addRunBundle(me.getFile() .getAbsolutePath()); launcher.prepare(); } return true; }

Target:
public boolean prepare() throws Exception { if (!prepared) { prepared = true; super.prepare(); ProjectLauncher launcher = getProjectLauncher(); if (controlPort > 0) { launcher.getRunProperties() .put(TESTER_CONTROLPORT, "" + controlPort); if (host != null) launcher.getRunProperties() .put(TESTER_HOST, "" + host); } else if (port > 0) { launcher.getRunProperties() .put(TESTER_PORT, "" + port); if (host != null) launcher.getRunProperties() .put(TESTER_HOST, "" + host); } launcher.getRunProperties() .put(TESTER_UNRESOLVED, getProject().getProperty(Constants.TESTUNRESOLVED, "true")); launcher.getRunProperties() .put(TESTER_DIR, getReportDir().getAbsolutePath()); launcher.getRunProperties() .put(TESTER_CONTINUOUS, "" + getContinuous()); if (getProject().is(Constants.RUNTRACE)) launcher.getRunProperties() .put(TESTER_TRACE, "true"); Collection<String> testnames = getTests(); if (testnames.size() > 0) { launcher.getRunProperties() .put(TESTER_NAMES, testnames.stream() .map(ProjectTesterImpl::maybeQuote) .collect(Collectors.joining(","))); } launcher.addRunBundle(me.getFile() .getAbsolutePath()); launcher.prepare(); } return true; }
Source:
public <T> T toObject(ParameterizedTypeReference<T> type) { Assert.notNull(type, "Target type must not be null!"); final String url = traverseToFinalUrl(true); return operations.exchange(url, GET, prepareRequest(headers), type).getBody(); }

Target:
public <T> T toObject(ParameterizedTypeReference<T> type) { Assert.notNull(type, "Target type must not be null!"); return operations.exchange(traverseToFinalUrl(true), GET, prepareRequest(headers), type).getBody(); }
Source:
public synchronized MetricCollector init(HiveConf conf) { if (!isInited) { maxSize = MetastoreConf.getLongVar(conf, MetastoreConf.ConfVars.REPL_METRICS_CACHE_MAXSIZE); isInited = true; } return instance; }

Target:
public synchronized MetricCollector init(HiveConf conf) { if (!isInited) { maxSize = getMaxSize(conf); isInited = true; } return instance; }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mMapView = findViewById(R.id.mapView); ArcGISMap map = new ArcGISMap(Basemap.Type.STREETS, 48.354406, -99.998267, 2); mMapView.setMap(map); mButton = findViewById(R.id.applyRenderer); final ArcGISMapImageLayer imageLayer = new ArcGISMapImageLayer("<LINK_0>"); imageLayer.addDoneLoadingListener(new Runnable() { @Override public void run() { if(imageLayer.getLoadStatus() == LoadStatus.LOADED){ mMapView.setViewpointGeometryAsync(imageLayer.getFullExtent()); SublayerList sublayers = imageLayer.getSublayers(); countiesSublayer = (ArcGISMapImageSublayer) sublayers.get(2); } else { Toast.makeText(MainActivity.this,"ERROR:Layer did not load",Toast.LENGTH_LONG).show(); } } }); map.getOperationalLayers().add(imageLayer); final ClassBreaksRenderer classBreaksRenderer = createPopulationClassBreaksRenderer(); mButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { countiesSublayer.setRenderer(classBreaksRenderer) ; } }); }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mMapView = findViewById(R.id.mapView); ArcGISMap map = new ArcGISMap(Basemap.Type.STREETS, 48.354406, -99.998267, 2); mMapView.setMap(map); Button renderButton = findViewById(R.id.applyRenderer); final ArcGISMapImageLayer imageLayer = new ArcGISMapImageLayer(getString(R.string.census_map_server)); imageLayer.addDoneLoadingListener(() -> { if(imageLayer.getLoadStatus() == LoadStatus.LOADED){ mMapView.setViewpointGeometryAsync(imageLayer.getFullExtent()); SublayerList sublayers = imageLayer.getSublayers(); countiesSublayer = (ArcGISMapImageSublayer) sublayers.get(2); } else { Log.e(TAG,imageLayer.getLoadError().getMessage()); } }); map.getOperationalLayers().add(imageLayer); final ClassBreaksRenderer classBreaksRenderer = createPopulationClassBreaksRenderer(); renderButton.setOnClickListener(v -> countiesSublayer.setRenderer(classBreaksRenderer)); }
Source:
public static String convertXMLSourceToString(Source source) { StringWriter stringWriter = null; String xmlString; try { stringWriter = new StringWriter(); StreamResult xmlOutput = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setAttribute("indent-number", 4); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.transform(source, xmlOutput); xmlString = xmlOutput.getWriter().toString(); } catch (TransformerException e) { logger.error("Exception occurred while converting doc to string: ", e); throw new RuntimeException("Exception occurred while converting doc to string: ", e); } finally { if (stringWriter != null) { try { stringWriter.close(); } catch (IOException ignored) { } } } return xmlString; }

Target:
public static String convertXMLSourceToString(Source source) { try (StringWriter stringWriter = new StringWriter()) { StreamResult xmlOutput = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setAttribute("indent-number", 4); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.transform(source, xmlOutput); return xmlOutput.getWriter().toString(); } catch (TransformerException e) { logger.error("Exception occurred while converting doc to string: ", e); throw new RuntimeException("Exception occurred while converting doc to string: ", e); } catch (IOException e) { logger.error("Exception occurred while closing the StringWriter: ", e); throw new RuntimeException("Exception occurred while closing the StringWriter: ", e); } }
Source:
StringRepresentation getInstanceCurrentStatesRepresentation(String clusterName, String instanceName) throws JsonGenerationException, JsonMappingException, IOException { ZkClient zkClient = (ZkClient) getContext().getAttributes().get(RestAdminApplication.ZKCLIENT); ; String instanceSessionId = ClusterRepresentationUtil.getInstanceSessionId(zkClient, clusterName, instanceName); String message = ClusterRepresentationUtil .getMultiInstancePropertyNameListsAsString(zkClient, clusterName, instanceName, Arrays.asList(PropertyType.CURRENTSTATES, PropertyType.TASKCURRENTSTATES), instanceSessionId); StringRepresentation representation = new StringRepresentation(message, MediaType.APPLICATION_JSON); return representation; }

Target:
StringRepresentation getInstanceCurrentStatesRepresentation(String clusterName, String instanceName) throws JsonGenerationException, JsonMappingException, IOException { ZkClient zkClient = (ZkClient) getContext().getAttributes().get(RestAdminApplication.ZKCLIENT); ; String instanceSessionId = ClusterRepresentationUtil.getInstanceSessionId(zkClient, clusterName, instanceName); String message = ClusterRepresentationUtil .getInstancePropertyNameListAsString(zkClient, clusterName, instanceName, PropertyType.CURRENTSTATES, instanceSessionId, MediaType.APPLICATION_JSON); StringRepresentation representation = new StringRepresentation(message, MediaType.APPLICATION_JSON); return representation; }
Source:
public List<HueLamp> getLampsById(List<String> ids) { List<HueLamp> lamps = new ArrayList<>(); ids.forEach(id -> lamps.add(hueFacade.getAvailableLamps().get(id))); return lamps; }

Target:
public Set<HueLamp> getLampsById(List<String> ids) { return ids.stream() .map(id -> hueFacade.getAvailableLamps().get(id)) .collect(Collectors.toSet()); }
Source:
public static void main(String[] args) { TextAnalyticsApiKeyCredential credential = new TextAnalyticsApiKeyCredential("{api_key}"); TextAnalyticsAsyncClient client = new TextAnalyticsClientBuilder() .apiKey(credential) .endpoint("{endpoint}") .buildAsyncClient(); String text = "My cat might need to see a veterinarian."; client.extractKeyPhrases(text).subscribe( keyPhrase -> System.out.printf("Recognized phrases: %s.%n", keyPhrase), error -> System.err.println("There was an error extracting key phrases of the text." + error), () -> System.out.println("Key phrases extracted.")); credential.updateCredential("{valid_api_key}"); System.out.println("Recognized phrases:"); client.extractKeyPhrases(text).subscribe( keyPhrase -> System.out.printf("%s.%n", keyPhrase), error -> System.err.println("There was an error extracting key phrases of the text." + error), () -> System.out.println("Key phrases extracted.")); try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException ignored) { } }

Target:
public static void main(String[] args) { TextAnalyticsApiKeyCredential credential = new TextAnalyticsApiKeyCredential("{api_key}"); TextAnalyticsAsyncClient client = new TextAnalyticsClientBuilder() .apiKey(credential) .endpoint("{endpoint}") .buildAsyncClient(); String text = "My cat might need to see a veterinarian."; System.out.println("Extracted phrases:"); client.extractKeyPhrases(text).subscribe( keyPhrase -> System.out.printf("%s.%n", keyPhrase), error -> System.err.println("There was an error extracting key phrases of the text." + error), () -> System.out.println("Key phrases extracted.")); credential.updateCredential("{valid_api_key}"); System.out.println("Extracted phrases:"); client.extractKeyPhrases(text).subscribe( keyPhrase -> System.out.printf("%s.%n", keyPhrase), error -> System.err.println("There was an error extracting key phrases of the text." + error), () -> System.out.println("Key phrases extracted.")); try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException ignored) { } }
Source:
public static PhoenixExecutor createExecutor(Map<String, Object> jdbcProps) throws Exception { Util.validateJDBCProperties(jdbcProps, Lists.newArrayList("jdbcDriverClass", "jdbcUrl")); String driverClassName = (String) jdbcProps.get("jdbcDriverClass"); log.info("jdbc driver class: [{}]", driverClassName); Class.forName(driverClassName); String jdbcUrl = (String) jdbcProps.get("jdbcUrl"); log.info("jdbc url is: ", jdbcUrl); int queryTimeOutInSecs = -1; if(jdbcProps.containsKey("queryTimeoutInSecs")) { int timeout = (Integer) jdbcProps.get("queryTimeoutInSecs"); if(timeout < 0) { throw new IllegalArgumentException("queryTimeoutInSecs property can not be negative"); } } HikariConfig hikariConfig = new HikariConfig(); hikariConfig.setJdbcUrl(jdbcUrl); JdbcClient jdbcClient = new JdbcClient(jdbcUrl); log.info("creating tables"); String createPath = "phoenix/create_tables.sql"; jdbcClient.runScript(createPath); final HikariCPConnectionBuilder connectionBuilder = new HikariCPConnectionBuilder(hikariConfig); final ExecutionConfig executionConfig = new ExecutionConfig(queryTimeOutInSecs); CacheBuilder cacheBuilder = null; if(jdbcProps.containsKey("cacheSize")) { cacheBuilder = CacheBuilder.newBuilder().maximumSize((Integer)jdbcProps.get("cacheSize")); } return new PhoenixExecutor(executionConfig, connectionBuilder, cacheBuilder); }

Target:
public static PhoenixExecutor createExecutor(Map<String, Object> jdbcProps) throws Exception { Util.validateJDBCProperties(jdbcProps, Lists.newArrayList("jdbcDriverClass", "jdbcUrl")); String driverClassName = (String) jdbcProps.get("jdbcDriverClass"); log.info("jdbc driver class: [{}]", driverClassName); Class.forName(driverClassName); String jdbcUrl = (String) jdbcProps.get("jdbcUrl"); log.info("jdbc url is: ", jdbcUrl); int queryTimeOutInSecs = -1; if(jdbcProps.containsKey("queryTimeoutInSecs")) { queryTimeOutInSecs = (Integer) jdbcProps.get("queryTimeoutInSecs"); if(queryTimeOutInSecs < 0) { throw new IllegalArgumentException("queryTimeoutInSecs property can not be negative"); } } HikariConfig hikariConfig = new HikariConfig(); hikariConfig.setJdbcUrl(jdbcUrl); JdbcClient jdbcClient = new JdbcClient(jdbcUrl); log.info("creating tables"); String createPath = "phoenix/create_tables.sql"; jdbcClient.runScript(createPath); final HikariCPConnectionBuilder connectionBuilder = new HikariCPConnectionBuilder(hikariConfig); final ExecutionConfig executionConfig = new ExecutionConfig(queryTimeOutInSecs); CacheBuilder cacheBuilder = null; if(jdbcProps.containsKey("cacheSize")) { cacheBuilder = CacheBuilder.newBuilder().maximumSize((Integer)jdbcProps.get("cacheSize")); } return new PhoenixExecutor(executionConfig, connectionBuilder, cacheBuilder); }
Source:
public Map<String, List<String>> confusions() throws IOException { Map<String, List<String>> res = new HashMap<>(); for (CSVRecord record : parse(M2Resources.CONFUSIONS)) { String from = record.get("charFrom"); String to = record.get("charTo"); res.computeIfAbsent(from, x -> new ArrayList<>()).add(to); } return res; }

Target:
public Map<String, Collection<String>> confusions() throws IOException { Multimap<String, String> res = Multimaps.newListMultimap( new HashMap<>(), ArrayList::new); for (CSVRecord record : parse(M2Resources.CONFUSIONS)) { res.put(record.get("charFrom"), record.get("charTo")); } return Multimaps.asMap(res); }
Source:
public void testSetUnaryTestsWhenUnaryTestsIsNotNull() { final ItemDefinition wb = mock(ItemDefinition.class); ArgumentCaptor<UnaryTests> argument = ArgumentCaptor.forClass(UnaryTests.class); final org.kie.dmn.model.api.ItemDefinition dmn = mock(org.kie.dmn.model.api.ItemDefinition.class); final org.kie.dmn.model.api.UnaryTests dmnAllowedValues = mock(org.kie.dmn.model.api.UnaryTests.class); when(dmn.getAllowedValues()).thenReturn(dmnAllowedValues); setUnaryTests(wb, dmn); verify(wb).setAllowedValues(any(UnaryTests.class)); verify(wb).setAllowedValues(argument.capture()); assertEquals(wb, argument.getValue().getParent()); }

Target:
public void testSetUnaryTestsWhenUnaryTestsIsNotNull() { final ItemDefinition wb = mock(ItemDefinition.class); final ArgumentCaptor<UnaryTests> argument = ArgumentCaptor.forClass(UnaryTests.class); final org.kie.dmn.model.api.ItemDefinition dmn = mock(org.kie.dmn.model.api.ItemDefinition.class); final org.kie.dmn.model.api.UnaryTests dmnAllowedValues = mock(org.kie.dmn.model.api.UnaryTests.class); when(dmn.getAllowedValues()).thenReturn(dmnAllowedValues); setUnaryTests(wb, dmn); verify(wb).setAllowedValues(argument.capture()); assertEquals(wb, argument.getValue().getParent()); }
Source:
public void customerClassLoaderFunction() throws IOException { try { Path rootDir = fakeFileSystem(EXAMPLE_FUNCTION); URLClassLoader customerClassLoader = new CustomerClassLoader( rootDir.resolve("user/path").toString(), rootDir.resolve("opt/java").toString(), ClassLoader.getSystemClassLoader()); List<String> res = strip("file:" + rootDir.toString(), customerClassLoader.getURLs()); Assertions.assertEquals(Arrays.asList( "/user/path/", "/user/path/lib/4.jar", "/user/path/lib/A.jar", "/user/path/lib/a.jar", "/user/path/lib/b.jar", "/user/path/lib/z.jar", "/user/path/lib/λ.jar"), res); } catch(Throwable t) { if (!System.getProperty("sun.jnu.encoding").toLowerCase().contains("utf")){ Assertions.assertTrue(t.getMessage().contains("Malformed input or input contains unmappable characters")); } else { throw t; } } }

Target:
public void customerClassLoaderFunction() throws IOException { try { Path rootDir = fakeFileSystem(EXAMPLE_FUNCTION); URLClassLoader customerClassLoader = new CustomerClassLoader( rootDir.resolve("user/path").toString(), rootDir.resolve("opt/java").toString(), ClassLoader.getSystemClassLoader()); List<String> res = strip("file:" + rootDir.toString(), customerClassLoader.getURLs()); Assertions.assertEquals(Arrays.asList( "/user/path/", "/user/path/lib/4.jar", "/user/path/lib/A.jar", "/user/path/lib/a.jar", "/user/path/lib/b.jar", "/user/path/lib/z.jar", "/user/path/lib/λ.jar"), res); } catch(Throwable t) { String systemEncoding = System.getProperty("sun.jnu.encoding"); if (systemEncoding != null && !systemEncoding.toLowerCase().contains("utf")){ Assertions.assertTrue(t.getMessage().contains("Malformed input or input contains unmappable characters")); } else { throw t; } } }
Source:
public void shouldRespondWith422_whenEmailIsGreaterThan254Chars() { String payload = toJson( Map.of("amount", 100, "reference", "Some ref", "description", "hi", "return_url", "<LINK_0>", "email", "aVeryLongEaVeryLongEaVeryLongEaVeryLongEaVeryLongEaVeryLongEaVeryLongEaVeryLongEaVeryLongEaVeryLongEaVeryLongEaVeryLongEaVeryLongEaVeryLongEaVeryLongEaVeryLongEaVeryLongEaVeryLongEaVeryLongEaVeryLongE@aVeryLongEaVeryLongEaVeryLongEaVeryLongEaVeryLongEaVeryLongEaVeryLongEaVeryLongEaVeryLongEaVeryLongE.com")); postPaymentResponse(payload) .statusCode(422) .contentType(JSON) .body("size()", is(3)) .body("field", is("email")) .body("code", is("P0102")) .body("description", is("Invalid attribute value: email. Must be less than or equal to 254 characters length")); }

Target:
public void shouldRespondWith422_whenEmailIsGreaterThan254Chars() { String payload = toJson( Map.of("amount", 100, "reference", "Some ref", "description", "hi", "return_url", "<LINK_0>", "email", "aVeryLongEmail".repeat(20) + "@email.invalid")); postPaymentResponse(payload) .statusCode(422) .contentType(JSON) .body("size()", is(3)) .body("field", is("email")) .body("code", is("P0102")) .body("description", is("Invalid attribute value: email. Must be less than or equal to 254 characters length")); }
Source:
protected Result check() throws Exception { Result result; try (Handle handle = dbi.open()) { result = executorService.submit(new Callable<Result>() { @Override public Result call() throws Exception { handle.execute(validationQuery); return Result.healthy(); } }).get(duration.getQuantity(), duration.getUnit()); } catch (Exception e) { result = Result.unhealthy("Unable to successfully run validation query in %s", duration); } return result; }

Target:
protected Result check() throws Exception { return timeBoundHealthCheck.check(new Callable<Result>() { @Override public Result call() throws Exception { try (Handle handle = dbi.open()) { handle.execute(validationQuery); return Result.healthy(); } } }); }
Source:
public void sizeWhenReadingFilesystemThenIsCorrectNumberOfSchemaFiles() throws IOException { ClassPathResource resource = new ClassPathResource(this.schemaDocumentLocation); String[] schemas = resource.getFile().getParentFile().list((dir, name) -> name.endsWith(".xsd")); assertThat(schemas.length).isEqualTo(14) .withFailMessage("the count is equal to 12, if not then schemaDocument needs updating"); }

Target:
public void sizeWhenReadingFilesystemThenIsCorrectNumberOfSchemaFiles() throws IOException { ClassPathResource resource = new ClassPathResource(this.schemaDocumentLocation); String[] schemas = resource.getFile().getParentFile().list((dir, name) -> name.endsWith(".xsd")); assertThat(schemas.length).isEqualTo(14) .withFailMessage("the count is equal to 14, if not then schemaDocument needs updating"); }
Source:
public String title() { return "Upload Dashboards"; }

Target:
public String title() { return i18n.uploadDashboardsTitle(); }
Source:
public String printInvocations(Object mock) { Collection<Invocation> invocations = Mockito.mockingDetails(mock).getInvocations(); Collection<Stubbing> stubbings = Mockito.mockingDetails(mock).getStubbings(); if (invocations.isEmpty() && stubbings.isEmpty()) { return "No interactions and stubbings found for mock: " + mock; } String out = ""; int x = 1; for(Invocation i:invocations) { if (x == 1) { out += line("[Mockito] Interactions of: " + mock); } out += line(" " + x++ + ". " + i.toString()); out += line(" " + i.getLocation()); if (i.stubInfo() != null) { out += line(" - stubbed " + i.stubInfo().stubbedAt()); } } LinkedList<Stubbing> unused = ListUtil.filter(stubbings, new ListUtil.Filter<Stubbing>() { public boolean isOut(Stubbing s) { return s.wasUsed(); } }); if (unused.isEmpty()) { return out; } out += line("[Mockito] Unused stubbings of: " + mock); x = 1; for(Stubbing s:stubbings) { out += line(" " + x++ + ". " + s.getInvocation().toString()); out += line(" - stubbed " + s.getInvocation().getLocation()); } return out; }

Target:
public String printInvocations(Object mock) { Collection<Invocation> invocations = Mockito.mockingDetails(mock).getInvocations(); Collection<Stubbing> stubbings = Mockito.mockingDetails(mock).getStubbings(); if (invocations.isEmpty() && stubbings.isEmpty()) { return "No interactions and stubbings found for mock: " + mock; } StringBuilder sb = new StringBuilder(); int x = 1; for(Invocation i:invocations) { if (x == 1) { sb.append("[Mockito] Interactions of: ").append(mock).append("\n"); } sb.append(" ").append(x++).append(". ").append(i.toString()).append("\n"); sb.append(" ").append(i.getLocation()).append("\n"); if (i.stubInfo() != null) { sb.append(" - stubbed ").append(i.stubInfo().stubbedAt()).append("\n"); } } LinkedList<Stubbing> unused = ListUtil.filter(stubbings, new ListUtil.Filter<Stubbing>() { public boolean isOut(Stubbing s) { return s.wasUsed(); } }); if (unused.isEmpty()) { return sb.toString(); } sb.append("[Mockito] Unused stubbings of: " + mock).append("\n"); x = 1; for(Stubbing s:stubbings) { sb.append(" ").append(x++).append(". ").append(s.getInvocation()).append("\n"); sb.append(" - stubbed ").append(s.getInvocation().getLocation()).append("\n"); } return sb.toString(); }
Source:
public static void main(String[] args) { Traverson traverson = new Traverson(URI.create("http://localhost:8080"), MediaTypes.HAL_JSON); Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("location", "40.740337,-73.995146"); parameters.put("distance", "0.5miles"); PagedResources<Resource<Store>> resources = traverson. follow("stores", "search", "by-location"). withTemplateParameters(parameters). toObject(TYPE_REFERENCE); PageMetadata metadata = resources.getMetadata(); System.out.println(String.format("Got %s of %s stores: ", resources.getContent().size(), metadata.getTotalElements())); for (Resource<Store> resource : resources) { Store store = resource.getContent(); System.out.println(String.format("- %s - %s", store.name, store.address)); } }

Target:
public static void main(String[] args) { Traverson traverson = new Traverson(URI.create("http://localhost:8080"), MediaTypes.HAL_JSON); Map<String, Object> parameters = new HashMap<>(); parameters.put("location", "40.740337,-73.995146"); parameters.put("distance", "0.5miles"); PagedResources<Resource<Store>> resources = traverson. follow("stores", "search", "by-location"). withTemplateParameters(parameters). toObject(TYPE_REFERENCE); PageMetadata metadata = resources.getMetadata(); System.out.println(String.format("Got %s of %s stores: ", resources.getContent().size(), metadata.getTotalElements())); for (Resource<Store> resource : resources) { Store store = resource.getContent(); System.out.println(String.format("- %s - %s", store.name, store.address)); } }
Source:
public void testOutofElection() { HashMap<Long,Vote> outofelection = new HashMap<Long,Vote>(); outofelection.put(1L, new Vote(0x0, 5, ZxidUtils.makeZxid(15, 0), 0xa, 0x17, ServerState.FOLLOWING)); outofelection.put(2L, new Vote(0x0, 5, ZxidUtils.makeZxid(15, 0), 0xa, 0x17, ServerState.FOLLOWING)); outofelection.put(4L, new Vote(0x1, 5, ZxidUtils.makeZxid(15, 0), 0xa, 0x18, ServerState.FOLLOWING)); Vote vote = new Vote(0x1, 5, ZxidUtils.makeZxid(15, 0), 0xa, 0x18, ServerState.LEADING); outofelection.put(5L, vote); Notification n = new Notification(); n.version = vote.getVersion(); n.leader = vote.getId(); n.zxid = vote.getZxid(); n.electionEpoch = vote.getElectionEpoch(); n.state = vote.getState(); n.peerEpoch = vote.getPeerEpoch(); n.sid = 5L; fle.logicalclock.set(0x1); Assert.assertTrue("Termination predicate failed", fle.getVoteTracker(outofelection, new Vote(n.version, n.leader, n.zxid, n.electionEpoch, n.peerEpoch, n.state)).hasAllQuorums()); Assert.assertTrue("Leader check failed", fle.checkLeader(outofelection, n.leader, n.electionEpoch)); }

Target:
public void testOutofElection() { HashMap<Long,Vote> outofelection = new HashMap<Long,Vote>(); outofelection.put(1L, new Vote(0x0, 5, ZxidUtils.makeZxid(15, 0), 0xa, 0x17, ServerState.FOLLOWING)); outofelection.put(2L, new Vote(0x0, 5, ZxidUtils.makeZxid(15, 0), 0xa, 0x17, ServerState.FOLLOWING)); outofelection.put(4L, new Vote(0x1, 5, ZxidUtils.makeZxid(15, 0), 0xa, 0x18, ServerState.FOLLOWING)); Vote vote = new Vote(0x1, 5, ZxidUtils.makeZxid(15, 0), 0xa, 0x18, ServerState.LEADING); outofelection.put(5L, vote); Notification n = new Notification(); n.version = vote.getVersion(); n.leader = vote.getId(); n.zxid = vote.getZxid(); n.electionEpoch = vote.getElectionEpoch(); n.state = vote.getState(); n.peerEpoch = vote.getPeerEpoch(); n.sid = 5L; fle.logicalclock.set(0x1); Assert.assertTrue("Quorum check failed", fle.getVoteTracker(outofelection, new Vote(n.version, n.leader, n.zxid, n.electionEpoch, n.peerEpoch, n.state)).hasAllQuorums()); Assert.assertTrue("Leader check failed", fle.checkLeader(outofelection, n.leader, n.electionEpoch)); }
Source:
public <T, K extends Exception> T applyWithPermit(FunctionCheckedException<F, T, K> function) throws K { if (localThreadPool.tryAcquire()) { return applyAndRelease(localThreadPool, function); } if (sharedThreadPool.tryAcquire()) { return applyAndRelease(sharedThreadPool, function); } throw new TooManyRequestsException("ThreadPooledLockService was unable to acquire a permit to assign a server " + "thread to the request."); }

Target:
public <T, K extends Exception> T applyWithPermit(FunctionCheckedException<F, T, K> function) throws K { if (localThreadPool.tryAcquire()) { return applyAndRelease(localThreadPool, function); } if (sharedThreadPool.tryAcquire()) { return applyAndRelease(sharedThreadPool, function); } throw new TooManyRequestsException( "ThreadPooledLockService was unable to acquire a permit to assign a server thread to the request."); }
Source:
public Object get(WebRequest request) { boolean authenticated = Context.isAuthenticated(); SimpleObject session = new SimpleObject(); session.add("sessionId", request.getSessionId()).add("authenticated", authenticated); if (authenticated) { User user = Context.getAuthenticatedUser(); String rep = request.getParameter(RestConstants.REQUEST_PROPERTY_FOR_REPRESENTATION); if(null == rep || RestConstants.REPRESENTATION_DEFAULT.equals(rep)){ SimpleObject authenticatedUser = new SimpleObject(); authenticatedUser.add("uuid", user.getUuid()).add("display", StringUtils.isNotEmpty(user.getUsername()) ? user.getUsername() : user.getSystemId()); session.add("user", authenticatedUser); } else if(RestConstants.REPRESENTATION_FULL.equals(rep)){ SimpleObject authenticatedUser = (SimpleObject)ConversionUtil.convertToRepresentation(user, Representation.DEFAULT, UserConverter1_8.class); session.add("user", authenticatedUser); } } return session; }

Target:
public Object get(WebRequest request) { boolean authenticated = Context.isAuthenticated(); SimpleObject session = new SimpleObject(); session.add("sessionId", request.getSessionId()).add("authenticated", authenticated); if (authenticated) { String repParam = request.getParameter(RestConstants.REQUEST_PROPERTY_FOR_REPRESENTATION); Representation rep = (repParam != null) ? restService.getRepresentation(repParam) : Representation.DEFAULT; session.add("user",ConversionUtil.convertToRepresentation(Context.getAuthenticatedUser(), rep)); } return session; }
Source:
public void testSnapshotSyncStreamImplementation() throws Exception { initLogReplicationFSM(ReaderImplementation.STREAMS); writeToMap(); transitionAvailable.acquire(); fsm.input(new LogReplicationEvent(LogReplicationEventType.SNAPSHOT_SYNC_REQUEST)); System.out.println("**** Wait for snapshot sync to complete"); Queue<LogReplicationEntry> listenerQueue = ((TestDataSender) dataSender).getEntryQueue(); while (listenerQueue.size() < LARGE_NUM_ENTRIES/StreamsSnapshotReader.MAX_NUM_SMR_ENTRY) { sleep(WAIT_TIME); System.out.print("\nqueueSize " + listenerQueue.size() + "\n"); } System.out.print("\nqueueSize " + listenerQueue.size() + "\n"); assertThat(LARGE_NUM_ENTRIES/StreamsSnapshotReader.MAX_NUM_SMR_ENTRY).isLessThanOrEqualTo(listenerQueue.size()); writeTxIncrementalUpdates(); int incrementalUpdates = 0; while(incrementalUpdates < NUM_ENTRIES) { ((TestDataSender)dataSender).getEntryQueue().poll(); incrementalUpdates++; } assertThat(incrementalUpdates).isEqualTo(NUM_ENTRIES); }

Target:
public void testSnapshotSyncStreamImplementation() throws Exception { initLogReplicationFSM(ReaderImplementation.STREAMS); writeToMap(); transitionAvailable.acquire(); transition(LogReplicationEventType.SNAPSHOT_SYNC_REQUEST, LogReplicationStateType.IN_SNAPSHOT_SYNC, true); log.info("**** Wait for snapshot sync to complete"); Queue<LogReplicationEntry> listenerQueue = ((TestDataSender) dataSender).getEntryQueue(); while (listenerQueue.size() < LARGE_NUM_ENTRIES/StreamsSnapshotReader.MAX_NUM_SMR_ENTRY) { sleep(WAIT_TIME); } log.info("queueSize ", listenerQueue.size()); assertThat(LARGE_NUM_ENTRIES/StreamsSnapshotReader.MAX_NUM_SMR_ENTRY).isLessThanOrEqualTo(listenerQueue.size()); writeTxIncrementalUpdates(); int incrementalUpdates = 0; while(incrementalUpdates < NUM_ENTRIES) { ((TestDataSender)dataSender).getEntryQueue().poll(); incrementalUpdates++; } assertThat(incrementalUpdates).isEqualTo(NUM_ENTRIES); }
Source:
public synchronized RegisteredService save(final RegisteredService registeredService, final boolean publishEvent) { publishEvent(new CasRegisteredServicePreSaveEvent(this, registeredService)); var r = this.serviceRegistry.save(registeredService); this.services.put(r.getId(), r); saveInternal(registeredService); if (publishEvent) { publishEvent(new CasRegisteredServiceSavedEvent(this, r)); } return r; }

Target:
public synchronized RegisteredService save(final RegisteredService registeredService, final boolean publishEvent) { publishEvent(new CasRegisteredServicePreSaveEvent(this, registeredService)); val r = this.serviceRegistry.save(registeredService); this.services.put(r.getId(), r); saveInternal(registeredService); if (publishEvent) { publishEvent(new CasRegisteredServiceSavedEvent(this, r)); } return r; }
Source:
public void getConnection(ProxyTarget target, HttpServerExchange exchange, final ProxyCallback<ProxyConnection> callback, long timeout, TimeUnit timeUnit) { String containerId = containerResolver.resolveContainerId(exchange, configuration.getContainerInfosPerContainer()); LoadBalancingProxyClient client = containerClients.get(containerId); try { client.getConnection(target, exchange, new ProxyCallback<ProxyConnection>() { @Override public void completed(HttpServerExchange exchange, ProxyConnection result) { callback.completed(exchange, result); } @Override public void failed(HttpServerExchange httpServerExchange) { try { adminHandler.removeUnavailableServer(((CaptureHostLoadBalancingProxyClient) client).getUri()); } finally { callback.failed(exchange); ((CaptureHostLoadBalancingProxyClient) client).clear(); } } @Override public void couldNotResolveBackend(HttpServerExchange exchange) { callback.couldNotResolveBackend(exchange); } @Override public void queuedRequestFailed(HttpServerExchange exchange) { callback.queuedRequestFailed(exchange); } }, timeout, timeUnit); } catch (Exception e) { if (e instanceof SocketException || e instanceof UnknownHostException || e instanceof UnresolvedAddressException ) { adminHandler.removeUnavailableServer(((CaptureHostLoadBalancingProxyClient) client).getUri()); } throw new RuntimeException(e); } }

Target:
public void getConnection(ProxyTarget target, HttpServerExchange exchange, final ProxyCallback<ProxyConnection> callback, long timeout, TimeUnit timeUnit) { String containerId = containerResolver.resolveContainerId(exchange, configuration.getContainerInfosPerContainer()); CaptureHostLoadBalancingProxyClient client = containerClients.get(containerId); try { client.getConnection(target, exchange, new ProxyCallback<ProxyConnection>() { @Override public void completed(HttpServerExchange exchange, ProxyConnection result) { callback.completed(exchange, result); } @Override public void failed(HttpServerExchange httpServerExchange) { try { adminHandler.removeUnavailableServer(client.getUri()); } finally { callback.failed(exchange); client.clear(); } } @Override public void couldNotResolveBackend(HttpServerExchange exchange) { callback.couldNotResolveBackend(exchange); } @Override public void queuedRequestFailed(HttpServerExchange exchange) { callback.queuedRequestFailed(exchange); } }, timeout, timeUnit); } catch (Exception e) { if (e instanceof SocketException || e instanceof UnknownHostException || e instanceof UnresolvedAddressException ) { adminHandler.removeUnavailableServer(client.getUri()); } throw new RuntimeException(e); } }