auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static void fhirStoreExecuteBundle(String fhirStoreName, String data) throws IOException, URISyntaxException { CloudHealthcare client = createClient(); HttpClient httpClient = HttpClients.createDefault(); String baseUri = String.format("%sv1beta1/%s/fhir", client.getRootUrl(), fhirStoreName); URIBuilder uriBuilder = new URIBuilder(baseUri) .setParameter("access_token", getAccessToken()); StringEntity requestEntity = new StringEntity(data); HttpUriRequest request = RequestBuilder .post() .setUri(uriBuilder.build()) .setEntity(requestEntity) .addHeader("Content-Type", "application/fhir+json") .addHeader("Accept-Charset", "utf-8") .addHeader("Accept", "application/fhir+json; charset=utf-8") .build(); HttpResponse response = httpClient.execute(request); HttpEntity responseEntity = response.getEntity(); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { System.err.print(String.format( "Exception executing FHIR bundle: %s\n", response.getStatusLine().toString())); responseEntity.writeTo(System.err); throw new RuntimeException(); } System.out.print("FHIR bundle executed: "); responseEntity.writeTo(System.out); }

Target:
public static void fhirStoreExecuteBundle(String fhirStoreName, String data) throws IOException, URISyntaxException { CloudHealthcare client = createClient(); HttpClient httpClient = HttpClients.createDefault(); String baseUri = String.format("%sv1/%s/fhir", client.getRootUrl(), fhirStoreName); URIBuilder uriBuilder = new URIBuilder(baseUri) .setParameter("access_token", getAccessToken()); StringEntity requestEntity = new StringEntity(data); HttpUriRequest request = RequestBuilder .post() .setUri(uriBuilder.build()) .setEntity(requestEntity) .addHeader("Content-Type", "application/fhir+json") .addHeader("Accept-Charset", "utf-8") .addHeader("Accept", "application/fhir+json; charset=utf-8") .build(); HttpResponse response = httpClient.execute(request); HttpEntity responseEntity = response.getEntity(); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { System.err.print(String.format( "Exception executing FHIR bundle: %s\n", response.getStatusLine().toString())); responseEntity.writeTo(System.err); throw new RuntimeException(); } System.out.print("FHIR bundle executed: "); responseEntity.writeTo(System.out); }
Source:
public void write(DataOutput output) throws IOException { super.write(output); output.writeInt(vertexMap.size()); for (Map.Entry<I, byte[]> entry : vertexMap.entrySet()) { progress(); entry.getKey().write(output); int vertexDataSize = UnsafeByteArrayInputStream.getInt(entry.getValue(), 0); output.writeInt(vertexDataSize); output.write(entry.getValue(), 0, vertexDataSize); } }

Target:
public void write(DataOutput output) throws IOException { super.write(output); output.writeInt(vertexMap.size()); for (Map.Entry<I, byte[]> entry : vertexMap.entrySet()) { progress(); entry.getKey().write(output); int vertexDataSize; if (useUnsafeSerialization) { vertexDataSize = UnsafeByteArrayInputStream.getInt(entry.getValue(), 0); } else { vertexDataSize = Ints.fromByteArray(entry.getValue()); } output.writeInt(vertexDataSize); output.write(entry.getValue(), 0, vertexDataSize); } }
Source:
private void startListeningTCP() { new Thread(() -> { DataInputStream input = null; try { input = new DataInputStream(tcpSocket.getInputStream()); while (isActive) { byte[] buf = new byte[512]; input.read(buf); receiveTCP(buf); } } catch (IOException e) { e.printStackTrace(); } }).start(); }

Target:
private void startListeningTCP() { new Thread(() -> { DataInputStream input = null; try { input = new DataInputStream(tcpSocket.getInputStream()); while (isActive) { byte[] buf = new byte[512]; input.read(buf); if (buf.length == 0) { break; } receiveTCP(buf); } } catch (IOException e) { e.printStackTrace(); } }).start(); }
Source:
private void recreatePK(StatementExecutor executor, String tableName, PrimaryKey pk) throws OrmException { try { if (pk.oldNameInDb == null) { ui.message("WARN: primary key for table %s didn't exist ... ", tableName); } else { if (dialect instanceof DialectPostgreSQL) { executor.execute("ALTER TABLE " + tableName + " DROP CONSTRAINT " + pk.oldNameInDb); } else { executor.execute("ALTER TABLE " + tableName + " DROP PRIMARY KEY"); } } } catch (OrmException ignore) { ui.message("WARN: %s\n", ignore.getMessage()); } executor.execute("ALTER TABLE " + tableName + " ADD PRIMARY KEY(" + Joiner.on(",").join(pk.cols) + ")"); }

Target:
private void recreatePK(StatementExecutor executor, String tableName, PrimaryKey pk) throws OrmException { if (pk.oldNameInDb == null) { ui.message("WARN: primary key for table %s didn't exist ... ", tableName); } else { if (dialect instanceof DialectPostgreSQL) { executor.execute("ALTER TABLE " + tableName + " DROP CONSTRAINT " + pk.oldNameInDb); } else { executor.execute("ALTER TABLE " + tableName + " DROP PRIMARY KEY"); } } executor.execute("ALTER TABLE " + tableName + " ADD PRIMARY KEY(" + Joiner.on(",").join(pk.cols) + ")"); }
Source:
public TopologyDetails simScheduleNextHighest() { TopologyDetails td = tds.pop(); assignedCpu += td.getTotalRequestedCpu(); assignedMemory += td.getTotalRequestedMemOffHeap() + td.getTotalRequestedMemOnHeap(); Map<String, Double> tdRequestedGenericResource = td.getTotalRequestedGenericResources(); for (Map.Entry<String, Double> entry : tdRequestedGenericResource.entrySet()) { String resource = entry.getKey(); Double requestedAmount = entry.getValue(); assignedGenericResources.put(resource, assignedGenericResources.getOrDefault(resource, 0.0) + requestedAmount); } return td; }

Target:
public TopologyDetails simScheduleNextHighest() { TopologyDetails td = super.simScheduleNextHighest(); Map<String, Double> tdRequestedGenericResource = td.getTotalRequestedGenericResources(); for (Map.Entry<String, Double> entry : tdRequestedGenericResource.entrySet()) { String resource = entry.getKey(); Double requestedAmount = entry.getValue(); assignedGenericResources.put(resource, assignedGenericResources.getOrDefault(resource, 0.0) + requestedAmount); } return td; }
Source:
public static CompositeName toCompositeName(final Name name) throws InvalidNameException { if (name instanceof CompositeName) { return (CompositeName) name; } else { final CompositeName compositeName = new CompositeName(); compositeName.addAll(new CompositeName(name.toString())); return compositeName; } }

