auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void consumeIt(BatchIterator<Row> iterator) { boolean allLoaded; try { while (iterator.moveNext()) { rowCount++; resultReceiver.setNextRow(iterator.currentElement()); if (maxRows > 0 && rowCount % maxRows == 0) { activeIt = iterator; resultReceiver.batchFinished(); return; } } allLoaded = iterator.allLoaded(); } catch (Throwable t) { iterator.close(); completionFuture.complete(null); resultReceiver.fail(t); return; } if (allLoaded) { completionFuture.complete(null); iterator.close(); resultReceiver.allFinished(false); } else { iterator.loadNextBatch().whenComplete((r, f) -> { if (f == null) { consumeIt(iterator); } else { Throwable t = SQLExceptions.unwrap(f); iterator.close(); completionFuture.completeExceptionally(t); resultReceiver.fail(t); } }); } }

Target:
private void consumeIt(BatchIterator<Row> iterator) { boolean allLoaded; try { while (iterator.moveNext()) { rowCount++; resultReceiver.setNextRow(iterator.currentElement()); if (maxRows > 0 && rowCount % maxRows == 0) { activeIt = iterator; resultReceiver.batchFinished(); return; } } allLoaded = iterator.allLoaded(); } catch (Throwable t) { iterator.close(); completionFuture.completeExceptionally(t); resultReceiver.fail(t); return; } if (allLoaded) { completionFuture.complete(null); iterator.close(); resultReceiver.allFinished(false); } else { iterator.loadNextBatch().whenComplete((r, f) -> { if (f == null) { consumeIt(iterator); } else { Throwable t = SQLExceptions.unwrap(f); iterator.close(); completionFuture.completeExceptionally(t); resultReceiver.fail(t); } }); } }
Source:
public ListenableFuture<Optional<LabelMeta>> getMeta(final LabelId uid, final LabelType type) { final String qualifier = type.toString().toLowerCase() + "_meta"; final LabelMeta meta = labelMetas.get(uid, qualifier); return Futures.immediateFuture(Optional.of(meta)); }

Target:
public ListenableFuture<Optional<LabelMeta>> getMeta(final LabelId uid, final LabelType type) { final String qualifier = type.toString().toLowerCase() + "_meta"; final LabelMeta meta = labelMetas.get(uid, qualifier); return Futures.immediateFuture(Optional.fromNullable(meta)); }
Source:
protected void createControls(Composite composite) { fAncestor = createMergeViewer(composite, MergeViewerSide.ANCESTOR); fAncestor.addSelectionChangedListener(this); fLeft = createMergeViewer(composite, MergeViewerSide.LEFT); fLeft.addSelectionChangedListener(this); fRight = createMergeViewer(composite, MergeViewerSide.RIGHT); fRight.addSelectionChangedListener(this); final IThemeManager themeManager; if (PlatformUI.isWorkbenchRunning()) { themeManager = PlatformUI.getWorkbench().getThemeManager(); } else { themeManager = null; } final ITheme currentTheme; if (themeManager != null) { currentTheme = themeManager.getCurrentTheme(); } else { currentTheme = null; } boolean leftIsLocal = getCompareConfiguration().getBooleanProperty("LEFT_IS_LOCAL", false); fColors = new EMFCompareColor(composite.getDisplay(), leftIsLocal, currentTheme, getCompareConfiguration().getEventBus()); composite.addControlListener(new ControlListener() { public void controlResized(ControlEvent e) { redrawCenterControl(); } public void controlMoved(ControlEvent e) { } }); }

Target:
protected void createControls(Composite composite) { fAncestor = createMergeViewer(composite, MergeViewerSide.ANCESTOR); fAncestor.addSelectionChangedListener(this); fLeft = createMergeViewer(composite, MergeViewerSide.LEFT); fLeft.addSelectionChangedListener(this); fRight = createMergeViewer(composite, MergeViewerSide.RIGHT); fRight.addSelectionChangedListener(this); final ITheme currentTheme = getCurrentTheme(); boolean leftIsLocal = getCompareConfiguration().getBooleanProperty("LEFT_IS_LOCAL", false); fColors = new EMFCompareColor(composite.getDisplay(), leftIsLocal, currentTheme, getCompareConfiguration().getEventBus()); composite.addControlListener(new ControlListener() { public void controlResized(ControlEvent e) { redrawCenterControl(); } public void controlMoved(ControlEvent e) { } }); }
Source:
private static void validatePseudoScopedInjectionPoint(InjectionPoint ij, BeanManagerImpl beanManager, Set<Object> dependencyPath, Set<Bean<?>> validatedBeans) { Set<Bean<?>> resolved = beanManager.getBeans(ij); try { Bean<?> bean = beanManager.resolve(resolved); if (bean != null) { if (!(bean instanceof AbstractBuiltInBean<?>)) { if (!ij.isDelegate()) { boolean normalScoped = beanManager.isNormalScope(bean.getScope()); if (!normalScoped && !(bean instanceof SessionBean)) { reallyValidatePseudoScopedBean(bean, beanManager, dependencyPath, validatedBeans); } } } } } catch (AmbiguousResolutionException ex) { throw ValidatorLogger.LOG.injectionPointHasAmbiguousDependencies(ij, Formats.formatAnnotations(ij.getQualifiers()), Formats.formatInjectionPointType(ij.getType()), Formats.formatAsStackTraceElement(ij), InjectionPoints.getUnsatisfiedDependenciesAdditionalInfo(ij, beanManager)); } }

Target:
private static void validatePseudoScopedInjectionPoint(InjectionPoint ij, BeanManagerImpl beanManager, Set<Object> dependencyPath, Set<Bean<?>> validatedBeans) { Set<Bean<?>> resolved = beanManager.getBeans(ij); Bean<?> bean = null; try { bean = beanManager.resolve(resolved); } catch (AmbiguousResolutionException ex) { throw ValidatorLogger.LOG.injectionPointHasAmbiguousDependencies(ij, Formats.formatAnnotations(ij.getQualifiers()), Formats.formatInjectionPointType(ij.getType()), Formats.formatAsStackTraceElement(ij), WeldCollections.toMultiRowString(resolved)); } if (bean != null) { if (!(bean instanceof AbstractBuiltInBean<?>)) { if (!ij.isDelegate()) { boolean normalScoped = beanManager.isNormalScope(bean.getScope()); if (!normalScoped && !(bean instanceof SessionBean)) { reallyValidatePseudoScopedBean(bean, beanManager, dependencyPath, validatedBeans); } } } } }
Source:
protected String getChannelNameFromMessage(JsonNode message) throws IOException { return null; }

