auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static void calculateUq(final SAMRecord record, final ReferenceSequenceFileWalker refSeqWalker, final boolean isBisulfiteSequence) { final byte[] referenceBases = refSeqWalker.get(refSeqWalker.getSequenceDictionary().getSequenceIndex(record.getReferenceName())).getBases(); if (record.getBaseQualities() != SAMRecord.NULL_QUALS) { record.setAttribute(SAMTag.UQ.name(), SequenceUtil.sumQualitiesOfMismatches(record, referenceBases, 0, isBisulfiteSequence)); } }

Target:
public static void calculateUq(final SAMRecord record, final ReferenceSequenceFileWalker refSeqWalker, final boolean isBisulfiteSequence) { if (record.getBaseQualities() != SAMRecord.NULL_QUALS) { final byte[] referenceBases = refSeqWalker.get(refSeqWalker.getSequenceDictionary().getSequenceIndex(record.getReferenceName())).getBases(); record.setAttribute(SAMTag.UQ.name(), SequenceUtil.sumQualitiesOfMismatches(record, referenceBases, 0, isBisulfiteSequence)); } }
Source:
public void createsForkWithOrganization() throws Exception { final MkForks forks = new MkForks(new MkStorage.InFile(), "Test1", new Coordinates.Simple("tests1", "forks1") ); MatcherAssert.assertThat( forks.create("blah"), Matchers.notNullValue() ); }

Target:
public void createsForkWithOrganization() throws Exception { final Fork.Smart fork = new Fork.Smart( this.repo().forks().create("OneOrganization") ); MatcherAssert.assertThat( this.repo().forks().get(Integer.parseInt(fork.forkId())), Matchers.notNullValue() ); }
Source:
public Guid getVmTemplateId() { if (isImagesAlreadyOnTarget()) { return getParameters().getContainerId(); } else { return super.getVmTemplateId(); } }

Target:
public Guid getVmTemplateId() { if (isImagesAlreadyOnTarget()) { return getParameters().getContainerId(); } return super.getVmTemplateId(); }
Source:
public void search(SortedMap<Integer, String> topics, String submissionFile, Similarity similarity, int numHits, RerankerCascade cascade) throws IOException, ParseException { IndexSearcher searcher = new IndexSearcher(reader); searcher.setSimilarity(similarity); final String runTag = "BM25_EnglishAnalyzer_" + FIELD_BODY + "_" + similarity.toString(); PrintWriter out = new PrintWriter(Files.newBufferedWriter(Paths.get(submissionFile), StandardCharsets.US_ASCII)); QueryParser queryParser = new QueryParser(FIELD_BODY, new EnglishAnalyzer()); queryParser.setDefaultOperator(QueryParser.Operator.OR); for (Map.Entry<Integer, String> entry : topics.entrySet()) { int qID = entry.getKey(); String queryString = entry.getValue(); Query query = queryParser.parse(queryString); TopDocs rs = searcher.search(query, numHits); ScoreDoc[] hits = rs.scoreDocs; List<String> queryTokens = AnalyzerUtils.tokenize(new EnglishAnalyzer(), queryString); RerankerContext context = new RerankerContext(searcher, query, String.valueOf(qID), queryString, queryTokens, FIELD_BODY, null); ScoredDocuments docs = cascade.run(ScoredDocuments.fromTopDocs(rs, searcher), context); for (int i = 0; i < hits.length; i++) { int docId = hits[i].doc; Document doc = searcher.doc(docId); out.print(qID); out.print("\tQ0\t"); out.print(doc.get(FIELD_ID)); out.print("\t"); out.print(i + 1); out.print("\t"); out.print(hits[i].score); out.print("\t"); out.print(runTag); out.println(); } } out.flush(); out.close(); }

Target:
public void search(SortedMap<Integer, String> topics, String submissionFile, Similarity similarity, int numHits, RerankerCascade cascade) throws IOException, ParseException { final String runTag = "BM25_EnglishAnalyzer_" + FIELD_BODY + "_" + similarity.toString(); search(topics, submissionFile, similarity, numHits, cascade, runTag); }
Source:
public void initWithNiwsConfig(IClientConfig clientConfig) { if (clientConfig == null) { return; } clientName = clientConfig.getClientName(); if (clientName == null) { clientName = "default"; } vipAddresses = clientConfig.resolveDeploymentContextbasedVipAddresses(); maxAutoRetries = clientConfig.getPropertyAsInteger(CommonClientConfigKey.MaxAutoRetries, DefaultClientConfigImpl.DEFAULT_MAX_AUTO_RETRIES); maxAutoRetriesNextServer = clientConfig.getPropertyAsInteger(CommonClientConfigKey.MaxAutoRetriesNextServer,maxAutoRetriesNextServer); okToRetryOnAllOperations = clientConfig.getPropertyAsBoolean(CommonClientConfigKey.OkToRetryOnAllOperations, okToRetryOnAllOperations); tracer = getExecuteTracer(); if(clientConfig.getPropertyAsBoolean(CommonClientConfigKey.ForceClientPortConfiguration, false)){ if(clientConfig.getPropertyAsBoolean(CommonClientConfigKey.IsSecure, false)){ if(clientConfig.containsProperty(CommonClientConfigKey.SecurePort)){ overridePort = clientConfig.getPropertyAsInteger(CommonClientConfigKey.SecurePort, DefaultClientConfigImpl.DEFAULT_PORT); shouldUseOverridePort = true; }else{ logger.warn("%s set to force client port but no secure port is set, so ignoring", clientName); } }else{ if(clientConfig.containsProperty(CommonClientConfigKey.Port)){ overridePort = clientConfig.getPropertyAsInteger(CommonClientConfigKey.Port, DefaultClientConfigImpl.DEFAULT_PORT); shouldUseOverridePort = true; }else{ logger.warn("%s set to force client port but no secure port is set, so ignoring", clientName); } } } Monitors.registerObject("Client_" + clientName, this); }

