auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void fillParentJobIdIfExistsInGenInfo(Job userJob, InternalJob job) { if (userJob.getGenericInformation().containsKey(PARENT_JOB_ID)) { String parentJobIdString = userJob.getGenericInformation().get(PARENT_JOB_ID); try { long parentJobId = Long.parseLong(parentJobIdString); job.setParentId(parentJobId); } catch (NumberFormatException e) { logger.error("Cannot parse '" + PARENT_JOB_ID + "' in the generic info: " + parentJobIdString); } } }

Target:
private void fillParentJobIdIfExistsInGenInfo(Job userJob, InternalJob job) { if (userJob.getGenericInformation() != null && userJob.getGenericInformation().containsKey(PARENT_JOB_ID)) { String parentJobIdString = userJob.getGenericInformation().get(PARENT_JOB_ID); try { long parentJobId = Long.parseLong(parentJobIdString); job.setParentId(parentJobId); } catch (NumberFormatException e) { logger.error("Cannot parse '" + PARENT_JOB_ID + "' in the generic info: " + parentJobIdString); } } }
Source:
public static JsonSchemaNode createSchema(JsonParser parser) throws IOException { JsonSchemaNode dummy = new JsonSchemaStructNode(null); JsonSchemaStructNode parent = (JsonSchemaStructNode) dummy; JsonToken currentToken = parser.nextToken(); int nameLocation = -1; while (currentToken != null) { if (currentToken.isStructStart()) { JsonSchemaStructNode structNode = new JsonSchemaStructNode(parent); JsonSchemaNameValue nameValue = new JsonSchemaNameValue(nameLocation, structNode); parent.addChild(nameValue); parent = structNode; nameLocation = -1; } else if (currentToken == JsonToken.FIELD_NAME) { nameLocation = (int) getLocation(parser.getTokenLocation()); } else if (currentToken.isStructEnd()) { parent = parent.getParent(); nameLocation = -1; } else { JsonSchemaTerminalNode terminalNode = new JsonSchemaTerminalNode(parent); terminalNode.setValueStartLocation((int) getLocation(parser.getTokenLocation())); JsonSchemaNameValue nameValue = new JsonSchemaNameValue(nameLocation, terminalNode); parent.addChild(nameValue); nameLocation = -1; } currentToken = parser.nextToken(); } JsonSchemaNameValue nameValue = ((JsonSchemaStructNode) dummy).getChild(0); if (nameValue == null) { return null; } dummy = nameValue.getValue(); dummy.setParent(null); return dummy; }

Target:
public static JsonSchemaNode createSchema(JsonParser parser) throws IOException { JsonSchemaNode dummy = new JsonSchemaStructNode(null); JsonSchemaStructNode parent = (JsonSchemaStructNode) dummy; JsonToken currentToken = parser.nextToken(); int nameLocation = -1; if (currentToken == null) { return null; } while (currentToken != null) { if (currentToken.isStructStart()) { JsonSchemaStructNode structNode = new JsonSchemaStructNode(parent); JsonSchemaNameValue nameValue = new JsonSchemaNameValue(nameLocation, structNode); parent.addChild(nameValue); parent = structNode; nameLocation = -1; } else if (currentToken == JsonToken.FIELD_NAME) { nameLocation = (int) getTokenLocation(parser); } else if (currentToken.isStructEnd()) { parent = parent.getParent(); nameLocation = -1; } else { JsonSchemaTerminalNode terminalNode = new JsonSchemaTerminalNode(parent); terminalNode.setValueStartLocation((int) getTokenLocation(parser)); JsonSchemaNameValue nameValue = new JsonSchemaNameValue(nameLocation, terminalNode); parent.addChild(nameValue); nameLocation = -1; } currentToken = parser.nextToken(); } JsonSchemaNameValue nameValue = ((JsonSchemaStructNode) dummy).getChild(0); if (nameValue == null) { return null; } dummy = nameValue.getValue(); dummy.setParent(null); return dummy; }
Source:
public void onUnPublish() { logger.info("Stop recording: entry Id [" + liveEntry.id + "], asset Id [" + liveAsset.id + "], current media server index: " + index); if (liveAsset.tags.contains(Constants.RECORDING_ANCHOR_TAG_VALUE) && KalturaEntryServerNodeType.LIVE_PRIMARY.equals(index)) { logger.info("Cancel replacement is required"); if (liveEntry.recordedEntryId != null && liveEntry.recordedEntryId.length() > 0) { if (!isNewLiveRecordingEnabled) { KalturaAPI.getKalturaAPI().cancelReplace(liveEntry); } } } this.isLastChunk = true; super.onUnPublish(); this.stopRecording(); entryRecorders.remove(liveEntry.id); this.removeListener(this); }

Target:
public void onUnPublish() { logger.info("Stop recording: entry Id [" + liveEntry.id + "], asset Id [" + liveAsset.id + "], current media server index: " + index); if (liveAsset.tags.contains(Constants.RECORDING_ANCHOR_TAG_VALUE) && KalturaEntryServerNodeType.LIVE_PRIMARY.equals(index)) { logger.info("Cancel replacement is required"); if (liveEntry.recordedEntryId != null && liveEntry.recordedEntryId.length() > 0 && !isNewLiveRecordingEnabled) { KalturaAPI.getKalturaAPI().cancelReplace(liveEntry); } } this.isLastChunk = true; super.onUnPublish(); this.stopRecording(); entryRecorders.remove(liveEntry.id); this.removeListener(this); }
Source:
private void makeInsert(final ActionInsertFactCol52 column) { if (!addedInserts.contains(column.getBoundName())) { makeHeaderAndTitle(ACTION, ""); fieldRow.createCell(columnIndex).setCellValue(String.format("%s %s = new %s(); insert( %s );", column.getFactType(), column.getBoundName(), column.getFactType(), column.getBoundName())); addedInserts.add(column.getBoundName()); columnIndex++; } makeHeaderAndTitle(ACTION, column.getHeader()); fieldRow.createCell(columnIndex).setCellValue(makeSetMethod(column.getBoundName(), column.getFactField(), "$param")); }