Target:
protected String getChannelNameFromMessage(JsonNode message) throws IOException { return channelName; }
Source:
private void resolvePoolables(Pool pool) throws IOException { PoolableElementViewService svc = serviceManager.getPoolableElementViewService(); for (PoolElement pd : pool.getPoolContents()) { PoolableElementView resolved = svc.getByPreMigrationId(pd.getPoolableElementView().getPreMigrationId()); if (resolved == null) { throw new IllegalArgumentException( "No PoolableElement found with preMigrationId " + pd.getPoolableElementView().getPreMigrationId()); } pd.setPoolableElementView(resolved); } }

Target:
private void resolvePoolables(Pool pool) throws IOException { PoolableElementViewService svc = serviceManager.getPoolableElementViewService(); for (PoolElement element : pool.getPoolContents()) { PoolableElementView resolved = svc.getByPreMigrationId(element.getPoolableElementView().getPreMigrationId()); if (resolved == null) { throw new IllegalArgumentException( "No PoolableElement found with preMigrationId " + element.getPoolableElementView().getPreMigrationId()); } element.setPoolableElementView(resolved); } }
Source:
public boolean canEditToNewPackType(Donation existingDonation, PackType newPackType) { if(existingDonation.getTestBatch() != null && existingDonation.getTestBatch().getStatus() != null && !existingDonation.getTestBatch().getStatus().equals(TestBatchStatus.OPEN)) { if (newPackType.getTestSampleProduced() && !existingDonation.getPackType().getTestSampleProduced()) { return false; } if (existingDonation.getPackType().getTestSampleProduced() && !newPackType.getTestSampleProduced()) { return false; } } return true; }

Target:
public boolean canEditToNewPackType(Donation existingDonation, PackType newPackType) { if(existingDonation.isReleased() || isTestBatchNotOpen(existingDonation)) { if (existingDonation.getPackType().getTestSampleProduced() != newPackType.getTestSampleProduced()) { return false; } } return true; }
Source:
private void validateNetmaskInReply() throws InvalidSyntaxException { boolean hasIpv4Address = false; int numNetmask = 0; for (ConfigAttribute att : recognizedAttributeList) { if (att.hasEmptyValue()) { IkeManager.getIkeLog() .d( "IkeConfigPayload", "Found empty attribute in a Config Payload reply " + att.attributeType); } switch (att.attributeType) { case CONFIG_ATTR_INTERNAL_IP4_ADDRESS: if (!att.hasEmptyValue()) hasIpv4Address = true; break; case CONFIG_ATTR_INTERNAL_IP4_NETMASK: if (!att.hasEmptyValue()) numNetmask++; break; default: continue; } } if (!hasIpv4Address && numNetmask > 0) { throw new InvalidSyntaxException( "Found INTERNAL_IP4_NETMASK attribute but no INTERNAL_IP4_ADDRESS attribute"); } if (numNetmask > 1) { throw new InvalidSyntaxException("Found more than one INTERNAL_IP4_NETMASK"); } }

Target:
private void validateNetmaskInReply() throws InvalidSyntaxException { boolean hasIpv4Address = false; int numNetmask = 0; for (ConfigAttribute attr : recognizedAttributeList) { if (attr.isEmptyValue()) { IkeManager.getIkeLog() .d( "IkeConfigPayload", "Found empty attribute in a Config Payload reply " + attr.attributeType); } switch (attr.attributeType) { case CONFIG_ATTR_INTERNAL_IP4_ADDRESS: if (!attr.isEmptyValue()) hasIpv4Address = true; break; case CONFIG_ATTR_INTERNAL_IP4_NETMASK: if (!attr.isEmptyValue()) numNetmask++; break; default: continue; } } if (!hasIpv4Address && numNetmask > 0) { throw new InvalidSyntaxException( "Found INTERNAL_IP4_NETMASK attribute but no INTERNAL_IP4_ADDRESS attribute"); } if (numNetmask > 1) { throw new InvalidSyntaxException("Found more than one INTERNAL_IP4_NETMASK"); } }
Source:
public RunnerDetail registerRunner(String token, String description, Boolean active, List<String> tagList, Boolean runUntagged, Boolean locked, Integer maximumTimeout) throws GitLabApiException { Preconditions.checkNotNull(token, "token is necessary for registering a new runner"); GitLabApiForm formData = new GitLabApiForm() .withParam("token", token, true) .withParam("description", description, false) .withParam("active", active, false) .withParam("locked", locked, false) .withParam("run_untagged", runUntagged, false) .withParam("tag_list", tagList, false) .withParam("maximum_timeout", maximumTimeout, false); Response response = post(Response.Status.CREATED, formData.asMap(), "runners"); return (response.readEntity(RunnerDetail.class)); }

Target:
public RunnerDetail registerRunner(String token, String description, Boolean active, List<String> tagList, Boolean runUntagged, Boolean locked, Integer maximumTimeout) throws GitLabApiException { GitLabApiForm formData = new GitLabApiForm() .withParam("token", token, true) .withParam("description", description, false) .withParam("active", active, false) .withParam("locked", locked, false) .withParam("run_untagged", runUntagged, false) .withParam("tag_list", tagList, false) .withParam("maximum_timeout", maximumTimeout, false); Response response = post(Response.Status.CREATED, formData.asMap(), "runners"); return (response.readEntity(RunnerDetail.class)); }
Source:
public ReplicationConfig(VerifiableProperties verifiableProperties) { replicationTokenFactory = verifiableProperties.getString("replication.token.factory", "com.github.ambry.store.StoreFindTokenFactory"); replicationNumOfIntraDCReplicaThreads = verifiableProperties.getInt("replication.no.of.intra.dc.replica.threads", 1); replicationNumOfInterDCReplicaThreads = verifiableProperties.getInt("replication.no.of.inter.dc.replica.threads", 1); replicationConnectionPoolCheckoutTimeoutMs = verifiableProperties.getIntInRange("replication.connection.pool.checkout.timeout.ms", 5000, 1000, 10000); replicationTokenFlushIntervalSeconds = verifiableProperties.getIntInRange("replication.token.flush.interval.seconds", 300, 5, Integer.MAX_VALUE); replicationTokenFlushDelaySeconds = verifiableProperties.getIntInRange("replication.token.flush.delay.seconds", 5, 1, Integer.MAX_VALUE); replicationFetchSizeInBytes = verifiableProperties.getLongInRange("replication.fetch.size.in.bytes", 1048576, 0, 2097152); replicaWaitTimeBetweenReplicasMs = verifiableProperties.getIntInRange("replication.wait.time.between.replicas.ms", 1000, 0, 1000000); replicationMaxLagForWaitTimeInBytes = verifiableProperties.getLongInRange("replication.max.lag.for.wait.time.in.bytes", 5242880, 0, 104857600); validateMessageStream = verifiableProperties.getBoolean("replication.validate.message.stream", true); }

