auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected ModelAndView getRadiologyOrderFormWithNewRadiologyOrder() { ModelAndView modelAndView = new ModelAndView("module/radiology/radiologyOrderForm"); if (Context.isAuthenticated()) { RadiologyOrder radiologyOrder = new RadiologyOrder(); radiologyOrder.setStudy(new Study()); modelAndView.addObject("order", new Order()); modelAndView.addObject("isOrderActive", true); modelAndView.addObject("radiologyReport", null); modelAndView.addObject("radiologyOrder", radiologyOrder); modelAndView.addObject("hasCompletedPerformedStatus", false); modelAndView.addObject("reportNeedsToBeCreated", false); } return modelAndView; }

Target:
protected ModelAndView getRadiologyOrderFormWithNewRadiologyOrder() { ModelAndView modelAndView = new ModelAndView("module/radiology/radiologyOrderForm"); if (Context.isAuthenticated()) { RadiologyOrder radiologyOrder = new RadiologyOrder(); radiologyOrder.setStudy(new Study()); modelAndView.addObject("order", new Order()); modelAndView.addObject("isOrderActive", true); modelAndView.addObject("radiologyReport", null); modelAndView.addObject("radiologyOrder", radiologyOrder); } return modelAndView; }
Source:
void handleMemoryPool(String memoryPool, long before, long after) { AtomicLong last = getOrCreate(lastMemoryUsage, memoryPool); long diff1 = before - last.getAndSet(after); long diff2 = after - before; if (diff1 < 0) { diff1 = 0; } if (diff2 < 0) { diff2 = 0; } long increase = diff1 + diff2; if (increase > 0) { AtomicLong bytesAllocated = getOrCreate(bytesAllocatedMap, memoryPool); bytesAllocated.getAndAdd(increase); } }

Target:
void handleMemoryPool(String memoryPool, long before, long after) { long last = getAndSet(lastMemoryUsage, memoryPool, after); long diff1 = before - last; long diff2 = after - before; if (diff1 < 0) { diff1 = 0; } if (diff2 < 0) { diff2 = 0; } long increase = diff1 + diff2; if (increase > 0) { counter.labels(memoryPool).inc(increase); } }
Source:
public void setAzureCloudIdentityMapping(String stackCrn, Map<String, String> azureUserMapping, Map<String, String> azureGroupMapping) throws ApiException { ApiClient client = clouderaManagerProxiedClientFactory.getProxiedClouderaManagerClient(stackCrn); String clusterName = getClusterName(client); String rangerUserSyncRoleName = getRangerUserSyncRoleName(client, clusterName); RolesResourceApi rolesResourceApi = clouderaManagerApiFactory.getRolesResourceApi(client); if (!supportsCloudIdMapping(rolesResourceApi, clusterName, rangerUserSyncRoleName)) { LOGGER.info("This version of CM does not support cloud identity mapping. Skipping."); return; } ApiConfigList configList = new ApiConfigList(); configList.addItemsItem(newCloudIdentityConfig(AZURE_USER_MAPPING, azureUserMapping)); configList.addItemsItem(newCloudIdentityConfig(AZURE_GROUP_MAPPING, azureGroupMapping)); rolesResourceApi.updateRoleConfig(clusterName, rangerUserSyncRoleName, RANGER_SERVICE_NAME, "Updating Azure Cloud Identity Mapping through Cloudbreak", configList); triggerRoleRefresh(client, clusterName, RANGER_SERVICE_NAME, rangerUserSyncRoleName); }

Target:
public void setAzureCloudIdentityMapping(String stackCrn, Map<String, String> azureUserMapping, Map<String, String> azureGroupMapping) throws ApiException { ApiClient client = clouderaManagerProxiedClientFactory.getProxiedClouderaManagerClient(stackCrn); String clusterName = getClusterName(client); String rangerUserSyncRoleName = getRangerUserSyncRoleName(client, clusterName); RolesResourceApi rolesResourceApi = clouderaManagerApiFactory.getRolesResourceApi(client); if (!isCloudIdMappingSupported(rolesResourceApi, clusterName, rangerUserSyncRoleName)) { LOGGER.info("This version of CM does not support cloud identity mapping. Skipping."); } else { ApiConfigList configList = new ApiConfigList(); configList.addItemsItem(newCloudIdentityConfig(AZURE_USER_MAPPING, azureUserMapping)); configList.addItemsItem(newCloudIdentityConfig(AZURE_GROUP_MAPPING, azureGroupMapping)); rolesResourceApi.updateRoleConfig(clusterName, rangerUserSyncRoleName, RANGER_SERVICE_NAME, "Updating Azure Cloud Identity Mapping through Cloudbreak", configList); triggerRoleRefresh(client, clusterName, RANGER_SERVICE_NAME, rangerUserSyncRoleName); } }
Source:
public void getReserveTransactionsShouldReturnTheRequest() throws Exception { final AtomicReference<Request> bodyRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); final RestAdapter adapter = new RestAdapter.Builder().setEndpoint(MOCK_URL).setClient(new Client() { @Override public Response execute(Request request) throws IOException { bodyRef.set(request); latch.countDown(); return null; } }).build(); final ReserveService reserveService = adapter.create(ReserveService.class); reserveService.getReserveTransactions("foobar", new RetrofitPromise<List<Transaction>>()); latch.await(); Assert.assertEquals(bodyRef.get().getMethod(), "GET"); Assert.assertEquals(bodyRef.get().getUrl(), String.format("%s/v0/reserve/transactions", MOCK_URL)); Assert.assertTrue(bodyRef.get().getHeaders().contains(new Header("Range", "foobar"))); }

Target:
public void getReserveTransactionsShouldReturnTheRequest() throws Exception { final MockRestAdapter<List<Transaction>> adapter = new MockRestAdapter<>(null, null, null); adapter.request(new RepromiseFunction<BitreserveRestAdapter, List<Transaction>>() { @Override public Promise<List<Transaction>> call(BitreserveRestAdapter bitreserveRestAdapter) { ReserveService reserveService = adapter.getRestAdapter().create(ReserveService.class); RetrofitPromise<List<Transaction>> promise = new RetrofitPromise<>(); reserveService.getReserveTransactions("foobar", promise); return promise; } }); Request request = adapter.getRequest(); Assert.assertEquals(request.getMethod(), "GET"); Assert.assertEquals(request.getUrl(), "<LINK_0>"); Assert.assertTrue(request.getHeaders().contains(new Header("Range", "foobar"))); }
Source:
private void processSingleMailboxEntry(Collection<ProtectedMailboxStorageEntry> protectedMailboxStorageEntries) { var decryptedEntries = new ArrayList<>(getDecryptedEntries(protectedMailboxStorageEntries)); checkArgument(decryptedEntries.size() == 1); storeMailboxDataAndNotifyListeners(decryptedEntries.get(0)); }