Target:
public void initWithNiwsConfig(IClientConfig clientConfig) { if (clientConfig == null) { return; } clientName = clientConfig.getClientName(); if (clientName == null) { clientName = "default"; } vipAddresses = clientConfig.resolveDeploymentContextbasedVipAddresses(); maxAutoRetries = clientConfig.getPropertyAsInteger(CommonClientConfigKey.MaxAutoRetries, DefaultClientConfigImpl.DEFAULT_MAX_AUTO_RETRIES); maxAutoRetriesNextServer = clientConfig.getPropertyAsInteger(CommonClientConfigKey.MaxAutoRetriesNextServer,maxAutoRetriesNextServer); okToRetryOnAllOperations = clientConfig.getPropertyAsBoolean(CommonClientConfigKey.OkToRetryOnAllOperations, okToRetryOnAllOperations); tracer = getExecuteTracer(); Monitors.registerObject("Client_" + clientName, this); }
Source:
private static void runTest(ICache<Integer, Integer> icacheOnClient, NearCacheConfig.LocalUpdatePolicy localUpdatePolicy) throws InterruptedException { for (int i = 0; i < NUM_OF_KEYS; i++) { icacheOnClient.put(i, i); if (localUpdatePolicy.equals(INVALIDATE)) { icacheOnClient.get(i); } } AtomicBoolean stop = new AtomicBoolean(false); Runnable getter = () -> { while (!stop.get()) { for (int i = 0; i < NUM_OF_KEYS; i++) { icacheOnClient.get(i); } } }; Runnable putter = () -> { while (!stop.get()) { for (int i = 0; i < NUM_OF_KEYS; i++) { icacheOnClient.put(i, i); } } }; ExecutorService executor = Executors.newCachedThreadPool(); int numOfGetters = 3 * RuntimeAvailableProcessors.get(); for (int i = 0; i < numOfGetters; i++) { executor.execute(getter); } executor.execute(putter); sleepSeconds(20); stop.set(true); executor.shutdown(); executor.awaitTermination(30, TimeUnit.SECONDS); }

Target:
private static void runTest(ICache<Integer, Integer> icacheOnClient, NearCacheConfig.LocalUpdatePolicy localUpdatePolicy) throws InterruptedException { for (int i = 0; i < NUM_OF_KEYS; i++) { icacheOnClient.put(i, i); if (localUpdatePolicy.equals(INVALIDATE)) { icacheOnClient.get(i); } } AtomicBoolean stop = new AtomicBoolean(); Runnable getter = () -> { while (!stop.get()) { for (int i = 0; i < NUM_OF_KEYS; i++) { icacheOnClient.get(i); } } }; Runnable putter = () -> { while (!stop.get()) { for (int i = 0; i < NUM_OF_KEYS; i++) { icacheOnClient.put(i, i); } } }; ExecutorService executor = Executors.newCachedThreadPool(); int numOfGetters = 3 * RuntimeAvailableProcessors.get(); for (int i = 0; i < numOfGetters; i++) { executor.execute(getter); } executor.execute(putter); sleepSeconds(10); stop.set(true); executor.shutdown(); executor.awaitTermination(120, TimeUnit.SECONDS); }
Source:
private void initClientCache() { Region region = getClientCache().createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY) .create(REGION_NAME); region.registerInterest("ALL_KEYS"); }

Target:
private void initClientCache() { Region region = getClientCache().createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY) .create(REGION_NAME); region.registerInterestForAllKeys(InterestResultPolicy.KEYS); }
Source:
AzureMonitorExporter(MonitorExporterClient client, String instrumentationKey) { this.client = client; this.instrumentationKey = instrumentationKey; this.telemetryItemNamePrefix = "Microsoft.ApplicationInsights." + instrumentationKey + "."; }

Target:
AzureMonitorExporter(MonitorExporterClient client, String instrumentationKey) { this.client = client; this.instrumentationKey = instrumentationKey; String formattedInstrumentationKey = instrumentationKey.replaceAll("-", ""); this.telemetryItemNamePrefix = "Microsoft.ApplicationInsights." + formattedInstrumentationKey + "."; }
Source:
public Map<RelationKey, RelationWriteMetadata> writeSet() { Map<RelationKey, RelationWriteMetadata> map = new HashMap<RelationKey, RelationWriteMetadata>(2); map.put(sampleRelationKey, new RelationWriteMetadata(sampleRelationKey, getSchema(), true, true)); map.put(countRelationKey, new RelationWriteMetadata(countRelationKey, COUNT_SCHEMA, true, true)); return map; }

Target:
public Map<RelationKey, RelationWriteMetadata> writeSet() { return ImmutableMap.of(getRelationKey(), new RelationWriteMetadata( getRelationKey(), getSchema(), true, true), countRelationKey, new RelationWriteMetadata(countRelationKey, COUNT_SCHEMA, true, true)); }
Source:
protected final void activate(BundleContext bundleContext) { databindingServiceReference = bundleContext.getServiceReference(EMFFormsDatabindingEMF.class); if (databindingServiceReference == null) { throw new IllegalStateException( "The org.eclipse.emfforms.spi.core.services.databinding.emf.EMFFormsDatabindingEMF Service is not available!"); } setEMFFormsDatabinding(bundleContext.getService(databindingServiceReference)); }

Target:
protected final void activate(BundleContext bundleContext) { this.bundleContext = bundleContext; }
Source:
protected boolean canDoAction() { Guid userId = getParameters().getUserProfile().getUserId(); if (Guid.isNullOrEmpty(userId)) { userId = getUserId(); getParameters().getUserProfile().setUserId(userId); } else if (!userId.equals(getUserId())) { return failCanDoAction(EngineMessage.USER_NOT_AUTHORIZED_TO_PERFORM_ACTION); } String sshPublicKey = getParameters().getUserProfile().getSshPublicKey(); if (sshPublicKey == null || sshPublicKey.isEmpty()) { return true; } if (!OpenSSHUtils.isPublicKeysValid(sshPublicKey)) { return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_INVALID_PUBLIC_SSH_KEY); } return true; }

Target:
protected boolean canDoAction() { Guid userId = getParameters().getUserProfile().getUserId(); if (Guid.isNullOrEmpty(userId)) { userId = getUserId(); getParameters().getUserProfile().setUserId(userId); } else if (!userId.equals(getUserId())) { return failCanDoAction(EngineMessage.USER_NOT_AUTHORIZED_TO_PERFORM_ACTION); } String sshPublicKey = getParameters().getUserProfile().getSshPublicKey(); if (sshPublicKey == null || sshPublicKey.isEmpty()) { return true; } if (!OpenSSHUtils.arePublicKeysValid(sshPublicKey)) { return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_INVALID_PUBLIC_SSH_KEY); } return true; }
Source:
public void testRawStringLiterals() throws IOException { final String code = IOUtils.toString(CPPTokenizerTest.class.getResourceAsStream("cpp/issue-1784.cpp"), StandardCharsets.UTF_8); Tokens tokens = parse(code); System.out.println(tokens.getTokens()); assertTrue(TokenEntry.getEOF() != tokens.getTokens().get(0)); assertEquals(16, tokens.size()); }