Target:
public ReplicationConfig(VerifiableProperties verifiableProperties) { replicationTokenFactory = verifiableProperties.getString("replication.token.factory", "com.github.ambry.store.StoreFindTokenFactory"); replicationNumOfIntraDCReplicaThreads = verifiableProperties.getInt("replication.no.of.intra.dc.replica.threads", 1); replicationNumOfInterDCReplicaThreads = verifiableProperties.getInt("replication.no.of.inter.dc.replica.threads", 1); replicationConnectionPoolCheckoutTimeoutMs = verifiableProperties.getIntInRange("replication.connection.pool.checkout.timeout.ms", 5000, 1000, 10000); replicationTokenFlushIntervalSeconds = verifiableProperties.getIntInRange("replication.token.flush.interval.seconds", 300, 5, Integer.MAX_VALUE); replicationTokenFlushDelaySeconds = verifiableProperties.getIntInRange("replication.token.flush.delay.seconds", 5, 1, Integer.MAX_VALUE); replicationFetchSizeInBytes = verifiableProperties.getLongInRange("replication.fetch.size.in.bytes", 1048576, 0, 2097152); replicaWaitTimeBetweenReplicasMs = verifiableProperties.getIntInRange("replication.wait.time.between.replicas.ms", 1000, 0, 1000000); replicationMaxLagForWaitTimeInBytes = verifiableProperties.getLongInRange("replication.max.lag.for.wait.time.in.bytes", 5242880, 0, 104857600); validateMessageStream = verifiableProperties.getBoolean("replication.validate.message.stream", false); }
Source:
public byte[] toBytes(KafkaCheckpointLogKey key) { try { return mapper.writeValueAsBytes(ImmutableMap.of( SSP_GROUPER_FACTORY_FIELD, key.getGrouperFactoryClassName(), TASK_NAME_FIELD, key.getTaskName().toString(), TYPE_FIELD, key.getType() )); } catch (Exception e) { throw new SamzaException(e); } }

Target:
public byte[] toBytes(KafkaCheckpointLogKey key) { try { return mapper.writeValueAsBytes(ImmutableMap.of( SSP_GROUPER_FACTORY_FIELD, key.getGrouperFactoryClassName(), TASK_NAME_FIELD, key.getTaskName().toString(), TYPE_FIELD, key.getType() )); } catch (Exception e) { throw new SamzaException(String.format("Exception in serializing: %s", key), e); } }
Source:
public boolean removeRoute(@NonNull RouteInfo route) { if (Objects.equals(mIfaceName, route.getInterface())) { return false; } int i = findRouteIndexByDestination(route); if (i == -1) { return false; } mRoutes.remove(i); return true; }

Target:
public boolean removeRoute(@NonNull RouteInfo route) { if (!Objects.equals(mIfaceName, route.getInterface())) { return false; } int i = findRouteIndexByDestination(route); if (i == -1) { return false; } mRoutes.remove(i); return true; }
Source:
public void shouldNotEditAnAutoGenerationOptionProvidedWithAllNullParams() throws Exception { SimpleObject autoGenerationOption = new SimpleObject(); autoGenerationOption.add("location", null); autoGenerationOption.add("source", null); autoGenerationOption.add("manualEntryEnabled", null); autoGenerationOption.add("automaticGenerationEnabled", null); String json = new ObjectMapper().writeValueAsString(autoGenerationOption); MockHttpServletRequest req = request(RequestMethod.POST, getURI() + "/" + getUuid()); req.setContent(json.getBytes()); handle(req); }

Target:
public void shouldNotEditAnAutoGenerationOptionProvidedWithAllNullParams() throws Exception { SimpleObject autoGenerationOption = new SimpleObject(); String json = new ObjectMapper().writeValueAsString(autoGenerationOption); MockHttpServletRequest req = request(RequestMethod.POST, getURI() + "/" + getUuid()); req.setContent(json.getBytes()); handle(req); }
Source:
protected static boolean isRingTimeFromNextSmartAlarm(final DateTime currentTimeAlignedToStartOfMinute, final RingTime nextRingTimeFromWorker){ final boolean alarmNotYetRing = currentTimeAlignedToStartOfMinute.isAfter(nextRingTimeFromWorker.actualRingTimeUTC) == false; final boolean isProcessedSmartAlarm = nextRingTimeFromWorker.processed(); return alarmNotYetRing && isProcessedSmartAlarm; }

Target:
protected static boolean isRingTimeFromNextSmartAlarm(final DateTime currentTimeAlignedToStartOfMinute, final RingTime nextRingTimeFromWorker){ final boolean isNextSmartAlarm = currentTimeAlignedToStartOfMinute.isAfter(nextRingTimeFromWorker.actualRingTimeUTC) == false; final boolean isProcessedSmartAlarm = nextRingTimeFromWorker.processed(); return isNextSmartAlarm && isProcessedSmartAlarm; }
Source:
public Class<?> lookupIncludeClass(Class<?> objClass) { Annotation first = getFirstAnnotation(objClass, Arrays.asList(Exclude.class, Include.class)); if (first instanceof Include) { Class<?> declaringClass = lookupAnnotationDeclarationClass(objClass, Include.class); if (declaringClass != null) { return declaringClass; } } return null; }

Target:
public Class<?> lookupIncludeClass(Class<?> objClass) { Annotation first = getFirstAnnotation(objClass, Arrays.asList(Exclude.class, Include.class)); if (first instanceof Include) { Class<?> declaringClass = lookupAnnotationDeclarationClass(objClass, Include.class); if (declaringClass != null) { return declaringClass; } return objClass; } return null; }
Source:
private Node createImportedNode(final Node node) { assert !(node instanceof Document); final Document document; try { document = DFACTORY.newDocumentBuilder().newDocument(); } catch (final ParserConfigurationException ex) { throw new IllegalStateException(ex); } final Node imported = document.importNode(node, true); document.appendChild(imported); return imported; }

Target:
private Node createImportedNode(final Node node) { final Document document; try { document = DFACTORY.newDocumentBuilder().newDocument(); } catch (final ParserConfigurationException ex) { throw new IllegalStateException(ex); } final Node imported = document.importNode(node, true); document.appendChild(imported); return imported; }
Source:
public void start(BundleContext bundleContext) throws Exception { bundleContext.registerService(PetsStoreService.class.getName(), new PetsManagerImpl(), null); LOGGER.debug("Pet-Store BE Bundle started."); }