Target:
public static CompositeName toCompositeName(final Name name) throws InvalidNameException { if (name instanceof CompositeName) { return (CompositeName) name; } else { final CompositeName compositeName = new CompositeName(); compositeName.add(name.toString()); return compositeName; } }
Source:
public File getEmbeddingDirectory() { return new File(getReportDirectory().getAbsolutePath(), ReportBuilder.BASE_DIRECTORY + this.getDirectoryQualifier() + File.separatorChar + Configuration.EMBEDDINGS_DIRECTORY); }

Target:
public File getEmbeddingDirectory() { return new File(getReportDirectory().getAbsolutePath(), ReportBuilder.BASE_DIRECTORY + this.getDirectorySuffixWithSeparator() + File.separatorChar + Configuration.EMBEDDINGS_DIRECTORY); }
Source:
public Integer addSeries( AddSeriesDto dto, AddParticipantDto sellerDto, AddSeriesSalesDto saleDto, Integer requestId, Integer userId) { Integer seriesId = seriesService.add(dto, userId, false); if (saleDto != null) { if (saleDto.getSellerId() == null && sellerDto != null) { Integer sellerId = participantService.add(sellerDto); saleDto.setSellerId(sellerId); } seriesSalesService.add(saleDto, seriesId, userId); } Date now = new Date(); seriesImportDao.setSeriesIdAndChangeStatus( seriesId, new UpdateImportRequestStatusDbDto( requestId, now, SeriesImportRequestStatus.PARSING_SUCCEEDED, SeriesImportRequestStatus.IMPORT_SUCCEEDED) ); return seriesId; }

Target:
public Integer addSeries( AddSeriesDto dto, AddParticipantDto sellerDto, AddSeriesSalesDto saleDto, Integer requestId, Integer userId) { Integer seriesId = seriesService.add(dto, userId, false); if (saleDto != null) { if (saleDto.getSellerId() == null && sellerDto != null) { Integer sellerId = participantService.add(sellerDto); saleDto.setSellerId(sellerId); } seriesSalesService.add(saleDto, seriesId, userId); } Date now = new Date(); UpdateImportRequestStatusDbDto status = new UpdateImportRequestStatusDbDto( requestId, now, SeriesImportRequestStatus.PARSING_SUCCEEDED, SeriesImportRequestStatus.IMPORT_SUCCEEDED ); seriesImportDao.setSeriesIdAndChangeStatus(seriesId, status); return seriesId; }
Source:
public Response updateDefaultContributorRole( @PathParam("identifier") String dvIdtf, @PathParam("roleAlias") String roleAlias) { DataverseRole defaultRole; if (roleAlias.equals("none")) { defaultRole = null; } else { try { Dataverse dv = findDataverseOrDie(dvIdtf); defaultRole = roleService.findCustomRoleByAliasAndOwner(roleAlias, dv.getId()); } catch (Exception nre) { List<String> args = Arrays.asList(roleAlias); String retStringError = BundleUtil.getStringFromBundle("dataverses.api.update.default.contributor.role.failure.role.not.found", args); return error(Status.NOT_FOUND, retStringError); } if (!defaultRole.doesDvObjectClassHavePermissionForObject(Dataset.class)) { List<String> args = Arrays.asList(roleAlias); String retStringError = BundleUtil.getStringFromBundle("dataverses.api.update.default.contributor.role.failure.role.does.not.have.dataset.permissions", args); return error(Status.BAD_REQUEST, retStringError); } } try { Dataverse dv = findDataverseOrDie(dvIdtf); String defaultRoleName = defaultRole == null ? "None" : defaultRole.getName(); return response(req -> { execCommand(new UpdateDataverseDefaultContributorRoleCommand(defaultRole, req, dv)); List<String> args = Arrays.asList(dv.getDisplayName(), defaultRoleName); String retString = BundleUtil.getStringFromBundle("dataverses.api.update.default.contributor.role.success", args); return ok(retString); }); } catch (WrappedResponse wr) { return wr.getResponse(); } }

Target:
public Response updateDefaultContributorRole( @PathParam("identifier") String dvIdtf, @PathParam("roleAlias") String roleAlias) { DataverseRole defaultRole; if (roleAlias.equals(DataverseRole.NONE)) { defaultRole = null; } else { try { Dataverse dv = findDataverseOrDie(dvIdtf); defaultRole = rolesSvc.findCustomRoleByAliasAndOwner(roleAlias, dv.getId()); } catch (Exception nre) { List<String> args = Arrays.asList(roleAlias); String retStringError = BundleUtil.getStringFromBundle("dataverses.api.update.default.contributor.role.failure.role.not.found", args); return error(Status.NOT_FOUND, retStringError); } if (!defaultRole.doesDvObjectClassHavePermissionForObject(Dataset.class)) { List<String> args = Arrays.asList(roleAlias); String retStringError = BundleUtil.getStringFromBundle("dataverses.api.update.default.contributor.role.failure.role.does.not.have.dataset.permissions", args); return error(Status.BAD_REQUEST, retStringError); } } try { Dataverse dv = findDataverseOrDie(dvIdtf); String defaultRoleName = defaultRole == null ? BundleUtil.getStringFromBundle("permission.default.contributor.role.none.name") : defaultRole.getName(); return response(req -> { execCommand(new UpdateDataverseDefaultContributorRoleCommand(defaultRole, req, dv)); List<String> args = Arrays.asList(dv.getDisplayName(), defaultRoleName); String retString = BundleUtil.getStringFromBundle("dataverses.api.update.default.contributor.role.success", args); return ok(retString); }); } catch (WrappedResponse wr) { return wr.getResponse(); } }
Source:
public void canDoActionFails() { GlusterServiceParameters params = new GlusterServiceParameters(); params.setActionType("InvalidActionType"); cmd = spy(new ManageGlusterServiceCommand(params)); assertFalse(cmd.canDoAction()); params.setServiceType(ServiceType.SMB); cmd = spy(new ManageGlusterServiceCommand(params)); assertFalse(cmd.canDoAction()); params.setClusterId(null); params.setServerId(null); assertFalse(cmd.canDoAction()); }

Target:
public void canDoActionFails() { GlusterServiceParameters params = new GlusterServiceParameters(); params.setActionType("InvalidActionType"); cmd = spy(new ManageGlusterServiceCommand(params)); assertFalse(cmd.canDoAction()); params.setClusterId(null); params.setServerId(null); assertFalse(cmd.canDoAction()); }
Source:
public void checkVariableFormat(Task task, TaskVariable variable) throws JobValidationException { if (!Strings.isNullOrEmpty(variable.getModel())) { String model = variable.getModel().trim(); try { new ModelValidator(model).validate(variable.getValue()); } catch (Exception e) { throw new JobValidationException("Task '" + task.getName() + "': Variable '" + variable.getName() + "': Model " + variable.getModel() + ": " + e.getMessage(), e); } } }