Target:
private void processSingleMailboxEntry(Collection<ProtectedMailboxStorageEntry> protectedMailboxStorageEntries) { checkArgument(protectedMailboxStorageEntries.size() == 1); var decryptedEntries = new ArrayList<>(getDecryptedEntries(protectedMailboxStorageEntries)); if (decryptedEntries.size() == 1) { storeMailboxDataAndNotifyListeners(decryptedEntries.get(0)); } }
Source:
private void displayFilePage(FileSystem fs, String user, HttpServletRequest req, HttpServletResponse resp, Session session, Path path) throws IOException { Page page = newPage(req, resp, session, "azkaban/viewer/hdfs/velocity/hdfs-file.vm"); page.add("allowproxy", allowGroupProxy); page.add("viewerPath", viewerPath); page.add("viewerName", viewerName); List<Path> paths = new ArrayList<Path>(); List<String> segments = new ArrayList<String>(); getPathSegments(path, paths, segments); page.add("paths", paths); page.add("segments", segments); page.add("user", user); page.add("path", path.toString()); page.add("homedir", getHomeDir(fs)); boolean hasSchema = false; int viewerId = -1; for (int i = 0; i < viewers.size(); ++i) { HdfsFileViewer viewer = viewers.get(i); Set<Capability> capabilities = EnumSet.noneOf(Capability.class); try { capabilities = viewer.getCapabilities(fs, path); } catch (AccessControlException e) { page.add("error_message", "Permission denied(" + i + "): " + e.getMessage()); page.add("no_fs", "true"); page.render(); return; } if (capabilities.contains(Capability.READ)) { if (capabilities.contains(Capability.SCHEMA)) { hasSchema = true; } viewerId = i; break; } } page.add("viewerId", viewerId); page.add("hasSchema", hasSchema); try { FileStatus status = fs.getFileStatus(path); page.add("status", status); } catch (AccessControlException e) { page.add("error_message", "Permission denied: " + e.getMessage()); } catch (IOException e) { page.add("error_message", "Error: " + e.getMessage()); } page.render(); }

Target:
private void displayFilePage(FileSystem fs, String user, HttpServletRequest req, HttpServletResponse resp, Session session, Path path) throws IOException { Page page = newPage(req, resp, session, "azkaban/viewer/hdfs/velocity/hdfs-file.vm"); page.add("allowproxy", allowGroupProxy); page.add("viewerPath", viewerPath); page.add("viewerName", viewerName); List<Path> paths = new ArrayList<Path>(); List<String> segments = new ArrayList<String>(); getPathSegments(path, paths, segments); page.add("paths", paths); page.add("segments", segments); page.add("user", user); page.add("path", path.toString()); page.add("homedir", getHomeDir(fs)); boolean hasSchema = false; int viewerId = -1; for (int i = 0; i < viewers.size(); ++i) { HdfsFileViewer viewer = viewers.get(i); Set<Capability> capabilities = EnumSet.noneOf(Capability.class); try { capabilities = viewer.getCapabilities(fs, path); } catch (AccessControlException e) { page.add("error_message", "Permission denied (" + viewer.getName() + "): " + e.getMessage()); page.add("no_fs", "true"); page.render(); return; } if (capabilities.contains(Capability.READ)) { if (capabilities.contains(Capability.SCHEMA)) { hasSchema = true; } viewerId = i; break; } } page.add("viewerId", viewerId); page.add("hasSchema", hasSchema); try { FileStatus status = fs.getFileStatus(path); page.add("status", status); } catch (AccessControlException e) { page.add("error_message", "Permission denied: " + e.getMessage()); } catch (IOException e) { page.add("error_message", "Error: " + e.getMessage()); } page.render(); }
Source:
public void run() { while ( ! stop ) { while ( transferQueue.isEmpty() && ! stop ) { LockSupport.park( consumerBlocker ); } if ( ! transferQueue.isEmpty() ) { List<Changeset> changesets = new ArrayList<>(); transferQueue.drainTo( changesets ); ChangesetList changesetList = new ChangesetList( changesets ); try { LuceneBackendQueueTask luceneBackendQueueTask = new LuceneBackendQueueTask( changesetList.getWork(), resources, null ); luceneBackendQueueTask.run(); } finally { changesetList.markProcessed(); } } } log.stoppingSyncConsumerThread( indexName ); }

Target:
public void run() { while ( ! stop ) { while ( transferQueue.isEmpty() && ! stop ) { LockSupport.park(); } if ( ! transferQueue.isEmpty() ) { List<Changeset> changesets = new LinkedList<>(); transferQueue.drainTo( changesets ); ChangesetList changesetList = new ChangesetList( changesets ); try { LuceneBackendQueueTask luceneBackendQueueTask = new LuceneBackendQueueTask( changesetList.getWork(), resources, null ); luceneBackendQueueTask.run(); } finally { changesetList.markProcessed(); } } } log.stoppingSyncConsumerThread( indexName ); }
Source:
public VcrReplicationManager(CloudConfig cloudConfig, ReplicationConfig replicationConfig, ClusterMapConfig clusterMapConfig, StoreConfig storeConfig, StoreManager storeManager, StoreKeyFactory storeKeyFactory, ClusterMap clusterMap, VirtualReplicatorCluster virtualReplicatorCluster, CloudDestination cloudDestination, ScheduledExecutorService scheduler, ConnectionPool connectionPool, VcrMetrics vcrMetrics, NotificationSystem requestNotification, StoreKeyConverterFactory storeKeyConverterFactory, String transformerClassName) throws ReplicationException, IllegalStateException { super(replicationConfig, clusterMapConfig, storeKeyFactory, clusterMap, scheduler, virtualReplicatorCluster.getCurrentDataNodeId(), Collections.emptyList(), connectionPool, vcrMetrics.getMetricRegistry(), requestNotification, storeKeyConverterFactory, transformerClassName, null, storeManager); this.cloudConfig = cloudConfig; this.storeConfig = storeConfig; this.virtualReplicatorCluster = virtualReplicatorCluster; this.vcrMetrics = vcrMetrics; this.persistor = new CloudTokenPersistor(replicaTokenFileName, mountPathToPartitionInfos, replicationMetrics, clusterMap, tokenHelper, cloudDestination); this.cloudStorageCompactor = cloudConfig.cloudBlobCompactionEnabled ? new CloudStorageCompactor(cloudDestination, cloudConfig, partitionToPartitionInfo.keySet(), vcrMetrics) : null; if (!cloudConfig.cloudIsVcr && cloudConfig.vcrCrossColoReplicationPeerDatacenters.isEmpty()) { throw new IllegalStateException( "Either this should be a vcr replicator OR one or more vcr cross colo replication peer datacenter should be specified"); } }

