auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void getDSObyIdentifier(HttpServletRequest request, HttpServletResponse response, @RequestParam(PARAM) UUID uuid) throws IOException, SQLException, SearchServiceException { Context context = null; try { context = ContextUtil.obtainContext(request); for (DSpaceObjectService dSpaceObjectService : contentServiceFactory.getDSpaceObjectServices()) { DSpaceObject dso = dSpaceObjectService.find(context, uuid); if (dso != null) { DSpaceObjectRest dsor = converter.convert(dso); URI link = linkTo(dsor.getController(), dsor.getCategory(), English.plural(dsor.getType())) .slash(dsor.getId()).toUri(); response.setStatus(HttpServletResponse.SC_FOUND); response.sendRedirect(link.toString()); return; } } response.setStatus(HttpServletResponse.SC_NOT_FOUND); } finally { context.abort(); } }

Target:
public void getDSObyIdentifier(HttpServletRequest request, HttpServletResponse response, @RequestParam(PARAM) UUID uuid) throws IOException, SQLException, SearchServiceException { Context context = null; try { context = ContextUtil.obtainContext(request); for (DSpaceObjectService dSpaceObjectService : contentServiceFactory.getDSpaceObjectServices()) { DSpaceObject dso = dSpaceObjectService.find(context, uuid); if (dso != null) { DSpaceObjectRest dsor = converter.convert(dso); URI link = linkTo(dsor.getController(), dsor.getCategory(), dsor.getTypePlural()) .slash(dsor.getId()).toUri(); response.setStatus(HttpServletResponse.SC_FOUND); response.sendRedirect(link.toString()); return; } } response.setStatus(HttpServletResponse.SC_NOT_FOUND); } finally { context.abort(); } }
Source:
public List<QuotaConsumptionParameter> getQuotaVdsConsumptionParameters() { List<QuotaConsumptionParameter> list = new ArrayList<QuotaConsumptionParameter>(); VM vm = DbFacade.getInstance().getVmDao().get(getVmToAttach(getParameters().getVmPoolId())); setStoragePoolId(vm.getStoragePoolId()); list.add(new QuotaVdsGroupConsumptionParameter(vm.getQuotaId(), null, QuotaConsumptionParameter.QuotaAction.CONSUME, vm.getVdsGroupId(), vm.getCpuPerSocket() * vm.getNumOfSockets(), vm.getMemSizeMb())); return list; }

Target:
public List<QuotaConsumptionParameter> getQuotaVdsConsumptionParameters() { List<QuotaConsumptionParameter> list = new ArrayList<QuotaConsumptionParameter>(); if (vmToAttach != null) { VM vm = getVmDAO().get(vmToAttach); setStoragePoolId(vm.getStoragePoolId()); list.add(new QuotaVdsGroupConsumptionParameter(vm.getQuotaId(), null, QuotaConsumptionParameter.QuotaAction.CONSUME, vm.getVdsGroupId(), vm.getCpuPerSocket() * vm.getNumOfSockets(), vm.getMemSizeMb())); } return list; }
Source:
public void configurePipeline(PipelineConfigurer pipelineConfigurer) throws IllegalArgumentException { super.configurePipeline(pipelineConfigurer); if (!S3_LOG.equals(config.logFormat) && !CLF_LOG.equals(config.logFormat) && !CLOUDFRONT_LOG.equals(config.logFormat)) { LOG.error("Log format not currently supported."); throw new IllegalStateException("Unsupported log format: " + config.logFormat); } Schema inputSchema = pipelineConfigurer.getStageConfigurer().getInputSchema(); if (inputSchema != null) { if (!validateInputSchemaType(inputSchema.getType())) { throw new IllegalArgumentException( String.format("Unsupported inputType in schema, only Schema.Type.BYTES and Schema.Type.STRING " + "are supported InputType: %s", inputSchema.getType().toString())); } } pipelineConfigurer.getStageConfigurer().setOutputSchema(LOG_SCHEMA); }

Target:
public void configurePipeline(PipelineConfigurer pipelineConfigurer) throws IllegalArgumentException { super.configurePipeline(pipelineConfigurer); if (!S3_LOG.equals(config.logFormat) && !CLF_LOG.equals(config.logFormat) && !CLOUDFRONT_LOG.equals(config.logFormat)) { LOG.error("Log format not currently supported."); throw new IllegalStateException("Unsupported log format: " + config.logFormat); } Schema inputSchema = pipelineConfigurer.getStageConfigurer().getInputSchema(); if (inputSchema != null) { if (!inputSchema.getType().equals(Schema.Type.RECORD)) { throw new IllegalArgumentException("Only Input Schema of type Schema.Type.RECORD is supported"); } Schema.Field inputNameSchema = inputSchema.getField(config.inputName); try { if (inputNameSchema != null && inputNameSchema.getSchema() != null) { validateInputSchemaType(inputNameSchema.getSchema().getType()); } } catch (IllegalArgumentException e) { LOG.error(e.getMessage()); throw Throwables.propagate(e); } } pipelineConfigurer.getStageConfigurer().setOutputSchema(LOG_SCHEMA); }
Source:
private void assambleApnsClientBuilder(final iOSVariant iOSVariant, final ApnsClientBuilder builder) { if (iOSVariant.getCertificate() != null && iOSVariant.getPassphrase() != null) { try (final ByteArrayInputStream stream = new ByteArrayInputStream(iOSVariant.getCertificate())) { builder.setClientCredentials(stream, iOSVariant.getPassphrase()); if (ProxyConfiguration.hasHttpProxyConfig()) { if (ProxyConfiguration.hasBasicAuth()) { String user = ProxyConfiguration.getProxyUser(); String pass = ProxyConfiguration.getProxyPass(); builder.setProxyHandlerFactory( new HttpProxyHandlerFactory(ProxyConfiguration.proxyAddress(), user, pass)); } else { builder.setProxyHandlerFactory(new HttpProxyHandlerFactory(ProxyConfiguration.proxyAddress())); } } else if (ProxyConfiguration.hasSocksProxyConfig()) { builder.setProxyHandlerFactory(new Socks5ProxyHandlerFactory(ProxyConfiguration.socks())); } } catch (Exception e) { logger.error("Error reading certificate", e); } } throw new IllegalArgumentException("Not able to construct APNS client"); }