Target:
public void start(BundleContext bundleContext) throws Exception { bundleContext.registerService(PetsStoreService.class.getName(), new PetsManagerImpl(), null); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Pet-Store BE Bundle started."); } }
Source:
public List<AbstractProject> getTiedJobs() { List<AbstractProject> r = new ArrayList<>(); for (AbstractProject<?,?> p : Jenkins.get().allItems(AbstractProject.class, i -> i instanceof TopLevelItem && this.equals(i.getAssignedLabel()))) { r.add(p); } r.sort(Items.BY_FULL_NAME); return r; }

Target:
public List<AbstractProject> getTiedJobs() { return StreamSupport.stream(Jenkins.get().allItems(AbstractProject.class, i -> i instanceof TopLevelItem && this.equals(i.getAssignedLabel())).spliterator(), true) .sorted(Items.BY_FULL_NAME).collect(Collectors.toList()); }
Source:
public static boolean isNullOrBlank(String string) { if (string == null) { return true; } int length = string.length(); if (length > 0) { for (int i = 0; i < length; i++) { if (!Character.isWhitespace(string.charAt(i))) { return false; } } } return true; }

Target:
private static boolean isNullOrBlank(String string) { if (string == null) { return true; } int length = string.length(); if (length > 0) { for (int i = 0; i < length; i++) { if (!Character.isWhitespace(string.charAt(i))) { return false; } } } return true; }
Source:
private synchronized PackIndex idx() throws IOException { if (loadedIdx == null) { if (invalid) throw new PackInvalidException(packFile, invalidatingCause); try { final PackIndex idx = PackIndex.open(extFile(INDEX)); if (packChecksum == null) { packChecksum = idx.packChecksum; } else if (!Arrays.equals(packChecksum, idx.packChecksum)) { throw new PackMismatchException(MessageFormat.format( JGitText.get().packChecksumMismatch, packFile.getPath())); } loadedIdx = idx; } catch (InterruptedIOException e) { throw e; } catch (IOException e) { invalid = true; invalidatingCause = e; throw e; } } return loadedIdx; }

Target:
private synchronized PackIndex idx() throws IOException { if (loadedIdx == null) { if (invalid) { throw new PackInvalidException(packFile, invalidatingCause); } try { final PackIndex idx = PackIndex.open(extFile(INDEX)); if (packChecksum == null) { packChecksum = idx.packChecksum; } else if (!Arrays.equals(packChecksum, idx.packChecksum)) { throw new PackMismatchException(MessageFormat.format( JGitText.get().packChecksumMismatch, packFile.getPath())); } loadedIdx = idx; } catch (InterruptedIOException e) { throw e; } catch (IOException e) { invalid = true; invalidatingCause = e; throw e; } } return loadedIdx; }
Source:
private static Optional<HostAndPort> meshProxy(Optional<ProxyConfiguration> proxy) { if (!proxy.isPresent() || proxy.get().type() != ProxyConfiguration.Type.MESH) { return Optional.empty(); } return Optional.of(HostAndPort.fromString(proxy.get().hostAndPort().get())); }

Target:
private static Optional<HostAndPort> meshProxy(Optional<ProxyConfiguration> proxy) { if (proxy.isPresent() && proxy.get().type() == ProxyConfiguration.Type.MESH) { return Optional.of(HostAndPort.fromString(proxy.get().hostAndPort().get())); } else { return Optional.empty(); } }
Source:
public Builder withSteps(List<? extends FunnelStep> steps) { for (FunnelStep step : steps) { withStep(step); } return this; }

Target:
public Builder withSteps(List<? extends FunnelStep> steps) { if (null != this.steps) { throw new KeenQueryClientException( "Incorrect Usage: withSteps() called, which would clear any existing steps already added. " + "Don't add steps prior to calling withSteps(), or append additional steps by calling withStep()." ); } setSteps(steps); return this; }
Source:
public HibernateValidatorContext addValueExtractor(ValueExtractor<?> extractor) { valueExtractors.add( extractor ); return this; }

Target:
public HibernateValidatorContext addValueExtractor(ValueExtractor<?> extractor) { ValueExtractorDescriptor descriptor = new ValueExtractorDescriptor( extractor ); ValueExtractorDescriptor previous = valueExtractorDescriptors.put( descriptor.getKey(), descriptor ); if ( previous != null ) { throw LOG.getValueExtractorForTypeAndTypeUseAlreadyPresentException( extractor, previous.getValueExtractor() ); } return this; }
Source:
private static void compareJSONObject(JSONObject original, JSONObject marshalled) { checkKeys(original, marshalled); for (String originalKey : original.keySet()) { if (!OTHER_ATTRIBUTES.equals(originalKey) && !H_$.equals(originalKey)) { compareJSONObjectKey(original, marshalled, originalKey); } } }

Target:
private static void compareJSONObject(JSONObject original, JSONObject marshalled) { checkKeys(original, marshalled); for (String originalKey : original.keySet()) { if (!Objects.equals(OTHER_ATTRIBUTES, originalKey) && !Objects.equals(H_$, originalKey)) { compareJSONObjectKey(original, marshalled, originalKey); } } }
Source:
private FlowRefFactoryBean createDynamicFlowRefFactoryBean(Processor target, Object targetBuilder, ApplicationContext applicationContext) throws Exception { if (targetBuilder != null) { doReturn(targetBuilder).when(applicationContext).getBean(eq(PARSED_DYNAMIC_REFERENCED_FLOW)); } else { doReturn(target).when(applicationContext).getBean(eq(PARSED_DYNAMIC_REFERENCED_FLOW)); } return createFlowRefFactoryBean(FlowRefFactoryBeanTestCase.DYNAMIC_REFERENCED_FLOW, "flow", applicationContext); }

Target:
private FlowRefFactoryBean createDynamicFlowRefFactoryBean(Processor target, Object targetBuilder, ApplicationContext applicationContext) throws Exception { if (targetBuilder != null) { doReturn(targetBuilder).when(applicationContext).getBean(eq(PARSED_DYNAMIC_REFERENCED_FLOW)); } else { doReturn(target).when(applicationContext).getBean(eq(PARSED_DYNAMIC_REFERENCED_FLOW)); } return createFlowRefFactoryBean(DYNAMIC_REFERENCED_FLOW, "flow", applicationContext); }
Source:
public Optional<ImmutableFlyingData> with(Key<? extends BaseValue<?>> key, Object value, ImmutableFlyingData immutable) { return Optional.absent(); }

Target:
public Optional<ImmutableFlyingData> with(Key<? extends BaseValue<?>> key, Object value, ImmutableFlyingData immutable) { if (key.equals(Keys.IS_FLYING)) { return Optional.<ImmutableFlyingData>of(ImmutableDataCachingUtil.getManipulator(ImmutableSpongeFlyingData.class, value)); } return Optional.absent(); }
Source:
public void onPlansFetched(OnPlansFetched event) { cancelDomainCreditsCheckProgressDialog(); if (event.isError()) { AppLog.e(T.PLANS, PluginDetailActivity.class.getSimpleName() + ".onPlansFetched: " + event.error.type + " - " + event.error.message); } else { if (event.plans == null) { AppLog.e(T.PLANS, "Fetched user plans are null."); return; } PlanModel currentPlan = null; for (PlanModel plan : event.plans) { if (plan.isCurrentPlan()) { currentPlan = plan; break; } } boolean isDomainCreditAvailable = currentPlan != null && currentPlan.getHasDomainCredit(); if (isDomainCreditAvailable) { showDomainRegistrationDialog(); } else { dispatchInstallPluginAction(); } } }

Target:
public void onPlansFetched(OnPlansFetched event) { if (mCheckingDomainCreditsProgressDialog == null || !mCheckingDomainCreditsProgressDialog.isShowing()) { AppLog.w(T.PLANS, "User cancelled domain credit checking. Ignoring the result."); return; } cancelDomainCreditsCheckProgressDialog(); if (event.isError()) { AppLog.e(T.PLANS, PluginDetailActivity.class.getSimpleName() + ".onPlansFetched: " + event.error.type + " - " + event.error.message); Snackbar.make(mContainer, getString(R.string.plugin_check_domain_credit_error), AccessibilityUtils.getSnackbarDuration(this)).show(); } else { if (event.plans == null) { String errorMessage = "Failed to fetch user Plans. The result is null."; if (BuildConfig.DEBUG) { throw new IllegalStateException(errorMessage); } Snackbar.make(mContainer, getString(R.string.plugin_check_domain_credit_error), AccessibilityUtils.getSnackbarDuration(this)).show(); AppLog.e(T.PLANS, errorMessage); return; } PlanModel currentPlan = null; for (PlanModel plan : event.plans) { if (plan.isCurrentPlan()) { currentPlan = plan; break; } } boolean isDomainCreditAvailable = currentPlan != null && currentPlan.getHasDomainCredit(); if (isDomainCreditAvailable) { showDomainRegistrationDialog(); } else { dispatchInstallPluginAction(); } } }
Source:
public void setup() throws Exception { PowerMockito.whenNew(KubernetesClient.class).withAnyArguments().thenReturn(client); PowerMockito.spy(KubernetesConfig.class); PowerMockito.doReturn("default") .when(KubernetesConfig.class, "readFileContents", "/var/run/secrets/kubernetes.io/serviceaccount/namespace"); }

Target:
public void setup() throws Exception { PowerMockito.whenNew(KubernetesClient.class).withAnyArguments().thenReturn(client); }
Source:
public HttpResponse doSafeExit(StaplerRequest req) throws IOException { checkPermission(ADMINISTER); isQuietingDown = true; final String exitUser = getAuthentication().getName(); final String exitAddr = req!=null ? req.getRemoteAddr() : "unknown"; new Thread("safe-exit thread") { @Override public void run() { try { ACL.impersonate(ACL.SYSTEM); LOGGER.severe(String.format("Shutting down VM as requested by %s from %s", exitUser, exitAddr)); doQuietDown(true, 0); if (isQuietingDown) { cleanUp(); System.exit(0); } } catch (Exception e) { LOGGER.log(Level.WARNING, "Failed to shutdown Hudson",e); } } }.start(); return HttpResponses.plainText("Shutting down as soon as all jobs are complete"); }

Target:
public HttpResponse doSafeExit(StaplerRequest req) throws IOException { checkPermission(ADMINISTER); isQuietingDown = true; final String exitUser = getAuthentication().getName(); final String exitAddr = req!=null ? req.getRemoteAddr() : "unknown"; new Thread("safe-exit thread") { @Override public void run() { try { ACL.impersonate(ACL.SYSTEM); LOGGER.severe(String.format("Shutting down VM as requested by %s from %s", exitUser, exitAddr)); doQuietDown(true, 0); if (isQuietingDown) { cleanUp(); System.exit(0); } } catch (Exception e) { LOGGER.log(Level.WARNING, "Failed to shut down Jenkins", e); } } }.start(); return HttpResponses.plainText("Shutting down as soon as all jobs are complete"); }
Source:
private ScheduledExecutorService startKerberosLoginThread() { scheduledExecutorService = Executors.newScheduledThreadPool(1); scheduledExecutorService.submit(new Callable() { public Object call() throws Exception { if (runKerberosLogin()) { logger.info("Ran runKerberosLogin command successfully."); kinitFailCount = 0; logger.info("Scheduling Kerberos ticket refresh thread with interval " + getKerberosRefreshInterval() + " ms"); scheduledExecutorService .schedule(this, getKerberosRefreshInterval(), TimeUnit.MILLISECONDS); } else { kinitFailCount++; logger.info("runKerberosLogin failed for " + kinitFailCount + " time(s)."); if (kinitFailCount >= kinitFailThreshold()) { logger.error("runKerberosLogin failed for max attempts, calling close interpreter."); close(); } else { scheduledExecutorService.submit(this); } } return null; } }); return scheduledExecutorService; }

Target:
private ScheduledExecutorService startKerberosLoginThread() { scheduledExecutorService = Executors.newScheduledThreadPool(1); scheduledExecutorService.submit(new Callable() { public Object call() throws Exception { if (runKerberosLogin()) { LOGGER.info("Ran runKerberosLogin command successfully."); kinitFailCount = 0; LOGGER.info("Scheduling Kerberos ticket refresh thread with interval " + getKerberosRefreshInterval() + " ms"); scheduledExecutorService .schedule(this, getKerberosRefreshInterval(), TimeUnit.MILLISECONDS); } else { kinitFailCount++; LOGGER.info("runKerberosLogin failed for " + kinitFailCount + " time(s)."); if (kinitFailCount >= kinitFailThreshold()) { LOGGER.error("runKerberosLogin failed for max attempts, calling close interpreter."); close(); } else { scheduledExecutorService.schedule(this, 1, TimeUnit.SECONDS); } } return null; } }); return scheduledExecutorService; }
Source:
private void processWorkerMetrics(final String srcId, final MetricReportMsg metricReportMsg) { for (final ByteBuffer encodedBuffer : metricReportMsg.getCustomMetrics()) { final DolphinWorkerMetrics workerMetrics = metricMsgCodec.decode(encodedBuffer.array()); final Map<String, Integer> tableToNumBlocks = metricReportMsg.getTableToNumBlocks(); final String hostname = metricReportMsg.getHostname(); int numWorkers = 0; switch (workerMetrics.getType()) { case BatchMetrics: final BatchMetrics batchMetrics = workerMetrics.getBatchMetrics(); try { numWorkers = etMaster.getTable(inputTableId).getPartitionInfo().size(); } catch (TableNotExistException e) { throw new RuntimeException(e); } final WorkerMetrics convertedBatchMetrics = convertBatchMetrics(metricReportMsg, tableToNumBlocks, hostname, batchMetrics); metricManager.storeWorkerMetrics(srcId, convertedBatchMetrics); break; case EpochMetrics: final EpochMetrics epochMetrics = workerMetrics.getEpochMetrics(); final WorkerMetrics convertedEpochMetrics = convertEpochMetrics(metricReportMsg, hostname, epochMetrics); metricManager.storeWorkerMetrics(srcId, convertedEpochMetrics); break; default: throw new RuntimeException("Unknown message type"); } LOG.log(Level.INFO, "Received a worker metric from {0} (num running workers: {1}): {2}", new Object[] {srcId, numWorkers, workerMetrics}); } }

Target:
private void processWorkerMetrics(final String srcId, final MetricReportMsg metricReportMsg) { for (final ByteBuffer encodedBuffer : metricReportMsg.getCustomMetrics()) { final DolphinWorkerMetrics workerMetrics = metricMsgCodec.decode(encodedBuffer.array()); final Map<String, Integer> tableToNumBlocks = metricReportMsg.getTableToNumBlocks(); final String hostname = metricReportMsg.getHostname(); switch (workerMetrics.getType()) { case BatchMetrics: final BatchMetrics batchMetrics = workerMetrics.getBatchMetrics(); final WorkerMetrics convertedBatchMetrics = convertBatchMetrics(metricReportMsg, tableToNumBlocks, hostname, batchMetrics); metricManager.storeWorkerMetrics(srcId, convertedBatchMetrics); break; case EpochMetrics: final EpochMetrics epochMetrics = workerMetrics.getEpochMetrics(); final WorkerMetrics convertedEpochMetrics = convertEpochMetrics(metricReportMsg, hostname, epochMetrics); metricManager.storeWorkerMetrics(srcId, convertedEpochMetrics); break; default: throw new RuntimeException("Unknown message type"); } try { final int numWorkers = etMaster.getTable(inputTableId).getPartitionInfo().size(); LOG.log(Level.INFO, "Received a worker metric from {0} (num running workers: {1}): {2}", new Object[] {srcId, numWorkers, workerMetrics}); } catch (TableNotExistException e) { throw new RuntimeException(e); } } }
Source:
public void rateLimit(JoinPoint jp, RateLimit limit) throws RateLimitException { RateLimiter limiter = limiters.computeIfAbsent(createKey(jp), createLimiter(limit)); boolean acquired = limiter.tryAcquire(RATE_LIMIT_ACQUIRE_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS); if (acquired) { logger.debug("Acquired rate limit permission"); } else { logger.error("Could not acquire rate limit permission"); throw new RateLimitException(String.format("Rate limit exceeded. Please limit rate to %s requests/second.", limit.value())); } }

Target:
public void rateLimit(JoinPoint jp, RateLimit limit) throws RateLimitException { RateLimiter limiter = limiters.computeIfAbsent(getIPAddress(jp), createLimiter(limit)); boolean acquired = limiter.tryAcquire(RATE_LIMIT_ACQUIRE_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS); if (!acquired) { logger.error("Could not acquire rate limit permission"); throw new RateLimitException(String.format("Rate limit exceeded. Please limit rate to %d requests/second.", limit.value())); } logger.debug("Acquired rate limit permission"); }
Source:
public void defaultRemovalStrategyShutsDownNewestFirstWhenResizing() throws Exception { final List<Entity> creationOrder = Lists.newArrayList(); DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class) .configure("initialSize", 0) .configure("factory", new EntityFactory<Entity>() { @Override public Entity newEntity(Map flags, Entity parent) { Entity result = new TestEntityImpl(flags); creationOrder.add(result); return result; }})); cluster.start(ImmutableList.of(loc)); cluster.resize(1); cluster.resize(2); assertEquals(cluster.getCurrentSize(), (Integer)2); assertEquals(ImmutableSet.copyOf(cluster.getMembers()), ImmutableSet.copyOf(creationOrder), "actual="+cluster.getMembers()); Collection<Entity> preStopMembers = ImmutableList.copyOf(cluster.getMembers()); cluster.resize(1); assertEquals(cluster.getCurrentSize(), (Integer)1); Entity remainingEntity = cluster.getMembers().iterator().next(); for(Entity entity : preStopMembers) { assertTrue(entity.getCreationTime() >= remainingEntity.getCreationTime()); } }