Target:
protected void checkVariableFormat(Task task, TaskVariable variable) throws JobValidationException { if (!Strings.isNullOrEmpty(variable.getModel())) { String model = variable.getModel().trim(); try { new ModelValidator(model).validate(variable.getValue()); } catch (Exception e) { throw new JobValidationException("Task '" + task.getName() + "': Variable '" + variable.getName() + "': Model " + variable.getModel() + ": " + e.getMessage(), e); } } }
Source:
protected void onPause() { super.onPause(); stopTimer(); if (adapter != null) { adapter.unregisterDataSetObserver(mListStateObserver); } hereFunctionHandler.stopLocationUpdates(); }

Target:
protected void onPause() { super.onPause(); stopTimer(); if (adapter != null) { adapter.unregisterDataSetObserver(mListStateObserver); } hereFunctionHandler.unregisterEntitySelectActivity(); hereFunctionHandler.stopLocationUpdates(); }
Source:
public void testExecutionModePropagationFromEnvWithDefaultAndBoundedSource() throws Exception { final StreamExecutionEnvironment environment = new TestExecutionEnvironment( GlobalDataExchangeMode.ALL_EDGES_PIPELINED, ScheduleMode.EAGER, true); environment .fromSource( new MockSource(Boundedness.BOUNDED, 100), WatermarkStrategy.noWatermarks(), "bounded-source") .print(); environment.executeAsync(); }

Target:
public void testExecutionModePropagationFromEnvWithDefaultAndBoundedSource() { final StreamExecutionEnvironment environment = StreamExecutionEnvironment.getExecutionEnvironment(); environment .fromSource( new MockSource(Boundedness.BOUNDED, 100), WatermarkStrategy.noWatermarks(), "bounded-source") .print(); assertThat( environment.getStreamGraph(), hasProperties( GlobalDataExchangeMode.ALL_EDGES_PIPELINED, ScheduleMode.EAGER, true)); }
Source:
public String getDescription() { return getStatuteType().getName().getContent(I18N.getLocale()) + (studentStatute instanceof SeniorStatute ? (" (" + ((SeniorStatute) studentStatute).getRegistration().getDegree().getPresentationName() + ") ") : ""); }

Target:
public String getDescription() { return getStatuteType().getName().getContent() + (studentStatute instanceof SeniorStatute ? (" (" + ((SeniorStatute) studentStatute).getRegistration().getDegree().getPresentationName() + ") ") : ""); }
Source:
public byte[] getCacheKey() { int size = 1; List<byte[]> columns = Lists.newArrayListWithExpectedSize(this.columns.size()); for (String column : this.columns) { final byte[] bytes = StringUtils.toUtf8(column); columns.add(bytes); size += bytes.length + 1; } final ByteBuffer bytes = ByteBuffer.allocate(size).put(LIST_CACHE_PREFIX); for (byte[] column : columns) { bytes.put(column); bytes.put((byte) 0); } return bytes.array(); }

Target:
public byte[] getCacheKey() { int size = 1; List<byte[]> columns = Lists.newArrayListWithExpectedSize(this.columns.size()); for (String column : this.columns) { final byte[] bytes = StringUtils.toUtf8(column); columns.add(bytes); size += bytes.length + 1; } final ByteBuffer bytes = ByteBuffer.allocate(size).put(LIST_CACHE_PREFIX); for (byte[] column : columns) { bytes.put(column); bytes.put((byte) 0xff); } return bytes.array(); }
Source:
public Map<DateTime, TimeZoneHistory> timeZoneHistoryList(@Scope({OAuthScope.ADMINISTRATION_READ}) final AccessToken accessToken) { return timeZoneHistoryDAODynamoDB.getAllTimeZones(19670); }

Target:
public Map<DateTime, TimeZoneHistory> timeZoneHistoryList(@Scope({OAuthScope.ADMINISTRATION_READ}) final AccessToken accessToken) { return timeZoneHistoryDAODynamoDB.getAllTimeZones(accessToken.accountId); }
Source:
public static Iterable<Model> parseYaml(Iterable<IFile> files) { if (files == null || Iterables.isEmpty(files)) { return Lists.newArrayList(); } final SwaggerSchema schema = Activator.getDefault().getSchema(); final ObjectMapper mapper = createMapper(); final List<Model> modelSet = Lists.newArrayList(); for (IFile file : files) { Model model = new Model(schema, file.getFullPath()); try { mapper.reader() .withAttribute(ATTRIBUTE_MODEL, model) .withAttribute(ATTRIBUTE_PARENT, null) .withAttribute(ATTRIBUTE_POINTER, JsonPointer.compile("")) .withType(AbstractNode.class) .readValue(file.getLocationURI().toURL()); } catch (IllegalArgumentException | IOException e) { e.printStackTrace(); } modelSet.add(model); } return modelSet; }

Target:
public static Iterable<Model> parseYaml(Iterable<IFile> files) { if (files == null || Iterables.isEmpty(files)) { return Lists.newArrayList(); } final SwaggerSchema schema = Activator.getDefault().getSchema(); final List<Model> models = Lists.newArrayList(); for (IFile file : files) { Model model = new Model(schema, file.getFullPath()); try { reader(model).readValue(file.getLocationURI().toURL()); } catch (IllegalArgumentException | IOException e) { e.printStackTrace(); continue; } models.add(model); } return models; }
Source:
public void init() { registry = ModelRegistryService.getInstance(null); graph = mock(ModelGraph.class); registry.setEkbClassLoader(new EKBTestClassLoader()); registry.setGraphDb(graph); }

Target:
public void init() { registry = ModelRegistryService.getInstance(context); graph = mock(ModelGraph.class); registry.setEkbClassLoader(new EKBTestClassLoader()); registry.setGraphDb(graph); }
Source:
@Override public List findElements(String by, String using) { return super.findElements(by, using); }