Target:
private void assambleApnsClientBuilder(final iOSVariant iOSVariant, final ApnsClientBuilder builder) { if (iOSVariant.getCertificate() != null && iOSVariant.getPassphrase() != null) { try (final ByteArrayInputStream stream = new ByteArrayInputStream(iOSVariant.getCertificate())) { builder.setClientCredentials(stream, iOSVariant.getPassphrase()); if (ProxyConfiguration.hasHttpProxyConfig()) { if (ProxyConfiguration.hasBasicAuth()) { String user = ProxyConfiguration.getProxyUser(); String pass = ProxyConfiguration.getProxyPass(); builder.setProxyHandlerFactory( new HttpProxyHandlerFactory(ProxyConfiguration.proxyAddress(), user, pass)); } else { builder.setProxyHandlerFactory(new HttpProxyHandlerFactory(ProxyConfiguration.proxyAddress())); } } else if (ProxyConfiguration.hasSocksProxyConfig()) { builder.setProxyHandlerFactory(new Socks5ProxyHandlerFactory(ProxyConfiguration.socks())); } return; } catch (Exception e) { logger.error("Error reading certificate", e); } } throw new IllegalArgumentException("Not able to construct APNS client"); }
Source:
public String[] getContext(String document) { Collection<String> context = new LinkedList<>(); NGramModel model = new NGramModel(); model.add(document, minLength, maxLength); for (StringList tokenList : model) { if (tokenList.size() > 0) { context.add("ng=" + StringUtil.toLowerCase(tokenList.getToken(0))); } } return context.toArray(new String[context.size()]); }

Target:
public String[] getContext(String document) { Collection<String> context = new LinkedList<>(); NGramModel model = new NGramModel(); String normalized = normalizer.normalize(document).toString(); model.add(normalized, minLength, maxLength); for (StringList tokenList : model) { if (tokenList.size() > 0) { context.add("ng=" + StringUtil.toLowerCase(tokenList.getToken(0))); } } return context.toArray(new String[context.size()]); }
Source:
private void onDomRetrieved(String dom) { webView.loadDataWithBaseURL( wikiUrl, ((("<head>" + Wiki.getGlobalCustomCss()) + Wiki.getGlobalCustomJavaScript()) + "</head>") + dom, "text/html", "utf-8", null); }

Target:
private void onDomRetrieved(String dom) { webView.loadDataWithBaseURL( wikiUrl, "<head>" + Wiki.getGlobalCustomCss() + Wiki.getGlobalCustomJavaScript() + "</head>" + dom, "text/html", "utf-8", null); }
Source:
private String parseDuration() { NumberFormat formatter = new DecimalFormat("00"); int hours = (int) Math.floor(duration / 3600); int minutes = (int) Math.floor(duration / 60 % 60); int seconds = (int) Math.floor(duration % 60); return String.format("%s:%s:%s", formatter.format(hours), formatter.format(minutes), formatter.format(seconds)); }

Target:
private String parseDuration() { NumberFormat formatter = new DecimalFormat("00"); int hours = (int) Math.floor(duration / 3600), minutes = (int) Math.floor(duration / 60 % 60), seconds = (int) Math.floor(duration % 60); return String.format("%s:%s:%s", formatter.format(hours), formatter.format(minutes), formatter.format(seconds)); }
Source:
@Test public void computationSchedulerUsesSuppliedThreadFactory() throws InterruptedException { final AtomicReference<Thread> threadRef = new AtomicReference<Thread>(); ThreadFactory threadFactory = new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread thread = new Thread(r); threadRef.set(thread); return thread; } }; Scheduler scheduler = RxJavaSchedulersHook.createComputationScheduler(threadFactory); Worker worker = scheduler.createWorker(); final CountDownLatch latch = new CountDownLatch(1); worker.schedule(new Action0() { @Override public void call() { assertSame(threadRef.get(), Thread.currentThread()); latch.countDown(); } }); assertTrue(latch.await(10, SECONDS)); }

Target:
@Test public void computationSchedulerUsesSuppliedThreadFactory() throws InterruptedException { final AtomicReference<Thread> threadRef = new AtomicReference<Thread>(); ThreadFactory threadFactory = new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread thread = new Thread(r); threadRef.set(thread); return thread; } }; Scheduler scheduler = RxJavaSchedulersHook.createComputationScheduler(threadFactory); Worker worker = scheduler.createWorker(); final CountDownLatch latch = new CountDownLatch(1); worker.schedule(new Action0() { @Override public void call() { assertSame(threadRef.get(), Thread.currentThread()); latch.countDown(); } }); assertTrue(latch.await(10, SECONDS)); if (scheduler instanceof SchedulerLifecycle) { ((SchedulerLifecycle) scheduler).shutdown(); } }
Source:
public int read() throws IOException { try { return this.blobInputStream.read(); } catch (RuntimeException e) { if (e.getMessage().equals(Constants.STREAM_CLOSED)) { throw LoggingUtility.logError(logger, new IOException(e)); } throw LoggingUtility.logError(logger, e); } }

Target:
public int read() throws IOException { try { return this.blobInputStream.read(); } catch (RuntimeException e) { throw LoggingUtility.logError(logger, new IOException(e)); } }
Source:
public void refreshDetails(GlusterVolumeEntity volumeEntity) { AsyncDataProvider.getGlusterRemoveBricksStatus(new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object model, Object returnValue) { VdcQueryReturnValue vdcValue = (VdcQueryReturnValue) returnValue; GlusterVolumeTaskStatusEntity statusEntity = vdcValue.getReturnValue(); if (statusEntity != null) { showStatus(statusEntity); } else { cancelRefresh(); } } }), volumeEntity.getClusterId(), volumeEntity.getId(), getBricks()); }

Target:
public void refreshDetails(GlusterVolumeEntity volumeEntity) { AsyncDataProvider.getGlusterRemoveBricksStatus(new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object model, Object returnValue) { VdcQueryReturnValue vdcValue = (VdcQueryReturnValue) returnValue; GlusterVolumeTaskStatusEntity statusEntity = vdcValue.getReturnValue(); if (statusEntity != null) { showStatus(statusEntity); } } }), volumeEntity.getClusterId(), volumeEntity.getId(), getBricks()); }
Source:
public QueueSet getQueueSet(TaskPriority priority) { switch (priority) { case High: return highPriorityQueueSet; case Low: return lowPriorityQueueSet; default: throw new UnsupportedOperationException(); } }

Target:
public QueueSet getQueueSet(TaskPriority priority) { if (priority == TaskPriority.High) { return highPriorityQueueSet; } else { return lowPriorityQueueSet; } }
Source:
private List<String> toList(String list) { list = list.trim(); if(list.length()==0) return Collections.emptyList(); return Arrays.asList(list.split("<file/>")); }