Target:
public void defaultRemovalStrategyShutsDownNewestFirstWhenResizing() throws Exception { final List<Entity> creationOrder = Lists.newArrayList(); DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class) .configure("initialSize", 0) .configure("factory", new EntityFactory<Entity>() { @Override public Entity newEntity(Map flags, Entity parent) { Entity result = new TestEntityImpl(flags); creationOrder.add(result); return result; }})); cluster.start(ImmutableList.of(loc)); cluster.resize(1); Thread.sleep(1); cluster.resize(2); assertEquals(cluster.getCurrentSize(), (Integer)2); assertEquals(ImmutableSet.copyOf(cluster.getMembers()), ImmutableSet.copyOf(creationOrder), "actual="+cluster.getMembers()); cluster.resize(1); assertEquals(cluster.getCurrentSize(), (Integer)1); assertEquals(ImmutableList.copyOf(cluster.getMembers()), creationOrder.subList(0, 1)); }
Source:
protected void verify_internal_effects() { verify(iterables).assertHasOnlyOneElementSatisfying(info(), newArrayList(internalArray()), consumer); }

Target:
protected void verify_internal_effects() { verify(iterables).assertHasOnlyOneElementSatisfying(info(), list(internalArray()), consumer); }
Source:
public void addRecords(final TopicPartition partition, final Iterable<ConsumerRecord<byte[], byte[]>> records) { if (state() == State.CLOSED || state() == State.CLOSING) { log.info("Stream task is already in state, skip adding records to it.", id(), state()); } final int newQueueSize = partitionGroup.addRawRecords(partition, records); if (log.isTraceEnabled()) { log.trace("Added records into the buffered queue of partition {}, new queue size is {}", partition, newQueueSize); } if (newQueueSize > maxBufferedSize) { consumer.pause(singleton(partition)); } }