Target:
public VcrReplicationManager(CloudConfig cloudConfig, ReplicationConfig replicationConfig, ClusterMapConfig clusterMapConfig, StoreConfig storeConfig, StoreManager storeManager, StoreKeyFactory storeKeyFactory, ClusterMap clusterMap, VirtualReplicatorCluster virtualReplicatorCluster, CloudDestination cloudDestination, ScheduledExecutorService scheduler, ConnectionPool connectionPool, VcrMetrics vcrMetrics, NotificationSystem requestNotification, StoreKeyConverterFactory storeKeyConverterFactory, String transformerClassName) throws ReplicationException, IllegalStateException { super(replicationConfig, clusterMapConfig, storeKeyFactory, clusterMap, scheduler, virtualReplicatorCluster.getCurrentDataNodeId(), Collections.emptyList(), connectionPool, vcrMetrics.getMetricRegistry(), requestNotification, storeKeyConverterFactory, transformerClassName, null, storeManager); this.cloudConfig = cloudConfig; this.storeConfig = storeConfig; this.virtualReplicatorCluster = virtualReplicatorCluster; this.vcrMetrics = vcrMetrics; this.persistor = new CloudTokenPersistor(replicaTokenFileName, mountPathToPartitionInfos, replicationMetrics, clusterMap, tokenHelper, cloudDestination); this.cloudStorageCompactor = cloudConfig.cloudBlobCompactionEnabled ? new CloudStorageCompactor(cloudDestination, cloudConfig, partitionToPartitionInfo.keySet(), vcrMetrics) : null; if (cloudConfig.vcrSourceDatacenters.isEmpty()) { throw new IllegalStateException("One or more VCR cross colo replication peer datacenter should be specified"); } }
Source:
public URI getUri() { return URI.create(String.format(endpointFormat, LOCALHOST, s3Proxy.getPort())); }

Target:
public URI getUri() { return endpointUri; }
Source:
public void createShippingMethodWithPredicateAndLocalizedDescription() throws Exception { final CurrencyUnit currencyUnit = USD; final TaxRateDraft taxRate = TaxRateDraft.of("x20", 0.20, true, COUNTRY_CODE); withZone(client(), zone -> { withTaxCategory(client(), TaxCategoryDraft.of("taxcat", asList(taxRate)), taxCategory -> { final ZoneRateDraft zoneRateDraft = ZoneRateDraftBuilder.of(zone.toResourceIdentifier(), asList(ShippingRate.of(MoneyImpl.of(30, currencyUnit)))).build(); final ShippingMethodDraft draft = ShippingMethodDraftBuilder.of("standard shipping", LocalizedString.of(ENGLISH, "description"), taxCategory.toReference(), asList(zoneRateDraft), false) .predicate(CartPredicate.of("customer.email = \"john@example.com\"")) .build(); final ShippingMethod shippingMethod = client().executeBlocking(ShippingMethodCreateCommand.of(draft)); client().executeBlocking(ShippingMethodDeleteCommand.of(shippingMethod)); }); }, COUNTRY_CODE); }

Target:
public void createShippingMethodWithPredicateAndLocalizedDescription() throws Exception { final CurrencyUnit currencyUnit = USD; final TaxRateDraft taxRate = TaxRateDraft.of("x20", 0.20, true, COUNTRY_CODE); withZone(client(), zone -> { withTaxCategory(client(), TaxCategoryDraft.of("taxcat", asList(taxRate)), taxCategory -> { LocalizedString localizedDescription = LocalizedString.of(ENGLISH, "description"); final ZoneRateDraft zoneRateDraft = ZoneRateDraftBuilder.of(zone.toResourceIdentifier(), asList(ShippingRate.of(MoneyImpl.of(30, currencyUnit)))).build(); final ShippingMethodDraft draft = ShippingMethodDraftBuilder.of("standard shipping", localizedDescription, taxCategory.toReference(), asList(zoneRateDraft), false) .predicate(CartPredicate.of("customer.email = \"john@example.com\"")) .build(); final ShippingMethod shippingMethod = client().executeBlocking(ShippingMethodCreateCommand.of(draft)); assertThat(shippingMethod.getLocalizedDescription()).isEqualTo(localizedDescription); client().executeBlocking(ShippingMethodDeleteCommand.of(shippingMethod)); }); }, COUNTRY_CODE); }
Source:
public void applySecret(KubernetesEnvironment env, RuntimeIdentity runtimeIdentity, Secret secret) throws InfrastructureException { boolean secretAutomount = Boolean.parseBoolean(secret.getMetadata().getAnnotations().get(ANNOTATION_AUTOMOUNT)); for (PodData podData : env.getPodsData().values()) { if (!podData.getRole().equals(PodRole.DEPLOYMENT)) { continue; } for (Container container : podData.getSpec().getContainers()) { Optional<ComponentImpl> component = getComponent(env, container.getName()); if (component.isPresent() && isComponentAutomountFalse(component.get())) { continue; } if (!secretAutomount && (component.isEmpty() || !isComponentAutomountTrue(component.get()))) { continue; } for (Entry<String, String> secretDataEntry : secret.getData().entrySet()) { final String mountEnvName = envName(secret, secretDataEntry.getKey(), runtimeIdentity); container .getEnv() .add( new EnvVarBuilder() .withName(mountEnvName) .withValueFrom( new EnvVarSourceBuilder() .withSecretKeyRef( new SecretKeySelectorBuilder() .withName(secret.getMetadata().getName()) .withKey(secretDataEntry.getKey()) .build()) .build()) .build()); } } } }