Target:
private List<String> toList(String list) { list = list.trim(); if(list.length()==0) return Collections.emptyList(); return Arrays.asList(list.split(list.contains("<file/>") ? "<file/>" : " ")); }
Source:
public void testDeleteSupplementaryFolder() { ITmfTrace trace = fTrace; assertNotNull(trace); String suppFilesPath = TmfTraceManager.getSupplementaryFileDir(trace); try { assertFalse(isDirectoryEmpty(suppFilesPath)); trace.dispose(); TmfTraceManager.deleteSupplementaryFolder(trace); File parent = new File(suppFilesPath); assertFalse(parent.exists()); } catch (IOException e) { fail(e.getMessage()); } }

Target:
public void testDeleteSupplementaryFolder() throws IOException { ITmfTrace trace = fTrace; assertNotNull(trace); String suppFilesPath = TmfTraceManager.getSupplementaryFileDir(trace); assertFalse(isDirectoryEmpty(suppFilesPath)); trace.dispose(); TmfTraceManager.deleteSupplementaryFolder(trace); File parent = new File(suppFilesPath); assertFalse(parent.exists()); }
Source:
void runOnce() { if (transactionManager != null) { try { transactionManager.resetProducerIdIfNeeded(); if (!transactionManager.isTransactional()) { maybeWaitForProducerId(); } else if (transactionManager.hasUnresolvedSequences() && !transactionManager.hasFatalError()) { transactionManager.transitionToFatalError( new KafkaException("The client hasn't received acknowledgment for " + "some previously sent messages and can no longer retry them. It isn't safe to continue.")); } else if (transactionManager.hasInFlightTransactionalRequest()) { client.poll(retryBackoffMs, time.milliseconds()); return; } maybeBeginFlush(); TransactionManager.TxnRequestHandler nextRequestHandler = transactionManager.nextRequestHandler(accumulator.hasIncomplete()); if (nextRequestHandler != null) { if (maybeSendTransactionalRequest(nextRequestHandler)) { client.poll(retryBackoffMs, time.milliseconds()); } return; } if (transactionManager.hasFatalError() || !transactionManager.hasProducerId()) { RuntimeException lastError = transactionManager.lastError(); if (lastError != null) maybeAbortBatches(lastError); client.poll(retryBackoffMs, time.milliseconds()); return; } else if (transactionManager.hasAbortableError()) { accumulator.abortUndrainedBatches(transactionManager.lastError()); } } catch (AuthenticationException e) { log.trace("Authentication exception while processing transactional request: {}", e); transactionManager.authenticationFailed(e); } } long currentTimeMs = time.milliseconds(); long pollTimeout = sendProducerData(currentTimeMs); client.poll(pollTimeout, currentTimeMs); }

Target:
void runOnce() { if (transactionManager != null) { try { transactionManager.resetProducerIdIfNeeded(); if (!transactionManager.isTransactional()) { maybeWaitForProducerId(); } else if (transactionManager.hasUnresolvedSequences() && !transactionManager.hasFatalError()) { transactionManager.transitionToFatalError( new KafkaException("The client hasn't received acknowledgment for " + "some previously sent messages and can no longer retry them. It isn't safe to continue.")); } else if (maybeSendAndPollTransactionalRequest()) { return; } if (transactionManager.hasFatalError() || !transactionManager.hasProducerId()) { RuntimeException lastError = transactionManager.lastError(); if (lastError != null) maybeAbortBatches(lastError); client.poll(retryBackoffMs, time.milliseconds()); return; } else if (transactionManager.hasAbortableError()) { accumulator.abortUndrainedBatches(transactionManager.lastError()); } } catch (AuthenticationException e) { log.trace("Authentication exception while processing transactional request: {}", e); transactionManager.authenticationFailed(e); } } long currentTimeMs = time.milliseconds(); long pollTimeout = sendProducerData(currentTimeMs); client.poll(pollTimeout, currentTimeMs); }
Source:
public boolean apply(Entity entity) throws WorldEditException { BaseEntity state = entity.getState(); if (state != null) { Location newLocation; Location location = entity.getLocation(); Vector3 pivot = from.round().add(0.5, 0.5, 0.5); Vector3 newPosition = transform.apply(location.toVector().subtract(pivot)); Vector3 newDirection; newDirection = transform.isIdentity() ? entity.getLocation().getDirection() : transform.apply(location.getDirection()).subtract(transform.apply(Vector3.ZERO)).normalize(); newLocation = new Location(destination, newPosition.add(to.round().add(0.5, 0.5, 0.5)), newDirection); state = transformNbtData(state); if (state.getType() == EntityTypes.PAINTING) { CompoundTag tag = state.getNbtData(); if (tag != null) { boolean hasTilePosition = tag.containsKey("TileX") && tag.containsKey("TileY") && tag.containsKey("TileZ"); if (hasTilePosition) { newLocation = new Location(destination, tag.asInt("TileX"), tag.asInt("TileY"), tag.asInt("TileZ")); } } } boolean success = destination.createEntity(newLocation, state) != null; if (isRemoving() && success) { entity.remove(); } return success; } else { return false; } }

Target:
public boolean apply(Entity entity) throws WorldEditException { BaseEntity state = entity.getState(); if (state != null) { Location newLocation; Location location = entity.getLocation(); CompoundTag tag = state.getNbtData(); boolean hasTilePosition = tag != null && tag.containsKey("TileX") && tag.containsKey("TileY") && tag.containsKey("TileZ"); if (hasTilePosition) { location = location.setPosition(Vector3.at(tag.asInt("TileX"), tag.asInt("TileY"), tag.asInt("TileZ")).add(0.5, 0.5, 0.5)); } Vector3 pivot = from.round().add(0.5, 0.5, 0.5); Vector3 newPosition = transform.apply(location.toVector().subtract(pivot)); if (hasTilePosition) { newPosition = newPosition.subtract(0.5, 0.5, 0.5); } Vector3 newDirection; newDirection = transform.isIdentity() ? entity.getLocation().getDirection() : transform.apply(location.getDirection()).subtract(transform.apply(Vector3.ZERO)).normalize(); newLocation = new Location(destination, newPosition.add(to.round().add(0.5, 0.5, 0.5)), newDirection); state = transformNbtData(state); boolean success = destination.createEntity(newLocation, state) != null; if (isRemoving() && success) { entity.remove(); } return success; } else { return false; } }
Source:
Map<ConnectionInfo, ConnectionState> getCurrentConnections(final InputStream in) throws IOException { final Map<ConnectionInfo, ConnectionState> connectionToState = new HashMap<>(); try (final BufferedReader reader = new BufferedReader(new InputStreamReader(in))) { reader.readLine(); String line; while (null != (line = reader.readLine())) { final StringTokenizer tokenizer = new StringTokenizer(line); tokenizer.nextToken(); try { final String[] localAddress = tokenizer.nextToken().split(":"); final int localPort = Integer.parseInt(localAddress[1], 16); if (localPort != port) { continue; } final String[] remoteAddressPair = tokenizer.nextToken().split(":"); final InetAddress[] remoteAddresses = restoreAddresses(remoteAddressPair[0]); final int remotePort = Integer.parseInt(remoteAddressPair[1], 16); final ConnectionState connectionState = ConnectionState.fromCode(tokenizer.nextToken()); for (final InetAddress tmp : remoteAddresses) { connectionToState.put(new ConnectionInfo(tmp, remotePort), connectionState); } } catch (DecoderException | RuntimeException ex) { LOG.error("Failed to parse line, skipping: " + line, ex); } } } return connectionToState; }

