auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void checkForRegions() { Collection<Entry<ByteArrayWrapper, RedisData>> entrySet = keyRegistrar.keyInfos(); for (Entry<ByteArrayWrapper, RedisData> entry : entrySet) { ByteArrayWrapper key = entry.getKey(); RedisDataType type = entry.getValue().getType(); if (!regionCache.typeUsesDynamicRegions(type)) { continue; } if (cache.getRegion(key.toString()) != null) { continue; } try { regionCache.createRemoteRegionReferenceLocally(key, type); } catch (Exception e) { if (logger.errorEnabled()) { logger.error(e); } } } }

Target:
private void checkForRegions() { Collection<Entry<ByteArrayWrapper, RedisData>> entrySet = keyRegistrar.keyInfos(); for (Entry<ByteArrayWrapper, RedisData> entry : entrySet) { ByteArrayWrapper key = entry.getKey(); RedisDataType type = entry.getValue().getType(); if (!regionProvider.typeUsesDynamicRegions(type)) { continue; } if (cache.getRegion(key.toString()) != null) { continue; } try { regionProvider.createRemoteRegionReferenceLocally(key, type); } catch (Exception e) { if (logger.errorEnabled()) { logger.error(e); } } } }
Source:
private void generateVertxToJsonMethod(JDefinedClass jclass) { JMethod toJsonMethod = jclass.method(JMod.PUBLIC, jclass.owner().ref("io.vertx.core.json.JsonObject"), "toJson"); toJsonMethod.javadoc().add("Encode to JsonObject"); JBlock constructorBody = toJsonMethod.body(); constructorBody.directStatement("JsonObject obj = new JsonObject()"); constructorBody.add( jclass.owner() .ref(jclass.fullName() + "Converter") .staticInvoke("toJson") .arg(JExpr._this()) .arg(JExpr.ref("obj")) ); constructorBody._return(JExpr.ref("obj")); }

Target:
private void generateVertxToJsonMethod(JDefinedClass jclass) { JMethod toJsonMethod = jclass.method(JMod.PUBLIC, jclass.owner().ref("io.vertx.core.json.JsonObject"), "toJson"); toJsonMethod.javadoc().add("Encode to JsonObject"); JBlock constructorBody = toJsonMethod.body(); constructorBody.directStatement("JsonObject obj = new JsonObject();"); constructorBody.add( jclass.owner() .ref(jclass.fullName() + "Converter") .staticInvoke("toJson") .arg(JExpr._this()) .arg(JExpr.ref("obj")) ); constructorBody._return(JExpr.ref("obj")); }
Source:
public String toString() { if (getNamespaceURI().equals(XMLConstants.NULL_NS_URI)) { return getLocalPart(); } else { return "{" + getNamespaceURI() + "}" + getLocalPart(); } }

Target:
public String toString() { if (Objects.equals(getNamespaceURI(), XMLConstants.NULL_NS_URI)) { return getLocalPart(); } else { return "{" + getNamespaceURI() + "}" + getLocalPart(); } }
Source:
public void requestWhenBearerTokenResolverAllowsQueryParameterThenEitherHeaderOrQueryParameterIsAccepted() throws Exception { this.spring.register(AllowBearerTokenAsQueryParameterConfig.class, JwtDecoderConfig.class, BasicController.class).autowire(); JwtDecoder decoder = this.spring.getContext().getBean(JwtDecoder.class); when(decoder.decode(anyString())).thenReturn(JWT); DefaultBearerTokenResolver resolver = this.spring.getContext().getBean(DefaultBearerTokenResolver.class); resolver.setAllowUriQueryParameter(true); this.mvc.perform(get("/authenticated") .with(bearerToken(JWT_TOKEN))) .andExpect(status().isOk()) .andExpect(content().string(JWT_SUBJECT)); this.mvc.perform(get("/authenticated?access_token=" + JWT_TOKEN)) .andExpect(status().isOk()) .andExpect(content().string(JWT_SUBJECT)); }

Target:
public void requestWhenBearerTokenResolverAllowsQueryParameterThenEitherHeaderOrQueryParameterIsAccepted() throws Exception { this.spring.register(AllowBearerTokenAsQueryParameterConfig.class, JwtDecoderConfig.class, BasicController.class).autowire(); JwtDecoder decoder = this.spring.getContext().getBean(JwtDecoder.class); when(decoder.decode(anyString())).thenReturn(JWT); this.mvc.perform(get("/authenticated") .with(bearerToken(JWT_TOKEN))) .andExpect(status().isOk()) .andExpect(content().string(JWT_SUBJECT)); this.mvc.perform(get("/authenticated") .param("access_token", JWT_TOKEN)) .andExpect(status().isOk()) .andExpect(content().string(JWT_SUBJECT)); }
Source:
private static Map<String, X509Certificate> getTrustedCertificates() { ImmutableMap.Builder<String, X509Certificate> certificateMap = ImmutableMap.builder(); try { InputStream certificateResource = DefaultCas.class.getResourceAsStream(CA_CERTIFICATES_CRT); ByteArrayOutputStream inMemoryCertificates = new ByteArrayOutputStream(); ByteStreams.copy(certificateResource, inMemoryCertificates); List<X509Certificate> caCertificates = KeyStores.readX509Certificates(new ByteArrayInputStream(inMemoryCertificates.toByteArray())) .stream() .map(cert -> (X509Certificate) cert) .collect(Collectors.toList()); int index = 0; for (X509Certificate cert : caCertificates) { String certificateCommonName = cert.getSubjectX500Principal().getName().toLowerCase(Locale.ENGLISH); certificateMap.put(certificateCommonName, cert); log.debug( "Adding CA certificate", SafeArg.of("certificateIndex", index), SafeArg.of("certificateCount", caCertificates.size()), SafeArg.of("certificateCommonName", certificateCommonName), SafeArg.of("expiry", cert.getNotAfter()), SafeArg.of( "sha256Fingerprint", Hashing.sha256().hashBytes(cert.getEncoded()).toString())); index++; } } catch (CertificateException | IOException e) { throw new SafeRuntimeException("Could not read file as an X.509 certificate", e); } return certificateMap.build(); }