Target:
public void addRecords(final TopicPartition partition, final Iterable<ConsumerRecord<byte[], byte[]>> records) { final int newQueueSize = partitionGroup.addRawRecords(partition, records); if (log.isTraceEnabled()) { log.trace("Added records into the buffered queue of partition {}, new queue size is {}", partition, newQueueSize); } if (newQueueSize > maxBufferedSize) { consumer.pause(singleton(partition)); } }
Source:
public Set<String> getConsumedEvents() { Set<String> set = new HashSet<>(super.getConsumedEvents()); if (hasCells == null) { return set; } for(HasCell<T, ?> currentHasCell : hasCells) { if(currentHasCell instanceof Column) { Set<String> consumedEvents = ((Column)(currentHasCell)).getCell().getConsumedEvents(); if(consumedEvents != null) { set.addAll(consumedEvents); } } if(currentHasCell instanceof AbstractCell) { set.addAll(((AbstractCell)currentHasCell).getConsumedEvents()); } } return set; }

Target:
public Set<String> getConsumedEvents() { Set<String> set = new HashSet<>(super.getConsumedEvents()); if (hasCells == null) { return set; } for(HasCell<T, ?> currentHasCell : hasCells) { if(currentHasCell instanceof Column) { Set<String> consumedEvents = ((Column)(currentHasCell)).getCell().getConsumedEvents(); if(consumedEvents != null) { set.addAll(consumedEvents); } } if(currentHasCell instanceof Cell) { set.addAll(((Cell)currentHasCell).getConsumedEvents()); } } return set; }
Source:
public void scalaOutputTest() throws IOException, InterruptedException { Note note = ZeppelinServer.notebook.createNote("note1", anonymous); Paragraph p = note.addNewParagraph(anonymous); p.setText("%spark import java.util.Date\n" + "import java.net.URL\n" + "println(\"hello\")\n" ); note.run(p.getId(), true); assertEquals(Status.FINISHED, p.getStatus()); assertEquals("hello\n" + "import java.util.Date\n" + "import java.net.URL\n", p.getReturn().message().get(0).getData()); p.setText("%spark invalid_code"); note.run(p.getId(), true); assertEquals(Status.ERROR, p.getStatus()); assertTrue(p.getReturn().message().get(0).getData().contains("error: ")); p.setText("%spark(p1=v1,p2=v2) print(z.getInterpreterContext().getLocalProperties().size())"); note.run(p.getId(), true); assertEquals(Status.FINISHED, p.getStatus()); assertEquals("2", p.getReturn().message().get(0).getData()); List<InterpreterCompletion> completions = note.completion(p.getId(), "sc.", 2); assertTrue(completions.size() > 0); p.setText("%spark sc.range(1,10).map(e=>{Thread.sleep(1000); e}).collect()"); note.run(p.getId(), false); Thread.sleep(3000); p.abort(); Thread.sleep(3000); assertEquals(Status.ABORT, p.getStatus()); ZeppelinServer.notebook.removeNote(note.getId(), anonymous); }