Target:
Map<ConnectionInfo, ConnectionState> getCurrentConnections(final InputStream in) throws IOException { final Map<ConnectionInfo, ConnectionState> connectionToState = new HashMap<>(); try (final BufferedReader reader = new BufferedReader(new InputStreamReader(in))) { reader.readLine(); String line; while (null != (line = reader.readLine())) { final StringTokenizer tokenizer = new StringTokenizer(line); tokenizer.nextToken(); try { final String[] localAddress = tokenizer.nextToken().split(":"); final int localPort = Integer.parseInt(localAddress[1], 16); if (localPort != port) { continue; } final String[] remoteAddressPair = tokenizer.nextToken().split(":"); final InetAddress[] remoteAddresses = restoreAddresses(remoteAddressPair[0]); final int remotePort = Integer.parseInt(remoteAddressPair[1], 16); final ConnectionState connectionState = ConnectionState.fromCode(tokenizer.nextToken()); Stream.of(remoteAddresses) .map(address -> new ConnectionInfo(address, remotePort)) .forEach(info -> connectionToState.put(info, connectionState)); } catch (final DecoderException | RuntimeException ex) { LOG.error("Failed to parse line, skipping: " + line, ex); } } } return connectionToState; }
Source:
public void batchErrorReporting() throws SQLException { final int maxRetries = 2; final int retryBackoffMs = 1000; final int batchSize = 3; List<SinkRecord> records = new ArrayList<>(); SinkRecord record = new SinkRecord("stub", 0, null, null, null, null, 0); for (int i = 0; i < batchSize; i++) { records.add(record); } final JdbcDbWriter mockWriter = createMock(JdbcDbWriter.class); SinkTaskContext ctx = createMock(SinkTaskContext.class); mockWriter.write(records); SQLException exception = new SQLException("cause 1"); expectLastCall().andThrow(exception); mockWriter.write(anyObject()); expectLastCall().andThrow(exception).times(batchSize); JdbcSinkTask task = new JdbcSinkTask() { @Override void initWriter() { this.writer = mockWriter; } }; task.initialize(ctx); ErrantRecordReporter reporter = createMock(ErrantRecordReporter.class); expect(ctx.errantRecordReporter()).andReturn(reporter); expect(reporter.report(anyObject(), anyObject())).andReturn(createMock(Future.class)).times(batchSize); replayAll(); Map<String, String> props = new HashMap<>(); props.put(JdbcSinkConfig.CONNECTION_URL, "stub"); props.put(JdbcSinkConfig.MAX_RETRIES, String.valueOf(maxRetries)); props.put(JdbcSinkConfig.RETRY_BACKOFF_MS, String.valueOf(retryBackoffMs)); task.start(props); task.put(records); verifyAll(); }

Target:
public void batchErrorReporting() throws SQLException { final int maxRetries = 2; final int retryBackoffMs = 1000; final int batchSize = 3; List<SinkRecord> records = new ArrayList<>(); SinkRecord record = new SinkRecord("stub", 0, null, null, null, null, 0); for (int i = 0; i < batchSize; i++) { records.add(record); } final JdbcDbWriter mockWriter = createMock(JdbcDbWriter.class); SinkTaskContext ctx = createMock(SinkTaskContext.class); mockWriter.write(records); SQLException exception = new SQLException("cause 1"); expectLastCall().andThrow(exception); mockWriter.write(anyObject()); expectLastCall().andThrow(exception).times(batchSize); JdbcSinkTask task = new JdbcSinkTask() { @Override void initWriter() { this.writer = mockWriter; } }; task.initialize(ctx); ErrantRecordReporter reporter = createMock(ErrantRecordReporter.class); expect(ctx.errantRecordReporter()).andReturn(reporter); expect(reporter.report(anyObject(), anyObject())).andReturn(CompletableFuture.completedFuture(null)).times(batchSize); replayAll(); Map<String, String> props = new HashMap<>(); props.put(JdbcSinkConfig.CONNECTION_URL, "stub"); props.put(JdbcSinkConfig.MAX_RETRIES, String.valueOf(maxRetries)); props.put(JdbcSinkConfig.RETRY_BACKOFF_MS, String.valueOf(retryBackoffMs)); task.start(props); task.put(records); verifyAll(); }
Source:
UndeleteOperation(ClusterMap clusterMap, RouterConfig routerConfig, NonBlockingRouterMetrics routerMetrics, BlobId blobId, String serviceId, long operationTimeMs, Callback<Void> callback, Time time, FutureResult<Void> futureResult) { this.routerConfig = routerConfig; this.routerMetrics = routerMetrics; this.blobId = blobId; this.serviceId = serviceId; this.futureResult = futureResult; this.callback = callback; this.time = time; this.operationTimeMs = operationTimeMs; byte blobDcId = blobId.getDatacenterId(); String originatingDcName = clusterMap.getDatacenterName(blobDcId); this.operationTracker = new UndeleteOperationTracker(routerConfig, blobId.getPartition(), originatingDcName); }