Target:
private static Map<String, X509Certificate> getTrustedCertificates() { ImmutableMap.Builder<String, X509Certificate> certificateMap = ImmutableMap.builder(); try { List<X509Certificate> caCertificates = KeyStores.readX509Certificates( new ByteArrayInputStream(Resources.toByteArray(Resources.getResource(CA_CERTIFICATES_CRT)))) .stream() .map(cert -> (X509Certificate) cert) .collect(Collectors.toList()); int index = 0; for (X509Certificate cert : caCertificates) { String certificateCommonName = cert.getSubjectX500Principal().getName().toLowerCase(Locale.ENGLISH); certificateMap.put(certificateCommonName, cert); log.debug( "Adding CA certificate", SafeArg.of("certificateIndex", index), SafeArg.of("certificateCount", caCertificates.size()), SafeArg.of("certificateCommonName", certificateCommonName), SafeArg.of("expiry", cert.getNotAfter()), SafeArg.of( "sha256Fingerprint", Hashing.sha256().hashBytes(cert.getEncoded()).toString())); index++; } } catch (CertificateException | IOException e) { throw new SafeRuntimeException("Could not read file as an X.509 certificate", e); } return certificateMap.build(); }
Source:
private void sendError(HttpServletRequest request, HttpServletResponse response, String message) throws IOException { final Request baseRequest = Request.getBaseRequest(request); final Response baseResponse = Objects.requireNonNull(baseRequest).getResponse(); if (LOG.isDebugEnabled()) LOG.debug("OpenId authentication FAILED: {}", message); if (_errorPage == null) { if (LOG.isDebugEnabled()) LOG.debug("auth failed 403"); if (response != null) response.sendError(HttpServletResponse.SC_FORBIDDEN); } else { if (LOG.isDebugEnabled()) LOG.debug("auth failed {}", _errorPage); String redirectUri = URIUtil.addPaths(request.getContextPath(), _errorPage); if (message != null) { String query = URIUtil.combineQueryParams(ERROR_PARAMETER + "=" + UrlEncoded.encodeString(message), _errorQuery); redirectUri = URIUtil.addPaths(request.getContextPath(), _errorPath) + "?" + query; baseResponse.sendRedirect(getRedirectCode(baseRequest.getHttpVersion()), redirectUri); } baseResponse.sendRedirect(getRedirectCode(baseRequest.getHttpVersion()), redirectUri); } }

Target:
private void sendError(HttpServletRequest request, HttpServletResponse response, String message) throws IOException { final Request baseRequest = Request.getBaseRequest(request); final Response baseResponse = Objects.requireNonNull(baseRequest).getResponse(); if (LOG.isDebugEnabled()) LOG.debug("OpenId authentication FAILED: {}", message); if (_errorPage == null) { if (LOG.isDebugEnabled()) LOG.debug("auth failed 403"); if (response != null) response.sendError(HttpServletResponse.SC_FORBIDDEN); } else { if (LOG.isDebugEnabled()) LOG.debug("auth failed {}", _errorPage); String redirectUri = URIUtil.addPaths(request.getContextPath(), _errorPage); if (message != null) { String query = URIUtil.addQueries(ERROR_PARAMETER + "=" + UrlEncoded.encodeString(message), _errorQuery); redirectUri = URIUtil.addPathQuery(URIUtil.addPaths(request.getContextPath(), _errorPath), query); baseResponse.sendRedirect(getRedirectCode(baseRequest.getHttpVersion()), redirectUri); } baseResponse.sendRedirect(getRedirectCode(baseRequest.getHttpVersion()), redirectUri); } }
Source:
public CoreEvent process(CoreEvent event) throws MuleException { try { return processToApply(event, this); } catch (Exception error) { Throwable cause = error.getCause(); if (cause instanceof RetryContextInitializationException && cause.getCause() instanceof ExpressionRuntimeException) { throw ((ExpressionRuntimeException) cause.getCause()); } else { throw error; } } }

Target:
public CoreEvent process(CoreEvent event) throws MuleException { try { return processToApply(event, this); } catch (Exception error) { Throwable cause = error.getCause(); if (cause != null && cause instanceof RetryContextInitializationException && cause.getCause() instanceof ExpressionRuntimeException) { throw ((ExpressionRuntimeException) cause.getCause()); } else { throw error; } } }
Source:
public void create(final String version, List<String> participants) { LOG.info(String.format("Creating barrier with version: %s, participants: %s.", version, participants)); String barrierRoot = keyBuilder.getBarrierRoot(); String barrierParticipantsPath = keyBuilder.getBarrierParticipantsPath(version); String barrierStatePath = keyBuilder.getBarrierStatePath(version); zkUtils.validatePaths(new String[]{ barrierRoot, keyBuilder.getBarrierPath(version), barrierParticipantsPath, barrierStatePath}); LOG.info(String.format("Marking the barrier state: %s as %s.", barrierStatePath, State.NEW)); zkUtils.writeData(barrierStatePath, State.NEW); LOG.info("Subscribing child changes for the path: {}.", barrierParticipantsPath); zkUtils.subscribeChildChanges(barrierParticipantsPath, new ZkBarrierChangeHandler(version, participants, zkUtils)); barrierListenerOptional.ifPresent(zkBarrierListener -> zkBarrierListener.onBarrierCreated(version)); }

Target:
public void create(final String version, List<String> participants) { LOG.info(String.format("Creating barrier with version: %s, participants: %s.", version, participants)); String barrierRoot = keyBuilder.getBarrierRoot(); String barrierParticipantsPath = keyBuilder.getBarrierParticipantsPath(version); String barrierStatePath = keyBuilder.getBarrierStatePath(version); zkUtils.validatePaths(new String[]{ barrierRoot, keyBuilder.getBarrierPath(version), barrierParticipantsPath, barrierStatePath}); LOG.info("Marking the barrier state: as {}.", barrierStatePath, State.NEW); zkUtils.writeData(barrierStatePath, State.NEW); LOG.info("Subscribing child changes on the path: for barrier version: {}.", barrierParticipantsPath, version); zkUtils.subscribeChildChanges(barrierParticipantsPath, new ZkBarrierChangeHandler(version, participants, zkUtils)); barrierListenerOptional.ifPresent(zkBarrierListener -> zkBarrierListener.onBarrierCreated(version)); }
Source:
public int migrate(int currentVersion, MigrationDataProvider<ApplicationScope> migrationDataProvider, ProgressObserver observer) { final AdminClient adminClient = provider.getClient().admin(); final int latestVersion = dataVersion.getImplementationVersion(); observer.start(); migrationDataProvider.getData().flatMap(applicationScope -> { LegacyIndexIdentifier legacyIndexIdentifier = new LegacyIndexIdentifier(indexFig, applicationScope); String[] indexes = indexCache.getIndexes(legacyIndexIdentifier.getAlias(), AliasedEntityIndex.AliasType.Read); return Observable.from(indexes); }) .doOnNext(index -> { IndicesAliasesRequestBuilder aliasesRequestBuilder = adminClient.indices().prepareAliases(); aliasesRequestBuilder = adminClient.indices().prepareAliases(); aliasesRequestBuilder.addAlias(index, indexIdentifier.getAlias().getReadAlias()); observer.update(latestVersion,"EsIndexDataMigrationImpl: fixed index: " + index ); }) .doOnError(error -> { log.error("failed to migrate index", error); observer.failed(latestVersion,"EsIndexDataMigrationImpl: failed to migrate",error); }) .doOnCompleted(() -> observer.complete()) .toBlocking().lastOrDefault(null); return latestVersion; }