Target:
private void makeInsert(final ActionInsertFactCol52 column) { if (!addedInserts.contains(column.getBoundName())) { makeHeaderAndTitle(ACTION, ""); fieldRow.createCell(targetColumnIndex).setCellValue(MessageFormat.format("{0} {1} = new {2}(); insert( {1} );", column.getFactType(), column.getBoundName(), column.getFactType())); addedInserts.add(column.getBoundName()); targetColumnIndex++; } makeHeaderAndTitle(ACTION, column.getHeader()); fieldRow.createCell(targetColumnIndex).setCellValue(makeSetMethod(column.getBoundName(), column.getFactField(), "$param")); }
Source:
protected Map<Locator, MetricData> resultSetsToMetricData(Map<Locator, List<ResultSetFuture>> resultSets, Map<Locator, RollupType> locatorRollupType, Granularity granularity) { Map<Locator, MetricData> locatorMetricDataMap = new HashMap<Locator, MetricData>(); for (Map.Entry<Locator, List<ResultSetFuture>> entry : resultSets.entrySet() ) { Locator locator = entry.getKey(); List<ResultSetFuture> futures = entry.getValue(); try { RollupType rollupType = locatorRollupType.get(locator); DAbstractPreaggregatedIO io = rollupTypeToIO.get(rollupType); Table<Locator, Long, Rollup> locatorTimestampRollup = io.toLocatorTimestampRollup(futures, locator, granularity); Points<Rollup> points = convertToPoints(locatorTimestampRollup.row(locator)); DataType dataType = getDataType(locator, MetricMetadata.TYPE.name().toLowerCase()); MetricData.Type outputType = MetricData.Type.from(rollupType, dataType); MetricData metricData = new MetricData(points, getUnitString(locator), outputType); locatorMetricDataMap.put(locator, metricData); } catch (Exception ex) { Instrumentation.markReadError(); LOG.error(String.format("error reading preaggregated metric for locator %s, granularity %s", locator, granularity), ex); } } return locatorMetricDataMap; }

Target:
protected Map<Locator, MetricData> resultSetsToMetricData(Map<Locator, List<ResultSetFuture>> resultSets, Map<Locator, RollupType> locatorRollupType, Granularity granularity) { Map<Locator, MetricData> locatorMetricDataMap = new HashMap<Locator, MetricData>(); for (Map.Entry<Locator, List<ResultSetFuture>> entry : resultSets.entrySet() ) { Locator locator = entry.getKey(); List<ResultSetFuture> futures = entry.getValue(); try { RollupType rollupType = locatorRollupType.get(locator); DAbstractPreaggregatedIO io = rollupTypeToIO.get(rollupType); Table<Locator, Long, Rollup> locatorTimestampRollup = io.toLocatorTimestampRollup(futures, locator, granularity); Points<Rollup> points = convertToPoints(locatorTimestampRollup.row(locator)); DataType dataType = getDataType(locator, MetricMetadata.TYPE.name().toLowerCase()); MetricData.Type outputType = MetricData.Type.from(rollupType, dataType); MetricData metricData = new MetricData(points, getUnitString(locator), outputType); locatorMetricDataMap.put(locator, metricData); } catch (CacheException ex) { Instrumentation.markReadError(); LOG.error(String.format("error getting dataType for locator %s, granularity %s", locator, granularity), ex); } } return locatorMetricDataMap; }
Source:
public void getSettingsShouldReturnSettings() { HashMap<String, String> customStatus = new HashMap<String, String>(){ { put("currency", "USD"); put("hasNewsSubscription", "true"); put("hasOtpEnabled", "false"); put("theme", "minimalistic"); put("internationalizationUserSettingLanguage", "en-US"); put("internationalizationUserSettingDateTimeFormat", "en-GB"); put("internationalizationUserSettingNumberFormat", "en-AU"); } }; User user = Fixtures.loadUser(customStatus); Assert.assertEquals(user.getSettings().getCurrency(), "USD"); Assert.assertTrue(user.getSettings().getHasNewsSubscription()); Assert.assertFalse(user.getSettings().getHasOtpEnabled()); Assert.assertEquals(user.getSettings().getTheme(), "minimalistic"); Assert.assertEquals(user.getSettings().getIntl().getLanguage().getLocale(), "en-US"); Assert.assertEquals(user.getSettings().getIntl().getDateTimeFormat().getLocale(), "en-GB"); Assert.assertEquals(user.getSettings().getIntl().getNumberFormat().getLocale(), "en-AU"); }

Target:
public void getSettingsShouldReturnSettings() { HashMap<String, String> data = new HashMap<String, String>() {{ put("currency", "USD"); put("hasNewsSubscription", "true"); put("hasOtpEnabled", "false"); put("theme", "minimalistic"); put("internationalizationUserSettingLanguage", "en-US"); put("internationalizationUserSettingDateTimeFormat", "en-GB"); put("internationalizationUserSettingNumberFormat", "en-AU"); }}; User user = Fixtures.loadUser(data); Assert.assertEquals(user.getSettings().getCurrency(), "USD"); Assert.assertTrue(user.getSettings().getHasNewsSubscription()); Assert.assertFalse(user.getSettings().getHasOtpEnabled()); Assert.assertEquals(user.getSettings().getTheme(), "minimalistic"); Assert.assertEquals(user.getSettings().getIntl().getLanguage().getLocale(), "en-US"); Assert.assertEquals(user.getSettings().getIntl().getDateTimeFormat().getLocale(), "en-GB"); Assert.assertEquals(user.getSettings().getIntl().getNumberFormat().getLocale(), "en-AU"); }
Source:
public void testGetObjectOnDateReturnsSqlDate() throws Exception { Date date = new Date( 123456789 ); setNextRow( new Object[] { date } ); rowMeta.addValueMeta( new ValueMetaDate( "theDate" ) ); getTestObject().next(); Object value = getTestObject().getObject( 1 ); assertEquals( "java.sql.Timestamp", value.getClass().getName() ); assertTrue( value.toString().startsWith( "1970-01-02 " ) ); }

Target:
public void testGetObjectOnDateReturnsSqlDate() throws Exception { Date date = new Date( 123456789 ); setNextRow( new Object[] { date } ); rowMeta.addValueMeta( new ValueMetaDate( "theDate" ) ); getTestObject().next(); Object value = getTestObject().getObject( 1 ); assertEquals( "java.sql.Timestamp", value.getClass().getName() ); Timestamp timestampValue = (Timestamp) value; assertEquals( "2 Jan 1970 10:17:36 GMT", timestampValue.toGMTString() ); }
Source:
public static PaxosResources create( TimelockPaxosInstallationContext install, MetricsManager metrics, Supplier<PaxosRuntimeConfiguration> paxosRuntime, ExecutorService sharedExecutor) { PaxosRemoteClients remoteClients = ImmutablePaxosRemoteClients.of(install, metrics); HikariDataSource sqliteDataSource = SqliteConnections.getPooledDataSource(install.sqliteDataDirectory()); ImmutablePaxosResources.Builder resourcesBuilder = setupTimestampResources( install, sqliteDataSource, metrics, paxosRuntime, sharedExecutor, remoteClients); if (install.useLeaderForEachClient()) { return configureLeaderForEachClient( resourcesBuilder, install, sqliteDataSource, metrics, paxosRuntime, sharedExecutor, remoteClients); } else { return configureLeaderForAllClients( resourcesBuilder, install, sqliteDataSource, metrics, paxosRuntime, sharedExecutor, remoteClients); } }