Target:
UndeleteOperation(ClusterMap clusterMap, RouterConfig routerConfig, NonBlockingRouterMetrics routerMetrics, BlobId blobId, String serviceId, long operationTimeMs, Callback<Void> callback, Time time, FutureResult<Void> futureResult) { this.routerConfig = routerConfig; this.routerMetrics = routerMetrics; this.blobId = blobId; this.serviceId = serviceId; this.futureResult = futureResult; this.callback = callback; this.time = time; this.operationTimeMs = operationTimeMs; this.operationTracker = new UndeleteOperationTracker(routerConfig, blobId.getPartition(), clusterMap.getDatacenterName(blobId.getDatacenterId())); }
Source:
public void setUp() throws Exception { initMocks(this); when(dbHandlerMock.getGlucoseReading(anyLong())).thenReturn(glucoseReadingMock); when(glucoseReadingMock.getNotes()).thenReturn(MOCK_NOTE_FOR_TEST); when(glucoseReadingMock.getCreated()).thenReturn(new Date(System.currentTimeMillis())); when(glucoseReadingMock.getReading()).thenReturn(TEST_READING_VALUE); }

Target:
public void setUp() throws Exception { initMocks(this); when(dbHandlerMock.getGlucoseReading(anyLong())).thenReturn(glucoseReadingMock); when(glucoseReadingMock.getNotes()).thenReturn(MOCK_NOTE_FOR_TEST); when(glucoseReadingMock.getCreated()).thenReturn(new Date()); when(glucoseReadingMock.getReading()).thenReturn(TEST_READING_VALUE); }
Source:
public boolean setScannerEnabled(final IServer server, String scannerName, boolean enabled) { ModelNode op = new ModelNode(); op.get("operation").set("write-attribute"); op.get("name").set("scan-enabled"); op.get("value").set(enabled); ModelNode addr = op.get("address"); addr.add("subsystem", "deployment-scanner"); addr.add("scanner", scannerName); final String request = op.toJSONString(true); try { executeWithResult(server, request); } catch(Exception e) { return false; } return true; }

Target:
public boolean setScannerEnabled(final IServer server, String scannerName, boolean enabled) { ModelNode op = new ModelNode(); op.get("operation").set("write-attribute"); op.get("name").set("scan-enabled"); op.get("value").set(enabled); ModelNode addr = op.get("address"); addr.add("subsystem", "deployment-scanner"); addr.add("scanner", scannerName); final String request = op.toJSONString(true); try { executeWithResult(server, request); } catch(Exception e) { JBossServerCorePlugin.log(e); return false; } return true; }
Source:
Map<String, String> fetchAccountMetadata() { long startTimeMs = System.currentTimeMillis(); logger.trace("Start reading ZNRecord from path={}", znRecordPath); ZNRecord znRecord = helixStore.get(znRecordPath, null, AccessOption.PERSISTENT); logger.trace("Fetched ZNRecord from path={}, took time={} ms", znRecordPath, startTimeMs); if (znRecord == null) { logger.info("The ZNRecord to read does not exist on path={}", znRecordPath); return null; } Map<String, String> newAccountMap = fetchAccountMetadataFromZNRecord(znRecord); backupFileManager.persistState(newAccountMap, znRecord); return newAccountMap; }

Target:
Map<String, String> fetchAccountMetadata() { long startTimeMs = System.currentTimeMillis(); logger.trace("Start reading ZNRecord from path={}", znRecordPath); Stat stat = new Stat(); ZNRecord znRecord = helixStore.get(znRecordPath, stat, AccessOption.PERSISTENT); logger.trace("Fetched ZNRecord from path={}, took time={} ms", znRecordPath, System.currentTimeMillis() - startTimeMs); if (znRecord == null) { logger.info("The ZNRecord to read does not exist on path={}", znRecordPath); return null; } Map<String, String> newAccountMap = fetchAccountMetadataFromZNRecord(znRecord); if (newAccountMap != null) { backupFileManager.persistAccountMap(newAccountMap, stat); } return newAccountMap; }
Source:
public CompactionDetails getCompactionDetails(long totalCapacity, long usedCapacity, long segmentCapacity, long segmentHeaderSize, List<String> logSegmentsNotInJournal, BlobStoreStats blobStoreStats, String dataDir) throws StoreException { String storeId = blobStoreStats.getStoreId(); CompactionPolicySwitchInfo compactionPolicySwitchInfo = blobToCompactionPolicySwitchInfoMap.getOrDefault(storeId, new CompactionPolicySwitchInfo(new CompactionPolicyCounter(storeConfig), INIT_COMPACT_ALL_TIME)); blobToCompactionPolicySwitchInfoMap.put(storeId, compactionPolicySwitchInfo); CompactionPolicy selectCompactionPolicy = selectCompactionPolicyAndUpdateCompactionPolicySwitchInfo(dataDir, storeId, compactionPolicySwitchInfo); logger.info("Current compaction policy is : {}", selectCompactionPolicy); backUpCompactionPolicyInfo(dataDir, storeId, compactionPolicySwitchInfo); compactionPolicySwitchInfo.getCompactionPolicyCounter().increment(); return selectCompactionPolicy.getCompactionDetails(totalCapacity, usedCapacity, segmentCapacity, segmentHeaderSize, logSegmentsNotInJournal, blobStoreStats, null); }

Target:
public CompactionDetails getCompactionDetails(long totalCapacity, long usedCapacity, long segmentCapacity, long segmentHeaderSize, List<String> logSegmentsNotInJournal, BlobStoreStats blobStoreStats, String dataDir) throws StoreException { String storeId = blobStoreStats.getStoreId(); CompactionPolicySwitchInfo compactionPolicySwitchInfo = getCompactionPolicySwitchInfo(storeId, dataDir, blobStoreStats); CompactionPolicy selectCompactionPolicy = selectCompactionPolicyAndUpdateCompactionPolicySwitchInfo(compactionPolicySwitchInfo, storeId, dataDir); logger.info("Current compaction policy is : for store : {}, dataDir : {}", selectCompactionPolicy, storeId, dataDir); compactionPolicySwitchInfo.getCompactionPolicyCounter().increment(); backUpCompactionPolicyInfo(dataDir, compactionPolicySwitchInfo); return selectCompactionPolicy.getCompactionDetails(totalCapacity, usedCapacity, segmentCapacity, segmentHeaderSize, logSegmentsNotInJournal, blobStoreStats, dataDir); }
Source:
private void checkWorkDirectory() throws RuntimeConfigurationError { if (myWorkDirectory != null && !myWorkDirectory.isEmpty()) { File dir = new File(myWorkDirectory); try { if (!dir.isDirectory()) { throw new RuntimeConfigurationError("Incorrect path to working directory."); } } catch (SecurityException e) { throw new RuntimeConfigurationError("Access denied to working directory"); } } }