Target:
public void testRawStringLiterals() throws IOException { final String code = IOUtils.toString(CPPTokenizerTest.class.getResourceAsStream("cpp/issue-1784.cpp"), StandardCharsets.UTF_8); Tokens tokens = parse(code); assertTrue(TokenEntry.getEOF() != tokens.getTokens().get(0)); assertEquals(16, tokens.size()); }
Source:
public Response logout() { logoutCurrentUser(); Status status; Map<String, String> data = new HashMap<>(); if (zConf.isAuthorizationHeaderClear()) { status = Status.UNAUTHORIZED; data.put("clearAuthorizationHeader", "true"); } else { status = Status.FORBIDDEN; data.put("clearAuthorizationHeader", "false"); } if (isKnoxSSOEnabled()) { KnoxJwtRealm knoxJwtRealm = getJTWRealm(); StringBuilder redirectURL = new StringBuilder(knoxJwtRealm.getProviderUrl()); String redirect = knoxJwtRealm.getRedirectParam(); data.put("redirectURL", constructUrl(redirectURL, redirect, knoxJwtRealm.getLogout())); data.put("isLogoutAPI", knoxJwtRealm.getLogoutAPI().toString()); } else if (isKerberosRealmEnabled()) { KerberosRealm kerberosRealm = getKerberosRealm(); StringBuilder redirectURL = new StringBuilder(kerberosRealm.getProviderUrl()); String redirect = kerberosRealm.getRedirectParam(); data.put("redirectURL", constructUrl(redirectURL, redirect, kerberosRealm.getLogout())); } JsonResponse<Map<String, String>> response = new JsonResponse<>(status, "", data); LOG.info(response.toString()); return response.build(); }

Target:
public Response logout() { logoutCurrentUser(); Status status; Map<String, String> data = new HashMap<>(); if (zConf.isAuthorizationHeaderClear()) { status = Status.UNAUTHORIZED; data.put("clearAuthorizationHeader", "true"); } else { status = Status.FORBIDDEN; data.put("clearAuthorizationHeader", "false"); } if (isKnoxSSOEnabled()) { KnoxJwtRealm knoxJwtRealm = getJTWRealm(); data.put("redirectURL", constructUrl(knoxJwtRealm.getProviderUrl(), knoxJwtRealm.getRedirectParam(), knoxJwtRealm.getLogout())); data.put("isLogoutAPI", knoxJwtRealm.getLogoutAPI().toString()); } else if (isKerberosRealmEnabled()) { KerberosRealm kerberosRealm = getKerberosRealm(); data.put("redirectURL", constructUrl(kerberosRealm.getProviderUrl(), kerberosRealm.getRedirectParam(), kerberosRealm.getLogout())); data.put("isLogoutAPI", kerberosRealm.getLogoutAPI().toString()); } JsonResponse<Map<String, String>> response = new JsonResponse<>(status, "", data); LOG.info(response.toString()); return response.build(); }
Source:
private void handleFinalizingSuccess(final StateContext context) { log.info("Finalizing successful upload to {}", getUploadDescription()); if (stopImageTransferSession(context.entity)) { Guid transferingVdsId = context.entity.getVdsId(); if (verifyImage(transferingVdsId)) { setVolumeLegalityInStorage(true); unLockImage(); updateEntityPhase(ImageTransferPhase.FINISHED_SUCCESS); } else { setImageStatus(ImageStatus.ILLEGAL); updateEntityPhase(ImageTransferPhase.FINALIZING_FAILURE); } } }

Target:
private void handleFinalizingSuccess(final StateContext context) { log.info("Finalizing successful upload to {}", getUploadDescription()); if (stopImageTransferSession(context.entity)) { Guid transferingVdsId = context.entity.getVdsId(); if (verifyImage(transferingVdsId)) { setVolumeLegalityInStorage(LEGAL_IMAGE); unLockImage(); updateEntityPhase(ImageTransferPhase.FINISHED_SUCCESS); } else { setImageStatus(ImageStatus.ILLEGAL); updateEntityPhase(ImageTransferPhase.FINALIZING_FAILURE); } } }
Source:
private synchronized long generateBeginQuestionnaireTime(boolean debugging) { Logger.d(TAG, "Calculating time for new BeginQuestionnaire notification"); String startAllowedString = sharedPreferences.getString( "time_window_lb_key", getString(R.string.settings_time_window_lb_default)); now = Calendar.getInstance(); nowUpTime = SystemClock.elapsedRealtime(); Calendar start = (Calendar)now.clone(); startAllowedHour = Util.getHour(startAllowedString); startAllowedMinute = Util.getMinute(startAllowedString); start.set(Calendar.HOUR_OF_DAY, startAllowedHour); start.set(Calendar.MINUTE, startAllowedMinute); Calendar notifTime = (Calendar)start.clone(); notifTime.add(Calendar.MINUTE,30); if (now.getTimeInMillis() > notifTime.getTimeInMillis()) { notifTime.add(Calendar.DAY_OF_YEAR, 1); } long notifTimeMS; if (debugging) { notifTimeMS= now.getTimeInMillis() + 5000; } else { notifTimeMS = notifTime.getTimeInMillis(); } long delay = notifTimeMS - now.getTimeInMillis(); long milliseconds = delay; long hours = milliseconds / (60 * 60 * 1000); milliseconds %= 60 * 60 * 1000; long minutes = milliseconds / (60 * 1000); milliseconds %= 60 * 1000; long seconds = milliseconds / 1000; Logger.i(TAG, "BeginQuestionnaire notifcation scheduled in {0} hours, {1} minutes, " + "and {2} seconds", hours, minutes, seconds); return nowUpTime + delay; }

Target:
private synchronized long generateBeginQuestionnaireTime(boolean debugging) { fixNowAndGetAllowedWindow(); Logger.d(TAG, "Calculating time for new BeginQuestionnaire notification"); Calendar start = (Calendar)now.clone(); start.set(Calendar.HOUR_OF_DAY, startAllowedHour); start.set(Calendar.MINUTE, startAllowedMinute); Calendar nextStart = (Calendar)start.clone(); if (now.after(nextStart)) { nextStart.add(Calendar.DAY_OF_YEAR, 1); } long delay; if (debugging) { delay = DEBUG_DELAY; } else { delay = now.getTimeInMillis() - nextStart.getTimeInMillis() + QUESTIONNAIRE_DELAY_AFTER_WINDOW_START; } long milliseconds = delay; long hours = milliseconds / (60 * 60 * 1000); milliseconds %= 60 * 60 * 1000; long minutes = milliseconds / (60 * 1000); milliseconds %= 60 * 1000; long seconds = milliseconds / 1000; Logger.i(TAG, "BeginQuestionnaireService scheduled in {0} hours, {1} minutes, " + "and {2} seconds", hours, minutes, seconds); return nowUpTime + delay; }
Source:
protected void starting(Description description) { this.desc = description; super.starting(description); dirName = "target/" + desc.getClassName() + "/" + desc.getMethodName(); new File(dirName).mkdir(); FileSystem hdfs = null; Path newFilePath = new Path(dirName + "/" + filename); try { hdfs = FileSystem.get(new Configuration()); hdfs.createNewFile(newFilePath); } catch (IOException ex) { DTThrowable.rethrow(ex); } StringBuilder sb = new StringBuilder(); sb.append(SchemaUtils.jarResourceFileToString(filename)); byte[] byt = sb.toString().getBytes(); try { FSDataOutputStream fsOutStream = hdfs.create(newFilePath); fsOutStream.write(byt); fsOutStream.close(); } catch (IOException ex) { DTThrowable.rethrow(ex); } logger.debug("Written data to HDFS file."); }