Target:
public static PaxosResources create( TimelockPaxosInstallationContext install, MetricsManager metrics, Supplier<PaxosRuntimeConfiguration> paxosRuntime, ExecutorService sharedExecutor) { PaxosRemoteClients remoteClients = ImmutablePaxosRemoteClients.of(install, metrics); ImmutablePaxosResources.Builder resourcesBuilder = setupTimestampResources( install, metrics, paxosRuntime, sharedExecutor, remoteClients); if (install.useLeaderForEachClient()) { return configureLeaderForEachClient( resourcesBuilder, install, metrics, paxosRuntime, sharedExecutor, remoteClients); } else { return configureLeaderForAllClients( resourcesBuilder, install, metrics, paxosRuntime, sharedExecutor, remoteClients); } }
Source:
public void addDescription(ConceptDescription description) { if (description != null && StringUtils.isNotBlank(description.getDescription()) && (!descriptions.contains(description))) { description.setConcept(this); descriptions.add(description); } }

Target:
public void addDescription(ConceptDescription description) { if (description != null && StringUtils.isNotBlank(description.getDescription()) && !descriptions.contains(description)) { description.setConcept(this); descriptions.add(description); } }
Source:
public static String makeRandomId(int l) { if (l<=0) return ""; char[] id = new char[l]; int d = random.nextInt( (26+26) * (26+26+10) * (26+26+10) * (26+26+10) * (26+26+10)); int i = 0; id[i] = idCharsStart.charAt(d % (26+26)); d /= (26+26); if (++i<l) do { id[i] = idCharsSubseq.charAt(d%(26+26+10)); if (++i>=l) break; if (i%5==0) { d = random.nextInt( (26+26+10) * (26+26+10) * (26+26+10) * (26+26+10) * (26+26+10)); } else { d /= (26+26+10); } } while (true); return new String(id); }

Target:
public static String makeRandomId(int l) { return Identifiers.makeRandomId(l); }
Source:
public byte[] getData() { Object base = slice.getBase(); checkState(base instanceof byte[], "unexpected serialization type %s", base.getClass()); byte[] bytes = (byte[]) base; if (slice.isCompact()) { return bytes; } return slice.getBytes(); }

Target:
public byte[] getData() { if (slice.isCompact()) { Object base = slice.getBase(); checkState(base instanceof byte[], "unexpected serialization type %s", base.getClass()); return (byte[]) base; } return slice.getBytes(); }
Source:
public void deleteSslCert(final DeleteSslCertCmd deleteSslCertCmd) { final CallContext ctx = CallContext.current(); final Account caller = ctx.getCallingAccount(); final Long certId = deleteSslCertCmd.getId(); final SslCertVO certVO = _sslCertDao.findById(certId); if (certVO == null) { throw new InvalidParameterValueException("Invalid certificate id: " + certId); } _accountMgr.checkAccess(caller, SecurityChecker.AccessType.OperateEntry, true, certVO); final List<LoadBalancerCertMapVO> lbCertRule = _lbCertDao.listByCertId(certId); if (lbCertRule != null && !lbCertRule.isEmpty()) { String lbUuids = ""; for (final LoadBalancerCertMapVO rule : lbCertRule) { final LoadBalancerVO lb = _entityMgr.findById(LoadBalancerVO.class, rule.getLbId()); lbUuids += " " + lb.getUuid(); } throw new CloudRuntimeException("Certificate in use by a loadbalancer(s)" + lbUuids); } _sslCertDao.remove(certId); }

Target:
public void deleteSslCert(final DeleteSslCertCmd deleteSslCertCmd) { Preconditions.checkNotNull(deleteSslCertCmd); final CallContext ctx = CallContext.current(); final Account caller = ctx.getCallingAccount(); final Long certId = deleteSslCertCmd.getId(); final SslCertVO certVO = _sslCertDao.findById(certId); if (certVO == null) { throw new InvalidParameterValueException("Invalid certificate id: " + certId); } _accountMgr.checkAccess(caller, SecurityChecker.AccessType.OperateEntry, true, certVO); final List<LoadBalancerCertMapVO> lbCertRule = _lbCertDao.listByCertId(certId); if (lbCertRule != null && !lbCertRule.isEmpty()) { String lbUuids = ""; for (final LoadBalancerCertMapVO rule : lbCertRule) { final LoadBalancerVO lb = _entityMgr.findById(LoadBalancerVO.class, rule.getLbId()); lbUuids += " " + lb.getUuid(); } throw new CloudRuntimeException("Certificate in use by a loadbalancer(s)" + lbUuids); } _sslCertDao.remove(certId); }
Source:
public boolean isConcurrentTaskInWork() { return this.currentTask.getId() < 0 || !getConcurrentTasksInWork().isEmpty(); }

Target:
public boolean isConcurrentTaskInWork() { return !getConcurrentTasksInWork().isEmpty(); }
Source:
protected List<Diff> getDifferencesToMerge() { List<Diff> differencesToMerge = newArrayList(selectedDifferences); if (cascadingDifferencesFilterEnabled) { Set<Diff> setToMerge = Sets.newHashSet(differencesToMerge); for (Diff difftoMerge : ImmutableSet.copyOf(setToMerge)) { IMerger merger = mergerRegistry.getHighestRankingMerger(difftoMerge); if (merger instanceof IMerger2) { addAll(setToMerge, ((IMerger2)merger).getDirectMergeDependencies(difftoMerge, !leftToRight)); } } Iterable<Diff> cascadingDifferences = concat(transform(setToMerge, ComparisonUtil .getSubDiffs(leftToRight))); addAll(differencesToMerge, cascadingDifferences); } return differencesToMerge; }

Target:
protected List<Diff> getDifferencesToMerge() { List<Diff> differencesToMerge = newArrayList(selectedDifferences); if (cascadingDifferencesFilterEnabled) { Set<Diff> setToMerge = Sets.newHashSet(differencesToMerge); for (Diff difftoMerge : differencesToMerge) { IMerger merger = mergerRegistry.getHighestRankingMerger(difftoMerge); if (merger instanceof IMerger2) { addAll(setToMerge, ((IMerger2)merger).getDirectMergeDependencies(difftoMerge, !leftToRight)); } } Iterable<Diff> cascadingDifferences = concat(transform(setToMerge, ComparisonUtil .getSubDiffs(leftToRight))); addAll(differencesToMerge, cascadingDifferences); } return differencesToMerge; }
Source:
private void sendMessage() { TextInputControl messageTextField = messageTextField(); messageTextField.setDisable(true); final String text = messageTextField.getText(); chatService.sendMessageInBackground(receiver, text).thenAccept(message -> { messageTextField.clear(); messageTextField.setDisable(false); messageTextField.requestFocus(); }).exceptionally(throwable -> { throwable = throwable instanceof CompletionException ? throwable.getCause() : throwable; logger.warn("Message could not be sent: {}", text, throwable); notificationService.addNotification(new ImmediateErrorNotification( i18n.get("errorTitle"), i18n.get("chat.sendFailed"), throwable, i18n, reportingService) ); messageTextField.setDisable(false); messageTextField.requestFocus(); return null; }); }