Target:
private void checkWorkDirectory() throws RuntimeConfigurationError { if (StringUtil.isNotEmpty(myWorkDirectory)) { File dir = new File(myWorkDirectory); try { if (!dir.isDirectory()) { throw new RuntimeConfigurationError("Incorrect path to working directory."); } } catch (SecurityException e) { throw new RuntimeConfigurationError("Access denied to working directory"); } } }
Source:
@Override public void end(Xid xid, int flags) { assert this.xid.equals(xid); if (log.isDebugEnabled()) log.debug("XA resource end(...) [xid=" + xid + ", flags=<" + flags(flags) + ">]"); if ((flags & TMSUSPEND) == TMSUSPEND) { cacheTx.stop(); } else if ((flags & TMFAIL) > 0) { cacheTx.setRollbackOnly(); } }

Target:
@Override public void end(Xid xid, int flags) throws XAException { assert this.xid.equals(xid); if (log.isDebugEnabled()) log.debug("XA resource end(...) [xid=" + xid + ", flags=<" + flags(flags) + ">]"); if ((flags & TMSUSPEND) == TMSUSPEND) try { cacheTx.suspend(); } catch (Exception e) { throwException("Failed to suspend cache transaction: " + e.getMessage(), e); } else if ((flags & TMFAIL) > 0) cacheTx.setRollbackOnly(); }
Source:
private ContentResponse execute(Request req) { logger.debug("Sending HTTP request: {}", req.getMethod(), safeUri(req)); ContentResponse res = send(req); logger.debug("Received HTTP response: {}: {}", req.getMethod(), safeUri(req), res); if (HttpStatus.isSuccess(res.getStatus())) { return res; } else if (HttpStatus.isRedirection(res.getStatus())) { return res; } else if (HttpStatus.isClientError(res.getStatus())) { throw new TaskExecutionException("HTTP 4XX Client Error: " + requestStatus(req, res), ConfigElement.empty()); } else if (res.getStatus() >= 500 && res.getStatus() < 600) { throw new RuntimeException("HTTP 5XX Server Error: " + requestStatus(req, res)); } else { throw new RuntimeException("Unexpected HTTP status: " + requestStatus(req, res)); } }

Target:
private ContentResponse execute(Request req) { URI safeUri = safeUri(req); logger.debug("Sending HTTP request: {}", req.getMethod(), safeUri); ContentResponse res = send(req); logger.debug("Received HTTP response: {}: {}", req.getMethod(), safeUri, res); if (HttpStatus.isSuccess(res.getStatus())) { return res; } else if (HttpStatus.isRedirection(res.getStatus())) { return res; } else if (HttpStatus.isClientError(res.getStatus())) { switch (res.getStatus()) { case HttpStatus.REQUEST_TIMEOUT_408: case HttpStatus.TOO_MANY_REQUESTS_429: throw new RuntimeException("Failed HTTP request: " + requestStatus(req, res)); default: throw new TaskExecutionException("HTTP 4XX Client Error: " + requestStatus(req, res), ConfigElement.empty()); } } else if (res.getStatus() >= 500 && res.getStatus() < 600) { throw ephemeralError("HTTP 5XX Server Error: " + requestStatus(req, res)); } else { throw ephemeralError("Unexpected HTTP status: " + requestStatus(req, res)); } }
Source:
private Object doResumableUpload() throws IOException { String uploadId = startResumableUpload(); InsertChunkResponseObserver responseObserver; long writeOffset = 0; int retriesAttempted = 0; Hasher objectHasher = Hashing.crc32c().newHasher(); do { List<InsertObjectRequest.Builder> requestList = new ArrayList<>(); responseObserver = new InsertChunkResponseObserver(uploadId, writeOffset, objectHasher, requestList); stub.withDeadlineAfter(WRITE_STREAM_TIMEOUT.toMillis(), MILLISECONDS) .insertObject(responseObserver); try { responseObserver.done.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException( String.format("Resumable upload failed for '%s'", getResourceString()), e); } if (responseObserver.hasTransientError()) { writeOffset = getCommittedWriteSize(uploadId); } else { writeOffset += responseObserver.bytesWritten(); } } while (!responseObserver.hasFinalized()); return responseObserver.getResponseOrThrow(); }

Target:
private Object doResumableUpload() throws IOException { String uploadId = startResumableUpload(); InsertChunkResponseObserver responseObserver; long writeOffset = 0; int retriesAttempted = 0; Hasher objectHasher = Hashing.crc32c().newHasher(); TreeMap<Long, ByteString> dataChunkMap = new TreeMap<>(); do { responseObserver = new InsertChunkResponseObserver(uploadId, writeOffset, objectHasher, dataChunkMap); stub.withDeadlineAfter(WRITE_STREAM_TIMEOUT.toMillis(), MILLISECONDS) .insertObject(responseObserver); try { responseObserver.done.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException( String.format("Resumable upload failed for '%s'", getResourceString()), e); } if (responseObserver.hasTransientError()) { writeOffset = getCommittedWriteSize(uploadId); ++retriesAttempted; } else { writeOffset += responseObserver.bytesWritten(); retriesAttempted = 0; } if (retriesAttempted >= UPLOAD_RETRIES) { throw new IOException( String.format( "Too many retry attempts. Resumable upload failed for '%s'", resourceId)); } } while (!responseObserver.hasFinalized()); return responseObserver.getResponseOrThrow(); }
Source:
public void testConvertDs3RequestWithoutRequestPayload() { final Request testRequest = RequestConverter.toRequest( new Ds3Request("CreateBucketRequestHandler", HttpVerb.PUT, Classification.amazons3, Requirement.REQUIRED, Requirement.NOT_ALLOWED, null, null, null, null, false, null, ImmutableList.of(), ImmutableList.of())); assertFalse(testRequest.hasRequestPayload()); assertEquals(testRequest.getRequestPayload(), null); }

Target:
public void testConvertDs3RequestWithoutRequestPayload() { final Request testRequest = RequestConverter.toRequest(Ds3ModelFixtures.createBucketRequest()); assertFalse(testRequest.hasRequestPayload()); assertEquals(testRequest.getRequestPayload(), null); }
Source:
public void testSequentialCommand() throws Exception { final int NB_DOCS = 10; final int NB_COMMANDS = 10; for (int i = 0; i < NB_DOCS; i++) { DocumentModel doc = session.createDocumentModel("/", "doc" + i, "File"); session.createDocument(doc); } TransactionHelper.commitOrRollbackTransaction(); TransactionHelper.startTransaction(); List<String> commands = new ArrayList<>(NB_COMMANDS); for (int i = 0; i < NB_COMMANDS; i++) { commands.add(service.submit( new BulkCommand.Builder("dummySequential", "SELECT * FROM File").user("Administrator").build())); commands.add(service.submit( new BulkCommand.Builder("dummyConcurrent", "SELECT * FROM File").user("Administrator").build())); } assertTrue("Bulk action didn't finish", service.await(Duration.ofSeconds(60))); List<BulkStatus> results = new ArrayList<>(NB_COMMANDS); commands.forEach(id -> results.add(service.getStatus(id))); assertFalse(overlapCommands( results.stream().filter(r -> "dummySequential".equals(r.getAction())).collect(Collectors.toList()), true)); assertTrue(overlapCommands( results.stream().filter(r -> "dummyConcurrent".equals(r.getAction())).collect(Collectors.toList()), false)); }