Target:
public void applySecret(KubernetesEnvironment env, RuntimeIdentity runtimeIdentity, Secret secret) throws InfrastructureException { boolean secretAutomount = Boolean.parseBoolean(secret.getMetadata().getAnnotations().get(ANNOTATION_AUTOMOUNT)); for (PodData podData : env.getPodsData().values()) { if (!podData.getRole().equals(PodRole.DEPLOYMENT)) { continue; } for (Container container : podData.getSpec().getContainers()) { Optional<ComponentImpl> component = getComponent(env, container.getName()); if (component.isPresent() && isComponentAutomountFalse(component.get())) { continue; } if (!secretAutomount && (!component.isPresent() || !isComponentAutomountTrue(component.get()))) { continue; } for (Entry<String, String> secretDataEntry : secret.getData().entrySet()) { final String mountEnvName = envName(secret, secretDataEntry.getKey(), runtimeIdentity); container .getEnv() .add( new EnvVarBuilder() .withName(mountEnvName) .withValueFrom( new EnvVarSourceBuilder() .withSecretKeyRef( new SecretKeySelectorBuilder() .withName(secret.getMetadata().getName()) .withKey(secretDataEntry.getKey()) .build()) .build()) .build()); } } } }
Source:
public void setValue(String value, boolean fireEvents) { boolean newValue = false; if (value == null) { return; } List<String> values = getItemsToSelect(value); if (selectedItemsString == null || selectedItems.size() == values.size() && selectedItems.containsAll(values)) { return; } else { for (String item : values) { if (!checkBoxes.containsKey(item)) { addCheckBoxOptions(item); newValue = true; } } if (!newValue) { setSelections(values); } } }

Target:
public void setValue(String value, boolean fireEvents) { boolean newValue = false; if (value == null) { return; } List<String> values = Arrays.asList(value.split(",")); if (selectedItemsString == null || selectedItems.size() == values.size() && selectedItems.containsAll(values)) { return; } else { for (String item : values) { if (!checkBoxes.containsKey(item)) { addCheckBox(item); newValue = true; } } if (!newValue) { setSelections(values); } } if (fireEvents) { ValueChangeEvent.fire(this, value); } }
Source:
public void processAssignWorkAction() throws IOException, InterruptedException { new SystemEnvironment().set(SystemEnvironment.WEBSOCKET_ENABLED, true); ArgumentCaptor<Message> argumentCaptor = ArgumentCaptor.forClass(Message.class); agentController = createAgentController(); agentController.init(); agentController.process(new Message(Action.assignWork, MessageEncoding.encodeWork(new SleepWork("work1", 0)))); assertThat(agentController.getAgentRuntimeInfo().getRuntimeStatus(), is(AgentRuntimeStatus.Idle)); verify(webSocketSessionHandler, times(2)).sendAndWaitForAcknowledgement(argumentCaptor.capture()); verify(artifactsManipulator).setProperty(null, new Property("work1_result", "done")); Message message = argumentCaptor.getAllValues().get(1); assertThat(message.getAcknowledgementId(), notNullValue()); assertThat(message.getAction(), is(Action.ping)); assertThat(message.getData(), is(MessageEncoding.encodeData(agentController.getAgentRuntimeInfo()))); Message message2 = argumentCaptor.getAllValues().get(0); assertThat(message2.getAcknowledgementId(), notNullValue()); assertThat(message2.getAction(), is(Action.consoleOut)); assertThat(message2.getData(), is(MessageEncoding.encodeData(new ConsoleTransmission("Sleeping for 0 milliseconds", new JobIdentifier())))); }

Target:
public void processAssignWorkAction() throws IOException, InterruptedException { ArgumentCaptor<Message> argumentCaptor = ArgumentCaptor.forClass(Message.class); agentController = createAgentController(); agentController.init(); agentController.process(new Message(Action.assignWork, MessageEncoding.encodeWork(new SleepWork("work1", 0)))); assertThat(agentController.getAgentRuntimeInfo().getRuntimeStatus(), is(AgentRuntimeStatus.Idle)); verify(webSocketSessionHandler, times(1)).sendAndWaitForAcknowledgement(argumentCaptor.capture()); verify(artifactsManipulator).setProperty(null, new Property("work1_result", "done")); Message message = argumentCaptor.getAllValues().get(0); assertThat(message.getAcknowledgementId(), notNullValue()); assertThat(message.getAction(), is(Action.ping)); assertThat(message.getData(), is(MessageEncoding.encodeData(agentController.getAgentRuntimeInfo()))); }
Source:
public List<TKeyExtent> bulkImport(TInfo tinfo, TCredentials credentials, final long tid, final Map<TKeyExtent,Map<String,MapFileInfo>> files, final boolean setTime) throws ThriftSecurityException { if (!security.canPerformSystemActions(credentials)) throw new ThriftSecurityException(credentials.getPrincipal(), SecurityErrorCode.PERMISSION_DENIED); try { return watcher.run(Constants.BULK_ARBITRATOR_TYPE, tid, () -> { List<TKeyExtent> failures = new ArrayList<>(); files.entrySet().forEach((entry) -> { TKeyExtent tke = entry.getKey(); Map<String,MapFileInfo> fileMap = entry.getValue(); Map<FileRef,MapFileInfo> fileRefMap = new HashMap<>(); for (Entry<String,MapFileInfo> mapping : fileMap.entrySet()) { Path path = new Path(mapping.getKey()); FileSystem ns = fs.getVolumeByPath(path).getFileSystem(); path = ns.makeQualified(path); fileRefMap.put(new FileRef(path.toString(), path), mapping.getValue()); } Tablet importTablet = onlineTablets.get(new KeyExtent(tke)); if (importTablet == null) { failures.add(tke); } else { try { importTablet.importMapFiles(tid, fileRefMap, setTime); } catch (IOException ioe) { log.info("files not imported to {}: {}", fileMap.keySet(), new KeyExtent(tke), ioe.getMessage()); failures.add(tke); } } }); return failures; }); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } }

Target:
public List<TKeyExtent> bulkImport(TInfo tinfo, TCredentials credentials, final long tid, final Map<TKeyExtent,Map<String,MapFileInfo>> files, final boolean setTime) throws ThriftSecurityException { if (!security.canPerformSystemActions(credentials)) { throw new ThriftSecurityException(credentials.getPrincipal(), SecurityErrorCode.PERMISSION_DENIED); } try { return watcher.run(Constants.BULK_ARBITRATOR_TYPE, tid, () -> { List<TKeyExtent> failures = new ArrayList<>(); files.forEach((tke, fileMap) -> { Map<FileRef,MapFileInfo> fileRefMap = new HashMap<>(); fileMap.forEach((key, mapping) -> { Path path = new Path(key); FileSystem ns = fs.getVolumeByPath(path).getFileSystem(); path = ns.makeQualified(path); fileRefMap.put(new FileRef(path.toString(), path), mapping); }); Tablet importTablet = getOnlineTablet(new KeyExtent(tke)); if (importTablet == null) { failures.add(tke); } else { try { importTablet.importMapFiles(tid, fileRefMap, setTime); } catch (IOException ioe) { log.info("files not imported to {}: {}", fileMap.keySet(), new KeyExtent(tke), ioe.getMessage()); failures.add(tke); } } }); return failures; }); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } }
Source:
private Query parseQuery(String queryString, Analyzer analyzer) throws ParseException { Query query = null; switch(queryParserType) { case "QueryParser": QueryParser qp = new QueryParser(docDef.getPrimaryField(), analyzer) ; qp.setAllowLeadingWildcard(true) ; query = qp.parse(queryString); break; case "AnalyzingQueryParser": qp = new QueryParser(docDef.getPrimaryField(), analyzer) ; qp.setAllowLeadingWildcard(true) ; query = qp.parse(queryString); break; case "ComplexPhraseQueryParser": qp = new ComplexPhraseQueryParser(docDef.getPrimaryField(), analyzer); qp.setAllowLeadingWildcard(true) ; query = qp.parse(queryString); break; case "SurroundQueryParser": try { query = org.apache.lucene.queryparser.surround.parser.QueryParser.parse(queryString).makeLuceneQueryField(docDef.getPrimaryField(), new BasicQueryFactory()); } catch(org.apache.lucene.queryparser.surround.parser.ParseException e) { throw new ParseException(e.getMessage()); } break; default: log.warn("Unknown query parser type '" + queryParserType + "'. Defaulting to standard QueryParser") ; qp = new QueryParser(docDef.getPrimaryField(), analyzer) ; qp.setAllowLeadingWildcard(true) ; query = qp.parse(queryString); } return query ; }

Target:
private Query parseQuery(String queryString, Analyzer analyzer) throws ParseException { Query query = null; QueryParser qp = null; switch(queryParserType) { case "SurroundQueryParser": try { query = org.apache.lucene.queryparser.surround.parser.QueryParser.parse(queryString).makeLuceneQueryField(docDef.getPrimaryField(), new BasicQueryFactory()); } catch(org.apache.lucene.queryparser.surround.parser.ParseException e) { throw new ParseException(e.getMessage()); } return query; case "ComplexPhraseQueryParser": qp = new ComplexPhraseQueryParser(docDef.getPrimaryField(), analyzer); break; case "AnalyzingQueryParser": log.warn("Deprecated query parser type 'AnalyzingQueryParser'. Defaulting to standard QueryParser"); break; default: log.warn("Unknown query parser type '" + queryParserType + "'. Defaulting to standard QueryParser"); } if (qp == null) qp = new QueryParser(docDef.getPrimaryField(), analyzer); qp.setAllowLeadingWildcard(true); query = qp.parse(queryString); return query ; }
Source:
public <T extends RegisteredService> T findServiceByName(final String name, final Class<T> clazz) { var result= this.serviceRegistry.findServiceByExactServiceName(name, clazz); services.get(result.getId(), k-> result); return result; }

Target:
public <T extends RegisteredService> T findServiceByName(final String name, final Class<T> clazz) { if (StringUtils.isBlank(name)) { return null; } var service = getService(name, 0); if (service != null && service.getClass().equals(clazz)) { return (T) service; } else { LOGGER.trace("The service with name and type is not found in the cache; trying to find it from [{}]", name, clazz, serviceRegistry.getName()); service = this.serviceRegistry.findServiceByExactServiceName(name, clazz); if (service != null) { services.put(service.getId(), service); LOGGER.trace("The service is found in and populated to the cache ", serviceRegistry.getName(), service); } } return (T) validateRegisteredService(service); }
Source:
private GridFutureAdapter<?> startWrite(String key, byte[] valBytes) throws IgniteCheckedException { GridFutureAdapter<?> validationRes = validateBeforeWrite(key); if (validationRes != null) return validationRes; UUID reqId = UUID.randomUUID(); GridFutureAdapter<Boolean> fut = new GridFutureAdapter<>(); updateFutsStopLock.readLock().lock(); try { if (stopped) { fut.onDone(nodeStoppingException()); return fut; } updateFuts.put(reqId, fut); } finally { updateFutsStopLock.readLock().unlock(); } DiscoveryCustomMessage msg = new DistributedMetaStorageUpdateMessage(reqId, key, valBytes); ctx.discovery().sendCustomEvent(msg); return fut; }

Target:
private GridFutureAdapter<?> startWrite(String key, byte[] valBytes) throws IgniteCheckedException { UUID reqId = UUID.randomUUID(); GridFutureAdapter<?> fut = prepareWriteFuture(key, reqId); if (fut.isDone()) return fut; DiscoveryCustomMessage msg = new DistributedMetaStorageUpdateMessage(reqId, key, valBytes); ctx.discovery().sendCustomEvent(msg); return fut; }
Source:
public void expire() { if (super.isExpired()) { return; } super.expire(); try { updateStatsOnExpire(); this.transceiver.stop(); if (logger.isDebugEnabled() && getConference().includeInStatistics()) { logger.debug(transceiver.getNodeStats().prettyPrint(0)); } transceiver.teardown(); AbstractEndpointMessageTransport messageTransport = getMessageTransport(); if (messageTransport != null) { messageTransport.close(); } if (sctpManager != null) { sctpManager.closeConnection(); } } catch (Exception e) { logger.error("Exception while expiring: ", e); } bandwidthProbing.enabled = false; recurringRunnableExecutor.deRegisterRecurringRunnable(bandwidthProbing); getConference().encodingsManager.unsubscribe(this); dtlsTransport.close(); logger.info("Expired."); }

Target:
public void expire() { if (super.isExpired()) { return; } super.expire(); try { updateStatsOnExpire(); this.transceiver.stop(); if (logger.isDebugEnabled() && getConference().includeInStatistics()) { logger.debug(transceiver.getNodeStats().prettyPrint(0)); } transceiver.teardown(); AbstractEndpointMessageTransport messageTransport = getMessageTransport(); if (messageTransport != null) { messageTransport.close(); } if (sctpManager != null) { sctpManager.closeConnection(); } } catch (Exception e) { logger.error("Exception while expiring: ", e); } bandwidthProbing.enabled = false; recurringRunnableExecutor.deRegisterRecurringRunnable(bandwidthProbing); dtlsTransport.close(); logger.info("Expired."); }
Source:
public void populateDAG(DAG dag, Configuration conf) { POJOGenerator salesGenerator = dag.addOperator("Input1", new POJOGenerator()); POJOGenerator productGenerator = dag.addOperator("Input2", new POJOGenerator()); productGenerator.setSalesEvent(false); POJOInnerJoinOperator join = dag.addOperator("Join", new POJOInnerJoinOperator()); ConsoleOutputOperator output = dag.addOperator("Output", new ConsoleOutputOperator()); dag.addStream("SalesToJoin", salesGenerator.output, join.input1); dag.addStream("ProductToJoin", productGenerator.output, join.input2); dag.addStream("JoinToConsole", join.outputPort, output.input); dag.setInputPortAttribute(join.input1, Context.PortContext.TUPLE_CLASS, POJOGenerator.SalesEvent.class); dag.setInputPortAttribute(join.input2, Context.PortContext.TUPLE_CLASS, POJOGenerator.ProductEvent.class); dag.setOutputPortAttribute(join.outputPort,Context.PortContext.TUPLE_CLASS, POJOGenerator.SalesEvent.class); dag.setAttribute(join, Context.OperatorContext.PARTITIONER, new StatelessPartitioner<POJOInnerJoinOperator>(3)); }