Target:
@Override public List<T> findElements(String by, String using) { return super.findElements(by, using); }
Source:
private TreeSet<Entry<String, File>> jarsFirstSortedPluginsSet( Map<String, File> activePlugins) { TreeSet<Entry<String, File>> sortedPlugins = Sets.newTreeSet(new Comparator<Entry<String, File>>() { @Override public int compare(Entry<String, File> entry1, Entry<String, File> entry2) { String file1 = entry1.getValue().getName(); String file2 = entry2.getValue().getName(); int cmp = file1.compareTo(file2); if (file1.endsWith(".jar")) { return (file2.endsWith(".jar") ? cmp : -1); } else { return (file2.endsWith(".jar") ? +1 : cmp); } } }); Iterator<Entry<String, File>> it = activePlugins.entrySet().iterator(); while (it.hasNext()) { Entry<String,File> entry = it.next(); sortedPlugins.add( new AbstractMap.SimpleImmutableEntry<String, File>( entry.getKey(), entry.getValue())); } return sortedPlugins; }

Target:
private TreeSet<Entry<String, File>> jarsFirstSortedPluginsSet( Map<String, File> activePlugins) { TreeSet<Entry<String, File>> sortedPlugins = Sets.newTreeSet(new Comparator<Entry<String, File>>() { @Override public int compare(Entry<String, File> entry1, Entry<String, File> entry2) { String file1 = entry1.getValue().getName(); String file2 = entry2.getValue().getName(); int cmp = file1.compareTo(file2); if (file1.endsWith(".jar")) { return (file2.endsWith(".jar") ? cmp : -1); } else { return (file2.endsWith(".jar") ? +1 : cmp); } } }); addAllEntries(activePlugins, sortedPlugins); return sortedPlugins; }
Source:
static Map<String, String> collectQuery(List<NameValuePair> args) { val result = new HashMap<String, String>(); for (val pair : args) { result.put(pair.getName().toLowerCase(), pair.getValue()); } return result; }

Target:
static Map<String, String> collectQuery(List<NameValuePair> args) { val result = new ImmutableMap.Builder<String, String>(); for (val pair : args) { result.put(pair.getName().toLowerCase(), pair.getValue()); } return result.build(); }
Source:
private String asReference(String repoLocation, String path, String projectName, String tagName) { StringBuffer buffer = new StringBuffer(); buffer.append("scm:git:"); buffer.append(repoLocation); if (path != null) { Path projectPath = new Path(path); buffer.append(";path=\""); buffer.append(projectPath.toString()); buffer.append('"'); if (!projectPath.lastSegment().equals(projectName)) { buffer.append(";project=\""); buffer.append(projectName); buffer.append('"'); } } if (tagName != null && !tagName.equals("HEAD")) { buffer.append(";tag="); buffer.append(tagName); } return buffer.toString(); }

Target:
private String asReference(String repoLocation, String path, String projectName, String tagName) { final StringBuffer buffer = new StringBuffer(); buffer.append("scm:git:"); buffer.append(repoLocation); if (path != null) { final Path projectPath = new Path(path); buffer.append(";path=\""); buffer.append(projectPath.toString()); buffer.append('"'); if (!projectPath.lastSegment().equals(projectName)) { buffer.append(";project=\""); buffer.append(projectName); buffer.append('"'); } } if (tagName != null && !tagName.equals("master")) { buffer.append(";tag="); buffer.append(tagName); } return buffer.toString(); }
Source:
public static boolean checkAndRequestPermissions(final Activity activity, final Type type) { final Set<Type> types = new HashSet<>(); types.add(type); return checkAndRequestPermissions(activity, types); }

Target:
public static boolean checkAndRequestPermissions(final Activity activity, final Type type) { return checkAndRequestPermissions(activity, EnumSet.of(type)); }
Source:
public static QueryContext context(Session ses) { return (QueryContext)ses.getVariable("IGNITE_QUERY_CONTEXT").getObject(); }

Target:
public static QueryContext context(Session ses) { return (QueryContext)ses.getVariable(QCTX_VARIABLE_NAME).getObject(); }
Source:
public void testSanitizeForJs() { String unsanitized = "\\ \" ' #"; String expected = "\\\\ \\&quot; \\&#39; \\#"; String sanitized = Sanitizer.sanitizeForJs(unsanitized); assertEquals(null, Sanitizer.sanitizeForJs(null)); assertEquals(expected, sanitized); }

Target:
public void testSanitizeForJs() { sanitizeJs_receivesNull_returnsNull(); sanitizeJs_receivesUnsanitized_returnsSanitized(); }
Source:
private static RowGroupStatistics buildActualRowGroupStatistics(int rowGroupIndex, Map<StreamId, List<RowGroupIndex>> actualRowGroupStatistics) { return new RowGroupStatistics( BOTH, actualRowGroupStatistics.entrySet() .stream() .collect(Collectors.toMap((entry) -> entry.getKey().getColumn(), (entry) -> entry.getValue().get(rowGroupIndex).getColumnStatistics()))); }

Target:
private static RowGroupStatistics buildActualRowGroupStatistics(int rowGroupIndex, Map<StreamId, List<RowGroupIndex>> actualRowGroupStatistics) { return new RowGroupStatistics( BOTH, actualRowGroupStatistics.entrySet() .stream() .collect(Collectors.toMap(entry -> entry.getKey().getColumn(), entry -> entry.getValue().get(rowGroupIndex).getColumnStatistics()))); }
Source:
public Object handle(UnitOfWork<? extends CommandMessage<?>> unitOfWork, InterceptorChain interceptorChain) throws Exception { return InterceptorChainParameterResolverFactory.callWithInterceptorChain(interceptorChain, () -> { if (!delegate.canHandle(unitOfWork.getMessage())) { return interceptorChain.proceed(); } return delegate.handle(unitOfWork.getMessage(), target); }); }

Target:
public Object handle(UnitOfWork<? extends CommandMessage<?>> unitOfWork, InterceptorChain interceptorChain) throws Exception { return InterceptorChainParameterResolverFactory.callWithInterceptorChain( interceptorChain, () -> delegate.canHandle(unitOfWork.getMessage()) ? delegate.handle(unitOfWork.getMessage(), target) : interceptorChain.proceed()); }
Source:
public void shouldGetConflictExceptionFor_markChargeAsCaptureApproved_whenNoChargeExists() { String extChargeId = addChargeAndCardDetails(EXPIRED, ServicePaymentReference.of("ref"), ZonedDateTime.now().minusMinutes(90)); final String expectedErrorMessage = format("Operation for charge conflicting, %s, attempt to perform delayed capture on charge not in AWAITING CAPTURE REQUEST state.", extChargeId); connectorRestApiClient .withAccountId(accountId) .withChargeId(extChargeId) .postMarkChargeAsCaptureApproved() .statusCode(CONFLICT.getStatusCode()) .contentType(JSON) .body(JSON_MESSAGE_KEY, contains(expectedErrorMessage)) .body("error_identifier", Matchers.is(ErrorIdentifier.GENERIC.toString())); }