Target:
protected void starting(Description description) { this.desc = description; super.starting(description); dirName = "target/" + desc.getClassName(); new File(dirName).mkdir(); FileSystem fileSystem = null; Path newFilePath = new Path(dirName + "/" + filename); try { fileSystem = LocalFileSystem.get(new Configuration()); fileSystem.createNewFile(newFilePath); } catch (IOException ex) { DTThrowable.rethrow(ex); } StringBuilder sb = new StringBuilder(); sb.append(SchemaUtils.jarResourceFileToString(filename)); byte[] byt = sb.toString().getBytes(); try { FSDataOutputStream fsOutStream = fileSystem.create(newFilePath); fsOutStream.write(byt); fsOutStream.close(); } catch (IOException ex) { DTThrowable.rethrow(ex); } }
Source:
public List<ExperimentTaskResult> getResultsOfExperiment(String experimentId) { MapSqlParameterSource parameters = new MapSqlParameterSource(); parameters.addValue("id", experimentId); List<ExperimentTaskResult> result = this.template.query(GET_EXPERIMENT_RESULTS, parameters, new ExperimentTaskResultRowMapper()); for (ExperimentTaskResult e : result) { getVersion(e); addAdditionalResults(e); addSubTasks(e); } return result; }

Target:
public List<ExperimentTaskResult> getResultsOfExperiment(String experimentId) { MapSqlParameterSource parameters = new MapSqlParameterSource(); parameters.addValue("id", experimentId); List<ExperimentTaskResult> result = this.template.query(GET_EXPERIMENT_RESULTS, parameters, new ExperimentTaskResultRowMapper()); for (ExperimentTaskResult e : result) { addAdditionalResults(e); addSubTasks(e); } return result; }
Source:
public void testSmallTraceSequential() throws TmfAnalysisException, IOException, TmfTraceException { String tracePath; tracePath = FileLocator.toFileURL(CtfTestTrace.ARM_64_BIT_HEADER.getTraceURL()).getPath(); assertNotNull(tracePath); TmfTrace testTrace = new CtfTmfTrace(); SystemCallLatencyAnalysis syscallModule = new SystemCallLatencyAnalysis(); IAnalysisModule kernelModule = new KernelAnalysisModule(); final IAnalysisModuleSource source = new IAnalysisModuleSource() { @Override public @NonNull Iterable<IAnalysisModuleHelper> getAnalysisModules() { return Arrays.asList(new AnalysisModuleHelper(kernelModule), new AnalysisModuleHelper(syscallModule)); } }; TmfAnalysisManager.registerModuleSource(source); testTrace.initTrace(null, tracePath, CtfTmfEvent.class); kernelModule.setTrace(testTrace); syscallModule.setTrace(testTrace); try { testTrace.traceOpened(new TmfTraceOpenedSignal(this, testTrace, null)); } catch (NullPointerException e) { } kernelModule.schedule(); kernelModule.waitForCompletion(); syscallModule.schedule(); syscallModule.waitForCompletion(); final @Nullable ISegmentStore<@NonNull ISegment> segmentStore = syscallModule.getResults(); assertNotNull(segmentStore); assertEquals(1801, segmentStore.size()); }

Target:
public void testSmallTraceSequential() throws TmfAnalysisException, IOException, TmfTraceException { String tracePath; tracePath = FileLocator.toFileURL(CtfTestTrace.ARM_64_BIT_HEADER.getTraceURL()).getPath(); assertNotNull(tracePath); TmfTrace testTrace = new LttngKernelTrace(); SystemCallLatencyAnalysis syscallModule = new SystemCallLatencyAnalysis(); IAnalysisModule kernelModule = new KernelAnalysisModule(); final IAnalysisModuleSource source = new IAnalysisModuleSource() { @Override public @NonNull Iterable<IAnalysisModuleHelper> getAnalysisModules() { return Arrays.asList(new AnalysisModuleHelper(kernelModule), new AnalysisModuleHelper(syscallModule)); } }; TmfAnalysisManager.registerModuleSource(source); testTrace.initTrace(null, tracePath, CtfTmfEvent.class); kernelModule.setTrace(testTrace); syscallModule.setTrace(testTrace); try { testTrace.traceOpened(new TmfTraceOpenedSignal(this, testTrace, null)); } catch (NullPointerException e) { } kernelModule.schedule(); kernelModule.waitForCompletion(); syscallModule.schedule(); syscallModule.waitForCompletion(); final @Nullable ISegmentStore<@NonNull ISegment> segmentStore = syscallModule.getResults(); assertNotNull(segmentStore); assertEquals(1801, segmentStore.size()); }
Source:
private static void multipartUpload(EncryptedServerSideMultipartManager multipart) { String uploadObject = MantaClient.SEPARATOR + mantaUsername + "/stor/multipart"; try { MantaMetadata metadata = new MantaMetadata(); metadata.put("e-secretkey", "My Secret Value"); EncryptedMultipartUpload<ServerSideMultipartUpload> upload = multipart.initiateUpload(uploadObject, metadata); MantaMultipartUploadPart part1 = multipart.uploadPart(upload, 1, RandomUtils.nextBytes(5242880)); MantaMultipartUploadPart part2 = multipart.uploadPart(upload, 2, RandomUtils.nextBytes(1000000)); MantaMultipartUploadTuple[] parts = new MantaMultipartUploadTuple[] { part1, part2 }; Stream<MantaMultipartUploadTuple> partsStream = Arrays.stream(parts); multipart.complete(upload, partsStream); System.out.println(uploadObject + " is now assembled!"); } catch (IOException e) { ContextedRuntimeException exception = new ContextedRuntimeException( "A network error occurred when doing a multipart upload to Manta."); exception.setContextValue("path", uploadObject); throw exception; } }