Target:
public void populateDAG(DAG dag, Configuration conf) { POJOGenerator salesGenerator = dag.addOperator("Input1", new POJOGenerator()); POJOGenerator productGenerator = dag.addOperator("Input2", new POJOGenerator()); productGenerator.setSalesEvent(false); POJOInnerJoinOperator join = dag.addOperator("Join", new POJOInnerJoinOperator()); ConsoleOutputOperator output = dag.addOperator("Output", new ConsoleOutputOperator()); dag.addStream("SalesToJoin", salesGenerator.output, join.input1); dag.addStream("ProductToJoin", productGenerator.output, join.input2); dag.addStream("JoinToConsole", join.outputPort, output.input); dag.setInputPortAttribute(join.input1, Context.PortContext.TUPLE_CLASS, POJOGenerator.SalesEvent.class); dag.setInputPortAttribute(join.input2, Context.PortContext.TUPLE_CLASS, POJOGenerator.ProductEvent.class); dag.setOutputPortAttribute(join.outputPort,Context.PortContext.TUPLE_CLASS, POJOGenerator.SalesEvent.class); }
Source:
protected void onCreate(Bundle savedInstanceState) { PreferenceManager.setDefaultValues(this, R.layout.fragment_settings, false); Utilities.setThemeToActivity(this, getApplicationContext()); super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_budget); mBudgetNameView = (EditText) findViewById(R.id.budget_name); mBudgetAmountView = (EditText) findViewById(R.id.budget_amount); mBudgetDateView = (DatePicker) findViewById(R.id.budget_date); mRecurringView = (CheckBox) findViewById(R.id.budget_recur); createButtonView = (Button) findViewById(R.id.create_budget_button); mBudgetDurationView = (Spinner) findViewById(R.id.budget_duration); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.duration_array, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mBudgetDurationView.setAdapter(adapter); }

Target:
protected void onCreate(Bundle savedInstanceState) { Utilities.setActivityTheme(this, getApplicationContext()); super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_budget); mBudgetNameView = (EditText) findViewById(R.id.budget_name); mBudgetAmountView = (EditText) findViewById(R.id.budget_amount); mBudgetDateView = (DatePicker) findViewById(R.id.budget_date); mRecurringView = (CheckBox) findViewById(R.id.budget_recur); createButtonView = (Button) findViewById(R.id.create_budget_button); mBudgetDurationView = (Spinner) findViewById(R.id.budget_duration); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.duration_array, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mBudgetDurationView.setAdapter(adapter); }
Source:
protected ScheduleExpression getScheduleExpression(String cronExpression, Date start, Date end, String timeZone) { String[] splittedCronJob = cronExpression.split(" "); ScheduleExpression scheduledExpression = new ScheduleExpression(); scheduledExpression .second(splittedCronJob[0]) .minute(splittedCronJob[1]) .hour(splittedCronJob[2]) .dayOfMonth(splittedCronJob[3]) .month(splittedCronJob[4]) .dayOfWeek(StringUtils.equals(splittedCronJob[5], "?") ? "*" : splittedCronJob[5]) .year(splittedCronJob[6]) .start(start); if (end != null) { scheduledExpression.end(end); } if (timeZone != null && !timeZone.isEmpty()) { scheduledExpression.timezone(timeZone); } return scheduledExpression; }

Target:
protected ScheduleExpression getScheduleExpression(String cronExpression, Date start, Date end, String timeZone) { String[] splittedCronJob = cronExpression.split(" "); ScheduleExpression scheduledExpression = new ScheduleExpression(); scheduledExpression .second(splittedCronJob[0]) .minute(splittedCronJob[1]) .hour(splittedCronJob[2]) .dayOfMonth(splittedCronJob[3]) .month(splittedCronJob[4]) .dayOfWeek(StringUtils.equals(splittedCronJob[5], "?") ? "*" : splittedCronJob[5]) .year(splittedCronJob[6]) .start(start); if (end != null) { scheduledExpression.end(end); } if (StringUtils.isNotBlank(timeZone)) { scheduledExpression.timezone(timeZone); } return scheduledExpression; }
Source:
public SpecialAdminDashboardPageObject openSpecialAdminDashboard() { getUrl(Domain + "wiki/Special:AdminDashboard"); return new SpecialAdminDashboardPageObject(driver); }

Target:
public SpecialAdminDashboardPageObject openSpecialAdminDashboard() { getUrl(Global.DOMAIN + URLsContent.specialAdminDashboard); return new SpecialAdminDashboardPageObject(driver); }
Source:
public void testPut() { await( multimapCache.put("names", "julien").thenCompose(r1 -> multimapCache.put("names", "oihana").thenCompose(r2 -> multimapCache.put("names", "julien").thenCompose(r3 -> multimapCache.get("names").thenAccept(v -> { assertTrue(v.contains("julien")); assertEquals(1, v.stream().filter(n -> n.equals("julien")).count()); } ) ) ) ) ); await( multimapCache.get("names").thenAccept(v -> { assertFalse(v.contains("koldo")); assertEquals(2, v.size()); } ) ); }