Target:
public void shouldGetConflictExceptionFor_markChargeAsCaptureApproved_whenNoChargeExists() { String extChargeId = addChargeAndCardDetails(EXPIRED, ServicePaymentReference.of("ref"), ZonedDateTime.now().minusMinutes(90)); final String expectedErrorMessage = format("Operation for charge conflicting, %s, attempt to perform delayed capture on charge not in AWAITING CAPTURE REQUEST state.", extChargeId); connectorRestApiClient .withAccountId(accountId) .withChargeId(extChargeId) .postMarkChargeAsCaptureApproved() .statusCode(CONFLICT.getStatusCode()) .contentType(JSON) .body(JSON_MESSAGE_KEY, contains(expectedErrorMessage)) .body("error_identifier", is(ErrorIdentifier.GENERIC.toString())); }
Source:
private static Map<String, PartitionStatistics> getPartitionsStatistics(SemiTransactionalHiveMetastore metastore, SchemaTableName table, List<HivePartition> hivePartitions) { if (hivePartitions.isEmpty()) { return ImmutableMap.of(); } boolean unpartitioned = hivePartitions.stream().anyMatch(partition -> partition.getPartitionId().equals(UNPARTITIONED_ID)); if (unpartitioned) { checkArgument(hivePartitions.size() == 1, "expected only one hive partition"); } if (unpartitioned) { return ImmutableMap.of(UNPARTITIONED_ID, metastore.getTableStatistics(table.getSchemaName(), table.getTableName())); } else { Set<String> partitionNames = hivePartitions.stream() .map(HivePartition::getPartitionId) .collect(toImmutableSet()); return metastore.getPartitionStatistics(table.getSchemaName(), table.getTableName(), partitionNames); } }

Target:
private static Map<String, PartitionStatistics> getPartitionsStatistics(SemiTransactionalHiveMetastore metastore, SchemaTableName table, List<HivePartition> hivePartitions) { if (hivePartitions.isEmpty()) { return ImmutableMap.of(); } boolean unpartitioned = hivePartitions.stream().anyMatch(partition -> partition.getPartitionId().equals(UNPARTITIONED_ID)); if (unpartitioned) { checkArgument(hivePartitions.size() == 1, "expected only one hive partition"); return ImmutableMap.of(UNPARTITIONED_ID, metastore.getTableStatistics(table.getSchemaName(), table.getTableName())); } Set<String> partitionNames = hivePartitions.stream() .map(HivePartition::getPartitionId) .collect(toImmutableSet()); return metastore.getPartitionStatistics(table.getSchemaName(), table.getTableName(), partitionNames); }
Source:
public CatalogProtos.FragmentProto getProto() { JdbcFragmentProto.Builder builder = JdbcFragmentProto.newBuilder(); builder.setInputSourceId(this.inputSourceId); builder.setUri(this.uri); if(hostNames != null) { List inputList = new ArrayList<>(); inputList.addAll(Arrays.asList(hostNames)); builder.addAllHosts(inputList); } CatalogProtos.FragmentProto.Builder fragmentBuilder = CatalogProtos.FragmentProto.newBuilder(); fragmentBuilder.setId(this.inputSourceId); fragmentBuilder.setDataFormat("JDBC"); fragmentBuilder.setContents(builder.buildPartial().toByteString()); return fragmentBuilder.build(); }

Target:
public CatalogProtos.FragmentProto getProto() { JdbcFragmentProto.Builder builder = JdbcFragmentProto.newBuilder(); builder.setInputSourceId(this.inputSourceId); builder.setUri(this.uri); if(hostNames != null) { builder.addAllHosts(Arrays.asList(hostNames)); } CatalogProtos.FragmentProto.Builder fragmentBuilder = CatalogProtos.FragmentProto.newBuilder(); fragmentBuilder.setId(this.inputSourceId); fragmentBuilder.setDataFormat("JDBC"); fragmentBuilder.setContents(builder.buildPartial().toByteString()); return fragmentBuilder.build(); }
Source:
public Object clone() throws CloneNotSupportedException { return super.clone(); }

Target:
public Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException("Clone is not supported for the RunIngestModulesAction"); }
Source:
private void compareWorkAndCreditNameVisibility(Work work) { Visibility workVisibility = work.getVisibility(); for (Contributor contributor : work.getWorkContributors().getContributor()) { if (contributor.getCreditName() != null && contributor.getCreditName().getVisibility() != null && contributor.getCreditName().getVisibility().isMoreRestrictiveThan(workVisibility)) { LOGGER.warn("Client posting work with visibility ({}) less restrictive than its contributor credit name ({})", new Object[] { work.getWorkTitle().getTitle(), workVisibility.toString(), contributor.getCreditName().getContent(), contributor.getCreditName().getVisibility().toString() }); } } }

Target:
private void compareWorkAndCreditNameVisibility(Work work) { Visibility workVisibility = work.getVisibility(); for (Contributor contributor : work.getWorkContributors().getContributor()) { if (contributor.getCreditName() != null && contributor.getCreditName().getVisibility() != null && contributor.getCreditName().getVisibility().isMoreRestrictiveThan(workVisibility)) { LOGGER.error("Client posting work with visibility ({}) less restrictive than its contributor credit name ({})", new Object[] { work.getWorkTitle().getTitle(), workVisibility.toString(), contributor.getCreditName().getContent(), contributor.getCreditName().getVisibility().toString() }); } } }
Source:
public static synchronized boolean reload() { LOGGER.info("Configuration is being reloaded"); InputStream stream; Long default_max_age; String default_url; try { PROPERTIES.clear(); stream = new FileInputStream(PATH); PROPERTIES.load(stream); stream.close(); default_url = PROPERTIES.getProperty(ACTION_URL_PROP); if (!Utils.isValidURL(default_url)) { LOGGER.error("Invalid configuration value in " + PATH + " file " + ACTION_URL_PROP + ": " + default_url); return false; } try { default_max_age = Long.parseLong(PROPERTIES.getProperty(MAX_AGE_PROP)); } catch (NumberFormatException nfe) { LOGGER.error("Invalid configuration value in " + PATH + " file " + MAX_AGE_PROP + ": " + nfe); return false; } } catch (IOException e) { default_url = DEFAULT_PERSEO_FE_URL; default_max_age = DEFAULT_MAX_AGE; } String perseo_fe_url = System.getenv(PERSEO_FE_URL_ENV); perseo_fe_url = perseo_fe_url != null ? perseo_fe_url : default_url; if (Utils.isValidURL(perseo_fe_url)) { actionRule = perseo_fe_url + "/actions/do"; } else { LOGGER.error("Invalid configuration environment var value for " + PERSEO_FE_URL_ENV + ": " + perseo_fe_url); return false; } LOGGER.debug("actionRule: " + actionRule); String max_age_string = System.getenv(PERSEO_MAX_AGE_ENV); try { maxAge = max_age_string != null ? Long.parseLong(max_age_string) : default_max_age; } catch (NumberFormatException nfe) { LOGGER.error("Invalid configuration environment var value for " + PERSEO_MAX_AGE_ENV + ": " + nfe); return false; } return true; }