Target:
private void sendMessage() { TextInputControl messageTextField = messageTextField(); messageTextField.setDisable(true); final String text = messageTextField.getText(); chatService.sendMessageInBackground(receiver, text).thenAccept(message -> { messageTextField.clear(); messageTextField.setDisable(false); messageTextField.requestFocus(); }).exceptionally(throwable -> { throwable = ConcurrentUtil.unwrapIfCompletionException(throwable); logger.warn("Message could not be sent: {}", text, throwable); notificationService.addNotification(new ImmediateErrorNotification( i18n.get("errorTitle"), i18n.get("chat.sendFailed"), throwable, i18n, reportingService) ); messageTextField.setDisable(false); messageTextField.requestFocus(); return null; }); }
Source:
private void initialize() { this.contentResolver.registerContentObserver(getContentUri(), true, getContentObserver()); Observable<ContentProviderOperation> operationObservable = updateSubject .flatMap(pair -> createOperation(pair.first, pair.second)); updateSubscription = groupOperations(operationObservable) .observeOn(Schedulers.computation()) .map(ArrayList::new) .doOnNext(list -> Log.v(TAG, "Grouped list of " + list.size())) .doOnNext(operations -> { try { ContentProviderResult[] result = contentResolver.applyBatch(getAuthority(), operations); Log.v(TAG, String.format("Applied %s operations", result.length)); } catch (RemoteException | OperationApplicationException e) { Log.e(TAG, "Error applying operations", e); } }) .flatMap(Observable::from) .map(ContentProviderOperation::getUri) .subscribe(locker::release, error -> Log.e(TAG, "Error while handling data! Processing may be blocked.", error)); }

Target:
private void initialize() { contentResolver.registerContentObserver(getContentUri(), true, getContentObserver()); Observable<ContentProviderOperation> operationObservable = updateSubject .onBackpressureBuffer() .observeOn(Schedulers.io()) .flatMap(pair -> createOperation(pair.first, pair.second)); updateSubscription = groupOperations(operationObservable) .observeOn(Schedulers.computation()) .map(ArrayList::new) .doOnNext(list -> Log.v(TAG, "Grouped list of " + list.size())) .doOnNext(operations -> { try { ContentProviderResult[] result = contentResolver.applyBatch(getAuthority(), operations); Log.v(TAG, String.format("Applied %s operations", result.length)); } catch (RemoteException | OperationApplicationException e) { Log.e(TAG, "Error applying operations", e); } }) .flatMap(Observable::from) .map(ContentProviderOperation::getUri) .subscribe(locker::release, error -> Log.e(TAG, "Error while handling data update!", error)); }
Source:
private void generateResponseParser(final Ds3Request ds3Request) throws IOException, TemplateException { final Template tmpl = getResponseParserTemplate(ds3Request); final ResponseParser responseParser = toResponseParser(ds3Request); final Path responsePath = toResponseParserPath(responseParser.getName()); LOG.info("Getting outputstream for file:" + responsePath.toString()); try (final OutputStream outStream = fileUtils.getOutputFile(responsePath); final Writer writer = new OutputStreamWriter(outStream)) { tmpl.process(responseParser, writer); } }

Target:
private void generateResponseParser(final Ds3Request ds3Request) throws IOException, TemplateException { final Template tmpl = getResponseParserTemplate(ds3Request); final ResponseParser responseParser = toResponseParser(ds3Request); final Path responsePath = toResponseParserPath(responseParser.getName()); LOG.info("Getting outputstream for file: {}", responsePath.toString()); try (final OutputStream outStream = fileUtils.getOutputFile(responsePath); final Writer writer = new OutputStreamWriter(outStream)) { tmpl.process(responseParser, writer); } }
Source:
public static void cleanup(Job job) throws IOException { final Path jobDir = getJobPath(job.getJobID(), job.getWorkingDirectory()); final FileSystem fs = jobDir.getFileSystem(job.getConfiguration()); JobHelper.deleteWithRetry(fs, jobDir, true); JobHelper.deleteWithRetry(fs, getJobClassPathDir(job.getJobName(), job.getWorkingDirectory()), true); }

Target:
public static void cleanup(Job job) throws IOException { final Path jobDir = getJobPath(job.getJobID(), job.getWorkingDirectory()); final FileSystem fs = jobDir.getFileSystem(job.getConfiguration()); RuntimeException e = null; try { JobHelper.deleteWithRetry(fs, jobDir, true); } catch (RuntimeException ex) { e = ex; } try { JobHelper.deleteWithRetry(fs, getJobClassPathDir(job.getJobName(), job.getWorkingDirectory()), true); } catch (RuntimeException ex) { if (e == null) { e = ex; } else { e.addSuppressed(ex); } } if (e != null) { throw e; } }
Source:
private DocumentMetadata.Builder createBasicMetadata(Result sourceResult, DocumentMetadata.Builder metaBuilder) { handlePublicationType(sourceResult.getInstance(), metaBuilder); handleTitle(sourceResult.getTitle(), metaBuilder); handleDescription(sourceResult.getDescription(), metaBuilder); handleLanguage(sourceResult.getLanguage(), metaBuilder); handlePublisher(sourceResult.getPublisher(), metaBuilder); if (sourceResult instanceof Publication) { handleJournal(((Publication)sourceResult).getJournal(), metaBuilder); } handleYear(sourceResult.getDateofacceptance(), metaBuilder); handleKeywords(sourceResult.getSubject(), metaBuilder); return metaBuilder; }

Target:
private void createBasicMetadata(Result sourceResult, DocumentMetadata.Builder metaBuilder) { handlePublicationType(sourceResult.getInstance(), metaBuilder); handleTitle(sourceResult.getTitle(), metaBuilder); handleDescription(sourceResult.getDescription(), metaBuilder); handleLanguage(sourceResult.getLanguage(), metaBuilder); handlePublisher(sourceResult.getPublisher(), metaBuilder); if (sourceResult instanceof Publication) { handleJournal(((Publication)sourceResult).getJournal(), metaBuilder); } handleYear(sourceResult.getDateofacceptance(), metaBuilder); handleKeywords(sourceResult.getSubject(), metaBuilder); }
Source:
public String toString() { return String.format( "%s: '%s' violated quota. Actual: %f, Threshold: %f", getClass().getName(), metricName, value, bound); }