Target:
public void testPut() { await( multimapCache.put(NAMES_KEY, JULIEN) .thenCompose(r1 -> multimapCache.put(NAMES_KEY, OIHANA)) .thenCompose(r2 -> multimapCache.put(NAMES_KEY, JULIEN)) .thenCompose(r3 -> multimapCache.get(NAMES_KEY)) .thenAccept(v -> { assertTrue(v.contains(JULIEN)); assertEquals(1, v.stream().filter(n -> n.equals(JULIEN)).count()); } ) ); await( multimapCache.get(NAMES_KEY).thenAccept(v -> { assertFalse(v.contains(KOLDO)); assertEquals(2, v.size()); } ) ); await( multimapCache.put(EMPTY_KEY, RAMON) .thenCompose(r1 -> multimapCache.get(EMPTY_KEY) .thenAccept(v -> { assertTrue(v.contains(RAMON)); assertEquals(1, v.stream().filter(n -> n.equals(RAMON)).count()); })) ); await( multimapCache.put(NAMES_KEY, PEPE) .thenCompose(r1 -> multimapCache.get(NAMES_KEY) .thenAccept(v -> { assertTrue(v.contains(PEPE)); assertEquals(1, v.stream().filter(n -> n.equals(PEPE)).count()); })) ); }
Source:
public void edit(final GlusterVolumeGeoRepCreateModel object) { driver.edit(object); setSuggestedConfigViolations(object.getRecommendationViolations()); setQueryFailureMessage(object.getQueryFailureMessage()); }

Target:
public void edit(final GlusterVolumeGeoRepCreateModel object) { driver.edit(object); setSuggestedConfigViolations(object.getRecommendationViolations()); object.getShowEligibleVolumes().getEntityChangedEvent().addListener(new IEventListener<EventArgs>() { @Override public void eventRaised(Event<? extends EventArgs> ev, Object sender, EventArgs args) { boolean overrideSuggestedConfig = object.getShowEligibleVolumes().getEntity(); if(!overrideSuggestedConfig) { object.getVolumesForForceSessionCreate(); } else { object.getEligibleVolumes(); } } }); IEventListener<EventArgs> clusterEventListener = new IEventListener<EventArgs>() { @Override public void eventRaised(Event<? extends EventArgs> ev, Object sender, EventArgs args) { String selectedCluster = object.getSlaveClusters().getSelectedItem(); List<GlusterVolumeEntity> volumesInCurrentCluster = new ArrayList<GlusterVolumeEntity>(); if(selectedCluster != null) { volumesInCurrentCluster = object.getVolumesInCluster(selectedCluster, object.getVolumeList()); } if(volumesInCurrentCluster.size() > 0) { object.getSlaveVolumes().setItems(volumesInCurrentCluster, volumesInCurrentCluster.get(0)); } else { object.getSlaveVolumes().setItems(volumesInCurrentCluster); } } }; object.getSlaveClusters().getSelectedItemChangedEvent().addListener(clusterEventListener); IEventListener<EventArgs> slaveVolumeEventListener = new IEventListener<EventArgs>() { @Override public void eventRaised(Event<? extends EventArgs> ev, Object sender, EventArgs args) { GlusterVolumeEntity selectedSlaveVolume = object.getSlaveVolumes().getSelectedItem(); Set<String> hostsInCurrentVolume = new HashSet<String>(); if(!object.getShowEligibleVolumes().getEntity() && selectedSlaveVolume != null) { object.updateRecommendatonViolations(); } if(selectedSlaveVolume != null) { hostsInCurrentVolume = object.getHostNamesForVolume(selectedSlaveVolume); } object.getSlaveHosts().setItems(hostsInCurrentVolume); } }; object.getSlaveVolumes().getSelectedItemChangedEvent().addListener(slaveVolumeEventListener); }
Source:
public void setValueList(List<String> valueList) { StringBuilder valueBilder = new StringBuilder(); for (String val : valueList) { valueBilder.append(val); valueBilder.append("; "); } this.value = valueBilder.toString(); }

Target:
public void setValueList(List<String> valueList) { StringBuilder valueBuilder = new StringBuilder(); for (String val : valueList) { valueBuilder.append(val); valueBuilder.append("; "); } this.value = valueBuilder.toString(); }
Source:
public void processEvent(DiscoveryServiceEvent event) throws LogReplicationDiscoveryServiceException { log.info("Process event {}", event.getType()); switch (event.type) { case DISCOVER_INIT_TOPOLOGY: startDiscovery(); break; case ACQUIRE_LOCK: processLockAcquire(); break; case RELEASE_LOCK: processLockRelease(); break; case DISCOVERED_TOPOLOGY: processTopologyChangeNotification(event); break; case UPGRADE: processUpgrade(event); break; default: log.error("Invalid event type {}", event.type); } }

Target:
public void processEvent(DiscoveryServiceEvent event) { log.info("Process event {}", event.getType()); switch (event.getType()) { case DISCOVER_INIT_TOPOLOGY: startDiscovery(); break; case ACQUIRE_LOCK: processLockAcquire(); break; case RELEASE_LOCK: processLockRelease(); break; case DISCOVERED_TOPOLOGY: processTopologyChangeNotification(event); break; case UPGRADE: processUpgrade(event); break; default: log.error("Invalid event type {}", event.getType()); } }
Source:
public Object construct(String componentName) { if (componentName.equals(StreamingMarshaller.class.getName())) { return ComponentAlias.of(KnownComponentNames.INTERNAL_MARSHALLER); } else if (componentName.equals(PersistenceMarshaller.class.getName())) { return ComponentAlias.of(KnownComponentNames.PERSISTENCE_MARSHALLER); } switch (componentName) { case KnownComponentNames.PERSISTENCE_MARSHALLER: return new PersistenceMarshallerImpl(); case KnownComponentNames.INTERNAL_MARSHALLER: return new GlobalMarshaller(); default: throw new IllegalArgumentException(String.format("Marshaller name '%s' not recognised", componentName)); } }

Target:
public Object construct(String componentName) { if (componentName.equals(StreamingMarshaller.class.getName())) { return ComponentAlias.of(KnownComponentNames.INTERNAL_MARSHALLER); } switch (componentName) { case KnownComponentNames.PERSISTENCE_MARSHALLER: return new PersistenceMarshallerImpl(); case KnownComponentNames.INTERNAL_MARSHALLER: return new GlobalMarshaller(); default: throw new IllegalArgumentException(String.format("Marshaller name '%s' not recognised", componentName)); } }
Source:
public long getLong(int length, boolean signed) throws CTFReaderException { if (length > BIT_LONG) { throw new CTFReaderException("Cannot read a long longer than 64 bits. Rquested: " + length); } if (length > BIT_INT) { final int highShift = length-BIT_INT; long a = getInt() & 0x00000000FFFFFFFFL; long b = getInt(highShift, false); long retVal; a &= 0xFFFFFFFFL; b &= ((1L << highShift) - 1L); retVal = (this.byteOrder == ByteOrder.BIG_ENDIAN) ? ((a << highShift) | b) : ((b << BIT_INT) | a); if (signed && ((retVal & (1L << (length - 1))) != 0L)) { int signExtendBits = BIT_LONG - length; long l = retVal << signExtendBits; long m = l >> signExtendBits; retVal = m; } return retVal; } return getInt(length, signed); }