Target:
public static synchronized boolean reload() { LOGGER.info("Configuration is being reloaded"); InputStream stream; String defaultMaxAge; String defaultURL; String actionPath = "/actions/do"; try { PROPERTIES.clear(); stream = new FileInputStream(PATH); PROPERTIES.load(stream); stream.close(); defaultURL = PROPERTIES.getProperty(ACTION_URL_PROP); defaultMaxAge = PROPERTIES.getProperty(MAX_AGE_PROP); } catch (IOException e) { defaultURL = DEFAULT_PERSEO_FE_URL; defaultMaxAge = String.valueOf(DEFAULT_MAX_AGE); } String perseoFeURLEnv = System.getenv(PERSEO_FE_URL_ENV); perseoFeURLEnv = perseoFeURLEnv != null ? perseoFeURLEnv : defaultURL; if (Utils.isValidURL(perseoFeURLEnv)) { actionRule = perseoFeURLEnv.contains(actionPath) ? perseoFeURLEnv : perseoFeURLEnv + actionPath; } else { LOGGER.error("Invalid value for " + PERSEO_FE_URL_ENV + ": " + perseoFeURLEnv); return false; } String maxAgeEnv = System.getenv(PERSEO_MAX_AGE_ENV); try { maxAge = maxAgeEnv != null ? Long.parseLong(maxAgeEnv) : Long.parseLong(defaultMaxAge); } catch (NumberFormatException nfe) { LOGGER.error("Invalid value for " + PERSEO_MAX_AGE_ENV + ": " + nfe); return false; } return true; }
Source:
private boolean isIncrementalAlarm(String reductionKey, OnmsAlarm alarm) { return outstandingAlarms.containsKey(reductionKey) && alarmEqualityChecker.equalsExcludingOnFirst(protobufMapper.toAlarm(alarm).build(), outstandingAlarms.get(reductionKey)); }

Target:
private boolean isIncrementalAlarm(String reductionKey, OnmsAlarm alarm) { OpennmsModelProtos.Alarm existingAlarm = outstandingAlarms.get(reductionKey); return existingAlarm != null && alarmEqualityChecker.equalsExcludingOnFirst(protobufMapper.toAlarm(alarm), existingAlarm); }
Source:
public UserInterface getDefaultUI() { if (isHeadless()) return null; if (defaultUI != null) return defaultUI; if (uiList().isEmpty()) return null; return uiList().get(0); }

Target:
public UserInterface getDefaultUI() { if (isHeadless()) return HeadlessUI.getInstance(); if (defaultUI != null) return defaultUI; if (uiList().isEmpty()) return null; return uiList().get(0); }
Source:
protected InternalSecurityContext( String username ) { this.username = username; principals.add(SimplePrincipal.newInstance(username)); }

Target:
protected InternalSecurityContext( String username ) { this.username = username; }
Source:
private synchronized OutputStream addPostSteps(ProcessingStepHandler handler, IArtifactDescriptor descriptor, OutputStream destination, IProgressMonitor monitor) { ArrayList<ProcessingStep> steps = new ArrayList<>(); steps.add(new SignatureVerifier()); Set<String> skipChecksums = ARTIFACT_MD5_CHECKSUM_ENABLED ? Collections.<String> emptySet() : Collections.singleton(ChecksumUtilities.MD5); addChecksumVerifiers(descriptor, steps, skipChecksums, IArtifactDescriptor.ARTIFACT_CHECKSUM); if (steps.isEmpty()) return destination; ProcessingStep[] stepArray = steps.toArray(new ProcessingStep[steps.size()]); return handler.link(stepArray, destination, monitor); }

Target:
private synchronized OutputStream addPostSteps(ProcessingStepHandler handler, IArtifactDescriptor descriptor, OutputStream destination, IProgressMonitor monitor) { ArrayList<ProcessingStep> steps = new ArrayList<>(); steps.add(new SignatureVerifier()); Set<String> skipChecksums = ARTIFACT_MD5_CHECKSUM_ENABLED ? Collections.emptySet() : Collections.singleton(ChecksumUtilities.MD5); addChecksumVerifiers(descriptor, steps, skipChecksums, IArtifactDescriptor.ARTIFACT_CHECKSUM); if (steps.isEmpty()) return destination; ProcessingStep[] stepArray = steps.toArray(new ProcessingStep[steps.size()]); return handler.link(stepArray, destination, monitor); }
Source:
private SearchScrollHits<String> newSearchScrollHits(List<SearchHit<String>> hits) { return new SearchHitsImpl<String>(1, TotalHitsRelation.EQUAL_TO, 0, "1234", hits, null); }

Target:
private SearchScrollHits<String> newSearchScrollHits(List<SearchHit<String>> hits) { return new SearchHitsImpl<String>(hits.size(), TotalHitsRelation.EQUAL_TO, 0, "1234", hits, null); }
Source:
public void run() { try { stats.addQueuedTime(Duration.nanosSince(queuedTime)); long start = System.nanoTime(); backupStore.get().backupShard(uuid, source); stats.addCopyShardDataRate(new DataSize(source.length(), BYTE), Duration.nanosSince(start)); if (enableVerification) { File restored = new File(localFileSystem.get().pathToFile(storageService.getStagingFile(uuid)) + ".validate"); backupStore.get().restoreShard(uuid, restored); if (!filesEqual(source, restored)) { stats.incrementBackupCorruption(); File quarantineBase = localFileSystem.get().pathToFile(storageService.getQuarantineFile(uuid)); File quarantineOriginal = new File(quarantineBase.getPath() + ".original"); File quarantineRestored = new File(quarantineBase.getPath() + ".restored"); log.error("Backup is corrupt after write. Quarantining local file: %s", quarantineBase); if (!this.source.renameTo(quarantineOriginal) || !restored.renameTo(quarantineRestored)) { log.warn("Quarantine of corrupt backup shard failed: %s", uuid); } throw new PrestoException(RAPTOR_BACKUP_CORRUPTION, "Backup is corrupt after write: " + uuid); } if (!restored.delete()) { log.warn("Failed to delete staging file: %s", restored); } } stats.incrementBackupSuccess(); } catch (Throwable t) { stats.incrementBackupFailure(); throw t; } }