Target:
private static void multipartUpload(EncryptedServerSideMultipartManager multipart) { String uploadObject = SEPARATOR + mantaUsername + SEPARATOR + "stor" + SEPARATOR + "multipart"; try { MantaMetadata metadata = new MantaMetadata(); metadata.put("e-secretkey", "My Secret Value"); EncryptedMultipartUpload<ServerSideMultipartUpload> upload = multipart.initiateUpload(uploadObject, metadata); MantaMultipartUploadPart part1 = multipart.uploadPart(upload, 1, RandomUtils.nextBytes(5242880)); MantaMultipartUploadPart part2 = multipart.uploadPart(upload, 2, RandomUtils.nextBytes(1000000)); MantaMultipartUploadTuple[] parts = new MantaMultipartUploadTuple[] { part1, part2 }; Stream<MantaMultipartUploadTuple> partsStream = Arrays.stream(parts); multipart.complete(upload, partsStream); System.out.println(uploadObject + " is now assembled!"); } catch (IOException e) { ContextedRuntimeException exception = new ContextedRuntimeException( "A network error occurred when doing a multipart upload to Manta."); exception.setContextValue("path", uploadObject); throw exception; } }
Source:
public void testInitialization() { AbstractTest test = new MyTest(); EXPECTED_RESULT = false; test.setUp(); EXPECTED_RESULT = true; test.setUp(); }

Target:
public void testInitialization() { MyTest test = new MyTest(); EXPECTED_RESULT = false; test.setUp(); EXPECTED_RESULT = true; test.setUp(); }
Source:
public void testLockUseAfterPartitionWithMajority() throws Throwable { ClusteredLockManager clm0 = EmbeddedClusteredLockManagerFactory.from(getCacheManagers().get(0)); ClusteredLockManager clm1 = EmbeddedClusteredLockManagerFactory.from(getCacheManagers().get(1)); ClusteredLockManager clm2 = EmbeddedClusteredLockManagerFactory.from(getCacheManagers().get(2)); ClusteredLockManager clm3 = EmbeddedClusteredLockManagerFactory.from(getCacheManagers().get(3)); ClusteredLockManager clm4 = EmbeddedClusteredLockManagerFactory.from(getCacheManagers().get(4)); ClusteredLockManager clm5 = EmbeddedClusteredLockManagerFactory.from(getCacheManagers().get(5)); assertTrue(clm0.defineLock(LOCK_NAME)); assertFalse(clm1.defineLock(LOCK_NAME)); assertFalse(clm2.defineLock(LOCK_NAME)); assertFalse(clm3.defineLock(LOCK_NAME)); assertFalse(clm4.defineLock(LOCK_NAME)); assertFalse(clm5.defineLock(LOCK_NAME)); ClusteredLock lock0 = clm0.get(LOCK_NAME); ClusteredLock lock1 = clm1.get(LOCK_NAME); ClusteredLock lock2 = clm2.get(LOCK_NAME); ClusteredLock lock3 = clm3.get(LOCK_NAME); ClusteredLock lock4 = clm4.get(LOCK_NAME); ClusteredLock lock5 = clm5.get(LOCK_NAME); splitCluster(new int[]{0, 1, 2, 3}, new int[]{4, 5}); asList(lock0, lock1, lock2, lock3).forEach(lock -> { assertTrue("Lock acquisition should be true " + lock, await(lock.tryLock(29, TimeUnit.SECONDS) .thenApply(tryLockRequest -> { if (tryLockRequest) { await(lock.unlock()); } return tryLockRequest; }).exceptionally(ex -> { fail("Should not be failing from majority partition " + lock + " " + ex.getMessage()); return null; }))); }); assertFailureFromMinorityPartition(lock4); assertFailureFromMinorityPartition(lock5); }

Target:
public void testLockUseAfterPartitionWithMajority() throws Throwable { ClusteredLockManager clm0 = EmbeddedClusteredLockManagerFactory.from(getCacheManagers().get(0)); ClusteredLockManager clm1 = EmbeddedClusteredLockManagerFactory.from(getCacheManagers().get(1)); ClusteredLockManager clm2 = EmbeddedClusteredLockManagerFactory.from(getCacheManagers().get(2)); ClusteredLockManager clm3 = EmbeddedClusteredLockManagerFactory.from(getCacheManagers().get(3)); ClusteredLockManager clm4 = EmbeddedClusteredLockManagerFactory.from(getCacheManagers().get(4)); ClusteredLockManager clm5 = EmbeddedClusteredLockManagerFactory.from(getCacheManagers().get(5)); assertTrue(clm0.defineLock(LOCK_NAME)); assertFalse(clm1.defineLock(LOCK_NAME)); assertFalse(clm2.defineLock(LOCK_NAME)); assertFalse(clm3.defineLock(LOCK_NAME)); assertFalse(clm4.defineLock(LOCK_NAME)); assertFalse(clm5.defineLock(LOCK_NAME)); ClusteredLock lock0 = clm0.get(LOCK_NAME); ClusteredLock lock1 = clm1.get(LOCK_NAME); ClusteredLock lock2 = clm2.get(LOCK_NAME); ClusteredLock lock3 = clm3.get(LOCK_NAME); ClusteredLock lock4 = clm4.get(LOCK_NAME); ClusteredLock lock5 = clm5.get(LOCK_NAME); splitCluster(new int[]{0, 1, 2, 3}, new int[]{4, 5}); asList(lock0, lock1, lock2, lock3).forEach(lock -> { assertTryLock(lock); }); assertFailureFromMinorityPartition(lock4); assertFailureFromMinorityPartition(lock5); }
Source:
public void changeToAdvancedConfiguration() { isAdvanced.setDefaultValue(true); isAdvanceChangedHandler(); }

Target:
public void changeToAdvancedConfiguration() { isAdvanced.setValue(true); isAdvanceChangedHandler(); }
Source:
private void handleIntent(Intent intent) { if (intent == null) return; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { return; } if (Objects.equals(intent.getAction(), Intent.ACTION_VIEW)) { Uri uri = intent.getData(); if (uri != null) { handleDeeplink(uri); } } }

Target:
private void handleIntent(Intent intent) { if (intent == null) { return; } if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { return; } if (Objects.equals(intent.getAction(), Intent.ACTION_VIEW)) { Uri uri = intent.getData(); if (uri != null) { handleDeeplink(uri); } } }
Source:
public Cluster getCluster(Guid clusterId) { return DbFacade.getInstance().getClusterDao().get(clusterId); }

Target:
public Cluster getCluster(Guid clusterId) { return getClusterDao().get(clusterId); }
Source:
public GraphQuery queryGraph(Graph graph, String queryString, Authorizations authorizations) { return new ElasticSearchSearchGraphQuery( getClient(), getConfig().getIndicesToQuery(), graph, queryString, getAllPropertyDefinitions(), getConfig().getScoringStrategy(), getConfig().getNameSubstitutionStrategy(), authorizations); }