Target:
public String toString() { return getClass().getName() + ": '" + metricName + "' violated quota. Actual: " + value + ", Threshold: " + bound; }
Source:
public Geocode() throws IOException { String defaultCountryDatabasePath = "/usr/share/GeoIP/GeoIP2-Country.mmdb"; String defaultCityDatabasePath = "/usr/share/GeoIP/GeoIP2-City.mmdb"; String countryDatabasepath = System.getProperty("maxmind.database.country"); String cityDatabasePath = System.getProperty("maxmind.database.city"); if (countryDatabasepath == null || countryDatabasepath.isEmpty()) countryDatabasepath = defaultCountryDatabasePath; if (cityDatabasePath == null || cityDatabasePath.isEmpty()) cityDatabasePath = defaultCityDatabasePath; LOG.info("Country Database: " + countryDatabasepath); LOG.info("City database: " + cityDatabasePath); countryDatabaseReader = new DatabaseReader.Builder(new File(countryDatabasepath)).build(); cityDatabaseReader = new DatabaseReader.Builder(new File(cityDatabasePath)).build(); }

Target:
public Geocode() throws IOException { String defaultCountryDatabasePath = "/usr/share/GeoIP/GeoIP2-Country.mmdb"; String defaultCityDatabasePath = "/usr/share/GeoIP/GeoIP2-City.mmdb"; String countryDatabasepath = System.getProperty("maxmind.database.country", defaultCountryDatabasePath); String cityDatabasePath = System.getProperty("maxmind.database.city", defaultCityDatabasePath); LOG.info("Country Database: " + countryDatabasepath); LOG.info("City database: " + cityDatabasePath); countryDatabaseReader = new DatabaseReader.Builder(new File(countryDatabasepath)).build(); cityDatabaseReader = new DatabaseReader.Builder(new File(cityDatabasePath)).build(); }
Source:
public static List<ModeledSegment> makeCalls(final TargetCollection<TargetCoverage> targets, final List<ModeledSegment> segments, final double zThreshold) { Utils.nonNull(segments, "Can't make calls on a null list of segments."); Utils.nonNull(targets, "Can't make calls on a null list of targets."); ParamUtils.isPositiveOrZero(zThreshold, "zThreshold must be positive or zero."); final double nonExtremeCoverage = targets.targets() .stream() .mapToDouble(TargetCoverage::getCoverage) .filter(c -> c < NON_NEUTRAL_THRESHOLD_HIGH && c > NON_NEUTRAL_THRESHOLD_LOW) .toArray(); final double neutralCoverage = new Median().evaluate(nonExtremeCoverage); final double[] nearNeutralCoverage = segments.stream() .filter(s -> (SegmentUtils.meanTargetCoverage(s, targets) - neutralCoverage) < COPY_NEUTRAL_CUTOFF_HIGH && (SegmentUtils.meanTargetCoverage(s, targets) - neutralCoverage) > COPY_NEUTRAL_CUTOFF_LOW) .flatMap(s -> targets.targets(s).stream()) .mapToDouble(TargetCoverage::getCoverage) .toArray(); final double neutralSigma = new StandardDeviation().evaluate(nearNeutralCoverage); for (final ModeledSegment segment : segments) { final double Z = (SegmentUtils.meanTargetCoverage(segment, targets) - neutralCoverage)/neutralSigma; final String call = Z < -zThreshold ? DELETION_CALL: (Z > zThreshold ? AMPLIFICATION_CALL : NEUTRAL_CALL); segment.setCall(call); } return segments; }

Target:
public static List<ModeledSegment> makeCalls(final TargetCollection<TargetCoverage> targets, final List<ModeledSegment> segments, final double zThreshold) { Utils.nonNull(segments, "Can't make calls on a null list of segments."); Utils.nonNull(targets, "Can't make calls on a null list of targets."); ParamUtils.isPositiveOrZero(zThreshold, "zThreshold must be positive or zero."); final double nonExtremeCoverage = targets.targets() .stream() .mapToDouble(TargetCoverage::getCoverage) .filter(c -> Math.abs(c) < NON_NEUTRAL_THRESHOLD) .toArray(); final double neutralCoverage = new Median().evaluate(nonExtremeCoverage); final double[] nearNeutralCoverage = segments.stream() .filter(s -> Math.abs(SegmentUtils.meanTargetCoverage(s, targets) - neutralCoverage) < COPY_NEUTRAL_CUTOFF) .flatMap(s -> targets.targets(s).stream()) .mapToDouble(TargetCoverage::getCoverage) .toArray(); final double neutralSigma = new StandardDeviation().evaluate(nearNeutralCoverage); for (final ModeledSegment segment : segments) { final double Z = (SegmentUtils.meanTargetCoverage(segment, targets) - neutralCoverage)/neutralSigma; final String call = Z < -zThreshold ? DELETION_CALL: (Z > zThreshold ? AMPLIFICATION_CALL : NEUTRAL_CALL); segment.setCall(call); } return segments; }
Source:
private void initActivityLogUsingAppLogMessage(AppLogLine appLog, String[] tokens) { String actionName = tokens[POSITION_OF_ACTION_NAME]; String actionUrl = tokens[POSITION_OF_ACTION_URL]; long time = appLog.getTimeUsec() / 1000; Builder builder = new Builder(actionName, actionUrl, time); builder.withActionResponse(tokens[POSITION_OF_ACTION_RESPONSE]); builder.withLogId(tokens[POSITION_OF_LOG_ID]); builder.withLogMessage(tokens[POSITION_OF_LOG_MESSAGE]); builder.withMasqueradeUserRole(tokens[POSITION_OF_USER_ROLE].contains(Const.ActivityLog.ROLE_MASQUERADE_POSTFIX)); builder.withUserEmail(tokens[POSITION_OF_USER_EMAIL]); builder.withUserGoogleId(tokens[POSITION_OF_USER_GOOGLEID]); builder.withUserName(tokens[POSITION_OF_USER_NAME]); String userRole = tokens[POSITION_OF_USER_ROLE]; builder.withUserRole(userRole.replace(Const.ActivityLog.ROLE_MASQUERADE_POSTFIX, "")); try { long actionTimeTaken = tokens.length == ActivityLogEntry.POSITION_OF_LOG_TIMETAKEN + 1 ? Long.parseLong(tokens[ActivityLogEntry.POSITION_OF_LOG_TIMETAKEN].trim()) : 0; builder.withActionTimeTaken(actionTimeTaken); } catch (NumberFormatException e) { log.severe(String.format(Const.ActivityLog.MESSAGE_ERROR_LOG_MESSAGE_FORMAT, Arrays.toString(tokens))); } constructFromBuilder(builder); }