Target:
public void run() { try { stats.addQueuedTime(Duration.nanosSince(queuedTime)); long start = System.nanoTime(); backupStore.get().backupShard(uuid, source); stats.addCopyShardDataRate(new DataSize(source.length(), BYTE), Duration.nanosSince(start)); if (!enableVerification) { stats.incrementBackupSuccess(); return; } File restored = new File(localFileSystem.get().pathToFile(storageService.getStagingFile(uuid)) + ".validate"); backupStore.get().restoreShard(uuid, restored); if (!filesEqual(source, restored)) { stats.incrementBackupCorruption(); File quarantineBase = localFileSystem.get().pathToFile(storageService.getQuarantineFile(uuid)); File quarantineOriginal = new File(quarantineBase.getPath() + ".original"); File quarantineRestored = new File(quarantineBase.getPath() + ".restored"); log.error("Backup is corrupt after write. Quarantining local file: %s", quarantineBase); if (!this.source.renameTo(quarantineOriginal) || !restored.renameTo(quarantineRestored)) { log.warn("Quarantine of corrupt backup shard failed: %s", uuid); } throw new PrestoException(RAPTOR_BACKUP_CORRUPTION, "Backup is corrupt after write: " + uuid); } if (!restored.delete()) { log.warn("Failed to delete staging file: %s", restored); } stats.incrementBackupSuccess(); } catch (Throwable t) { stats.incrementBackupFailure(); throw t; } }
Source:
private PackList scanPacksImpl(final PackList old) { final Map<String, PackFile> forReuse = reuseMap(old); final FileSnapshot snapshot = FileSnapshot.save(packDirectory); final Set<String> names = listPackDirectory(); final List<PackFile> list = new ArrayList<PackFile>(names.size() >> 2); boolean foundNew = false; for (final String indexName : names) { if (indexName.length() != 49 || !indexName.endsWith(".idx")) continue; final String base = indexName.substring(0, indexName.length() - 3); final List<PackExt> extensions = new ArrayList<PackExt>( PackExt.values().length); for (PackExt ext : PackExt.values()) { final String name = base + ext.getExtension(); if (names.contains(name)) extensions.add(ext); } if (!extensions.contains(PACK)) { continue; } final String packName = base + PACK.getExtension(); final PackFile oldPack = forReuse.remove(packName); if (oldPack != null) { list.add(oldPack); continue; } final File packFile = new File(packDirectory, packName); list.add(new PackFile(packFile, extensions)); foundNew = true; } if (!foundNew && forReuse.isEmpty() && snapshot.equals(old.snapshot)) { old.snapshot.setClean(snapshot); return old; } for (final PackFile p : forReuse.values()) { p.close(); } if (list.isEmpty()) return new PackList(snapshot, NO_PACKS.packs); final PackFile[] r = list.toArray(new PackFile[list.size()]); Arrays.sort(r, PackFile.SORT); return new PackList(snapshot, r); }

Target:
private PackList scanPacksImpl(final PackList old) { final Map<String, PackFile> forReuse = reuseMap(old); final FileSnapshot snapshot = FileSnapshot.save(packDirectory); final Set<String> names = listPackDirectory(); final List<PackFile> list = new ArrayList<PackFile>(names.size() >> 2); boolean foundNew = false; for (final String indexName : names) { if (indexName.length() != 49 || !indexName.endsWith(".idx")) continue; final String base = indexName.substring(0, indexName.length() - 3); final List<PackExt> extensions = new ArrayList<PackExt>( PackExt.values().length); for (PackExt ext : PackExt.values()) { if (names.contains(base + ext.getExtension())) extensions.add(ext); } if (!extensions.contains(PACK)) { continue; } final String packName = base + PACK.getExtension(); final PackFile oldPack = forReuse.remove(packName); if (oldPack != null) { list.add(oldPack); continue; } final File packFile = new File(packDirectory, packName); list.add(new PackFile(packFile, extensions)); foundNew = true; } if (!foundNew && forReuse.isEmpty() && snapshot.equals(old.snapshot)) { old.snapshot.setClean(snapshot); return old; } for (final PackFile p : forReuse.values()) { p.close(); } if (list.isEmpty()) return new PackList(snapshot, NO_PACKS.packs); final PackFile[] r = list.toArray(new PackFile[list.size()]); Arrays.sort(r, PackFile.SORT); return new PackList(snapshot, r); }
Source:
public Optional<Git> execute() { try { boolean newRepository = !repoDir.exists(); final org.eclipse.jgit.api.Git _git = org.eclipse.jgit.api.Git.init().setBare(true).setDirectory(repoDir).call(); if (leaders != null) { new WriteConfiguration(_git.getRepository(), cfg -> { cfg.setInt("core", null, "repositoryformatversion", 1); cfg.setString("extensions", null, "refsStorage", "reftree"); }).execute(); } final Repository repo = new FileRepositoryBuilder() .setGitDir(repoDir) .build(); final org.eclipse.jgit.api.Git git = new org.eclipse.jgit.api.Git(repo); if(!sslVerify) { StoredConfig config = repo.getConfig(); config.setBoolean( "http", null, "sslVerify", false ); config.save(); } if (setupGitHooks(newRepository)) { final File repoHookDir = new File(repoDir, "hooks"); try { FileUtils.copyDirectory(hookDir, repoHookDir); } catch (final Exception ex) { throw new RuntimeException(ex); } for (final File file : repoHookDir.listFiles()) { if (file != null && file.isFile()) { file.setExecutable(true); } } } return Optional.of(new GitImpl(git, leaders)); } catch (final Exception ex) { throw new IOException(ex); } }