Target:
public long getLong(int length, boolean signed) throws CTFReaderException { if (length > BIT_LONG) { throw new CTFReaderException("Cannot read a long longer than 64 bits. Rquested: " + length); } if (length > BIT_INT) { final int highShift = length - BIT_INT; long a = getInt() & 0x00000000FFFFFFFFL; long b = getInt(highShift, false); long retVal; a &= 0xFFFFFFFFL; b &= ((1L << highShift) - 1L); retVal = (this.byteOrder == ByteOrder.BIG_ENDIAN) ? ((a << highShift) | b) : ((b << BIT_INT) | a); if (signed) { int signExtendBits = BIT_LONG - length; retVal = (retVal << signExtendBits) >> signExtendBits; } return retVal; } return getInt(length, signed); }
Source:
private static WebArchive createDeployment() { WebArchive war = ShrinkWrap.create(WebArchive.class, DEPLOYMENT_FILE_NAME); war.addPackage(SimpleWebserviceEndpointImpl.class.getPackage()); war.addClass(SimpleWebserviceEndpointImpl.class); war.addAsWebInfResource("web.xml", "web.xml"); return war; }

Target:
private WebArchive createDeployment() { WebArchive war = ShrinkWrap.create(WebArchive.class, DEPLOYMENT_FILE_NAME); war.addPackage(SimpleWebserviceEndpointImpl.class.getPackage()); war.addClass(SimpleWebserviceEndpointImpl.class); war.addAsWebInfResource("web.xml", "web.xml"); return war; }
Source:
public Config loadConfiguration(ConfigType configType, StorageType stype, int tenantId) throws I18nMgtEmailConfigException { Config config = null; switch (stype) { case REGISTRY: cm.setReader(new RegistryConfigReader()); switch (configType) { case EMAIL: cm.setConfig(new EmailNotificationConfig()); cm.setResourcePath(I18nMgtConstants.EMAIL_TEMPLATE_PATH); config = cm.loadConfig(tenantId); if (config == null) { throw new I18nMgtEmailConfigException("Default email templates haven't written successfully"); } break; default: throw new I18nMgtEmailConfigException("Configuration type not supported"); } break; case DB: break; case FILE: break; default: throw new I18nMgtEmailConfigException("Configuration storage type not supported"); } return config; }

Target:
public Config loadConfiguration(ConfigType configType, StorageType stype, int tenantId) throws I18nMgtEmailConfigException { Config config = null; switch (stype) { case REGISTRY: cm.setReader(new RegistryConfigReader()); switch (configType) { case EMAIL: cm.setConfig(new EmailNotificationConfig()); cm.setResourcePath(I18nMgtConstants.EMAIL_TEMPLATE_PATH); config = cm.loadConfig(tenantId); if (config == null) { throw new I18nMgtEmailConfigException("Default email templates haven't written successfully"); } break; default: throw new I18nMgtEmailConfigException("Configuration type not supported"); } break; case DB: case FILE: break; default: throw new I18nMgtEmailConfigException("Configuration storage type not supported"); } return config; }
Source:
private ByteBuffer parsePacketSPB(ByteBuffer pcapPacketHeader, int blockLength) throws IOException, BadPcapFileException { ByteBuffer pcapPacketData; int packetLen = pcapPacketHeader.getInt(); long includedPacketLength = ConversionHelper.unsignedIntToLong(packetLen); SeekableByteChannel fFileChannel = getFileChannel(); if (fFileChannel.size() - fFileChannel.position() < includedPacketLength) { throw new BadPcapFileException(String.format("%04x", includedPacketLength) + " is causing buffer overrun."); } if (packetLen > Integer.MAX_VALUE) { throw new BadPcapFileException(String.format("%04x", packetLen) + " is bigger than 2^31-1 bytes are not supported."); } pcapPacketData = ByteBuffer.allocate((int) includedPacketLength); pcapPacketData.clear(); ByteOrder fByteOrder = getByteOrder(); pcapPacketHeader.order(fByteOrder); fFileChannel.read(pcapPacketData); pcapPacketData.flip(); fFileChannel.position(fFileChannel.position() + blockLength - packetLen - PcapFileValues.PCAPNG_PACKET_HEADER_SIZE - PcapFileValues.PCAPNG_HEADER_SIZE * 2); return pcapPacketData; }

Target:
private ByteBuffer parsePacketSPB(ByteBuffer pcapPacketHeader, int blockLength) throws IOException, BadPcapFileException { ByteBuffer pcapPacketData; int packetLen = pcapPacketHeader.getInt(); long includedPacketLength = ConversionHelper.unsignedIntToLong(packetLen); SeekableByteChannel fFileChannel = getFileChannel(); if (fFileChannel.size() - fFileChannel.position() < includedPacketLength) { throw new BadPcapFileException(String.format("%04x", includedPacketLength) + " is causing buffer overrun."); } if (packetLen > Integer.MAX_VALUE) { throw new BadPcapFileException(String.format("%04x", packetLen) + " is bigger than 2^31-1 bytes are not supported."); } pcapPacketData = ByteBuffer.allocate((int) includedPacketLength); pcapPacketData.clear(); ByteOrder byteOrder = getByteOrder(); pcapPacketHeader.order(byteOrder); fFileChannel.read(pcapPacketData); pcapPacketData.flip(); return pcapPacketData; }
Source:
private void setupVdsNetworkInterfaceDao() { List<VdsNetworkInterface> expectedVdsNetworkInterface = Collections.singletonList(vdsNetworkInterface); InterfaceDao vdsNetworkInterfaceDaoMock = mock(InterfaceDao.class); when(vdsNetworkInterfaceDaoMock.getVdsInterfacesByNetworkId(networkId)).thenReturn(expectedVdsNetworkInterface); when(getDbFacadeMockInstance().getInterfaceDao()).thenReturn(vdsNetworkInterfaceDaoMock); NetworkDao networkDaoMock = mock(NetworkDao.class); when(getDbFacadeMockInstance().getNetworkDao()).thenReturn(networkDaoMock); }

Target:
private void setupVdsNetworkInterfaceDao() { when(getDbFacadeMockInstance().getInterfaceDao()).thenReturn(vdsNetworkInterfaceDaoMock); List<VdsNetworkInterface> expectedVdsNetworkInterface = Collections.singletonList(vdsNetworkInterface); when(vdsNetworkInterfaceDaoMock.getVdsInterfacesByNetworkId(networkId)).thenReturn( expectedVdsNetworkInterface); }