auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void unmanagedDeployment() throws Exception { ops.viewDeployment(browser, navigation, DEPLOYMENT_MED_10); String content = page.getDeploymentContentTableRow("Managed"); assertTrue(content.contains("false")); content = page.getDeploymentContentTableRow("Managed"); assertTrue(content.contains("false")); content = page.getDeploymentContentTableRow("Status"); assertTrue("Status of deployment should be 'OK'", content.contains("OK")); }

Target:
public void unmanagedDeployment() throws Exception { page.viewDeployment(DEPLOYMENT_UNMANAGED_10); String content = page.getDeploymentContentTableRow("Managed"); assertTrue(content.contains("false")); content = page.getDeploymentContentTableRow("Status"); assertTrue("Status of deployment should be 'OK'", content.contains("OK")); }
Source:
private Callable<Void> readRecoveredStateTask(RecoveredInputChannel inputChannel, ChannelStateReader reader, boolean verifyRelease) { return () -> { try { inputChannel.readRecoveredState(reader); } catch (Throwable t) { assertTrue("The expected exception should only happen in the case of released channel.", verifyRelease && inputChannel.isReleased()); } return null; }; }

Target:
private Callable<Void> readRecoveredStateTask(RecoveredInputChannel inputChannel, ChannelStateReader reader, boolean verifyRelease) { return () -> { try { inputChannel.readRecoveredState(reader); } catch (Throwable t) { if (!(verifyRelease && inputChannel.isReleased())) { throw new AssertionError("Exceptions are expected here only if the input channel was released", t); } } return null; }; }
Source:
private ArrayList<SearchResult> ctxSearch(String query, SearchControls sc, LdapContext ctx) throws NamingException { NamingEnumeration<SearchResult> resultQuery = null; ArrayList<SearchResult> result = new ArrayList<SearchResult>(); if (subDNs != null && subDNs.size() > 0){ for (String subDN : subDNs.getList()) { resultQuery = ctx.search(subDN + "," + baseDN, query, sc); try { if (resultQuery != null && resultQuery.hasMore()) { result.addAll(Collections.list(resultQuery)); } } finally { closeQuietly(resultQuery); resultQuery = null; } } } else { resultQuery = ctx.search(baseDN, query, sc); try { if (resultQuery != null && resultQuery.hasMore()) { result.addAll(Collections.list(resultQuery)); } } finally { closeQuietly(resultQuery); resultQuery = null; } } return result; }

Target:
private ArrayList<SearchResult> ctxSearch(String query, SearchControls sc, LdapContext ctx) throws NamingException { ArrayList<SearchResult> result = new ArrayList<SearchResult>(); if (subDNs != null && subDNs.size() > 0){ for (String subDN : subDNs.getList()) { addSearchResult(result, subDN + "," + baseDN, query, sc, ctx); } } else { addSearchResult(result, baseDN, query, sc, ctx); } return result; }
Source:
public void whenMatchExactlyEnabled_disablesPrefs() { rule.mainMenu() .clickOnMenu() .clickGeneralSettings() .clickFormManagement() .clickUpdateForms() .clickOption(R.string.match_exactly) .assertDisabled(R.string.automatic_download); }

Target:
public void whenMatchExactlyEnabled_disablesPrefs() { new MainMenuPage(rule).assertOnPage() .clickOnMenu() .clickGeneralSettings() .clickFormManagement() .clickUpdateForms() .clickOption(R.string.match_exactly) .assertEnabled(R.string.form_update_frequency_title) .assertDisabled(R.string.automatic_download); }
Source:
private void writeNormalizedConfigDocuments(Collection<Report> reports) { for (Report report : reports) { for (Configuration.Setup setup : report.getConfiguration().getSetups()) { Set<Integer> slaves = report.getCluster().getSlaves(setup.group); Set<String> normalized = new HashSet<>(); for (Map.Entry<Integer, Map<String, Properties>> entry : report.getNormalizedServiceConfigs().entrySet()) { if (slaves.contains(entry.getKey()) && entry.getValue() != null) { normalized.addAll(entry.getValue().keySet()); } } for (String config : normalized) { NormalizedConfigDocument document = new NormalizedConfigDocument( targetDir, report.getConfiguration().name, setup.group, report.getCluster(), config, report.getNormalizedServiceConfigs(), slaves); freemarker.template.Configuration cfg = initConfig(); try { document.createReportDirectory(); Template reportTemplate = cfg.getTemplate("normalizedReport.ftl"); PrintWriter printWriter = new PrintWriter(targetDir + File.separator + document.getFileName()); Map root = new HashMap(); root.put("normalized", document); reportTemplate.process(root, printWriter); printWriter.close(); } catch (Exception e) { log.error("Templating exception", e); } } } } }

Target:
private void writeNormalizedConfigDocuments(Collection<Report> reports) { for (Report report : reports) { for (Configuration.Setup setup : report.getConfiguration().getSetups()) { Set<Integer> slaves = report.getCluster().getSlaves(setup.group); Set<String> normalized = new HashSet<>(); for (Map.Entry<Integer, Map<String, Properties>> entry : report.getNormalizedServiceConfigs().entrySet()) { if (slaves.contains(entry.getKey()) && entry.getValue() != null) { normalized.addAll(entry.getValue().keySet()); } } for (String config : normalized) { NormalizedConfigDocument document = new NormalizedConfigDocument( targetDir, report.getConfiguration().name, setup.group, report.getCluster(), config, report.getNormalizedServiceConfigs(), slaves); document.createReportDirectory(); Map root = new HashMap(); root.put("normalized", document); processTemplate(root, targetDir, document.getFileName(), "normalizedReport.ftl"); } } } }
Source:
public UniversalServerPluginProvider(DynamicSet<ServerPluginProvider> sf) { this.serverPluginProviders = sf; }