Target:
public GraphQuery queryGraph(Graph graph, String queryString, Authorizations authorizations) { return new ElasticSearchSearchGraphQuery( getClient(), getConfig().getIndicesToQuery(), graph, queryString, getAllPropertyDefinitions(), getConfig().getScoringStrategy(), this.nameSubstitutionStrategy, authorizations); }
Source:
private static Expr.ObjectBinding createBindings(ColumnSelectorFactory columnSelectorFactory, Expr expression) { final Map<String, Supplier<Number>> suppliers = Maps.newHashMap(); for (String columnName : Parser.findRequiredBindings(expression)) { final ColumnCapabilities columnCapabilities = columnSelectorFactory.getColumnCapabilities(columnName); final ValueType nativeType = columnCapabilities != null ? columnCapabilities.getType() : null; final Supplier<Number> supplier; if (nativeType == ValueType.FLOAT) { final FloatColumnSelector selector = columnSelectorFactory.makeFloatColumnSelector(columnName); supplier = new Supplier<Number>() { @Override public Number get() { return selector.get(); } }; } else if (nativeType == ValueType.LONG) { final LongColumnSelector selector = columnSelectorFactory.makeLongColumnSelector(columnName); supplier = new Supplier<Number>() { @Override public Number get() { return selector.get(); } }; } else if (nativeType == null) { final ObjectColumnSelector selector = columnSelectorFactory.makeObjectColumnSelector(columnName); final Class clazz = selector == null ? null : selector.classOfObject(); if (selector == null || (clazz != Object.class && Number.class.isAssignableFrom(clazz))) { supplier = null; } else { supplier = new Supplier<Number>() { @Override public Number get() { return tryParse(selector.get()); } }; } } else { supplier = null; } if (supplier != null) { suppliers.put(columnName, supplier); } } return Parser.withSuppliers(suppliers); }

Target:
private static Expr.ObjectBinding createBindings(ColumnSelectorFactory columnSelectorFactory, Expr expression) { final Map<String, Supplier<Number>> suppliers = Maps.newHashMap(); for (String columnName : Parser.findRequiredBindings(expression)) { final ColumnCapabilities columnCapabilities = columnSelectorFactory.getColumnCapabilities(columnName); final ValueType nativeType = columnCapabilities != null ? columnCapabilities.getType() : null; final Supplier<Number> supplier; if (nativeType == ValueType.FLOAT) { supplier = supplierFromFloatSelector(columnSelectorFactory.makeFloatColumnSelector(columnName)); } else if (nativeType == ValueType.LONG) { supplier = supplierFromLongSelector(columnSelectorFactory.makeLongColumnSelector(columnName)); } else if (nativeType == null) { supplier = supplierFromObjectSelector(columnSelectorFactory.makeObjectColumnSelector(columnName)); } else { supplier = null; } if (supplier != null) { suppliers.put(columnName, supplier); } } return Parser.withSuppliers(suppliers); }
Source:
public Binding getObject() throws Exception { String destination; DestinationType destinationType; if (destinationQueue != null) { destination = destinationQueue.getName(); destinationType = DestinationType.QUEUE; } else { destination = destinationExchange.getName(); destinationType = DestinationType.EXCHANGE; } Binding binding = new Binding(destination, destinationType, exchange, routingKey != null ? routingKey : destination, arguments); if (this.shouldDeclare != null) { binding.setShouldDeclare(this.shouldDeclare); } if (this.adminsThatShouldDeclare != null) { binding.setAdminsThatShouldDeclare(this.adminsThatShouldDeclare); } return binding; }

Target:
public Binding getObject() throws Exception { String destination; DestinationType destinationType; if (destinationQueue != null) { destination = destinationQueue.getName(); destinationType = DestinationType.QUEUE; } else { destination = destinationExchange.getName(); destinationType = DestinationType.EXCHANGE; } Binding binding = new Binding(destination, destinationType, exchange, routingKey, arguments); if (this.shouldDeclare != null) { binding.setShouldDeclare(this.shouldDeclare); } if (this.adminsThatShouldDeclare != null) { binding.setAdminsThatShouldDeclare(this.adminsThatShouldDeclare); } return binding; }
Source:
static Notification success(Context context) { return AutoForegroundNotification.success(context, NotificationsUtils.GENERAL_NORMAL_CHANNEL_ID, R.string.notification_site_creation_title_success, R.string.notification_site_creation_created, R.drawable.ic_my_sites_24dp, R.color.blue_wordpress); }

Target:
static Notification success(Context context) { return AutoForegroundNotification.success(context, context.getString(R.string.notification_channel_normal_id), R.string.notification_site_creation_title_success, R.string.notification_site_creation_created, R.drawable.ic_my_sites_24dp, R.color.blue_wordpress); }
Source:
public static void init(final EventBus eventBus) { commonModel = CommonModel.newInstance(); ModelInitializedEvent.fire(eventBus); commonModel.getSelectedItemChangedEvent().addListener(new IEventListener() { @Override public void eventRaised(Event ev, Object sender, EventArgs args) { MainModelSelectionChangeEvent.fire(eventBus, commonModel.getSelectedItem()); } }); commonModel.getSignedOutEvent().addListener(new IEventListener() { @Override public void eventRaised(Event ev, Object sender, EventArgs args) { Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { commonModel = null; } }); } }); }

Target:
public static void init(final EventBus eventBus) { commonModel = CommonModel.newInstance(); commonModel.getSelectedItemChangedEvent().addListener(new IEventListener() { @Override public void eventRaised(Event ev, Object sender, EventArgs args) { MainModelSelectionChangeEvent.fire(eventBus, commonModel.getSelectedItem()); } }); }
Source:
private void setTitle(String fileName, Metacard metacard) { if (metacard.getAttribute(Metacard.TITLE) == null) { metacard.setAttribute(new AttributeImpl(Metacard.TITLE, fileName)); } }

Target:
private void setTitle(String fileName, Metacard metacard) { if (metacard.getAttribute(Core.TITLE) == null) { metacard.setAttribute(new AttributeImpl(Core.TITLE, fileName)); } }
Source:
public BigInteger getMinValue() { if (!signed) return BigInteger.ZERO; BigInteger capacity = BigInteger.ONE.shiftLeft(length); return capacity.divide(BigInteger.valueOf(2)).negate(); }