Target:
public void scalaOutputTest() throws IOException, InterruptedException { Note note = ZeppelinServer.notebook.createNote("note1", anonymous); Paragraph p = note.addNewParagraph(anonymous); p.setText("%spark import java.util.Date\n" + "import java.net.URL\n" + "println(\"hello\")\n" ); note.run(p.getId(), true); assertEquals(Status.FINISHED, p.getStatus()); assertEquals("hello\n" + "import java.util.Date\n" + "import java.net.URL\n", p.getReturn().message().get(0).getData()); p.setText("%spark invalid_code"); note.run(p.getId(), true); assertEquals(Status.ERROR, p.getStatus()); assertTrue(p.getReturn().message().get(0).getData().contains("error: ")); p.setText("%spark(p1=v1,p2=v2) print(z.getInterpreterContext().getLocalProperties().size())"); note.run(p.getId(), true); assertEquals(Status.FINISHED, p.getStatus()); assertEquals("2", p.getReturn().message().get(0).getData()); List<InterpreterCompletion> completions = note.completion(p.getId(), "sc.", 2); assertTrue(completions.size() > 0); p.setText("%spark sc.range(1,10).map(e=>{Thread.sleep(1000); e}).collect()"); note.run(p.getId(), false); waitForRunning(p); p.abort(); waitForFinish(p); assertEquals(Status.ABORT, p.getStatus()); ZeppelinServer.notebook.removeNote(note.getId(), anonymous); }
Source:
public T get() { if (persistence == null) { synchronized (this) { this.persistence = build(conn, databases); } } if (disableCaching) { persistence.disableCaching(); } return persistence; }

Target:
public T get() { if (persistence == null) { synchronized (this) { if (persistence == null) { this.persistence = build(conn, databases); } } } if (disableCaching) { persistence.disableCaching(); } return persistence; }
Source:
private int sweepBatch(TableReference tableRef, List<CellToSweep> batch, RunType runType, int deleteBatchSize) { int numberOfSweptCells = 0; Multimap<Cell, Long> currentBatch = ArrayListMultimap.create(); List<Cell> currentBatchSentinels = Lists.newArrayList(); for (CellToSweep cell : batch) { if (cell.needsSentinel()) { currentBatchSentinels.add(cell.cell()); } if (currentBatch.size() + cell.sortedTimestamps().size() < deleteBatchSize) { currentBatch.putAll(cell.cell(), TDecorators.wrap(cell.sortedTimestamps())); continue; } TLongList remainingCellTimestamps = cell.sortedTimestamps(); while (currentBatch.size() + remainingCellTimestamps.size() >= deleteBatchSize) { int numberOfTimestampsForThisBatch = deleteBatchSize - currentBatch.size(); TLongList timestampsForThisBatch = remainingCellTimestamps.subList(0, numberOfTimestampsForThisBatch); currentBatch.putAll(cell.cell(), TDecorators.wrap(timestampsForThisBatch)); if (runType == RunType.FULL) { cellsSweeper.sweepCells(tableRef, currentBatch, currentBatchSentinels); } numberOfSweptCells += currentBatch.size(); currentBatch = ArrayListMultimap.create(); currentBatchSentinels = Lists.newArrayList(); remainingCellTimestamps = remainingCellTimestamps.subList( numberOfTimestampsForThisBatch, remainingCellTimestamps.size()); } currentBatch.putAll(cell.cell(), TDecorators.wrap(remainingCellTimestamps)); } if (!currentBatch.isEmpty() && runType == RunType.FULL) { cellsSweeper.sweepCells(tableRef, currentBatch, currentBatchSentinels); } numberOfSweptCells += currentBatch.size(); return numberOfSweptCells; }