Target:
UniversalServerPluginProvider(DynamicSet<ServerPluginProvider> sf) { this.serverPluginProviders = sf; }
Source:
protected boolean isFeatureEditable(final String propertyPath) { boolean editable = true; EStructuralFeature feature = getFeature(propertyPath); EObject source = getSource(); if (source instanceof RTPort) { RTPort rtPort = (RTPort) source; UMLRTPort port = UMLRTPort.getInstance(rtPort.getBase_Port()); if (null != port) { UMLRTProtocol protocol = port.getType(); if ((protocol != null) && SystemElementsUtils.isSystemProtocol(protocol.toUML())) { editable = false; } else if (IRealTimeConstants.KIND.equals(propertyPath)) { editable = true; } else if (feature == UMLRealTimePackage.Literals.RT_PORT__IS_NOTIFICATION) { editable = port.isBehavior(); } else if (feature == UMLRealTimePackage.Literals.RT_PORT__IS_WIRED) { editable = !port.isInherited(); editable = editable && port.isBehavior() && !port.isConnected() && !RTPortUtils.isLegacySpp(port.toUML()) && !RTPortUtils.isLegacySap(port.toUML()); } else if (feature == UMLRealTimePackage.Literals.RT_PORT__IS_PUBLISH) { editable = false; } else if (feature == UMLRealTimePackage.Literals.RT_PORT__REGISTRATION) { editable = !rtPort.isWired() && !port.isInherited(); } else if (feature == UMLRealTimePackage.Literals.RT_PORT__REGISTRATION_OVERRIDE) { editable = !rtPort.isWired() && !port.isInherited(); } else { editable = super.isFeatureEditable(propertyPath); } } } else if (source instanceof CapsulePart) { UMLRTCapsulePart capsulePart = UMLRTCapsulePart.getInstance(((CapsulePart) source).getBase_Property()); editable = capsulePart != null; if (editable && IRealTimeConstants.KIND.equals(propertyPath)) { editable = !"*".equals(capsulePart.getReplicationFactorAsString()); } } else { editable = super.isFeatureEditable(propertyPath); } return editable; }

Target:
protected boolean isFeatureEditable(final String propertyPath) { boolean editable = true; EStructuralFeature feature = getFeature(propertyPath); EObject source = getSource(); if (source instanceof RTPort) { RTPort rtPort = (RTPort) source; UMLRTPort port = UMLRTPort.getInstance(rtPort.getBase_Port()); if (null != port) { UMLRTProtocol protocol = port.getType(); if ((protocol != null) && SystemElementsUtils.isSystemProtocol(protocol.toUML())) { editable = false; } else if (IRealTimeConstants.KIND.equals(propertyPath)) { editable = true; } else if (feature == UMLRealTimePackage.Literals.RT_PORT__IS_NOTIFICATION) { editable = port.isBehavior(); } else if (feature == UMLRealTimePackage.Literals.RT_PORT__IS_WIRED) { editable = !port.isInherited(); editable = editable && port.isBehavior() && !port.isConnected() && !RTPortUtils.isLegacySpp(port.toUML()) && !RTPortUtils.isLegacySap(port.toUML()); } else if (feature == UMLRealTimePackage.Literals.RT_PORT__IS_PUBLISH) { editable = false; } else if (feature == UMLRealTimePackage.Literals.RT_PORT__REGISTRATION) { editable = !rtPort.isWired() && !port.isInherited(); } else if (feature == UMLRealTimePackage.Literals.RT_PORT__REGISTRATION_OVERRIDE) { editable = !rtPort.isWired() && !port.isInherited(); } else { editable = super.isFeatureEditable(propertyPath); } } } else if (source instanceof CapsulePart) { editable = true; } else { editable = super.isFeatureEditable(propertyPath); } return editable; }
Source:
public void putMetadata(String key, Object value) { metadata.put(key, value); }

Target:
public void putMetadata(String key, Object value) { if (metadata == null) { metadata = new HashMap<>(); } metadata.put(key, value); }
Source:
public void debug() { ActiveMQServerLogger.LOGGER.debugStarted(globalSizeBytes.get(), numberOfMessages.get()); }

Target:
public void debug() { logger.info("size = " + globalSizeBytes + " bytes, messages = " + numberOfMessages); }
Source:
static private void validateGenotypes(final VariantContext variantContext) { final ArrayList<Genotype> genotypes = variantContext.genotypes.getGenotypes(); if (genotypes == null) { throw new IllegalStateException("Genotypes is null"); } for (int i = 0; i < genotypes.size(); i++) { final Genotype genotype = genotypes.get(i); if (genotype.isAvailable()) { final List<Allele> alleles = genotype.getAlleles(); for (int j = 0, size = alleles.size(); j < size; j++) { final Allele gAllele = alleles.get(j); if (!variantContext.hasAllele(gAllele) && gAllele.isCalled()) { throw new IllegalStateException("Allele in genotype " + gAllele + " not in the variant context " + alleles); } } } } }

Target:
private static void validateGenotypes(final VariantContext variantContext) { final ArrayList<Genotype> genotypes = variantContext.genotypes.getGenotypes(); if (genotypes == null) { throw new IllegalStateException("Genotypes is null"); } for (int i = 0; i < genotypes.size(); i++) { final Genotype genotype = genotypes.get(i); if (genotype.isAvailable()) { final List<Allele> alleles = genotype.getAlleles(); for (int j = 0, size = alleles.size(); j < size; j++) { final Allele gAllele = alleles.get(j); if (!variantContext.hasAllele(gAllele) && gAllele.isCalled()) { throw new IllegalStateException("Allele in genotype " + gAllele + " not in the variant context " + alleles); } } } } }
Source:
public List<Entity> findLastJobs() { final List<Entity> jobs = new ArrayList<>(); Instant weekAgo = Instant.now().minus(7, ChronoUnit.DAYS).truncatedTo(ChronoUnit.DAYS); User currentUser = userAccountService.getCurrentUser(); dataService .getMeta() .getEntityTypes() .filter(this::isAllowedJobExecutionEntityType) .forEach( e -> { Query<Entity> q = dataService.query(e.getId()).ge(JobExecutionMetaData.SUBMISSION_DATE, weekAgo); if (!Boolean.TRUE.equals(currentUser.isSuperuser())) { q.and().eq(USER, currentUser.getUsername()); } dataService.findAll(e.getId(), q).forEach(jobs::add); }); jobs.sort( (job1, job2) -> job2.getInstant(SUBMISSION_DATE).compareTo(job1.getInstant(SUBMISSION_DATE))); if (jobs.size() > MAX_JOBS_TO_RETURN) { return jobs.subList(0, MAX_JOBS_TO_RETURN); } return jobs; }