Target:
private static ActivityLogEntry initActivityLogUsingAppLogMessage(AppLogLine appLog, String[] tokens) { String actionName = tokens[POSITION_OF_ACTION_NAME]; String actionUrl = tokens[POSITION_OF_ACTION_URL]; long time = appLog.getTimeUsec() / 1000; Builder builder = new Builder(actionName, actionUrl, time); builder.withActionResponse(tokens[POSITION_OF_ACTION_RESPONSE]) .withLogId(tokens[POSITION_OF_LOG_ID]) .withLogMessage(tokens[POSITION_OF_LOG_MESSAGE]) .withMasqueradeUserRole( tokens[POSITION_OF_USER_ROLE].contains(Const.ActivityLog.ROLE_MASQUERADE_POSTFIX)) .withUserEmail(tokens[POSITION_OF_USER_EMAIL]) .withUserGoogleId(tokens[POSITION_OF_USER_GOOGLEID]) .withUserName(tokens[POSITION_OF_USER_NAME]); String userRole = tokens[POSITION_OF_USER_ROLE]; builder.withUserRole(userRole.replace(Const.ActivityLog.ROLE_MASQUERADE_POSTFIX, "")); try { long actionTimeTaken = tokens.length == ActivityLogEntry.POSITION_OF_LOG_TIMETAKEN + 1 ? Long.parseLong(tokens[ActivityLogEntry.POSITION_OF_LOG_TIMETAKEN].trim()) : 0; builder.withActionTimeTaken(actionTimeTaken); } catch (NumberFormatException e) { log.severe(String.format(Const.ActivityLog.MESSAGE_ERROR_LOG_MESSAGE_FORMAT, Arrays.toString(tokens))); } return builder.build(); }
Source:
public Cluster(String name, String region, Set<String> soloInstances) { Validate.notNull(name); Validate.notNull(region); Validate.notNull(autoScalingGroups); this.name = name; this.region = region; for (String soleInstance : soloInstances) { this.soloInstances.add(soleInstance); } }

Target:
public Cluster(String name, String region, Set<String> soloInstances) { Validate.notNull(name); Validate.notNull(region); Validate.notNull(soloInstances); this.name = name; this.region = region; for (String soleInstance : soloInstances) { this.soloInstances.add(soleInstance); } }
Source:
public String checkIPythonPrerequisite(String pythonExec) { ProcessBuilder processBuilder = new ProcessBuilder(pythonExec, "-m", "pip", "freeze"); File stderrFile = null; File stdoutFile = null; try { stderrFile = File.createTempFile("zeppelin", ".txt"); processBuilder.redirectError(stderrFile); stdoutFile = File.createTempFile("zeppelin", ".txt"); processBuilder.redirectOutput(stdoutFile); Process proc = processBuilder.start(); int ret = proc.waitFor(); if (ret != 0) { return "Fail to run pip freeze.\n" + IOUtils.toString(new FileInputStream(stderrFile)); } try (FileInputStream in = new FileInputStream(stdoutFile)) { String freezeOutput = IOUtils.toString(in); if (!freezeOutput.contains("jupyter-client=")) { return "jupyter-client is not installed."; } if (!freezeOutput.contains("ipykernel=")) { return "ipykernel is not installed"; } if (!freezeOutput.contains("ipython=")) { return "ipython is not installed"; } if (!freezeOutput.contains("grpcio=")) { return "grpcio is not installed"; } if (!freezeOutput.contains("protobuf=")) { return "protobuf is not installed"; } LOGGER.info("IPython prerequisite is met"); } } catch (Exception e) { LOGGER.warn("Fail to checkIPythonPrerequisite", e); return "Fail to checkIPythonPrerequisite: " + ExceptionUtils.getStackTrace(e); } finally { FileUtils.deleteQuietly(stderrFile); FileUtils.deleteQuietly(stdoutFile); } return ""; }

Target:
public String checkIPythonPrerequisite(String pythonExec) { ProcessBuilder processBuilder = new ProcessBuilder(pythonExec, "-m", "pip", "freeze"); try { File stderrFile = File.createTempFile("zeppelin", ".txt"); processBuilder.redirectError(stderrFile); File stdoutFile = File.createTempFile("zeppelin", ".txt"); processBuilder.redirectOutput(stdoutFile); Process proc = processBuilder.start(); int ret = proc.waitFor(); if (ret != 0) { return "Fail to run pip freeze.\n" + IOUtils.toString(new FileInputStream(stderrFile)); } String freezeOutput = IOUtils.toString(new FileInputStream(stdoutFile)); if (!freezeOutput.contains("jupyter-client=")) { return "jupyter-client is not installed."; } if (!freezeOutput.contains("ipykernel=")) { return "ipykernel is not installed"; } if (!freezeOutput.contains("ipython=")) { return "ipython is not installed"; } if (!freezeOutput.contains("grpcio=")) { return "grpcio is not installed"; } if (!freezeOutput.contains("protobuf=")) { return "protobuf is not installed"; } LOGGER.info("IPython prerequisite is met"); } catch (Exception e) { LOGGER.warn("Fail to checkIPythonPrerequisite", e); return "Fail to checkIPythonPrerequisite: " + ExceptionUtils.getStackTrace(e); } return ""; }
Source:
public ZipVaultPackage upload(InputStream in, boolean replace) throws IOException, PackageExistsException { MemoryArchive archive = new MemoryArchive(true); File tempFile = File.createTempFile("upload", ".zip"); InputStreamPump pump = new InputStreamPump(in , archive); try { try { FileUtils.copyInputStreamToFile(pump, tempFile); } catch (Exception e) { String msg = "Stream could be read successfully."; log.error(msg); throw new IOException(msg, e); } if (archive.getJcrRoot() == null) { String msg = "Stream is not a content package. Missing 'jcr_root'."; log.error(msg); throw new IOException(msg); } final MetaInf inf = archive.getMetaInf(); PackagePropertiesImpl props = new PackagePropertiesImpl() { @Override protected Properties getPropertiesMap() { return inf.getProperties(); } }; PackageId pid = props.getId(); if (pid == null) { pid = createRandomPid(); } if (!pid.isValid()) { throw new IllegalArgumentException("Unable to create package. Illegal package name."); } File oldPkgFile = getPackageFile(pid); String path = oldPkgFile.exists() ? oldPkgFile.getAbsolutePath() : getInstallationPath(pid); String name = Text.getName(path); if (oldPkgFile.exists()) { if (replace) { oldPkgFile.delete(); } else { throw new PackageExistsException("Package already exists: " + pid).setId(pid); } } ZipVaultPackage pkg = new ZipVaultPackage(archive, true); File pkgFile = getPackageFile(pid); FileUtils.moveFile(tempFile, pkgFile); dispatch(PackageEvent.Type.UPLOAD, pid, null); return pkg; } finally { pump.close(); } }