Target:
public void testSequentialCommand() throws Exception { final int nbDocs = 10; final int nbCommands = 10; for (int i = 0; i < nbDocs; i++) { DocumentModel doc = session.createDocumentModel("/", "doc" + i, "File"); session.createDocument(doc); } TransactionHelper.commitOrRollbackTransaction(); TransactionHelper.startTransaction(); List<String> commands = new ArrayList<>(nbCommands); for (int i = 0; i < nbCommands; i++) { commands.add(service.submit( new BulkCommand.Builder("dummySequential", "SELECT * FROM File").user("Administrator").build())); commands.add(service.submit( new BulkCommand.Builder("dummyConcurrent", "SELECT * FROM File").user("Administrator").build())); } assertTrue("Bulk action didn't finish", service.await(Duration.ofSeconds(60))); List<BulkStatus> results = commands.stream().map(service::getStatus).collect(Collectors.toList()); assertFalse(overlapCommands( results.stream().filter(r -> "dummySequential".equals(r.getAction())).collect(Collectors.toList()), true)); assertTrue(overlapCommands( results.stream().filter(r -> "dummyConcurrent".equals(r.getAction())).collect(Collectors.toList()), false)); }
Source:
public void shouldTrimImageNames() { userProperties.setProperty("ryuk.container.image", " testcontainersofficial/ryuk:0.3.1 "); assertEquals("trailing whitespace was not removed from image name property", "testcontainersofficial/ryuk:0.3.1",newConfig().getRyukImage()); }

Target:
public void shouldTrimImageNames() { userProperties.setProperty("ryuk.container.image", " testcontainers/ryuk:0.3.1 "); assertEquals("trailing whitespace was not removed from image name property", "testcontainers/ryuk:0.3.1",newConfig().getRyukImage()); }
Source:
public static Optional<Properties> getPropertiesFile(String propertiesFilePath){ try { InputStream input = new FileInputStream(propertiesFilePath); Properties properties = new Properties(); properties.load(input); return Optional.ofNullable(properties); }catch(Exception e){ logger.error("Error while reading property file '"+propertiesFilePath+"'",e); return Optional.ofNullable(null); } }

Target:
public static Properties getPropertiesFile(String propertiesFilePath) throws IOException { InputStream input = new FileInputStream(propertiesFilePath); Properties properties = new Properties(); properties.load(input); return properties; }
Source:
public UfsStatus remove(AlluxioURI path) { UfsStatus removed = mStatuses.remove(path); if (removed == null) { return null; } mChildren.remove(path); return removed; }

Target:
public UfsStatus remove(AlluxioURI path) { Preconditions.checkNotNull(path, "can't remove null status cache path"); UfsStatus removed = mStatuses.remove(path); mChildren.remove(path); return removed; }
Source:
public static Object parse(final String value, final boolean allowMore) throws JSONException { return parse(value, 0, value.length(), allowMore); }

Target:
public static JSONObject parse(final String value, final boolean allowMore) throws JSONException { return (JSONObject) parse(value, 0, value.length(), allowMore); }
Source:
public static void addService(final ServiceTarget serviceTarget, final GitRepository gitRepository, final File repoRoot, final File tmpRoot) { if (gitRepository != null) { ContentRepository.Factory.addService(serviceTarget, new GitContentRepository(gitRepository, repoRoot, tmpRoot, OBSOLETE_CONTENT_TIMEOUT, LOCK_TIMEOUT)); } else { ContentRepository.Factory.addService(serviceTarget, repoRoot, tmpRoot); } }

Target:
public static void addService(final ServiceTarget serviceTarget, final GitRepository gitRepository, final File repoRoot, final File tmpRoot) { ContentRepository.Factory.addService(serviceTarget, new GitContentRepository(gitRepository, repoRoot, tmpRoot, OBSOLETE_CONTENT_TIMEOUT, LOCK_TIMEOUT)); }
Source:
public void testExpandByIdWithPreExpansionWithCount() throws Exception { myDaoConfig.setPreExpandValueSets(true); loadAndPersistCodeSystemAndValueSet(HTTPVerb.POST); myTermSvc.preExpandDeferredValueSetsToTerminologyTables(); Parameters respParam = ourClient .operation() .onInstance(myExtensionalVsId) .named("expand") .withParameter(Parameters.class, "count", new IntegerType(1)) .execute(); ValueSet expanded = (ValueSet) respParam.getParameter().get(0).getResource(); String resp = myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(expanded); ourLog.info(resp); assertThat(resp, stringContainsInOrder( "<total value=\"24\"/>\n", "<offset value=\"0\"/>\n", "<parameter>\n", "<name value=\"offset\"/>\n", "<valueInteger value=\"0\"/>\n", "</parameter>\n", "<parameter>\n", "<name value=\"count\"/>\n", "<valueInteger value=\"1\"/>\n", "</parameter>\n", "<contains>\n", "<system value=\"<LINK_0>\"/>\n", "<code value=\"8450-9\"/>\n", "<display value=\"Systolic blood pressure--expiration\"/>\n", "</contains>\n", "</expansion>")); }