Target:
public BigInteger getMinValue() { if (!signed) { return BigInteger.ZERO; } BigInteger capacity = BigInteger.ONE.shiftLeft(length); return capacity.divide(BigInteger.valueOf(2)).negate(); }
Source:
public static SerializerEncoding fromHeaders(HttpHeaders headers) { final String mimeContentType = headers.getValue(CONTENT_TYPE); if (mimeContentType == null) { LOGGER.warning("'{}' not found. Returning default encoding: {}", CONTENT_TYPE, JSON); return JSON; } final String[] parts = mimeContentType.split(";"); final String mimeType = parts[0].toLowerCase(Locale.ROOT); final String[] mimeTypeParts = mimeType.split("/"); if (mimeTypeParts.length != 2) { LOGGER.warning("Content-Type '{}' does not match mime-type formatting 'type/'subtype'. " + "Returning default: {}", mimeType, DEFAULT_ENCODING); return DEFAULT_ENCODING; } for (SerializerEncodingMimeTypes serializerEncodingMimeTypes : SUPPORTED_MIME_TYPES) { if (serializerEncodingMimeTypes.matches(mimeTypeParts[0], mimeTypeParts[1])) { return serializerEncodingMimeTypes.getEncoding(); } } LOGGER.warning("Content-Type '{}' does not match any supported one. Returning default: {}", mimeType, DEFAULT_ENCODING); return DEFAULT_ENCODING; }

Target:
public static SerializerEncoding fromHeaders(HttpHeaders headers) { final String mimeContentType = headers.getValue(CONTENT_TYPE); if (mimeContentType == null || mimeContentType.isEmpty()) { LOGGER.warning("'{}' not found. Returning default encoding: {}", CONTENT_TYPE, DEFAULT_ENCODING); return DEFAULT_ENCODING; } final SerializerEncoding encoding = SUPPORTED_MIME_TYPES.get(mimeContentType); if (encoding != null) { return encoding; } final String[] parts = mimeContentType.split(";"); final String[] mimeTypeParts = parts[0].split("/"); if (mimeTypeParts.length != 2) { LOGGER.warning("Content-Type '{}' does not match mime-type formatting 'type'/'subtype'. " + "Returning default: {}", parts[0], DEFAULT_ENCODING); return DEFAULT_ENCODING; } final String subtype = mimeTypeParts[1]; final int lastIndex = subtype.lastIndexOf("+"); if (lastIndex == -1) { return DEFAULT_ENCODING; } final String mimeTypeSuffix = subtype.substring(lastIndex + 1); final SerializerEncoding serializerEncoding = SUPPORTED_SUFFIXES.get(mimeTypeSuffix); if (serializerEncoding != null) { return serializerEncoding; } LOGGER.warning("Content-Type '{}' does not match any supported one. Returning default: {}", mimeContentType, DEFAULT_ENCODING); return DEFAULT_ENCODING; }
Source:
public RemoveWatchesType remove(Watcher watcher) { this.watcher = watcher == null ? null : client.getNamespaceWatcherMap().getNamespaceWatcher(watcher); return this; }

Target:
public RemoveWatchesType remove(Watcher watcher) { if(watcher == null) { this.watcher = null; } else { this.watcher = client.getNamespaceWatcherMap().get(watcher); if(this.watcher == null) { this.watcher = watcher; } } return this; }
Source:
public void lock() { this.delegate.lock(); while (true) { try { while (!doLock()) { Thread.sleep(100); } break; } catch (CannotSerializeTransactionException | TransactionTimedOutException | QueryTimeoutException | DeadlockLoserDataAccessException e) { } catch (InterruptedException e) { } catch (Exception e) { this.delegate.unlock(); rethrowAsLockException(e); } } }

Target:
public void lock() { this.delegate.lock(); while (true) { try { while (!doLock()) { Thread.sleep(100); } break; } catch (TransientDataAccessException e) { } catch (InterruptedException e) { } catch (Exception e) { this.delegate.unlock(); rethrowAsLockException(e); } } }
Source:
public void testTokenFetch() { boolean authManagerEnabled = WikipediaApp.getInstance().isAuthManagerEnabled(); long millis = System.currentTimeMillis(); Site testWiki = new Site("test.wikipedia.org"); String username = "someusername" + millis; String password = "somepassword" + millis; String repeat = password; CompatCreateAccountResult result; if (authManagerEnabled) { AMSubject subject = new AMSubject(username, password, repeat, null); subject.execute(); result = subject.await(); } else { Subject subject = new Subject(username, password, null); subject.execute(); result = subject.await(); } if ((authManagerEnabled && result.getAuthManagerCreateAccountResult() instanceof AMCreateAccountSuccessResult) || (!authManagerEnabled && result.getLegacyCreateAccountResult() instanceof CreateAccountSuccessResult)) { return; } assertThat(result, authManagerEnabled ? instanceOf(AMCreateAccountCaptchaResult.class) : instanceOf(CreateAccountCaptchaResult.class)); CaptchaResult captchaResult = authManagerEnabled ? ((AMCreateAccountCaptchaResult) result.getAuthManagerCreateAccountResult()).getCaptchaResult() : ((CreateAccountCaptchaResult) result.getLegacyCreateAccountResult()).getCaptchaResult(); assertThat(captchaResult, notNullValue()); assertThat(captchaResult.getCaptchaId(), not(isEmptyOrNullString())); String expectedCaptchaUrlPrefix = WikipediaApp.getInstance().getSite().scheme() + "://test.wikipedia.org/w/index.php?title=Special:Captcha/image"; assertThat(captchaResult.getCaptchaUrl(testWiki), startsWith(expectedCaptchaUrlPrefix)); }

Target:
public void testTokenFetch() { long millis = System.currentTimeMillis(); final String username = "someusername" + millis; final String password = "somepassword" + millis; final String repeat = password; CompatCreateAccountResult createAccountResult; new AMLoginInfoTask() { @Override public void onCatch(Throwable caught) { L.e("AMLoginInfoTask failed: " + caught.getMessage()); } @Override public void onFinish(AMLoginInfoResult result) { if (result.getEnabled()) { L.i("Logging in with AuthManager"); AMSubject subject = new AMSubject(username, password, repeat, null); subject.execute(); handleCreateAccountResult(subject.await()); } else { L.i("Logging in with legacy login"); Subject subject = new Subject(username, password, null); subject.execute(); handleCreateAccountResult(subject.await()); } } }.execute(); }
Source:
public void connect() throws IOException { logger.debug("Entering connect. is in transaction: {}", inTransaction); try { String queueName = getQueueName(getAppId(), getOperatorId()); logger.debug("Base is null: {}", getBase() == null); if (getBase() != null) { logger.debug("Session is null: {}", getBase().getSession() == null); } Queue queue = getBase().getSession().createQueue(queueName); QueueBrowser browser = getBase().getSession().createBrowser(queue,"operatorId=" + String.valueOf(getOperatorId())); boolean hasStore; try { Enumeration enumeration = browser.getEnumeration(); hasStore = enumeration.hasMoreElements(); } catch (JMSException ex) { throw new RuntimeException(ex); } producer = getBase().getSession().createProducer(queue); consumer = getBase().getSession().createConsumer(queue, "operatorId=" + String.valueOf(getOperatorId())); connected = true; logger.debug("Connected. is in transaction: {}", inTransaction); if (!hasStore) { beginTransaction(); BytesMessage message = getBase().getSession().createBytesMessage(); message.setIntProperty(OPERATOR_ID, getOperatorId()); message.writeLong(-1L); producer.send(message); commitTransaction(); } } catch (JMSException ex) { throw new RuntimeException(ex); } logger.debug("Exiting connect. is in transaction: {}", inTransaction); }