Target:
public ZipVaultPackage upload(InputStream in, boolean replace) throws IOException, PackageExistsException { MemoryArchive archive = new MemoryArchive(false); File tempFile = File.createTempFile("upload", ".zip"); try (InputStreamPump pump = new InputStreamPump(in, archive)) { try { FileUtils.copyInputStreamToFile(pump, tempFile); } catch (Exception e) { String msg = "Stream could be read successfully."; log.error(msg); throw new IOException(msg, e); } if (archive.getJcrRoot() == null) { String msg = "Stream is not a content package. Missing 'jcr_root'."; log.error(msg); throw new IOException(msg); } final MetaInf inf = archive.getMetaInf(); PackagePropertiesImpl props = new PackagePropertiesImpl() { @Override protected Properties getPropertiesMap() { return inf.getProperties(); } }; PackageId pid = props.getId(); if (pid == null) { throw new IllegalArgumentException("Unable to create package. No package pid set."); } if (!pid.isValid()) { throw new IllegalArgumentException("Unable to create package. Illegal package name."); } File oldPkgFile = getPackageFile(pid); FSInstallState state = getInstallState(pid); if (oldPkgFile != null && oldPkgFile.exists()) { if (replace && !state.isExternal()) { oldPkgFile.delete(); } else { throw new PackageExistsException("Package already exists: " + pid).setId(pid); } } ZipVaultPackage pkg = new ZipVaultPackage(archive, true); registerSubPackages(pkg, replace); File pkgFile = buildPackageFile(pid); FileUtils.moveFile(tempFile, pkgFile); dispatch(Type.UPLOAD, pid, null); return pkg; } }
Source:
public void createTable(final String tableName, final Set<String> columnFamilies, byte[][] splitKeys) { checkTableAndCf(tableName, columnFamilies); try (final Admin admin = _connection.getAdmin()) { final TableDescriptorBuilder tableBuilder = getTableDescriptorBuilder(tableName, columnFamilies); admin.createTable(tableBuilder.build(),splitKeys); } catch (IOException e) { throw new MetaModelException(e); } }

Target:
public void createTable(final String tableName, final Set<String> columnFamilies, byte[][] splitKeys) { checkTableAndColumnFamilies(tableName, columnFamilies); try (final Admin admin = _connection.getAdmin()) { final TableDescriptorBuilder tableBuilder = getTableDescriptorBuilder(tableName, columnFamilies); admin.createTable(tableBuilder.build(),splitKeys); } catch (IOException e) { throw new MetaModelException(e); } }
Source:
public void selectLocalRevision(long timeStamp){ IFileRevision entry = null; if (entries != null) { for (IFileRevision entrie : entries) { if (entrie.getTimestamp() == timeStamp) { entry = entrie; break; } } }else if (cvsFileHistory != null) { IFileRevision[] tempEntries = cvsFileHistory.getFileRevisions(); for (IFileRevision tempEntrie : tempEntries) { if (tempEntrie.getTimestamp() == timeStamp) { entry = tempEntrie; break; } } } if (entry != null) { IStructuredSelection selection = new StructuredSelection(entry); treeViewer.getTree().setRedraw(false); treeViewer.setSelection(selection, true); treeViewer.getTree().setRedraw(true); } else { treeViewer.getTree().deselectAll(); } }

Target:
public void selectLocalRevision(long timeStamp){ IFileRevision entry = null; if (entries != null) { for (IFileRevision e : entries) { if (e.getTimestamp() == timeStamp) { entry = e; break; } } }else if (cvsFileHistory != null) { IFileRevision[] tempEntries = cvsFileHistory.getFileRevisions(); for (IFileRevision tempEntry : tempEntries) { if (tempEntry.getTimestamp() == timeStamp) { entry = tempEntry; break; } } } if (entry != null) { IStructuredSelection selection = new StructuredSelection(entry); treeViewer.getTree().setRedraw(false); treeViewer.setSelection(selection, true); treeViewer.getTree().setRedraw(true); } else { treeViewer.getTree().deselectAll(); } }
Source:
private Builder merge(Builder other) { Optional<Currency> common = currencies.keySet() .stream() .filter(other.currencies::containsKey) .findFirst(); if (!common.isPresent()) { throw new IllegalArgumentException("There are no currencies in common between " + currencies.keySet() + " and " + other.currencies.keySet()); } Currency commonCurrency = common.get(); other.currencies.entrySet() .stream() .filter(e -> !e.getKey().equals(commonCurrency) && !currencies.containsKey(e.getKey())) .forEach(e -> addCurrencyPair(commonCurrency, e.getKey(), other.getRate(commonCurrency, e.getKey()))); return this; }

Target:
private Builder merge(Builder other) { Optional<Currency> common = currencies.keySet() .stream() .filter(other.currencies::containsKey) .findFirst(); Currency commonCurrency = common.orElseThrow(() -> new IllegalArgumentException("There are no currencies in common between " + currencies.keySet() + " and " + other.currencies.keySet())); other.currencies.entrySet() .stream() .filter(isNewCurrency(commonCurrency)) .forEach(e -> addCurrencyPair(commonCurrency, e.getKey(), other.getRate(commonCurrency, e.getKey()))); return this; }
Source:
public StubSchemaManagementWorkAssert matches(StubSchemaManagementWork expected) { ToStringTreeBuilder builder = new ToStringTreeBuilder( ToStringStyle.multilineDelimiterStructure() ); builder.startObject(); boolean hasAnyMismatch; boolean mismatch = checkForMismatch( builder, "type", expected.getType(), actual.getType() ); hasAnyMismatch = mismatch; builder.endObject(); if ( hasAnyMismatch ) { Assert.fail( messageBase + builder.toString() ); } return this; }

Target:
public StubSchemaManagementWorkAssert matches(StubSchemaManagementWork expected) { ToStringTreeBuilder builder = new ToStringTreeBuilder( ToStringStyle.multilineDelimiterStructure() ); builder.startObject(); boolean hasAnyMismatch = checkForMismatch( builder, "type", expected.getType(), actual.getType() ); builder.endObject(); if ( hasAnyMismatch ) { Assert.fail( messageBase + builder.toString() ); } return this; }
Source:
public void saveState(FileTailerState state) throws FileTailerStateProcessorException { createDirs(stateDirPath); LOG.debug("Start saving File Tailer state .."); try { FileOutputStream fileOut = new FileOutputStream(stateDirPath + "/" + stateFileName); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(state); out.close(); fileOut.close(); LOG.debug("File Tailer state saved successfully"); } catch (IOException e) { LOG.error("Can not save File Tailer state: {}", e.getMessage()); throw new FileTailerStateProcessorException(e.getMessage()); } }