Target:
public int migrate(int currentVersion, MigrationDataProvider<ApplicationScope> migrationDataProvider, ProgressObserver observer) { final AdminClient adminClient = provider.getClient().admin(); final int latestVersion = dataVersion.getImplementationVersion(); entityIndex.initialize(); observer.start(); try { migrationDataProvider.getData().flatMap(applicationScope -> { LegacyIndexIdentifier legacyIndexIdentifier = new LegacyIndexIdentifier(indexFig, applicationScope); String[] indexes = indexCache.getIndexes(legacyIndexIdentifier.getAlias(), AliasedEntityIndex.AliasType.Read); return Observable.from(indexes); }) .doOnNext(index -> { IndicesAliasesRequestBuilder aliasesRequestBuilder = adminClient.indices().prepareAliases(); aliasesRequestBuilder = adminClient.indices().prepareAliases(); try { aliasesRequestBuilder.addAlias(index, indexIdentifier.getAlias().getReadAlias()).get(); } catch (InvalidAliasNameException e) { log.debug("Failed to add alias due to name conflict",e); } observer.update(latestVersion, "EsIndexDataMigrationImpl: fixed index: " + index); }) .doOnCompleted(() -> observer.complete()) .toBlocking().lastOrDefault(null); }catch (Exception e){ log.error("Failed to migrate index", e); throw e; } return latestVersion; }
Source:
public void insert(final String id, final SupervisorSpec spec) { dbi.withHandle( new HandleCallback<Void>() { @Override public Void withHandle(Handle handle) throws Exception { final String version = new DateTime().toString(); handle.createStatement( String.format( "INSERT INTO %s (id, spec_id, version, payload) VALUES (:id, :spec_id, :version, :payload)", getSupervisorsTable() ) ) .bind("id", String.format("%s_%s_%s", id, version, UUIDUtils.generateUuid())) .bind("spec_id", id) .bind("version", version) .bind("payload", jsonMapper.writeValueAsBytes(spec)) .execute(); return null; } } ); }

Target:
public void insert(final String id, final SupervisorSpec spec) { dbi.withHandle( new HandleCallback<Void>() { @Override public Void withHandle(Handle handle) throws Exception { handle.createStatement( String.format( "INSERT INTO %s (spec_id, created_date, payload) VALUES (:spec_id, :created_date, :payload)", getSupervisorsTable() ) ) .bind("spec_id", id) .bind("created_date", new DateTime().toString()) .bind("payload", jsonMapper.writeValueAsBytes(spec)) .execute(); return null; } } ); }
Source:
private void initLargeRequestThrottlingSettings() { setLargeRequestMaxBytes(Integer.getInteger("zookeeper.largeRequestMaxBytes", 100 * 1024 * 1024)); setLargeRequestThreshold(Integer.getInteger("zookeeper.largeRequestThreshold", -1)); }

Target:
private void initLargeRequestThrottlingSettings() { setLargeRequestMaxBytes(Integer.getInteger("zookeeper.largeRequestMaxBytes", largeRequestMaxBytes)); setLargeRequestThreshold(Integer.getInteger("zookeeper.largeRequestThreshold", -1)); }
Source:
public void testCache() { final AtomicBoolean criticalVariable = new AtomicBoolean(); SequencerServerCache cache = new SequencerServerCache(1, Address.NOT_FOUND); final long firstValue = 1L; final long secondValue = 2L; final int iterations = 10; final ConflictTxStream firstKey = new ConflictTxStream(UUID.randomUUID(), new byte[]{}, firstValue); final ConflictTxStream secondKey = new ConflictTxStream(UUID.randomUUID(), new byte[]{}, secondValue); for (int i = 0; i < iterations; i++) { criticalVariable.set(false); cache.put(firstKey); cache.put(secondKey); assertThat(cache.size()).isOne(); assertThat(cache.getIfPresent(firstKey)).isNull(); } }

Target:
public void testCache() { final AtomicBoolean criticalVariable = new AtomicBoolean(); SequencerServerCache cache = new SequencerServerCache(1, Address.NOT_FOUND); final long firstValue = 1L; final long secondValue = 2L; final int iterations = 10; final ConflictTxStream firstKey = new ConflictTxStream(UUID.randomUUID(), new byte[]{}, firstValue); final ConflictTxStream secondKey = new ConflictTxStream(UUID.randomUUID(), new byte[]{}, secondValue); for (int i = 0; i < iterations; i++) { cache.put(firstKey); cache.put(secondKey); assertThat(cache.size()).isOne(); assertThat(cache.get(firstKey)).isEqualTo(Address.NON_ADDRESS); } }
Source:
protected void deployPartialComponent(RuntimeContext ctx, Set<TargetExtensions> extensionPoints, StreamRef component) throws IOException { RegistrationInfo ri = ((DefaultRuntimeContext) ctx).createRegistrationInfo(component); String alias = ri.getName().getName(); String name = alias.concat("-partial"); Set<Pair<String, String>> targets = extensionPoints.stream() .map(TargetExtensions::getTargetExtensions) .flatMap(Set::stream) .collect(Collectors.toSet()); String ext = Arrays.stream(ri.getExtensions()) .filter(e -> targets.contains( Pair.of(e.getTargetComponent().getName(), e.getExtensionPoint()))) .map(Extension::toXML) .reduce((o, x) -> o + x) .orElse(""); InlineURLFactory.install(); ctx.deploy(new InlineRef(name, String.format("<component name=\"%s\"><alias>%s</alias>%s</component>", name, alias, ext))); }