Target:
public void connect() throws IOException { logger.debug("Entering connect. is in transaction: {}", inTransaction); try { logger.debug("Base is null: {}", getBase() == null); if (getBase() != null) { logger.debug("Session is null: {}", getBase().getSession() == null); } metaQueueName = getBase().getSubject() + ".metadata"; String appOperatorId = getAppId() + "_" + getOperatorId(); Queue queue = getBase().getSession().createQueue(metaQueueName); QueueBrowser browser = getBase().getSession().createBrowser(queue, APP_OPERATOR_ID + " = '" + appOperatorId + "'"); boolean hasStore; try { Enumeration enumeration = browser.getEnumeration(); hasStore = enumeration.hasMoreElements(); } catch (JMSException ex) { throw new RuntimeException(ex); } producer = getBase().getSession().createProducer(queue); consumer = getBase().getSession().createConsumer(queue, APP_OPERATOR_ID + " = '" + appOperatorId + "'"); connected = true; logger.debug("Connected. is in transaction: {}", inTransaction); if (!hasStore) { beginTransaction(); BytesMessage message = getBase().getSession().createBytesMessage(); message.setStringProperty(APP_OPERATOR_ID, appOperatorId); message.writeLong(-1L); producer.send(message); commitTransaction(); } } catch (JMSException ex) { throw new RuntimeException(ex); } logger.debug("Exiting connect. is in transaction: {}", inTransaction); }
Source:
public String getFeedbackUrl(String siteId) { return ServerConfigurationService.getPortalUrl() + "/site/" + siteId + "/page/" + SkinnableCharonPortal.CONTACT_US_URL_SUFFIX; }

Target:
private String getFeedbackUrl(String siteId) { return ServerConfigurationService.getPortalUrl() + "/site/" + siteId + "/page/" + SkinnableCharonPortal.CONTACT_US_URL_SUFFIX; }
Source:
public void addInput(Page page) { checkState(needsInput(), "Operator is already finishing"); requireNonNull(page, "page is null"); long memorySize = 0; for (Aggregator aggregate : aggregates) { aggregate.processPage(page); memorySize += aggregate.getEstimatedSize(); } if (partial || useSystemMemoryPool) { systemMemoryContext.setBytes(memorySize); } else { userMemoryContext.setBytes(memorySize); } }

Target:
public void addInput(Page page) { checkState(needsInput(), "Operator is already finishing"); requireNonNull(page, "page is null"); long memorySize = 0; for (Aggregator aggregate : aggregates) { aggregate.processPage(page); memorySize += aggregate.getEstimatedSize(); } if (useSystemMemory) { systemMemoryContext.setBytes(memorySize); } else { userMemoryContext.setBytes(memorySize); } }
Source:
public void work() { openSystemSession(); for (String string : docIds) { DocumentModel doc = null; try { doc = session.getDocument(new IdRef(string)); } catch (DocumentNotFoundException e) { log.warn("Document impacted by retention no longer exists {}", string); continue; } Record record = doc.getAdapter(Record.class); if (record == null) { log.warn("Document should be impacted by retention but is no longer a Record: {}", string); continue; } Framework.getService(RetentionManager.class) .evalExpressionEventBasedRules(record, docsToCheckAndEvents.get(string), session); } }

Target:
public void work() { openSystemSession(); RetentionManager retentionManager = Framework.getService(RetentionManager.class); for (String string : docIds) { DocumentModel doc; try { doc = session.getDocument(new IdRef(string)); } catch (DocumentNotFoundException e) { log.warn("Document impacted by retention no longer exists {}", string); continue; } Record record = doc.getAdapter(Record.class); if (record == null) { log.warn("Document should be impacted by retention but is no longer a Record: {}", string); continue; } retentionManager.evalExpressionEventBasedRules(record, docsToCheckAndEvents.get(string), session); } }
Source:
public YouViewResult delete(String elementId) { final String queryUrl = buildDeleteQuery(elementId); log.trace(String.format("Sending Delete request: %s", queryUrl)); Retryer<HttpResponse> retryer = getHttpRequestRetryer(); Callable<HttpResponse> deleteCall = new Callable<HttpResponse>() { @Override public HttpResponse call() throws Exception { deleteRetryCount++; log.trace(String.format("YouView delete retry count - %s.", deleteRetryCount)); return httpClient.delete(queryUrl); } }; try { HttpResponse response = retryer.call(deleteCall); deleteRetryCount = 0; if (response.statusCode() == HttpServletResponse.SC_ACCEPTED) { String transactionUrl = parseIdFrom(response.header("Location")); log.trace("Delete successful. Transaction url: " + transactionUrl); return success(transactionUrl, clock.now(), response.statusCode()); } else { return failure(response.body(), clock.now(), response.statusCode()); } } catch (ExecutionException e) { throw new YouViewClientException("Error deleting id " + elementId, e); } catch (RetryException e) { throw new YouViewClientException("Error deleting id " + elementId, e); } }

Target:
public YouViewResult delete(String elementId) { final String queryUrl = buildDeleteQuery(elementId); log.trace("Sending Delete request: {}", queryUrl); Retryer<HttpResponse> retryer = getHttpRequestRetryer(); Callable<HttpResponse> deleteCall = new Callable<HttpResponse>() { @Override public HttpResponse call() throws Exception { deleteRetryCount++; if (deleteRetryCount > 1) { log.warn("YouView delete retry count - {}", deleteRetryCount); } return httpClient.delete(queryUrl); } }; try { HttpResponse response = retryer.call(deleteCall); deleteRetryCount = 0; if (response.statusCode() == HttpServletResponse.SC_ACCEPTED) { String transactionUrl = parseIdFrom(response.header("Location")); log.trace("Delete successful. Transaction url: " + transactionUrl); return success(transactionUrl, clock.now(), response.statusCode()); } else { return failure(response.body(), clock.now(), response.statusCode()); } } catch (ExecutionException e) { throw new YouViewClientException("Error deleting id " + elementId, e); } catch (RetryException e) { throw new YouViewClientException("Error deleting id " + elementId, e); } }