Target:
public List<Entity> findLastJobs() { final List<Entity> jobs = new ArrayList<>(); Instant weekAgo = Instant.now().minus(7, ChronoUnit.DAYS).truncatedTo(ChronoUnit.DAYS); User currentUser = userAccountService.getCurrentUser(); dataService .getMeta() .getEntityTypes() .filter(this::isAllowedJobExecutionEntityType) .forEach( e -> { Query<Entity> q = dataService.query(e.getId()).ge(JobExecutionMetaData.SUBMISSION_DATE, weekAgo); if (!currentUser.isSuperuser()) { q.and().eq(USER, currentUser.getUsername()); } dataService.findAll(e.getId(), q).forEach(jobs::add); }); jobs.sort( (job1, job2) -> job2.getInstant(SUBMISSION_DATE).compareTo(job1.getInstant(SUBMISSION_DATE))); if (jobs.size() > MAX_JOBS_TO_RETURN) { return jobs.subList(0, MAX_JOBS_TO_RETURN); } return jobs; }
Source:
private static List<ContainerUUID> getColumnContainers (Element splitBody ) { Pattern parseContainerPatter = Pattern.compile( "(?<=#parseContainer\\(').*?(?='\\))" ); List<ContainerUUID> containers = new ArrayList<>(); Matcher matcher = parseContainerPatter.matcher( splitBody.text() ); while ( matcher.find() ) { String parseContainerArguments = matcher.group(); if (parseContainerArguments != null) { String[] splitArguments = parseContainerArguments.split(","); String id = splitArguments[0]; String uuid = splitArguments.length > 1 ? splitArguments[1] : ParseContainer.DEFAULT_UUID_VALUE; containers.add(new ContainerUUID(id, uuid)); } } return containers; }

Target:
private static List<ContainerUUID> getColumnContainers (Element splitBody ) { List<ContainerUUID> containers = new ArrayList<>(); Matcher matcher = parseContainerPatter.matcher( splitBody.text() ); while ( matcher.find() ) { String parseContainerArguments = matcher.group(); if (parseContainerArguments != null) { String[] splitArguments = parseContainerArguments.split(","); String id = splitArguments[0]; String uuid = splitArguments.length > 1 ? splitArguments[1] : ParseContainer.DEFAULT_UUID_VALUE; containers.add(new ContainerUUID(id, uuid)); } } return containers; }
Source:
public Optional<Statistic> getById(String id) { return Optional.ofNullable(this.statisticMappings.get(id.toLowerCase())); }

Target:
public Optional<Statistic> getById(String id) { return Optional.ofNullable(this.statisticMappings.get(id.toLowerCase(Locale.ENGLISH))); }
Source:
private static String getExtension(File file) { String name = file.getName(); int ext = name.lastIndexOf("."); return 0 < ext ? name.substring(ext, name.length()) : ""; }

Target:
private static String getExtension(File file) { return getExtension(file.getName()); }
Source:
public Color getDiffImageColor() { int rgba = new BigInteger(diffImageColorRgbaHex.substring(2), 16).intValue(); return new Color(rgba, true); }