Target:
public void saveState(FileTailerState state) throws FileTailerStateProcessorException { try { Preconditions.checkNotNull(state); } catch (NullPointerException e) { LOG.info("Cannot save null state"); return; } createDirs(stateDir); LOG.debug("Start saving File Tailer state .."); try { JsonWriter jsonWriter = new JsonWriter(Files.newWriter(stateFile, UTF_8)); try { GSON.toJson(state, FileTailerState.class, jsonWriter); LOG.debug("File Tailer state saved successfully"); } finally { try { jsonWriter.close(); } catch (IOException e) { LOG.error("Cannot close JSON Writer for file {}: {}", stateFile.getAbsolutePath(), e.getMessage(), e); } } } catch (IOException e) { LOG.error("Cannot close JSON Writer for file {}: {}", stateFile.getAbsolutePath(), e.getMessage(), e); } }
Source:
public static void setUser(@Nullable final byte[] idBytes, @Nullable final byte[] emailBytes, @Nullable final byte[] nameBytes) { String id = new String(idBytes, Charset.defaultCharset()); String email = new String(emailBytes, Charset.defaultCharset()); String name = new String(nameBytes, Charset.defaultCharset()); setUser(id, email, name); }

Target:
public static void setUser(@Nullable final byte[] idBytes, @Nullable final byte[] emailBytes, @Nullable final byte[] nameBytes) { String id = idBytes == null ? null : new String(idBytes, UTF8Charset); String email = emailBytes == null ? null : new String(emailBytes, UTF8Charset); String name = nameBytes == null ? null : new String(nameBytes, UTF8Charset); setUser(id, email, name); }
Source:
private boolean doRemove(Iterator<? extends Lifecycle> it, String storeType, Lifecycle wrapper, Lifecycle actual) { if (actual.getClass().getName().equals(storeType)) { wrapper.stop(); if (actual != wrapper) { actual.stop(); } it.remove(); return true; } return false; }

Target:
private void doRemove(Iterator<? extends Lifecycle> it, String storeType, Lifecycle wrapper, Lifecycle actual) { if (actual.getClass().getName().equals(storeType)) { wrapper.stop(); if (actual != wrapper) { actual.stop(); } it.remove(); storeStatuses.remove(wrapper); } }
Source:
public void testPackageSearch(@NugetRepository(storageId = STORAGE_ID, repositoryId = REPOSITORY_RELEASES_1) Repository repository, @NugetTestArtifact(storageId = STORAGE_ID, repositoryId = REPOSITORY_RELEASES_1, id = "Org.Carlspring.Strongbox.Nuget.Test.Search", versions = "1.0.0") Path packagePath) throws Exception { final String storageId = repository.getStorage().getId(); final String repositoryId = repository.getId(); String url = getContextBaseUrl() + "/storages/{storageId}/{repositoryId}/Search()/$count?searchTerm={searchTerm}&targetFramework="; mockMvc.header(HttpHeaders.USER_AGENT, "NuGet/*") .when() .get(url, storageId, repositoryId, "Test.Search") .then() .statusCode(HttpStatus.OK.value()) .and() .log().body() .and() .assertThat() .body(equalTo("1")); NugetArtifactCoordinates coordinates = (NugetArtifactCoordinates) RepositoryFiles.readCoordinates( (RepositoryPath) packagePath.normalize()); url = getContextBaseUrl() + "/storages/{storageId}/{repositoryId}/Search()?$skip={skip}&$top={stop}&searchTerm={searchTerm}&targetFramework="; MockMvcResponse response = mockMvc.header(HttpHeaders.USER_AGENT, "NuGet/*") .when() .get(url, storageId, repositoryId, 0, 30, "Test.Search") .then() .statusCode(HttpStatus.OK.value()) .extract().response(); XmlPath doc = new XmlPath(response.body().asString()); assertEquals(doc.getString("atom:feed.title"), "Packages"); assertEquals(doc.getString("atom:feed.entry[0].title"), coordinates.getId()); }

Target:
public void testPackageSearch(@NugetRepository(storageId = STORAGE_ID, repositoryId = REPOSITORY_RELEASES_1) Repository repository, @NugetTestArtifact(storageId = STORAGE_ID, repositoryId = REPOSITORY_RELEASES_1, id = "Org.Carlspring.Strongbox.Nuget.Test.Search", versions = "1.0.0") Path packagePath) throws Exception { final String storageId = repository.getStorage().getId(); final String repositoryId = repository.getId(); String url = getContextBaseUrl() + "/storages/{storageId}/{repositoryId}/Search()/$count?searchTerm={searchTerm}&targetFramework="; mockMvc.header(HttpHeaders.USER_AGENT, "NuGet/*") .when() .get(url, storageId, repositoryId, "Test.Search") .then() .statusCode(HttpStatus.OK.value()) .and() .log().body() .and() .assertThat() .body(equalTo("1")); NugetArtifactCoordinates coordinates = (NugetArtifactCoordinates) RepositoryFiles.readCoordinates( (RepositoryPath) packagePath.normalize()); url = getContextBaseUrl() + "/storages/{storageId}/{repositoryId}/Search()?$skip={skip}&$top={stop}&searchTerm={searchTerm}&targetFramework="; mockMvc.header(HttpHeaders.USER_AGENT, "NuGet/*") .when() .get(url, storageId, repositoryId, 0, 30, "Test.Search") .then() .statusCode(HttpStatus.OK.value()) .and() .assertThat() .body("feed.title", equalTo("Packages")) .and() .assertThat() .body("feed.entry[0].title", equalTo(coordinates.getId())); }
Source:
public void setup() { when(version.getValue()).thenReturn(CLUSTER_VERSION); when(osRepository.getNetworkDevices(0, any(Version.class))).thenReturn(NETWORK_DEVICES); when(osRepository.getNetworkDevices(0, null)).thenReturn(NETWORK_DEVICES); validator = new VmNicValidator(nic, version); validatorType = new VmNicValidator(nic, version, 0); }

Target:
public void setup() { when(version.getValue()).thenReturn(CLUSTER_VERSION); when(osRepository.getNetworkDevices(eq(0), any(Version.class))).thenReturn(NETWORK_DEVICES); SimpleDependecyInjector.getInstance().bind(OsRepository.class, osRepository); validator = new VmNicValidator(nic, version); validatorType = new VmNicValidator(nic, version, 0); }