Target:
public Optional<Git> execute() { try { boolean newRepository = !repoDir.exists(); final org.eclipse.jgit.api.Git _git = org.eclipse.jgit.api.Git.init().setBare(true).setDirectory(repoDir).call(); if (leaders != null) { new WriteConfiguration(_git.getRepository(), cfg -> { cfg.setInt("core", null, "repositoryformatversion", 1); cfg.setString("extensions", null, "refsStorage", "reftree"); }).execute(); } final Repository repo = new FileRepositoryBuilder() .setGitDir(repoDir) .build(); final org.eclipse.jgit.api.Git git = new org.eclipse.jgit.api.Git(repo); setupSSLVerify(repo); if (setupGitHooks(newRepository)) { final File repoHookDir = new File(repoDir, "hooks"); try { FileUtils.copyDirectory(hookDir, repoHookDir); } catch (final Exception ex) { throw new RuntimeException(ex); } for (final File file : repoHookDir.listFiles()) { if (file != null && file.isFile()) { file.setExecutable(true); } } } return Optional.of(new GitImpl(git, leaders)); } catch (final Exception ex) { throw new IOException(ex); } }
Source:
private JsonElement evaluate(LDUser user, FeatureStore featureStore, List<FeatureRequestEvent> events) throws EvaluationError { boolean prereqOk = true; for (Prerequisite prereq : prerequisites) { FeatureFlag prereqFeatureFlag = featureStore.get(prereq.getKey()); JsonElement prereqEvalResult = null; if (prereqFeatureFlag == null) { logger.error("Could not retrieve prerequisite flag: " + prereq.getKey() + " when evaluating: " + key); return null; } else if (prereqFeatureFlag.isOn()) { prereqEvalResult = prereqFeatureFlag.evaluate(user, featureStore, events); try { JsonElement variation = prereqFeatureFlag.getVariation(prereq.getVariation()); if (prereqEvalResult == null || variation == null || !prereqEvalResult.equals(variation)) { prereqOk = false; } } catch (EvaluationError err) { prereqOk = false; } } else { prereqOk = false; } events.add(new FeatureRequestEvent(prereqFeatureFlag.getKey(), user, prereqEvalResult, null)); } if (prereqOk) { return getVariation(evaluateIndex(user)); } return null; }

Target:
private JsonElement evaluate(LDUser user, FeatureStore featureStore, List<FeatureRequestEvent> events) throws EvaluationException { boolean prereqOk = true; for (Prerequisite prereq : prerequisites) { FeatureFlag prereqFeatureFlag = featureStore.get(prereq.getKey()); JsonElement prereqEvalResult = null; if (prereqFeatureFlag == null) { logger.error("Could not retrieve prerequisite flag: " + prereq.getKey() + " when evaluating: " + key); return null; } else if (prereqFeatureFlag.isOn()) { prereqEvalResult = prereqFeatureFlag.evaluate(user, featureStore, events); try { JsonElement variation = prereqFeatureFlag.getVariation(prereq.getVariation()); if (prereqEvalResult == null || variation == null || !prereqEvalResult.equals(variation)) { prereqOk = false; } } catch (EvaluationException err) { logger.warn("Error evaluating prerequisites: " + err.getMessage()); prereqOk = false; } } else { prereqOk = false; } events.add(new FeatureRequestEvent(prereqFeatureFlag.getKey(), user, prereqEvalResult, null)); } if (prereqOk) { return getVariation(evaluateIndex(user)); } return null; }
Source:
public void deleteCourseCascade(String courseId) { if (getCourse(courseId) == null) { return; } coursesDb.deleteCourse(courseId); AttributesDeletionQuery query = AttributesDeletionQuery.builder() .withCourseId(courseId) .build(); instructorsLogic.deleteInstructors(query); studentsLogic.deleteStudents(query); feedbackSessionsLogic.deleteFeedbackSessions(query); fqLogic.deleteFeedbackQuestions(query); frLogic.deleteFeedbackResponses(query); frcLogic.deleteFeedbackResponseComments(query); }

Target:
public void deleteCourseCascade(String courseId) { if (getCourse(courseId) == null) { return; } AttributesDeletionQuery query = AttributesDeletionQuery.builder() .withCourseId(courseId) .build(); frcLogic.deleteFeedbackResponseComments(query); frLogic.deleteFeedbackResponses(query); fqLogic.deleteFeedbackQuestions(query); feedbackSessionsLogic.deleteFeedbackSessions(query); studentsLogic.deleteStudents(query); instructorsLogic.deleteInstructors(query); coursesDb.deleteCourse(courseId); }
Source:
public boolean sourceStatus(String servicePID) { try { List<Source> sources = helper.getSources(); for (Source source : sources) { if (source instanceof ConfiguredService) { ConfiguredService cs = (ConfiguredService) source; try { Configuration config = helper.getConfiguration(cs); if (config != null && config.getProperties().get("service.pid").equals(servicePID)) { try { return source.isAvailable(); } catch (Exception e) { LOGGER.debug( String.format("Couldn't get availability on source %s", servicePID), e); } } } catch (IOException e) { LOGGER.debug("Couldn't find configuration for source '{}'", source.getId()); } } else { LOGGER.debug("Source '{}' not a configured service", source.getId()); } } } catch (InvalidSyntaxException e) { LOGGER.debug("Could not get service reference list"); } return false; }

Target:
public boolean sourceStatus(String servicePID) { try { List<Source> sources = helper.getSources(); for (Source source : sources) { if (source instanceof ConfiguredService) { ConfiguredService cs = (ConfiguredService) source; try { Configuration config = helper.getConfiguration(cs); if (config != null && config.getProperties().get("service.pid").equals(servicePID)) { try { return source.isAvailable(); } catch (Exception e) { LOGGER.debug("Couldn't get availability on source {}", servicePID, e); } } } catch (IOException e) { LOGGER.debug("Couldn't find configuration for source '{}'", source.getId()); } } else { LOGGER.debug("Source '{}' not a configured service", source.getId()); } } } catch (InvalidSyntaxException e) { LOGGER.debug("Could not get service reference list"); } return false; }
Source:
public Collection<AdvertisedSocketAddress> resolve( AdvertisedSocketAddress initialAddress ) { AdvertisedSocketAddress[] srvAddresses = new AdvertisedSocketAddress[0]; try { srvAddresses = srvRecordResolver.resolveSrvRecord( initialAddress.getHostname() ); } catch ( NamingException e ) { log.error( format( "Failed to resolve srv records '%s'", initialAddress.getHostname() ), e ); } Set<AdvertisedSocketAddress> addresses = new HashSet<>( Arrays.asList( srvAddresses ) ); userLog.info( "Resolved initial host '%s' to %s", initialAddress, addresses ); return addresses; }

Target:
public Collection<AdvertisedSocketAddress> resolve( AdvertisedSocketAddress initialAddress ) { try { Set<AdvertisedSocketAddress> addresses = srvRecordResolver .resolveSrvRecord( initialAddress.getHostname() ) .map( srvRecord -> new AdvertisedSocketAddress( srvRecord.host, srvRecord.port ) ) .collect( Collectors.toSet() ); userLog.info( "Resolved initial host '%s' to %s", initialAddress, addresses ); if ( addresses.isEmpty() ) { log.error( "Failed to resolve srv records for '%s'", initialAddress.getHostname() ); } return addresses; } catch ( NamingException e ) { log.error( "Failed to resolve srv records for '%s'", initialAddress.getHostname(), e ); return Collections.emptySet(); } }