Target:
protected void deployPartialComponent(RuntimeContext ctx, Set<TargetExtensions> extensionPoints, StreamRef component) throws IOException { RegistrationInfo ri = ((DefaultRuntimeContext) ctx).createRegistrationInfo(component); String name = ri.getName().getName() + "-partial"; Set<String> targets = extensionPoints.stream() .map(TargetExtensions::getTargetExtensions) .flatMap(Set::stream) .collect(Collectors.toSet()); String ext = Arrays.stream(ri.getExtensions()) .filter(e -> targets.contains(TargetExtensions.newTargetExtension( e.getTargetComponent().getName(), e.getExtensionPoint()))) .map(Extension::toXML) .collect(Collectors.joining()); InlineURLFactory.install(); ctx.deploy(new InlineRef(name, String.format("<component name=\"%s\">%s</component>", name, ext))); }
Source:
public void testEmptyStruct() { CompatibilityReport report = getCompatibilityReport(NestedEmptyStruct.class, NestedEmptyStruct.class); assertTrue(report.prettyMessages().contains("new struct is an empty struct: /required_empty/")); assertTrue(report.prettyMessages().contains("new struct is an empty struct: /optional_empty/")); assertTrue(report.hasEmptyStruct()); }

Target:
public void testEmptyStruct() { CompatibilityReport report = getCompatibilityReport(NestedEmptyStruct.class, NestedEmptyStruct.class); assertEquals("encountered an empty struct: required_empty\nencountered an empty struct: optional_empty",report.prettyMessages()); assertTrue(report.hasEmptyStruct()); }
Source:
public Mono<AccessToken> getToken(TokenRequestContext request) { AtomicReference<Throwable> cause = new AtomicReference<>(); List<CredentialUnavailableException> exceptions = new ArrayList<>(4); return Flux.fromIterable(credentials) .flatMap(p -> p.getToken(request).onErrorResume(CredentialUnavailableException.class, t -> { exceptions.add(t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { StringBuilder message = new StringBuilder("Tried " + credentials.stream().map(c -> c.getClass().getSimpleName()) .collect(Collectors.joining(", ")) + " but failed to acquire a token for any of them. Please verify the" + " environment for either of them" + " and see more details in the causes below."); CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException(current.getMessage(), last); } return Mono.error(new CredentialUnavailableException(message.toString(), last)); })); }

Target:
public Mono<AccessToken> getToken(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(4); return Flux.fromIterable(credentials) .flatMap(p -> p.getToken(request).onErrorResume(CredentialUnavailableException.class, t -> { exceptions.add(t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { StringBuilder message = new StringBuilder("Tried " + credentials.stream().map(c -> c.getClass().getSimpleName()) .collect(Collectors.joining(", ")) + " but failed to acquire a token for any of them. Please verify the" + " environment for the credentials" + " and see more details in the causes below."); CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException(current.getMessage(), last); } return Mono.error(new CredentialUnavailableException(message.toString(), last)); })); }
Source:
public void testBasicOperation() throws Exception { assertNotNull(fExperiment); assertNotNull(fTraces); SelectTracesOperation selectTracesOperation = new SelectTracesOperation(NonNullUtils.checkNotNull(fExperiment), fTraces, new HashMap<String, TmfTraceElement>()); PlatformUI.getWorkbench().getProgressService().run(true, true, selectTracesOperation); validateTracesExperiment(false); }

Target:
public void testBasicOperation() throws Exception { assertNotNull(fExperiment); assertNotNull(fTraces); SelectTracesOperation selectTracesOperation = new SelectTracesOperation(Objects.requireNonNull(fExperiment), fTraces, new HashMap<String, TmfTraceElement>()); PlatformUI.getWorkbench().getProgressService().run(true, true, selectTracesOperation); validateTracesExperiment(false); }
Source:
private List<PatchLineComment> byCommentStatus( ResultSet<PatchLineComment> comments, final PatchLineComment.Status status) throws OrmException { return Lists.newArrayList( Iterables.filter(comments, new Predicate<PatchLineComment>() { @Override public boolean apply(PatchLineComment input) { return (input.getStatus() == status); } }) ); }

Target:
private static List<PatchLineComment> byCommentStatus( ResultSet<PatchLineComment> comments, final PatchLineComment.Status status) { return Lists.newArrayList( Iterables.filter(comments, new Predicate<PatchLineComment>() { @Override public boolean apply(PatchLineComment input) { return (input.getStatus() == status); } }) ); }
Source:
public static String installJava6IfPossible() { return installPackageOr(MutableMap.of("apt", "openjdk-6-jdk","yum", "java-1.6.0-openjdk-devel"), null, chain("which zypper", sudo("zypper --non-interactive addrepo <LINK_1> java_sles_11"), sudo("zypper --non-interactive addrepo <LINK_2> java_suse_11"), sudo("zypper --non-interactive addrepo <LINK_0> java_suse_12"), alternatives(installPackageOrFail(MutableMap.of("zypper", "java-1_6_0-openjdk-devel"), null), installPackage(MutableMap.of("zypper", "java-1_6_0-ibm"), null)))); }

Target:
public static String installJava6IfPossible() { return ok(installJava6()); }
Source:
public static ResourceTable buildResourceTable(AndroidManifest appManifest) { List<ResourcePath> allLibraryResourcePaths = new LinkedList<>(); addTransitiveResourcePaths(appManifest.getLibraryManifests(), allLibraryResourcePaths); return buildResourceTable(appManifest.getPackageName(), appManifest.getResourcePath(), allLibraryResourcePaths); }

Target:
public static ResourceTable buildResourceTable(AndroidManifest appManifest) { List<ResourcePath> allResourcePaths = appManifest.getIncludedResourcePaths(); PackageResourceIndex resourceIndex = new PackageResourceIndex(appManifest.getPackageName()); ResourceTable resourceTable = new ResourceTable(resourceIndex); ResourceRemapper resourceRemapper = null; for (ResourcePath resourcePath : allResourcePaths) { if (resourceRemapper == null) { resourceRemapper = new ResourceRemapper(resourcePath.getRClass()); } else { resourceRemapper.remapRClass(resourcePath.getRClass()); } if (resourcePath.getRClass() != null) { ResourceExtractor.populate(resourceIndex, resourcePath.getRClass()); } } for (ResourcePath resourcePath : allResourcePaths) { ResourceParser.load(appManifest.getPackageName(), resourcePath, resourceTable); } return resourceTable; }
Source:
public void setUsePatternFly(final boolean usePatternFly) { setWrapperStyleName(""); setContentWidgetContainerStyleName(""); setContentWidgetContainerStyleName(""); setLabelStyleName(""); if (usePatternFly) { addContentWidgetStyleName(PatternflyConstants.FORM_CONTROL); addWrapperStyleName(PatternflyConstants.FORM_GROUP); } else { addContentWidgetContainerStyleName(style.contentWidget()); addWrapperStyleName(style.wrapper()); } addContentWidgetContainerStyleName("avw_contentWidget_pfly_fix"); addWrapperStyleName("avw_wrapper_pfly_fix"); addLabelStyleName(style.label()); addLabelStyleName(style.labelEnabled()); }

Target:
public void setUsePatternFly(final boolean usePatternFly) { removeLabelStyleName(style.label_legacy()); removeContentWidgetStyleName(style.contentWidget_legacy()); removeContentWidgetStyleName(Styles.FORM_CONTROL); removeContentWidgetContainerStyleName(style.contentWidgetContainer_legacy()); removeContentWidgetContainerStyleName("avw_contentWidgetContainer_pfly_fix"); removeWrapperStyleName(Styles.FORM_GROUP); removeWrapperStyleName(style.wrapper_legacy()); removeWrapperStyleName("avw_wrapper_pfly_fix"); if (usePatternFly) { addContentWidgetStyleName(Styles.FORM_CONTROL); addWrapperStyleName(Styles.FORM_GROUP); } else { addLabelStyleName(style.label_legacy()); addContentWidgetStyleName(style.contentWidget_legacy()); addContentWidgetContainerStyleName(style.contentWidgetContainer_legacy()); addContentWidgetContainerStyleName("avw_contentWidgetContainer_pfly_fix"); addWrapperStyleName(style.wrapper_legacy()); addWrapperStyleName("avw_wrapper_pfly_fix"); } }
Source:
public CatchupFuture catchup(long sequence) { try (LockResource stateLock = new LockResource(mStateLock)) { Preconditions.checkState(mSuspended, "Not suspended"); Preconditions.checkState(!mResumeInProgress, "Resume in progress"); Preconditions.checkState(mCatchupThread == null || !mCatchupThread.isAlive(), "Catch-up task in progress."); Preconditions.checkState(sequence >= 0, "Invalid sequence: %d", sequence); Preconditions.checkState(mLastAppliedSequence <= sequence, "Can't catchup to past. Current: %d, Requested: %d", mLastAppliedSequence, sequence); LOG.info("Catching up state machine to sequence: {}", sequence); if (mLastAppliedSequence == sequence) { return CatchupFuture.completed(); } mCatchupThread = new RaftJournalCatchupThread(sequence); mCatchupThread.start(); return new CatchupFuture(mCatchupThread); } }

Target:
public CatchupFuture catchup(long sequence) { try (LockResource stateLock = new LockResource(mStateLock)) { Preconditions.checkState(mSuspended, "Not suspended"); Preconditions.checkState(!mResumeInProgress, "Resume in progress"); Preconditions.checkState(mCatchupThread == null || !mCatchupThread.isAlive(), "Catch-up task in progress."); Preconditions.checkState(sequence >= 0, "Invalid negative sequence: %d", sequence); Preconditions.checkState(mLastAppliedSequence <= sequence, "Can't catchup to past. Current: %d, Requested: %d", mLastAppliedSequence, sequence); LOG.info("Catching up state machine to sequence: {}", sequence); if (mLastAppliedSequence == sequence) { return CatchupFuture.completed(); } mCatchupThread = new RaftJournalCatchupThread(sequence); mCatchupThread.start(); return new CatchupFuture(mCatchupThread); } }
Source:
private static Iterable<? extends ZipkinCompatBinaryAnnotation> spanMetadataToZipkinBinaryAnnotations( Span span, ZipkinCompatEndpoint endpoint) { return span.getMetadata().entrySet().stream() .map(entry -> ZipkinCompatBinaryAnnotation.of(entry.getKey(), entry.getValue(), endpoint)) .collect(Collectors.toList()); }

Target:
private static Iterable<? extends ZipkinCompatBinaryAnnotation> spanMetadataToZipkinBinaryAnnotations( Span span, ZipkinCompatEndpoint endpoint) { List<ZipkinCompatBinaryAnnotation> binaryAnnotations = Lists.newArrayList(); for (Map.Entry<String, String> entry : span.getMetadata().entrySet()) { binaryAnnotations.add(ZipkinCompatBinaryAnnotation.of(entry.getKey(), entry.getValue(), endpoint)); } return binaryAnnotations; }
Source:
private void triggerPipeline(Pipeline pipeline) { Observable<OrcaService.TriggerResponse> orcaResponse = createTriggerObservable(pipeline) .retryWhen(new RetryWithDelay(retryCount, retryDelayMillis)) .doOnNext(this::onOrcaResponse) .doOnError(throwable -> onOrcaError(pipeline, throwable)); if (pipeline.getTrigger() != null && pipeline.getTrigger().isPropagateAuth()) { orcaResponse.subscribe(); } else { User korkUser = new User(); if (fiatStatus.isEnabled() && pipeline.getTrigger() != null) { korkUser.setEmail(pipeline.getTrigger().getRunAsUser()); } try { AuthenticatedRequest.propagate(() -> orcaResponse.subscribe(), korkUser).call(); } catch (Exception e) { registry.counter("orca.error").increment(); log.error("Unable to trigger pipeline {}: {}", pipeline, e); } } }

Target:
private void triggerPipeline(Pipeline pipeline) { Observable<OrcaService.TriggerResponse> orcaResponse = createTriggerObservable(pipeline) .retryWhen(new RetryWithDelay(retryCount, retryDelayMillis)) .doOnNext(this::onOrcaResponse) .doOnError(throwable -> onOrcaError(pipeline, throwable)); if (pipeline.getTrigger() != null && pipeline.getTrigger().isPropagateAuth()) { orcaResponse.subscribe(); } else { User korkUser = new User(); if (fiatStatus.isEnabled() && pipeline.getTrigger() != null) { korkUser.setEmail(pipeline.getTrigger().getRunAsUser()); } try { AuthenticatedRequest.propagate(() -> orcaResponse.subscribe(), korkUser).call(); } catch (Exception e) { registry.counter("orca.error", "exception", e.getClass().getName()).increment(); log.error("Unable to trigger pipeline {}: {}", pipeline, e); } } }
Source:
public javax.ws.rs.core.Response toResponse(InvalidValueException e) { Fault fault = new Fault(); fault.setReason("Invalid Value"); fault.setDetail(e.getMessage()); return Response.status(Response.Status.BAD_REQUEST).entity(fault).build(); }

Target:
public Response toResponse(InvalidValueException e) { Fault fault = new Fault(); fault.setReason("Invalid Value"); fault.setDetail(e.getMessage()); return Response.status(Response.Status.BAD_REQUEST).entity(fault).build(); }
Source:
public void setup() { super.setup(); virtualGuestApi = api.getVirtualGuestApi(); datacenter = Iterables.get(api.getDatacenterApi().listDatacenters(), 0); if (datacenter == null) Assert.fail(); }

Target:
public void setup() { super.setup(); virtualGuestApi = api.getVirtualGuestApi(); datacenter = Iterables.get(api.getDatacenterApi().listDatacenters(), 0); assertNotNull(datacenter, "Datacenter must not be null"); }
Source:
public Multimap<String, String> getMultimap() { final ImmutableMultimap.Builder<String, String> builder = ImmutableMultimap.builder(); for (final String key : headers.keySet()) { builder.putAll(key, headers.get(key)); } return builder.build(); }

Target:
public Multimap<String, String> getMultimap() { final ImmutableMultimap.Builder<String, String> builder = ImmutableMultimap.builder(); builder.putAll(headers); return builder.build(); }
Source:
private String constructNicsWithNetworksString(Map<String, Set<String>> nicsWithNetworks) { StringBuilder nicsWithNetworksBuilder = new StringBuilder(); for (Entry<String, Set<String>> nicToNetworks : nicsWithNetworks.entrySet()) { nicsWithNetworksBuilder.append(nicToNetworks.getKey()); nicsWithNetworksBuilder.append(" ("); for (String network : nicToNetworks.getValue()) { nicsWithNetworksBuilder.append(network); nicsWithNetworksBuilder.append(", "); } nicsWithNetworksBuilder.delete(nicsWithNetworksBuilder.length() - 2, nicsWithNetworksBuilder.length()); nicsWithNetworksBuilder.append("), "); } String nicsWithNetworksString = nicsWithNetworksBuilder.toString(); return nicsWithNetworksBuilder.delete(nicsWithNetworksString.length() - 2, nicsWithNetworksString.length()) .toString(); }

Target:
private String constructNicsWithNetworksString(Map<String, Set<String>> nicsWithNetworks) { List<String> reportedNics = new ArrayList<>(nicsWithNetworks.size()); for (Entry<String, Set<String>> nicToNetworks : nicsWithNetworks.entrySet()) { reportedNics.add(String.format("%s (%s)", nicToNetworks.getKey(), StringUtils.join(nicToNetworks.getValue(), ", "))); } return StringUtils.join(reportedNics, ", "); }
Source:
public String toString() { StringBuilder builder = new StringBuilder(); for (LogReplicationMetadataType type : LogReplicationMetadataType.values()) { builder.append(type).append(": "); switch (type) { case TOPOLOGY_CONFIG_ID: builder.append(getTopologyConfigId()); break; case LAST_SNAPSHOT_STARTED: builder.append(getLastSnapStartTimestamp()); break; case LAST_SNAPSHOT_TRANSFERRED: builder.append(getLastSnapTransferDoneTimestamp()); break; case LAST_SNAPSHOT_APPLIED: builder.append(getLastAppliedBaseSnapshotTimestamp()); break; case LAST_SNAPSHOT_SEQ_NUM: builder.append(getLastSnapSeqNum()); break; case LAST_LOG_ENTRY_PROCESSED: builder.append(getLastProcessedLogTimestamp()); break; case REMAINING_REPLICATION_PERCENT: builder.append(getReplicationRemainingPercent()); default: } builder.append(" "); } return builder.toString(); }

Target:
public String toString() { StringBuilder builder = new StringBuilder(); for (LogReplicationMetadataType type : LogReplicationMetadataType.values()) { builder.append(type).append(": "); switch (type) { case TOPOLOGY_CONFIG_ID: builder.append(getTopologyConfigId()); break; case LAST_SNAPSHOT_STARTED: builder.append(getLastSnapStartTimestamp()); break; case LAST_SNAPSHOT_TRANSFERRED: builder.append(getLastSnapTransferDoneTimestamp()); break; case LAST_SNAPSHOT_APPLIED: builder.append(getLastAppliedBaseSnapshotTimestamp()); break; case LAST_SNAPSHOT_SEQ_NUM: builder.append(getLastSnapSeqNum()); break; case LAST_LOG_ENTRY_PROCESSED: builder.append(getLastProcessedLogTimestamp()); break; default: } builder.append(" "); } builder.append("Replication Completion: "); Map<String, ReplicationStatusVal> replicationStatusMap = getReplicationRemainingPercent(); replicationStatusMap.entrySet().forEach( entry -> builder.append(entry.getKey()) .append(entry.getValue().getReplicationCompletion())); builder.append("Data Consistent: ").append(getDataConsistentOnStandby()); return builder.toString(); }
Source:
protected RowExpression visitSearchedCaseExpression(SearchedCaseExpression node, Void context) { END to: RowExpression lhsArg = null; for (WhenClause whenClause : node.getWhenClauses()) { Expression predicate = whenClause.getOperand(); if (ExpressionTreeUtils.isEqualComparisonExpression(predicate) || ExpressionTreeUtils.isInValuesComparisonExpression(predicate)) { RowExpression operand = process(predicate.getChildren().get(0), context); if (lhsArg != null && !operand.equals(lhsArg)) { lhsArg = null; break; } lhsArg = operand; } else { lhsArg = null; break; } } if (lhsArg != null) { ImmutableList.Builder<WhenClause> newWhenClauses = ImmutableList.builder(); for (WhenClause whenClause : node.getWhenClauses()) { if (ExpressionTreeUtils.isInValuesComparisonExpression(whenClause.getOperand())) { for (Expression value : ((InListExpression) ((InPredicate) whenClause.getOperand()).getValueList()).getValues()) { newWhenClauses.add(new WhenClause(value, whenClause.getResult())); } } else { newWhenClauses.add( new WhenClause( (Expression) whenClause.getOperand().getChildren().get(1), whenClause.getResult())); } } return buildSwitch(lhsArg, newWhenClauses.build(), node.getDefaultValue(), getType(node), context); } END return buildSwitch(new ConstantExpression(true, BOOLEAN), node.getWhenClauses(), node.getDefaultValue(), getType(node), context); }

Target:
protected RowExpression visitSearchedCaseExpression(SearchedCaseExpression node, Void context) { END to: RowExpression caseOperand = null; for (WhenClause whenClause : node.getWhenClauses()) { Expression predicate = whenClause.getOperand(); if (isEqualComparisonExpression(predicate) || isInValuesComparisonExpression(predicate)) { RowExpression operand = process(predicate.getChildren().get(0), context); if (caseOperand != null && !operand.equals(caseOperand)) { caseOperand = null; break; } caseOperand = operand; } else { caseOperand = null; break; } } if (caseOperand != null) { ImmutableList.Builder<WhenClause> newWhenClauses = ImmutableList.builder(); for (WhenClause whenClause : node.getWhenClauses()) { if (isInValuesComparisonExpression(whenClause.getOperand())) { for (Expression value : ((InListExpression) ((InPredicate) whenClause.getOperand()).getValueList()).getValues()) { newWhenClauses.add(new WhenClause(value, whenClause.getResult())); } } else { newWhenClauses.add( new WhenClause( (Expression) whenClause.getOperand().getChildren().get(1), whenClause.getResult())); } } return buildSwitch(caseOperand, newWhenClauses.build(), node.getDefaultValue(), getType(node), context); } END return buildSwitch(new ConstantExpression(true, BOOLEAN), node.getWhenClauses(), node.getDefaultValue(), getType(node), context); }
Source:
protected <T> T doFindOne(String collectionName, DBObject query, DBObject fields, Class<T> entityClass) { EntityReader<? super T, DBObject> readerToUse = this.mongoConverter; MongoPersistentEntity<?> entity = mappingContext.getPersistentEntity(entityClass); DBObject mappedQuery = queryMapper.getMappedObject(query, entity); DBObject mappedFields = entity == null ? fields : fields == null ? null : queryMapper.getMappedObject(fields, entity); return executeFindOneInternal(new FindOneCallback(mappedQuery, mappedFields), new ReadDbObjectCallback<T>( readerToUse, entityClass), collectionName); }

Target:
protected <T> T doFindOne(String collectionName, DBObject query, DBObject fields, Class<T> entityClass) { EntityReader<? super T, DBObject> readerToUse = this.mongoConverter; MongoPersistentEntity<?> entity = mappingContext.getPersistentEntity(entityClass); DBObject mappedQuery = queryMapper.getMappedObject(query, entity); DBObject mappedFields = fields == null ? null : queryMapper.getMappedObject(fields, entity); return executeFindOneInternal(new FindOneCallback(mappedQuery, mappedFields), new ReadDbObjectCallback<T>( readerToUse, entityClass), collectionName); }
Source:
private void endProcessTracingSpan(Context processSpanContext, Signal<Void> signal) { if (!processSpanContext.getData("scope").isPresent() || tracerProvider == null) { return; } Closeable close = (Closeable) processSpanContext.getData("scope").get(); try { close.close(); } catch (IOException ioException) { logger.error("EventProcessor.run() endTracingSpan().close() failed with an error %s", ioException); } tracerProvider.endSpan(processSpanContext, signal); }

Target:
private void endProcessTracingSpan(Context processSpanContext, Signal<Void> signal) { Optional<Object> spanScope = processSpanContext.getData("scope"); if (!spanScope.isPresent() || !tracerProvider.isEnabled()) { return; } if (spanScope.get() instanceof Closeable) { Closeable close = (Closeable) processSpanContext.getData("scope").get(); try { close.close(); tracerProvider.endSpan(processSpanContext, signal); } catch (IOException ioException) { logger.error("EventProcessor.run() endTracingSpan().close() failed with an error %s", ioException); } } else { logger.warning(String.format(Locale.US, "Process span scope type is not of type Closeable, but type: %s. Not closing the scope and span", spanScope.get() != null ? spanScope.getClass() : "null")); } }
Source:
public String translate(final WebApplicationService targetService, final String triggerValue) { for (final Pattern pattern : translationMap.keySet()) { if (pattern.matcher(triggerValue).matches()) { return this.translationMap.get(pattern); } } if (this.ignoreIfNoMatchIsFound) { return defaultMfaMethod; } throw new UnrecognizedAuthenticationMethodException("MFA Method for " + triggerValue, targetService.getId()); }

Target:
public String translate(final WebApplicationService targetService, final String triggerValue) { for (final Pattern pattern : translationMap.keySet()) { if (pattern.matcher(triggerValue).matches()) { return this.translationMap.get(pattern); } } if (this.defaultMfaMethod != null) { return defaultMfaMethod; } throw new UnrecognizedAuthenticationMethodException(triggerValue, targetService.getId()); }
Source:
private Map<String, Object> getAttributes() { Map<String, Object> attributeValues = new HashMap<String, Object>(); for (String attribute : this.attributes) { int equalsIndex = -1; if((equalsIndex = attribute.indexOf(ATTRIBUTE_SEPARATOR)) > -1) { extractAttributeNameAndValue(attributeValues, attribute, equalsIndex); } else { attributeValues.put(attribute, ""); } } return attributeValues; }

Target:
private Map<String, Object> getAttributes() { Map<String, Object> attributeValues = new HashMap<String, Object>(); for (String attribute : attributes) { int equalsIndex = attribute.indexOf(ATTRIBUTE_SEPARATOR); if(equalsIndex > -1) { String attributeName = attribute.substring(0, equalsIndex); String attributeValue = attribute.substring(equalsIndex+1, attribute.length()); attributeValues.put(attributeName, attributeValue); } else { attributeValues.put(attribute, ""); } } return attributeValues; }
Source:
public GoalResource toResource(GoalDTO goal) { GoalResource goalResource = instantiateResource(goal); ControllerLinkBuilder selfLinkBuilder = getGoalLinkBuilder(userID, goal); addSelfLink(selfLinkBuilder, goalResource); addRemoveLink(selfLinkBuilder, goalResource); return goalResource; }

Target:
public GoalResource toResource(GoalDTO goal) { GoalResource goalResource = instantiateResource(goal); ControllerLinkBuilder selfLinkBuilder = getGoalLinkBuilder(userID, goal); addSelfLink(selfLinkBuilder, goalResource); addEditLink(selfLinkBuilder, goalResource); return goalResource; }
Source:
public static TopologyAPI.Config.Builder getConfigBuilder(Config config) { TopologyAPI.Config.Builder cBldr = TopologyAPI.Config.newBuilder(); Set<String> apiVars = config.getApiVars(); for (String key : config.keySet()) { Object value = config.get(key); if (key == null) { LOG.warning("ignore: null config key found"); continue; } if (value == null) { LOG.warning("ignore: config key " + key + " has null value"); continue; } TopologyAPI.Config.KeyValue.Builder b = TopologyAPI.Config.KeyValue.newBuilder(); b.setKey(key); if (apiVars.contains(key)) { b.setType(TopologyAPI.ConfigValueType.STRING_VALUE); b.setValue(value.toString()); } else { b.setType(TopologyAPI.ConfigValueType.JAVA_SERIALIZED_VALUE); b.setSerializedValue(ByteString.copyFrom(serialize(value))); } cBldr.addKvs(b); } return cBldr; }

Target:
public static TopologyAPI.Config.Builder getConfigBuilder(Config config) { TopologyAPI.Config.Builder cBldr = TopologyAPI.Config.newBuilder(); Set<String> apiVars = config.getApiVars(); for (String key : config.keySet()) { if (key == null) { LOG.warning("ignore: null config key found"); continue; } Object value = config.get(key); if (value == null) { LOG.warning("ignore: config key " + key + " has null value"); continue; } TopologyAPI.Config.KeyValue.Builder b = TopologyAPI.Config.KeyValue.newBuilder(); b.setKey(key); if (apiVars.contains(key)) { b.setType(TopologyAPI.ConfigValueType.STRING_VALUE); b.setValue(value.toString()); } else { b.setType(TopologyAPI.ConfigValueType.JAVA_SERIALIZED_VALUE); b.setSerializedValue(ByteString.copyFrom(serialize(value))); } cBldr.addKvs(b); } return cBldr; }
Source:
public LgoProductCurrency( @JsonProperty("id") String id, @JsonProperty("increment") BigDecimal increment, @JsonProperty("limits") LgoLimit limits) { this.id = id; this.increment = increment != null ? increment.stripTrailingZeros() : null; this.limits = limits; }

Target:
public LgoProductCurrency( @JsonProperty("id") String id, @JsonProperty("increment") BigDecimal increment, @JsonProperty("limits") LgoLimit limits) { this.id = id; this.increment = increment; this.limits = limits; }
Source:
public boolean isEmpty() { return blockBuilder == null || blockBuilder.getPositionCount() == 0; }

Target:
public boolean isEmpty() { if (blockBuilder == null) { return true; } verify(blockBuilder.getPositionCount() != 0); return false; }
Source:
protected void verifyAssumptionFailure(String... parameters) throws Exception { try { Action c = gaeSimulation.getActionObject(uri, parameters); c.executeAndPostProcess(); signalFailureToDetectException(); } catch (Throwable e) { assertTrue(e instanceof AssertionError); ignoreExpectedException(); } }

Target:
protected void verifyAssumptionFailure(String... parameters) throws Exception { try { Action c = gaeSimulation.getActionObject(uri, parameters); c.executeAndPostProcess(); signalFailureToDetectException(); } catch (AssertionError e) { ignoreExpectedException(); } }
Source:
public static IndexDocumentBuilder getIndexBuilder(File file, IndexWriter writer, TaggedValuePointable nodep, ArrayBackedValueStorage abvsFileNode, ITreeNodeIdProvider nodeIdProvider, ByteBufferInputStream bbis, DataInputStream di, String nodeId) throws IOException { XMLParser parser = new XMLParser(false, nodeIdProvider, nodeId); FunctionHelper.readInDocFromString(file.getPath(), bbis, di, abvsFileNode, parser); nodep.set(abvsFileNode.getByteArray(), abvsFileNode.getStartOffset(), abvsFileNode.getLength()); return new IndexDocumentBuilder(nodep, writer, file.getCanonicalPath()); }

Target:
public static IndexDocumentBuilder getIndexBuilder(File file, IndexWriter writer, TaggedValuePointable nodep, ArrayBackedValueStorage abvsFileNode, ITreeNodeIdProvider nodeIdProvider, ByteBufferInputStream bbis, DataInputStream di, String nodeId) throws IOException { IParser parser = new XMLParser(false, nodeIdProvider, nodeId); FunctionHelper.readInDocFromString(file.getPath(), bbis, di, abvsFileNode, parser); nodep.set(abvsFileNode.getByteArray(), abvsFileNode.getStartOffset(), abvsFileNode.getLength()); return new IndexDocumentBuilder(nodep, writer, file.getCanonicalPath()); }
Source:
public Item build() { Item item = null; if (GroupItem.TYPE.equals(itemType)) { item = new GroupItem(name, baseItem, groupFunction); } else { for (ItemFactory itemFactory : itemFactories) { item = itemFactory.createItem(itemType, name); } } if (item == null) { throw new IllegalStateException("No item factory could handle type " + itemType); } if (item instanceof ActiveItem) { ActiveItem activeItem = (ActiveItem) item; activeItem.setLabel(label); activeItem.setCategory(category); activeItem.addGroupNames(groups); activeItem.addTags(tags); } return item; }

Target:
public Item build() { Item item = null; if (GroupItem.TYPE.equals(itemType)) { item = new GroupItem(name, baseItem, groupFunction); } else { for (ItemFactory itemFactory : itemFactories) { item = itemFactory.createItem(itemType, name); if (item != null) { break; } } } if (item == null) { throw new IllegalStateException("No item factory could handle type " + itemType); } if (item instanceof ActiveItem) { ActiveItem activeItem = (ActiveItem) item; activeItem.setLabel(label); activeItem.setCategory(category); activeItem.addGroupNames(groups); } return item; }
Source:
public void testProcessTimeout() throws Exception { WaitingStage ws = new WaitingStage(); ws.setName("stagename"); RemotePipeline rp = mock(RemotePipeline.class); ws.setRemotePipeline(rp); HashMap<String, Object> map = new HashMap<String, Object>(); map.put("timeout", 1000); ws.setParameters(map); LocalDocument ld = mock(LocalDocument.class); when(rp.getDocument(any(LocalQuery.class))).thenReturn(ld); when(rp.releaseLastDocument()).thenReturn(true); ws.start(); Thread.sleep(1100); verify(ld, times(1)).addError(eq(ws.getStageName()), any(Throwable.class)); }

Target:
public void testProcessTimeout() throws Exception { WaitingStage ws = new WaitingStage(); ws.setName("stagename"); RemotePipeline rp = mock(RemotePipeline.class); ws.setRemotePipeline(rp); HashMap<String, Object> map = new HashMap<String, Object>(); map.put("timeout", 1000); ws.setParameters(map); LocalDocument ld = mock(LocalDocument.class); when(rp.getDocument(any(LocalQuery.class))).thenReturn(ld, (LocalDocument[]) null); when(rp.releaseLastDocument()).thenReturn(true); TimeProvider timeProvider = Mockito.mock(TimeProvider.class); when(timeProvider.getCurrentTime()).thenReturn(new Long(0), new Long(1001)); ws.setTimeProvider(timeProvider); ws.start(); verify(ld, times(1)).addError(eq(ws.getStageName()), any(Throwable.class)); }