Target:
private int sweepBatch(TableReference tableRef, List<CellToSweep> batch, RunType runType, int deleteBatchSize) { int numberOfSweptCells = 0; Multimap<Cell, Long> currentBatch = ArrayListMultimap.create(); List<Cell> currentBatchSentinels = Lists.newArrayList(); for (CellToSweep cell : batch) { if (cell.needsSentinel()) { currentBatchSentinels.add(cell.cell()); } List<Long> currentCellTimestamps = TDecorators.wrap(cell.sortedTimestamps()); if (currentBatch.size() + currentCellTimestamps.size() < deleteBatchSize) { currentBatch.putAll(cell.cell(), currentCellTimestamps); continue; } while (currentBatch.size() + currentCellTimestamps.size() >= deleteBatchSize) { int numberOfTimestampsForThisBatch = deleteBatchSize - currentBatch.size(); currentBatch.putAll(cell.cell(), currentCellTimestamps.subList(0, numberOfTimestampsForThisBatch)); if (runType == RunType.FULL) { cellsSweeper.sweepCells(tableRef, currentBatch, currentBatchSentinels); } numberOfSweptCells += currentBatch.size(); currentBatch.clear(); currentBatchSentinels.clear(); currentCellTimestamps = currentCellTimestamps.subList( numberOfTimestampsForThisBatch, currentCellTimestamps.size()); } currentBatch.putAll(cell.cell(), currentCellTimestamps); } if (!currentBatch.isEmpty() && runType == RunType.FULL) { cellsSweeper.sweepCells(tableRef, currentBatch, currentBatchSentinels); } numberOfSweptCells += currentBatch.size(); return numberOfSweptCells; }
Source:
public void write(KeyValue keyValue) throws IOException { this.mWriter.write(keyValue.getValue()); if (DELIMITER != 92){ this.mWriter.write(DELIMITER); } }

Target:
public void write(KeyValue keyValue) throws IOException { this.mWriter.write(keyValue.getValue()); if (addDelimiter){ this.mWriter.write(mDelimiter); } }
Source:
public void checkAccessModifier(Method method) { final int modifiers = method.getModifiers(); final boolean nonDefaultModifier = Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers) || Modifier.isPrivate(modifiers); if (nonDefaultModifier) { warnOnWrongModifier("Command handler method should be declared with default access modifier.", method); } }

Target:
public void checkAccessModifier(Method method) { final int modifiers = method.getModifiers(); final boolean nonDefaultModifier = Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers) || Modifier.isPrivate(modifiers); if (nonDefaultModifier) { warnOnWrongModifier("Command handler method should be declared with the default access modifier.", method); } }
Source:
public ImageData getImageData (int zoom) { copyImageDataFromDpiImageStorage(DPIUtil.mapZoomToImageSelectorIndex(zoom)); ImageData returnVal = getImageData (); copyImageDataFromDpiImageStorage(device.getImageSelector()); return returnVal; }

Target:
public ImageData getImageData (int zoom) { copyImageDataFromDpiImageStorage(DPIUtil.mapZoomToImageSelectorIndex(zoom)); ImageData returnVal = getImageData (); copyImageDataFromDpiImageStorage(getImageSelector()); return returnVal; }
Source:
public void defaultPrefix() throws Exception { final MockHttpServletRequest request = new MockHttpServletRequest("POST", "/hotels"); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain filterChain = new NoOpFilterChain(); filter.doFilter(request, response, filterChain); assertThat(filter.beforeRequestMessage).isNotNull(); assertThat(filter.beforeRequestMessage.startsWith(AbstractRequestLoggingFilter.DEFAULT_BEFORE_MESSAGE_PREFIX)).isTrue(); assertThat(filter.afterRequestMessage).isNotNull(); assertThat(filter.afterRequestMessage.startsWith(AbstractRequestLoggingFilter.DEFAULT_AFTER_MESSAGE_PREFIX)).isTrue(); }

Target:
public void defaultPrefix() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("POST", "/hotels"); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain filterChain = new NoOpFilterChain(); filter.doFilter(request, response, filterChain); assertThat(filter.beforeRequestMessage).startsWith(AbstractRequestLoggingFilter.DEFAULT_BEFORE_MESSAGE_PREFIX); assertThat(filter.afterRequestMessage).startsWith(AbstractRequestLoggingFilter.DEFAULT_AFTER_MESSAGE_PREFIX); }
Source:
public List<Resource> getAllowedResources(PerunSession sess, Member member) throws InternalErrorException, MemberNotExistsException, PrivilegeException { Utils.checkPerunSession(sess); if (!AuthzResolver.isAuthorized(sess, Role.PERUNADMIN) && !AuthzResolver.isAuthorized(sess, Role.VOADMIN, member) && !AuthzResolver.isAuthorized(sess, Role.ENGINE) && !AuthzResolver.isAuthorized(sess, Role.PERUNOBSERVER) && !AuthzResolver.isAuthorized(sess, Role.SELF, member) && !AuthzResolver.isAuthorized(sess, Role.VOOBSERVER, member)) { throw new PrivilegeException(sess, "getAllowedResources"); } getPerunBl().getMembersManagerBl().checkMemberExists(sess, member); return getResourcesManagerBl().getAllowedResources(sess, member); }

Target:
public List<Resource> getAllowedResources(PerunSession sess, Member member) throws InternalErrorException, MemberNotExistsException, PrivilegeException { Utils.checkPerunSession(sess); if (!AuthzResolver.isAuthorized(sess, Role.VOADMIN, member) && !AuthzResolver.isAuthorized(sess, Role.VOOBSERVER, member) && !AuthzResolver.isAuthorized(sess, Role.ENGINE) && !AuthzResolver.isAuthorized(sess, Role.PERUNOBSERVER) && !AuthzResolver.isAuthorized(sess, Role.SELF, member)) { throw new PrivilegeException(sess, "getAllowedResources"); } getPerunBl().getMembersManagerBl().checkMemberExists(sess, member); return getResourcesManagerBl().getAllowedResources(sess, member); }
Source:
public List<ImmutableBitSet> getKeys() { return null; }

Target:
public List<ImmutableBitSet> getKeys() { return Collections.emptyList(); }