Target:
public Color getDiffImageColor() { int rgba = Long.decode(diffImageColorRgbaHex).intValue(); return new Color(rgba, true); }
Source:
public ScarwoodBandits(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{2}{G}{G}"); this.subtype.add("Human"); this.subtype.add("Rogue"); this.power = new MageInt(2); this.toughness = new MageInt(2); this.addAbility(new ForestwalkAbility()); Ability ability = new SimpleActivatedAbility(Zone.BATTLEFIELD, new ScarwoodBanditsEffect(new GenericManaCost(2)), new ManaCostsImpl("{2}{G}")); ability.addCost(new TapSourceCost()); ability.addTarget(new TargetArtifactPermanent()); this.addAbility(ability); }

Target:
public ScarwoodBandits(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{2}{G}{G}"); this.subtype.add(SubType.HUMAN); this.subtype.add(SubType.ROGUE); this.power = new MageInt(2); this.toughness = new MageInt(2); this.addAbility(new ForestwalkAbility()); Ability ability = new SimpleActivatedAbility(Zone.BATTLEFIELD, new DoUnlessAnyOpponentPaysEffect( new ConditionalContinuousEffect( new GainControlTargetEffect(Duration.Custom, true), new SourceOnBattlefieldCondition(), "gain control of target artifact for as long as {this} remains on the battlefield"), new GenericManaCost(2)), new ManaCostsImpl("{2}{G}")); ability.addCost(new TapSourceCost()); ability.addTarget(new TargetArtifactPermanent()); this.addAbility(ability); }
Source:
public CompletableFuture<Boolean> setPointer(PublicSigningKey owner, PublicSigningKey signer, byte[] sharingKeySignedBtreeRootHashes) { byte[] message = signer.unsignMessage(sharingKeySignedBtreeRootHashes); HashCasPair cas = HashCasPair.fromCbor(CborObject.fromByteArray(message)); long t1 = System.currentTimeMillis(); return storage.recursivePin(cas.updated.get()).thenCompose(pins -> { if (!pins.contains(cas.updated.get())) return CompletableFuture.completedFuture(false); long t2 = System.currentTimeMillis(); if (LOGGING) System.out.println("Pinning "+cas.updated+" took: " + (t2 -t1) + " mS"); return target.setPointer(owner, signer, sharingKeySignedBtreeRootHashes) .thenCompose(b -> { if (!b) return CompletableFuture.completedFuture(false); long t3 = System.currentTimeMillis(); return !cas.original.isPresent() ? CompletableFuture.completedFuture(true) : storage.recursiveUnpin(cas.original.get()) .thenApply(unpins -> { long t4 = System.currentTimeMillis(); if (LOGGING) System.out.println("Unpinning "+cas.original+" took: " + (t4 -t3) + " mS"); return unpins.contains(cas.original.get()); }); }); }); }

Target:
public CompletableFuture<Boolean> setPointer(PublicSigningKey owner, PublicSigningKey signer, byte[] sharingKeySignedBtreeRootHashes) { byte[] message = signer.unsignMessage(sharingKeySignedBtreeRootHashes); HashCasPair cas = HashCasPair.fromCbor(CborObject.fromByteArray(message)); long t1 = System.currentTimeMillis(); return storage.recursivePin(cas.updated.get()).thenCompose(pins -> { if (!pins.contains(cas.updated.get())) { CompletableFuture<Boolean> err = new CompletableFuture<>(); err.completeExceptionally(new IllegalStateException("Couldn't pin new hash: " + cas.updated.get())); return err; } long t2 = System.currentTimeMillis(); if (LOGGING) System.out.println("Pinning "+cas.updated+" took: " + (t2 -t1) + " mS"); return target.setPointer(owner, signer, sharingKeySignedBtreeRootHashes) .thenCompose(b -> { if (!b) { CompletableFuture<Boolean> err = new CompletableFuture<>(); err.completeExceptionally(new IllegalStateException("Couldn't update mutable pointer, cas failed: " + cas)); return err; } long t3 = System.currentTimeMillis(); return !cas.original.isPresent() ? CompletableFuture.completedFuture(true) : storage.recursiveUnpin(cas.original.get()) .thenApply(unpins -> { long t4 = System.currentTimeMillis(); if (LOGGING) System.out.println("Unpinning "+cas.original+" took: " + (t4 -t3) + " mS"); return unpins.contains(cas.original.get()); }); }); }); }
Source:
private static String getMetricNameWithUniqueId(InstanceType instance, String name) { if (sSourceName == null) { switch (instance) { case CLIENT: if (CONF.isSet(PropertyKey.USER_APP_ID)) { sSourceName = CONF.get(PropertyKey.USER_APP_ID); } else { sSourceName = NetworkAddressUtils.getLocalHostMetricName(sResolveTimeout); } break; case WORKER: if (CONF.isSet(PropertyKey.WORKER_HOSTNAME)) { sSourceName = CONF.get(PropertyKey.WORKER_HOSTNAME); } else { sSourceName = NetworkAddressUtils.getLocalHostMetricName(sResolveTimeout); } break; case JOB_WORKER: if (CONF.isSet(PropertyKey.JOB_WORKER_HOSTNAME)) { sSourceName = CONF.get(PropertyKey.JOB_WORKER_HOSTNAME); } else { sSourceName = NetworkAddressUtils.getLocalHostMetricName(sResolveTimeout); } break; default: sSourceName = NetworkAddressUtils.getLocalHostMetricName(sResolveTimeout); break; } } if (name.startsWith(instance.toString())) { return Joiner.on(".").join(name, sSourceName); } return Joiner.on(".").join(instance, name, sSourceName); }

Target:
private static String getMetricNameWithUniqueId(InstanceType instance, String name) { if (name.startsWith(instance.toString())) { return Joiner.on(".").join(name, sSourceNameSupplier); } return Joiner.on(".").join(instance, name, sSourceNameSupplier); }
Source:
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { if (trustManager != null) { try { trustManager.checkServerTrusted(chain, authType); return; } catch (Exception e) { } } X509Certificate ca = getCACert(chain); if (ca != null) { if (!isAccepted(ca)) { System.err.println("SSL Error:Server certificate chain verification failed."); throw new CertificateException("Server certificate chain verification failed."); } String id = String.valueOf(System.currentTimeMillis()); X509TrustManager tmpTrustManager = null; try { ks.setCertificateEntry(id, ca); tmpTrustManager = initTrustManager(ks); } catch (Exception e) { System.err.println("ASF Truster: Failed to create tmp trust store : " + e.getMessage()); throw new CertificateException(e); } try { tmpTrustManager.checkServerTrusted(chain, authType); if (this.isSaveCA) { saveStore(); trustManager = tmpTrustManager; } return; } catch (CertificateException e) { System.err.println("SSL Error:Server certificate chain verification failed and \\nthe CA is missing."); throw e; } } else { System.err .println( "SSL Error:CA certificate is not in the server certificate chain.\nPlease use the keytool command to import the server certificate."); throw new CertificateException( "CA certificate is not in the server certificate chain.\\nPlease use the keytool command to import the server certificate."); } }

Target:
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { if (trustManager != null) { try { trustManager.checkServerTrusted(chain, authType); return; } catch (Exception e) { } } X509Certificate ca = getCACert(chain); if (ca != null) { if (!isAccepted(ca)) { throw new CertificateException("Server certificate chain verification failed."); } String id = String.valueOf(System.currentTimeMillis()); X509TrustManager tmpTrustManager = null; try { ks.setCertificateEntry(id, ca); tmpTrustManager = initTrustManager(ks); } catch (Exception e) { throw new CertificateException("ASF Truster: Failed to create tmp trust store", e); } try { tmpTrustManager.checkServerTrusted(chain, authType); if (this.isSaveCA) { saveStore(); trustManager = tmpTrustManager; } return; } catch (CertificateException e) { throw new CertificateException( "SSL Error:Server certificate chain verification failed and \nthe CA is missing.", e); } } else { throw new CertificateException( "CA certificate is not in the server certificate chain.\nPlease use the keytool command to import the server certificate."); } }
Source:
public void testSaveAndLoadSnapshotInfo() throws Exception { File rootDir = folder.newFolder(); OMRatisSnapshotInfo omRatisSnapshotInfo = new OMRatisSnapshotInfo(rootDir); Assert.assertEquals(0, omRatisSnapshotInfo.getTerm()); Assert.assertEquals(-1, omRatisSnapshotInfo.getIndex()); int snapshotIndex = 10; int termIndex = 2; omRatisSnapshotInfo.updateTerm(termIndex); omRatisSnapshotInfo.saveRatisSnapshotToDisk(snapshotIndex); Assert.assertEquals(2, omRatisSnapshotInfo.getTerm()); Assert.assertEquals(10, omRatisSnapshotInfo.getIndex()); OMRatisSnapshotInfo newSnapshotInfo = new OMRatisSnapshotInfo(rootDir); Assert.assertEquals(2, newSnapshotInfo.getTerm()); Assert.assertEquals(10, newSnapshotInfo.getIndex()); }

Target:
public void testSaveAndLoadSnapshotInfo() throws Exception { File rootDir = folder.newFolder(); OMRatisSnapshotInfo omRatisSnapshotInfo = new OMRatisSnapshotInfo(rootDir); Assert.assertEquals(0, omRatisSnapshotInfo.getTerm()); Assert.assertEquals(-1, omRatisSnapshotInfo.getIndex()); Random random = new Random(); int snapshotIndex = random.nextInt(50); int termIndex = random.nextInt(10); omRatisSnapshotInfo.updateTerm(termIndex); omRatisSnapshotInfo.saveRatisSnapshotToDisk(snapshotIndex); Assert.assertEquals(termIndex, omRatisSnapshotInfo.getTerm()); Assert.assertEquals(snapshotIndex, omRatisSnapshotInfo.getIndex()); OMRatisSnapshotInfo newSnapshotInfo = new OMRatisSnapshotInfo(rootDir); Assert.assertEquals(termIndex, newSnapshotInfo.getTerm()); Assert.assertEquals(snapshotIndex, newSnapshotInfo.getIndex()); }
Source:
public static void show(UIFacade uiFacade, RssUpdate update) { JEditorPane versionRow = createHtml(GanttLanguage.getInstance().formatText("updateAvailable", update.getVersion())); JEditorPane descriptionRow = createHtml(update.getDescription()); Box dialogBox = Box.createVerticalBox(); dialogBox.add(versionRow); dialogBox.add(descriptionRow); JPanel panel = new JPanel(); panel.add(dialogBox); OkAction okAction = new OkAction() { @Override public void actionPerformed(ActionEvent e) { } }; UIFacade.Dialog dlg = uiFacade.createDialog(panel, new Action[] { okAction, CancelAction.EMPTY }, ""); dlg.show(); }

Target:
public static void show(UIFacade uiFacade, RssUpdate update) { JEditorPane versionRow = createHtml(GanttLanguage.getInstance().formatText("updateAvailable", update.getVersion())); JEditorPane descriptionRow = createHtml(update.getDescription()); Box dialogBox = Box.createVerticalBox(); dialogBox.add(versionRow); dialogBox.add(descriptionRow); JPanel panel = new JPanel(); panel.add(dialogBox); OkAction okAction = new OkAction() { @Override public void actionPerformed(ActionEvent e) { } }; SwingUtilities.invokeLater(() -> { UIFacade.Dialog dlg = uiFacade.createDialog(panel, new Action[] { okAction, CancelAction.EMPTY }, ""); dlg.show(); }); }
Source:
public void testInitNonEmptyRepository() { try { File directory = createTempDirectory("testInitRepository2"); File someFile = new File(directory, "someFile"); someFile.createNewFile(); assertTrue(someFile.exists()); assertTrue(directory.listFiles().length > 0); InitCommand command = new InitCommand(); command.setDirectory(directory); Repository repository = command.call().getRepository(); addRepoToClose(repository); assertNotNull(repository); } catch (Exception e) { fail(e.getMessage()); } }

Target:
public void testInitNonEmptyRepository() throws IOException { File directory = createTempDirectory("testInitRepository2"); File someFile = new File(directory, "someFile"); someFile.createNewFile(); assertTrue(someFile.exists()); assertTrue(directory.listFiles().length > 0); InitCommand command = new InitCommand(); command.setDirectory(directory); Repository repository = command.call().getRepository(); addRepoToClose(repository); assertNotNull(repository); }
Source:
public ProviderInfo getProviderInfo() { return null; }

Target:
public ProviderInfo getProviderInfo() { return new ProviderInfo(BASIC_PROVIDER_NAME); }
Source:
protected void executeVmCommand() { MigrateBrokerVDSCommand<?> command = new MigrateBrokerVDSCommand<>(getParameters()); command.execute(); VDSReturnValue vdsReturnValue = command.getVDSReturnValue(); VM vm = getVmDao().get(getParameters().getVmId()); if (vdsReturnValue.getSucceeded()) { ResourceManager.getInstance().AddAsyncRunningVm(getParameters().getVmId()); ResourceManager.getInstance().InternalSetVmStatus(vm, VMStatus.MigratingFrom, vm.getStatusUpdatedTime()); vm.setMigratingToVds(getParameters().getDstVdsId()); vmManager.update(vm.getDynamicData()); getVDSReturnValue().setReturnValue(VMStatus.MigratingFrom); } else { log.error("Failed Vm migration"); getVDSReturnValue().setSucceeded(false); getVDSReturnValue().setReturnValue(vm.getStatus()); getVDSReturnValue().setVdsError(vdsReturnValue.getVdsError()); getVDSReturnValue().setExceptionString(vdsReturnValue.getExceptionString()); getVDSReturnValue().setExceptionObject(vdsReturnValue.getExceptionObject()); } }

Target:
protected void executeVmCommand() { MigrateBrokerVDSCommand<?> command = new MigrateBrokerVDSCommand<>(getParameters()); command.execute(); VDSReturnValue vdsReturnValue = command.getVDSReturnValue(); VM vm = getVmDao().get(getParameters().getVmId()); if (vdsReturnValue.getSucceeded()) { ResourceManager.getInstance().AddAsyncRunningVm(getParameters().getVmId()); ResourceManager.getInstance().InternalSetVmStatus(vm, VMStatus.MigratingFrom); vm.setMigratingToVds(getParameters().getDstVdsId()); vmManager.update(vm.getDynamicData()); getVDSReturnValue().setReturnValue(VMStatus.MigratingFrom); } else { log.error("Failed Vm migration"); getVDSReturnValue().setSucceeded(false); getVDSReturnValue().setReturnValue(vm.getStatus()); getVDSReturnValue().setVdsError(vdsReturnValue.getVdsError()); getVDSReturnValue().setExceptionString(vdsReturnValue.getExceptionString()); getVDSReturnValue().setExceptionObject(vdsReturnValue.getExceptionObject()); } }
Source:
public void testAnEnabledRoomIsAvailableInTheTablet() throws InterruptedException{ HomeTabletPage homeTabletPage = new HomeTabletPage(); SettingsPage settingsPage = homeTabletPage.clickSettingsBtn(); homeTabletPage = settingsPage.selectRoom(roomName); SearchPage searchPage = homeTabletPage.clickSearchBtn(); searchPage.clickCollapseAdvancedBtn(); searchPage.setName(roomName); Assert.assertTrue(searchPage.roomIsDiplayed(roomName)); }

Target:
public void testAnEnabledRoomIsAvailableInTheTablet() { HomeTabletPage homeTabletPage = new HomeTabletPage(); SettingsPage settingsPage = homeTabletPage.clickSettingsBtn(); homeTabletPage = settingsPage.selectRoom(roomName); SearchPage searchPage = homeTabletPage.clickSearchBtn() .clickCollapseAdvancedBtn() .setName(roomName); Assert.assertTrue(searchPage.roomIsDiplayed(roomName)); }
Source:
Matrix mul(Matrix that) { float[][] a = this.m; float[][] b = that.m; final int rowsA = a.length; final int colsA = a[0].length; final int rowsB = b.length; final int colsB = b[0].length; if (colsA != rowsB) { throw new AssertionError("Matrix with " + colsA + " columns cannot be multiplied with matrix with " + colsB + " rows"); } float[][] c = new float[rowsA][colsB]; for (int i = 0; i < rowsA; i++) { for (int j = 0; j < colsB; j++) { for (int k = 0; k < colsA; k++) { c[i][j] += a[i][k] * b[k][j]; } } } return new Matrix(c); }

Target:
Matrix mul(Matrix that) { float[][] a = this.m; float[][] b = that.m; final int rowsA = a.length; final int colsA = a[0].length; final int rowsB = b.length; final int colsB = b[0].length; if (colsA != rowsB) { throw new ArithmeticException("Matrix with " + colsA + " columns cannot be multiplied with matrix with " + colsB + " rows"); } float[][] c = new float[rowsA][colsB]; for (int i = 0; i < rowsA; i++) { for (int j = 0; j < colsB; j++) { for (int k = 0; k < colsA; k++) { c[i][j] += a[i][k] * b[k][j]; } } } return new Matrix(c); }
Source:
public TimerEvent(@JsonProperty("cronExpression") final String cronExpression) { this.cronExpression = cronExpression; }

Target:
public TimerEvent(@JsonProperty("cronExpression") final String cronExpression) { this.cronExpression = notEmpty(cronExpression, "cronExpression"); }
Source:
public void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { element.setAttribute(XMLConstants.ID,XMLConstants.CUSTOM_REPORTING_SERVICE); builder.setParentName(XMLConstants.DEFAULT_REPORTING_SERVICE); builder.addPropertyValue(XMLConstants.REPORT_TYPE,element.getAttribute(XMLConstants.REPORT_TYPE)); builder.addPropertyValue(XMLConstants.ROOT_TEMPLATE_LOCATION,element.getAttribute(XMLConstants.ROOT_TEMPLATE_LOCATION)); builder.addPropertyValue(XMLConstants.OUTPUT_REPORT_LOCATION,element.getAttribute(XMLConstants.OUTPUT_REPORT_LOCATION)); try{ parserContext.getRegistry().removeAlias(XMLConstants.REPORTING_SERVICE); } catch (Exception e){ } List<Element> elements = DomUtils.getChildElements(element); for(Element el : elements){ parserContext.getDelegate().parseCustomElement(el); } parserContext.getRegistry().registerAlias(XMLConstants.CUSTOM_REPORTING_SERVICE, XMLConstants.REPORTING_SERVICE); }

Target:
public void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { super.doParse(element,parserContext,builder); element.setAttribute(XMLConstants.ID,XMLConstants.CUSTOM_REPORTING_SERVICE); builder.setParentName(XMLConstants.DEFAULT_REPORTING_SERVICE); List<Element> elements = DomUtils.getChildElements(element); for(Element el : elements){ parserContext.getDelegate().parseCustomElement(el); } if(parserContext.getRegistry().getAliases(XMLConstants.REPORTING_SERVICE).length>0){ parserContext.getRegistry().removeAlias(XMLConstants.REPORTING_SERVICE); } parserContext.getRegistry().registerAlias(XMLConstants.CUSTOM_REPORTING_SERVICE, XMLConstants.REPORTING_SERVICE); }
Source:
private Fragment getFragment(String fragmentName) { if(fragmentName.equals(getString(R.string.playlist))) return new PlaylistFragment(); if(fragmentName.equals(getString(R.string.music_library))) return new MusicLibraryFragment(); if(fragmentName.equals(getString(R.string.menu))) return new MenuFragment(); return null; }

Target:
private Fragment getFragment(String fragmentName) { Fragment newFragment = null; if(fragmentName.equals(getString(R.string.playlist))){ newFragment = new PlaylistFragment(); } else if(fragmentName.equals(getString(R.string.music_library))){ newFragment = new MusicLibraryFragment(); } else if(fragmentName.equals(getString(R.string.menu))){ newFragment = new MenuFragment(); } return newFragment; }
Source:
public void testEventHandle() { ITmfContext ctx = fTrace.seekEvent(0); ITmfEvent event; while ((event = fTrace.getNext(ctx)) != null) { fStateProvider.processEvent(event); } fStateProvider.waitForEmptyQueue(); ITmfStateSystem ss = fStateProvider.getAssignedStateSystem(); assertNotNull(ss); assertEquals(ss.getAttributeName(0), "Ungrouped"); assertEquals(ss.getAttributeName(1), "counter"); assertEquals(ss.getAttributeName(2), "Grouped"); assertEquals(ss.getAttributeName(3), "CPU"); assertEquals(ss.getAttributeName(4), "0"); assertEquals(ss.getAttributeName(5), "counter"); assertEquals(ss.getAttributeName(6), "1"); assertEquals(ss.getAttributeName(7), "counter"); }

Target:
public void testEventHandle() { ITmfContext ctx = fTrace.seekEvent(0); ITmfEvent event; while ((event = fTrace.getNext(ctx)) != null) { fStateProvider.processEvent(event); } fStateProvider.waitForEmptyQueue(); ITmfStateSystem ss = fStateProvider.getAssignedStateSystem(); assertNotNull(ss); assertEquals(8, ss.getNbAttributes()); assertEquals("Ungrouped", ss.getAttributeName(0)); assertEquals("counter", ss.getAttributeName(1)); assertEquals("Grouped", ss.getAttributeName(2)); assertEquals("CPU", ss.getAttributeName(3)); assertEquals("0", ss.getAttributeName(4)); assertEquals("counter", ss.getAttributeName(5)); assertEquals("1", ss.getAttributeName(6)); assertEquals("counter", ss.getAttributeName(7)); }
Source:
public List<BusinessObjectBase> getSearchResults(Class<? extends BusinessObjectBase> businessObjectClass, MultivaluedMap<String, String> fieldValues) { List<BusinessObjectBase> results = super.getSearchResults(businessObjectClass, fieldValues); List createDoneBatchFiles = new ArrayList<CreateDoneBatchFile>(); for (Object file : results) { BatchFile batchFile = (BatchFile) file; CreateDoneBatchFile createDoneBatchFile; try { createDoneBatchFile = new CreateDoneBatchFile(batchFile.getId()); createDoneBatchFiles.add(createDoneBatchFile); } catch (FileNotFoundException e) { LOG.error( "An error has occured while creating a CreateDoneBatchFile from the BatchFile object in the search results: " + e.getMessage()); throw new RuntimeException(e); } } return createDoneBatchFiles; }

Target:
public List<BusinessObjectBase> getSearchResults(Class<? extends BusinessObjectBase> businessObjectClass, MultivaluedMap<String, String> fieldValues) { List<BusinessObjectBase> results = super.getSearchResults(businessObjectClass, fieldValues); List<BusinessObjectBase> createDoneBatchFiles = new ArrayList<BusinessObjectBase>(); for (Object file : results) { BatchFile batchFile = (BatchFile) file; CreateDoneBatchFile createDoneBatchFile; try { createDoneBatchFile = new CreateDoneBatchFile(batchFile.getId()); createDoneBatchFiles.add(createDoneBatchFile); } catch (FileNotFoundException e) { LOG.error( "getSearchResults(): An error has occured while creating a CreateDoneBatchFile from the BatchFile object in the search results: " + e.getMessage()); throw new RuntimeException(e); } } return createDoneBatchFiles; }
Source:
public boolean waitForInitialization() { try { fInitialized.await(); } catch (InterruptedException e) return fInitializationSucceeded; }

Target:
public boolean waitForInitialization() { try { fInitialized.await(); } catch (InterruptedException e) { return false; } return fInitializationSucceeded; }
Source:
protected AddVmFromTemplateCommand<AddVmParameters> createCommand() { initVM(); AddVmParameters param = new AddVmParameters(vm); return new AddVmFromTemplateCommand<>(param, null); }

Target:
protected AddVmFromTemplateCommand<AddVmParameters> createCommand() { initVM(); return new AddVmFromTemplateCommand<>(new AddVmParameters(vm), null); }
Source:
private void saveUserInfoToSharedPref(String userId, String emailAddress, String avatarUrl, String token) { PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit() .putBoolean("TOKEN_SAVED", true) .putString("USERNAME", userId) .putString("EMAIL", emailAddress) .putString("AVATAR_IMAGE_URL", avatarUrl) .putString("TOKEN", token) .apply(); }

Target:
private void saveUserInfoToSharedPref(String userId, String emailAddress, String avatarUrl, String token) { PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit() .putBoolean(TOKEN_SAVED_KEY, true) .putString(USERNAME_KEY, userId) .putString(EMAIL_KEY, emailAddress) .putString(AVATAR_IMAGE_KEY, avatarUrl) .putString(TOKEN_KEY, token) .apply(); }
Source:
public void replace(Object parentElementOrTreePath, final int index, Object element) { VirtualItem[] selectedItems = fTree.getSelection(); TreeSelection selection = (TreeSelection) getSelection(); VirtualItem[] itemsToDisassociate; if (parentElementOrTreePath instanceof TreePath) { TreePath elementPath = ((TreePath) parentElementOrTreePath).createChildPath(element); itemsToDisassociate = findItems(elementPath); } else { itemsToDisassociate = findItems(element); } for (VirtualItem parentItem : findItems(parentElementOrTreePath)) { if (index < parentItem.getItemCount()) { VirtualItem item = parentItem.getItem(new Index(index)); selection = adjustSelectionForReplace(selectedItems, selection, item, element, parentItem.getData()); for (VirtualItem itemToDisassociate : itemsToDisassociate) { if (itemToDisassociate != item && itemToDisassociate.getParent() == parentItem) { disassociate(itemToDisassociate); itemToDisassociate.getParent().clear(itemToDisassociate.getIndex()); } } associate(element, item); doUpdate(item); for (VirtualItem element2 : item.getItems()) { element2.setNeedsDataUpdate(); } } } if (!fPreservingSelecction) { internalSetSelection(selection, false); ISelection newSelection = getSelection(); if (!newSelection.equals(selection)) { handleInvalidSelection(selection, newSelection); } } validate(); }

Target:
public void replace(Object parentElementOrTreePath, final int index, Object element) { VirtualItem[] selectedItems = fTree.getSelection(); TreeSelection selection = (TreeSelection) getSelection(); VirtualItem[] itemsToDisassociate; if (parentElementOrTreePath instanceof TreePath) { TreePath elementPath = ((TreePath) parentElementOrTreePath).createChildPath(element); itemsToDisassociate = findItems(elementPath); } else { itemsToDisassociate = findItems(element); } for (VirtualItem parentItem : findItems(parentElementOrTreePath)) { if (index < parentItem.getItemCount()) { VirtualItem item = parentItem.getItem(new Index(index)); selection = adjustSelectionForReplace(selectedItems, selection, item, element, parentItem.getData()); for (VirtualItem itemToDisassociate : itemsToDisassociate) { if (itemToDisassociate != item && itemToDisassociate.getParent() == parentItem) { disassociate(itemToDisassociate); itemToDisassociate.getParent().clear(itemToDisassociate.getIndex()); } } associate(element, item); doUpdate(item); for (VirtualItem childitem : item.getItems()) { childitem.setNeedsDataUpdate(); } } } if (!fPreservingSelecction) { internalSetSelection(selection, false); ISelection newSelection = getSelection(); if (!newSelection.equals(selection)) { handleInvalidSelection(selection, newSelection); } } validate(); }
Source:
public Set<TypeJudgement> getImpliedJudgements(IQueryMetaContext context) { Set<TypeJudgement> result = new HashSet<TypeJudgement>(); IInputKey aggregateResultType = aggregator.getAggregateResultTypeAsInputKey(); for (TypeJudgement parameterJudgement : query.getTypeGuarantees()) { IInputKey inputKey = parameterJudgement.getInputKey(); Tuple judgementIndexTuple = parameterJudgement.getVariablesTuple(); Object[] judgementVariables = new Object[judgementIndexTuple.getSize()]; for (int i=0; i<judgementVariables.length; ++i) { judgementVariables[i] = actualParametersTuple.get((int) judgementIndexTuple.get(i)); } result.add(new TypeJudgement(inputKey, new FlatTuple(judgementVariables))); } if (aggregateResultType != null) { result.add(new TypeJudgement(aggregateResultType, new FlatTuple(resultVariable))); } return result; }

Target:
public Set<TypeJudgement> getImpliedJudgements(IQueryMetaContext context) { Set<TypeJudgement> result = new HashSet<TypeJudgement>(); for (TypeJudgement parameterJudgement : query.getTypeGuarantees()) { IInputKey inputKey = parameterJudgement.getInputKey(); if (context.isPosetKey(inputKey)) { Tuple judgementIndexTuple = parameterJudgement.getVariablesTuple(); Object[] judgementVariables = new Object[judgementIndexTuple.getSize()]; for (int i = 0; i < judgementVariables.length; ++i) { judgementVariables[i] = actualParametersTuple.get((int) judgementIndexTuple.get(i)); } result.add(new TypeJudgement(inputKey, new FlatTuple(judgementVariables))); } } IInputKey aggregateResultType = aggregator.getAggregateResultTypeAsInputKey(); if (aggregateResultType != null && context.isPosetKey(aggregateResultType)) { result.add(new TypeJudgement(aggregateResultType, new FlatTuple(resultVariable))); } return result; }
Source:
public EGVRecord[] getRecentEGVsPages(int numOfRecentPages) { if (numOfRecentPages < 1) { throw new IllegalArgumentException("Number of pages must be greater than 1."); } log.debug("Reading EGV page range..."); int endPage = readDataBasePageRange(RecordType.EGV_DATA); log.debug("Reading " + numOfRecentPages + " EGV page(s)..."); numOfRecentPages = numOfRecentPages - 1; EGVRecord[] allPages = new EGVRecord[0]; for (int i = Math.min(numOfRecentPages,endPage); i >= 0; i--) { int nextPage = endPage - i; log.debug("Reading #" + i + " EGV pages (page number " + nextPage + ")"); EGVRecord[] ithEGVRecordPage = readDataBasePage(RecordType.EGV_DATA, nextPage); EGVRecord[] result = Arrays.copyOf(allPages, allPages.length + ithEGVRecordPage.length); System.arraycopy(ithEGVRecordPage, 0, result, allPages.length, ithEGVRecordPage.length); allPages = result; } log.debug("Read complete of EGV pages."); return allPages; }

Target:
public EGVRecord[] getRecentEGVsPages(int numOfRecentPages) { if (numOfRecentPages < 1) { throw new IllegalArgumentException("Number of pages must be greater than 1."); } log.debug("Reading EGV page range..."); int endPage = readDataBasePageRange(RecordType.EGV_DATA); log.debug("Reading EGV page(s)...", numOfRecentPages); numOfRecentPages = numOfRecentPages - 1; EGVRecord[] allPages = new EGVRecord[0]; for (int i = Math.min(numOfRecentPages,endPage); i >= 0; i--) { int nextPage = endPage - i; log.debug("Reading #{} EGV pages (page number {})", i, nextPage); EGVRecord[] ithEGVRecordPage = readDataBasePage(RecordType.EGV_DATA, nextPage); EGVRecord[] result = Arrays.copyOf(allPages, allPages.length + ithEGVRecordPage.length); System.arraycopy(ithEGVRecordPage, 0, result, allPages.length, ithEGVRecordPage.length); allPages = result; } log.debug("Read complete of EGV pages."); return allPages; }
Source:
public Comparator<InstructorFeedbackResultsResponseRow> getResponseRowsSortOrder() { return Comparator.comparing((InstructorFeedbackResultsResponseRow obj) -> obj.getGiverTeam()) .thenComparing((InstructorFeedbackResultsResponseRow obj) -> obj.getGiverDisplayableIdentifier()) .thenComparing((InstructorFeedbackResultsResponseRow obj) -> obj.getDisplayableResponse()) .thenComparing((InstructorFeedbackResultsResponseRow obj) -> obj.getRecipientTeam()) .thenComparing((InstructorFeedbackResultsResponseRow obj) -> obj.getRecipientDisplayableIdentifier()); }

Target:
public Comparator<InstructorFeedbackResultsResponseRow> getResponseRowsSortOrder() { return Comparator.comparing(InstructorFeedbackResultsResponseRow::getGiverTeam) .thenComparing(InstructorFeedbackResultsResponseRow::getGiverDisplayableIdentifier) .thenComparing(InstructorFeedbackResultsResponseRow::getDisplayableResponse) .thenComparing(InstructorFeedbackResultsResponseRow::getRecipientTeam) .thenComparing(InstructorFeedbackResultsResponseRow::getRecipientDisplayableIdentifier); }
Source:
private ByteBuffer parsePayLoad(ByteBuffer pcapPacketHeader, int blockLength) throws IOException, BadPcapFileException { ByteBuffer pcapPacketData; int interfaceId = pcapPacketHeader.getInt(); getDataLinkTypeNg(interfaceId); pcapPacketHeader.getInt(); pcapPacketHeader.getInt(); int capturedLen = pcapPacketHeader.getInt(); pcapPacketHeader.getInt(); long includedPacketLength = ConversionHelper.unsignedIntToLong(capturedLen); SeekableByteChannel fileChannel = getFileChannel(); if (fileChannel.size() - fileChannel.position() < includedPacketLength) { throw new BadPcapFileException(String.format("%04x", includedPacketLength) + " is causing buffer overrun."); } if (capturedLen > Integer.MAX_VALUE) { throw new BadPcapFileException(String.format("%04x", capturedLen) + " packet length is bigger than 2^31-1 bytes are not supported."); } pcapPacketData = ByteBuffer.allocate((int) includedPacketLength); pcapPacketData.clear(); ByteOrder byteOrder = getByteOrder(); pcapPacketHeader.order(byteOrder); int payLoad = fileChannel.read(pcapPacketData); if (payLoad == 0) { throw new BadPcapFileException(String.format("%04x", payLoad) + " is a bad payload."); } pcapPacketData.flip(); fileChannel.position(fileChannel.position() + blockLength - capturedLen - PcapFileValues.PCAPNG_PACKET_HEADER_SIZE); return pcapPacketData; }

Target:
private ByteBuffer parsePayLoad(ByteBuffer pcapPacketHeader, int blockLength) throws IOException, BadPcapFileException { ByteBuffer pcapPacketData; int interfaceId = pcapPacketHeader.getInt(); getDataLinkTypeNg(interfaceId); pcapPacketHeader.getInt(); pcapPacketHeader.getInt(); int capturedLen = pcapPacketHeader.getInt(); pcapPacketHeader.getInt(); long includedPacketLength = ConversionHelper.unsignedIntToLong(capturedLen); SeekableByteChannel fileChannel = getFileChannel(); if (fileChannel.size() - fileChannel.position() < includedPacketLength) { throw new BadPcapFileException(String.format("%04x", includedPacketLength) + " is causing buffer overrun."); } pcapPacketData = ByteBuffer.allocate((int) includedPacketLength); ByteOrder byteOrder = getByteOrder(); pcapPacketHeader.order(byteOrder); int payLoad = fileChannel.read(pcapPacketData); if (payLoad == 0) { throw new BadPcapFileException(String.format("%04x", payLoad) + " is a bad payload."); } pcapPacketData.flip(); fileChannel.position(fileChannel.position() - capturedLen); return pcapPacketData; }
Source:
public void testConfiguredWithContext() { Context.CancellableContext context = Context.current().withDeadlineAfter(1, TimeUnit.SECONDS, mockExecutor); context.run(new Runnable() { @Override public void run() { CallOptionsConfig config = new CallOptionsConfig.Builder().setUseTimeout(true).build(); CallOptionsFactory factory = new CallOptionsFactory.ConfiguredCallOptionsFactory(config); Assert.assertEquals( Context.current().getDeadline().timeRemaining(TimeUnit.MILLISECONDS), getDeadlineMs(factory, MutateRowRequest.getDefaultInstance()), 100.0 ); } }); }

Target:
public void testConfiguredWithContext() { Deadline deadline = DeadlineUtil.deadlineWithFixedTime(1, TimeUnit.SECONDS, NOW); Context.CancellableContext context = Context.current().withDeadline(deadline, mockExecutor); context.run(new Runnable() { @Override public void run() { CallOptionsConfig config = new CallOptionsConfig.Builder() .setUseTimeout(true) .setShortRpcTimeoutMs((int) TimeUnit.SECONDS.toMillis(100)) .setLongRpcTimeoutMs((int) TimeUnit.SECONDS.toMillis(1000)) .build(); CallOptionsFactory factory = new CallOptionsFactory.ConfiguredCallOptionsFactory(config); assertEqualsDeadlines( TimeUnit.SECONDS.toMillis(1), getDeadlineMs(factory, MutateRowRequest.getDefaultInstance()) ); } }); }