Target:
public void testExpandByIdWithPreExpansionWithCount() throws Exception { myDaoConfig.setPreExpandValueSets(true); loadAndPersistCodeSystemAndValueSet(HTTPVerb.POST); myTermSvc.preExpandDeferredValueSetsToTerminologyTables(); Parameters respParam = ourClient .operation() .onInstance(myExtensionalVsId) .named("expand") .withParameter(Parameters.class, "count", new IntegerType(1)) .execute(); ValueSet expanded = (ValueSet) respParam.getParameter().get(0).getResource(); String resp = myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(expanded); ourLog.info(resp); assertEquals(24, expanded.getExpansion().getTotal()); assertEquals(0, expanded.getExpansion().getOffset()); assertEquals("offset", expanded.getExpansion().getParameter().get(0).getName()); assertEquals(0, expanded.getExpansion().getParameter().get(0).getValueIntegerType().getValue().intValue()); assertEquals("count", expanded.getExpansion().getParameter().get(1).getName()); assertEquals(1, expanded.getExpansion().getParameter().get(1).getValueIntegerType().getValue().intValue()); assertEquals(1, expanded.getExpansion().getContains().size()); assertEquals("<LINK_0>", expanded.getExpansion().getContainsFirstRep().getSystem()); assertEquals("8450-9", expanded.getExpansion().getContainsFirstRep().getCode()); assertEquals("Systolic blood pressure--expiration", expanded.getExpansion().getContainsFirstRep().getDisplay()); }
Source:
private boolean registerLibvirtSecretsImpl(VDS vds, List<LibvirtSecret> libvirtSecrets, boolean clearUnusedSecrets) { VDSReturnValue returnValue = Backend.getInstance().getResourceManager().RunVdsCommand( VDSCommandType.RegisterLibvirtSecrets, new RegisterLibvirtSecretsVDSParameters(vds.getId(), libvirtSecrets, clearUnusedSecrets)); if (!returnValue.getSucceeded()) { log.error("Failed to register libvirt secret on vds {}.", vds.getName()); return false; } return true; }

Target:
private boolean registerLibvirtSecretsImpl(VDS vds, List<LibvirtSecret> libvirtSecrets, boolean clearUnusedSecrets) { VDSReturnValue returnValue = Backend.getInstance().getResourceManager().RunVdsCommand( VDSCommandType.RegisterLibvirtSecrets, new RegisterLibvirtSecretsVDSParameters(vds.getId(), libvirtSecrets, clearUnusedSecrets)); return returnValue.getSucceeded(); }
Source:
public String toString() { return "FinalizingFieldAccessPostAggregator{" + "name'" + name + '\'' + ", fieldName='" + fieldName + '\'' + '}'; }

Target:
public String toString() { return "FinalizingFieldAccessPostAggregator{" + "name='" + name + '\'' + ", fieldName='" + fieldName + '\'' + '}'; }
Source:
private boolean isUsingDefaultPassword() { return getPlaintextPasswordFromProperties().equals("autogenerated"); }

Target:
private boolean isUsingDefaultPassword() { return "autogenerated".equals(getPlaintextPasswordFromProperties()); }
Source:
private void verifyResults(TestScenario testScenario, TestCase testCase, ApmMockServer apmServer) throws TestFailException { Collection<?> objects = getCapturedData(testScenario.getEnvironment().getType(), apmServer); System.out.println("Captured objects:\n" + objects); String json; try { json = serialize(objects); } catch (IOException e) { throw new TestFailException(testCase, "Failed to serialize traces", e); } for (JsonPathVerify jsonPathVerify: testCase.getVerify().getJsonPath()) { if (!JsonPathVerifier.verify(json, jsonPathVerify)) { throw new TestFailException(testCase, jsonPathVerify); } } }

Target:
private List<JsonPathVerify> verifyResults(TestScenario testScenario, TestCase testCase, ApmMockServer apmServer) { Collection<?> objects = getCapturedData(testScenario.getEnvironment().getType(), apmServer); log.info(String.format("Captured objects:\n%s", objects)); String json; try { json = serialize(objects); } catch (IOException ex) { log.severe(String.format("Failed to serialize traces: %s", objects)); throw new RuntimeException("Failed to serialize traces = " + objects, ex); } List<JsonPathVerify> failedJsonPathVerify = new ArrayList<>(); for (JsonPathVerify jsonPathVerify: testCase.getVerify().getJsonPath()) { if (!JsonPathVerifier.verify(json, jsonPathVerify)) { failedJsonPathVerify.add(jsonPathVerify); } } return failedJsonPathVerify; }
Source:
protected String createProcessTitle(Map<String, String> context) { return "Reindex"; }

Target:
protected String createProcessTitle(Map<String, String> context) { return Strings.apply("Reindexing mapping '%s'", context.get("ed")); }
Source:
public PollResponse<T> waitUntil(LongRunningOperationStatus statusToWaitFor) { if (statusToWaitFor == null) { throw logger.logExceptionAsWarning(new IllegalArgumentException("Null value for status is not allowed.")); } PollingContext<T> currentTerminalPollContext = this.terminalPollContext; if (currentTerminalPollContext != null && currentTerminalPollContext.getLatestResponse().getStatus() == statusToWaitFor) { return currentTerminalPollContext.getLatestResponse(); } else { PollingContext<T> context = this.pollingContext.clone(); AsyncPollResponse<T, U> asyncPollResponse = pollingLoop(context) .takeUntil(apr -> matchStatus(apr, statusToWaitFor)) .last() .switchIfEmpty(Mono.error(new NoSuchElementException("Polling completed without receiving the given" + "status '" + statusToWaitFor + "'."))) .block(); PollResponse<T> response = toPollResponse(asyncPollResponse); if (response.getStatus().isComplete()) { this.terminalPollContext = context; } return response; } }

Target:
public PollResponse<T> waitUntil(LongRunningOperationStatus statusToWaitFor) { Objects.requireNonNull(statusToWaitFor, "'statusToWaitFor' cannot be null."); PollingContext<T> currentTerminalPollContext = this.terminalPollContext; if (currentTerminalPollContext != null && currentTerminalPollContext.getLatestResponse().getStatus() == statusToWaitFor) { return currentTerminalPollContext.getLatestResponse(); } else { PollingContext<T> context = this.pollingContext.copy(); AsyncPollResponse<T, U> asyncPollResponse = pollingLoop(context) .takeUntil(apr -> matchStatus(apr, statusToWaitFor)) .last() .switchIfEmpty(Mono.error(new NoSuchElementException("Polling completed without receiving the given" + "status '" + statusToWaitFor + "'."))) .block(); PollResponse<T> response = toPollResponse(asyncPollResponse); if (response.getStatus().isComplete()) { this.terminalPollContext = context; } return response; } }
Source:
public static Deployment.ProvisioningState provisioningStateFromString(final String text) { if (text != null) { for (Deployment.ProvisioningState status : Deployment.ProvisioningState.values()) { if (text.equalsIgnoreCase(status.name())) { return status; } } } return Deployment.ProvisioningState.UNRECOGNIZED; }

Target:
public static Deployment.ProvisioningState provisioningStateFromString(final String text) { return (Deployment.ProvisioningState) GetEnumValue.fromValueOrDefault(text, Deployment.ProvisioningState.UNRECOGNIZED); }