auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected List<KubernetesNamespaceMeta> fetchNamespaces() throws KubernetesClientException, InfrastructureException { try { return clientFactory .create() .namespaces() .list() .getItems() .stream() .map(this::asNamespaceMeta) .collect(Collectors.toList()); } catch (KubernetesClientException e) { throw new InfrastructureException( "Error occurred when tried to list all available namespaces. Cause: " + e.getMessage(), e); } }

Target:
protected List<KubernetesNamespaceMeta> fetchNamespaces() throws InfrastructureException { try { return clientFactory .create() .namespaces() .list() .getItems() .stream() .map(this::asNamespaceMeta) .collect(Collectors.toList()); } catch (KubernetesClientException e) { throw new InfrastructureException( "Error occurred when tried to list all available namespaces. Cause: " + e.getMessage(), e); } }
Source:
public ValidationResult isStorageFormatCompatibleWithDomain() { StorageFormatType storageFormat = storageDomain.getStorageFormat(); StorageType storageType = storageDomain.getStorageType(); StorageDomainType storageDomainFunction = storageDomain.getStorageDomainType(); boolean validationSucceeded = true; if (storageFormat == StorageFormatType.V2) { if ( !(storageDomainFunction.isDataDomain() && storageType.isBlockDomain()) ) { validationSucceeded = false; } } if (storageFormat == StorageFormatType.V3 || storageFormat == StorageFormatType.V4) { if (!storageDomainFunction.isDataDomain()) { validationSucceeded = false; } } return validationSucceeded? ValidationResult.VALID : new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_STORAGE_DOMAIN_FORMAT_ILLEGAL_HOST, String.format("$storageFormat %1$s", storageDomain.getStorageFormat())); }

Target:
public ValidationResult isStorageFormatCompatibleWithDomain() { StorageFormatType storageFormat = storageDomain.getStorageFormat(); StorageType storageType = storageDomain.getStorageType(); StorageDomainType storageDomainFunction = storageDomain.getStorageDomainType(); boolean validationSucceeded = true; if (storageFormat == StorageFormatType.V2) { if ( !(storageDomainFunction.isDataDomain() && storageType.isBlockDomain()) ) { validationSucceeded = false; } } if (storageFormat.compareTo(StorageFormatType.V3) > 0) { if (!storageDomainFunction.isDataDomain()) { validationSucceeded = false; } } return validationSucceeded? ValidationResult.VALID : new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_STORAGE_DOMAIN_FORMAT_ILLEGAL_HOST, String.format("$storageFormat %1$s", storageDomain.getStorageFormat())); }
Source:
public static synchronized void cancelAll(String id) { Set<Entry<Runnable, TaskInfo>> entrySet = TASKS.entrySet(); synchronized (TASKS) { Iterator<Entry<Runnable, TaskInfo>> iterator = entrySet.iterator(); while (iterator.hasNext()) { Entry<Runnable, TaskInfo> next = iterator.next(); Runnable task = next.getKey(); TaskInfo info = next.getValue(); if (info.id.equals(id)) { Handler handler = info.handlerReference.get(); if (handler != null) { handler.removeCallbacks(task); } } } } }

Target:
public static synchronized void cancelAll(String id) { Set<Entry<Runnable, TaskInfo>> entrySet = TASKS.entrySet(); Iterator<Entry<Runnable, TaskInfo>> iterator = entrySet.iterator(); while (iterator.hasNext()) { Entry<Runnable, TaskInfo> next = iterator.next(); Runnable task = next.getKey(); TaskInfo info = next.getValue(); if (info.id.equals(id)) { info.handler.removeCallbacks(task); } } }
Source:
public void testNonBlockingAcquireBuffer() { SslBufferPool pool = new ThreadLocalSslBufferPool(1, true, true, 1); ByteBuffer buf1 = pool.acquireBuffer(); Assert.assertEquals(pool.getUnacquiredPoolSize(), 0); ByteBuffer buf2 = pool.acquireBuffer(); pool.releaseBuffer(buf1); pool.releaseBuffer(buf2); }

Target:
public void testNonBlockingAcquireBuffer() { SslBufferPool pool = new ThreadLocalSslBufferPool(1, true, true, 1); ByteBuffer buf1 = null; ByteBuffer buf2 = null; try { buf1 = pool.acquireBuffer(); Assert.assertEquals(pool.getUnacquiredPoolSize(), 0); buf2 = pool.acquireBuffer(); } finally { pool.releaseBuffer(buf1); pool.releaseBuffer(buf2); } }
Source:
public void initialize(TransformContext context) throws Exception { super.initialize(context); metrics = context.getMetrics(); logger = LoggerFactory.getLogger(ScriptTransform.class.getName() + " - Stage:" + context.getStageName()); try { Class<?> somClass = Class.forName("jdk.nashorn.api.scripting.ScriptObjectMirror"); somValuesMethod = somClass.getMethod("values"); } catch (NoSuchMethodException e) { throw new RuntimeException( "Failed to get method ScriptObjectMirror#values() for converting ScriptObjectMirror to List. " + "Please check your version of Nashorn is supported.", e); } catch (ClassNotFoundException e) { } init(context); }

Target:
public void initialize(TransformContext context) throws Exception { super.initialize(context); metrics = context.getMetrics(); try { Class<?> somClass = Class.forName("jdk.nashorn.api.scripting.ScriptObjectMirror"); somValuesMethod = somClass.getMethod("values"); } catch (NoSuchMethodException e) { throw new RuntimeException( "Failed to get method ScriptObjectMirror#values() for converting ScriptObjectMirror to List. " + "Please check your version of Nashorn is supported.", e); } catch (ClassNotFoundException e) { } init(context); }
Source:
public T LIMIT(int value) { sql().limit = String.valueOf(value); sql().limitingRowsStrategy = SQLStatement.LimitingRowsStrategy.OFFSET_LIMIT; return getSelf(); }

Target:
public T LIMIT(int value) { return LIMIT(String.valueOf(value)); }
Source:
public void testServerShouldTerminateConnectionIdleForTooLong() throws InterruptedException { int inactivityTime = 3; Server server = new Server(randomPort); server.setClientInactivityTimeout(inactivityTime); Runnable serverTask = () -> { try { server.listen(); } catch (InterruptedException e) { e.printStackTrace(); } }; Thread thread = new Thread(serverTask); thread.start(); EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { } } ); Long started = System.currentTimeMillis() / 1000L; ChannelFuture f = b.connect("localhost", randomPort).sync(); f.channel().closeFuture().sync(); Long ended = System.currentTimeMillis() / 1000L; int diff = (int) (ended - started); assertThat(diff, is(greaterThanOrEqualTo(inactivityTime))); } finally { group.shutdownGracefully(); server.stop(); } }

Target:
public void testServerShouldTerminateConnectionIdleForTooLong() throws InterruptedException { int inactivityTime = 3; Server server = new Server(randomPort, inactivityTime); Runnable serverTask = () -> { try { server.listen(); } catch (InterruptedException e) { e.printStackTrace(); } }; Thread thread = new Thread(serverTask); thread.start(); EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { } } ); Long started = System.currentTimeMillis() / 1000L; ChannelFuture f = b.connect("localhost", randomPort).sync(); f.channel().closeFuture().sync(); Long ended = System.currentTimeMillis() / 1000L; double diff = ended - started; assertThat(diff, is(closeTo(inactivityTime, 0.1))); } finally { group.shutdownGracefully(); server.stop(); } }
Source:
public double getBatteryResistanceSafely() throws InvalidSensorException { readStatus3(); if (System.currentTimeMillis() - lastRead > PDP.MAX_AGE) { throw new InvalidSensorException("Can not read voltage from PDP"); } return cachedResistance; }

Target:
public double getBatteryResistanceSafely() throws InvalidSensorException { readStatus(3); if (System.currentTimeMillis() - lastRead > PDP.MAX_AGE) { throw new InvalidSensorException("Can not read battery resistance from PDP"); } return cachedResistance; }
Source:
public XMLTagScanner() { IToken string = new Token(new TextAttribute(Preferences.getInstance() .getColor(PreferenceKey.COLOR_STRING))); IToken interpolation = new Token(new TextAttribute(Preferences .getInstance().getColor(PreferenceKey.COLOR_INTERPOLATION))); List<IRule> l = new ArrayList<IRule>(); l.add(new StringSubRule(LexicalConstants.QUOT_STRING, DOLLAR_LEFT_BRACE, 2, string)); l.add(new InterpolationRule(LexicalConstants.DOLLAR, interpolation)); l.add(new InterpolationRule(LexicalConstants.HASH, interpolation)); l.add(new SingleLineRule(LexicalConstants.QUOT_STRING, LexicalConstants.QUOT_STRING, string, LexicalConstants.BACKSLASH)); l.add(new SingleLineRule(LexicalConstants.APOS_STRING, LexicalConstants.APOS_STRING, string, LexicalConstants.BACKSLASH)); l.add(new WhitespaceRule(new WhitespaceDetector())); setRules(l.toArray(new IRule[l.size()])); }

Target:
public XMLTagScanner() { IToken string = new Token(new TextAttribute(Preferences.getInstance() .getColor(PreferenceKey.COLOR_STRING))); IToken interpolation = new Token(new TextAttribute(Preferences .getInstance().getColor(PreferenceKey.COLOR_INTERPOLATION))); setRules(new IRule[] { new StringSubRule(LexicalConstants.QUOT_STRING, DOLLAR_LEFT_BRACE, 2, string), new InterpolationRule(LexicalConstants.DOLLAR, interpolation), new InterpolationRule(LexicalConstants.HASH, interpolation), new SingleLineRule(LexicalConstants.QUOT_STRING, LexicalConstants.QUOT_STRING, string, LexicalConstants.BACKSLASH), new SingleLineRule(LexicalConstants.APOS_STRING, LexicalConstants.APOS_STRING, string, LexicalConstants.BACKSLASH), new WhitespaceRule(new WhitespaceDetector()) }); }
Source:
public void removeNode(Node node) { InetAddress host = null; String nodeName = node.getNodeInformation().getName(); if ((host = registeredNodes.remove(nodeName)) != null) { removedNodes.putIfAbsent(host, new AtomicInteger(0)); removedNodes.get(host).incrementAndGet(); if (!registeredNodes.containsValue(host)) { freeHosts.put(host, removedNodes.remove(host).intValue()); try { this.killNodeImpl(node, host); } catch (Exception e) { logger.trace("An exception occurred during node removal", e); } } logger.debug("Node " + nodeName + " removed. #freeHosts:" + freeHosts.size() + " #registered nodes: " + registeredNodes.size()); } else { logger.error("Node " + nodeName + " is not known as a node belonging to this infrastructure manager"); } }

Target:
public void removeNode(Node node) { InetAddress host = null; String nodeName = node.getNodeInformation().getName(); if ((host = registeredNodes.remove(nodeName)) != null) { logger.debug("Removing node " + node.getNodeInformation().getURL() + " from " + this.getClass().getSimpleName()); removedNodes.putIfAbsent(host, new AtomicInteger(0)); removedNodes.get(host).incrementAndGet(); if (!registeredNodes.containsValue(host)) { try { this.killNodeImpl(node, host); } catch (Exception e) { logger.trace("An exception occurred during node removal", e); } freeHosts.putIfAbsent(host, removedNodes.remove(host).intValue()); } logger.info("Node " + nodeName + " removed. #freeHosts:" + freeHosts.size() + " #registered nodes: " + registeredNodes.size()); } else { logger.error("Node " + nodeName + " is not known as a node belonging to this infrastructure manager"); } }
Source:
protected void executeCancellation() { if (!session.isHost() || session.getRemoteUsers().isEmpty()) sessionManager.stopSession(SessionEndReason.LOCAL_USER_LEFT); }

Target:
protected void executeCancellation() { if (session.isHost() && session.getRemoteUsers().isEmpty()) sessionManager.stopSession(SessionEndReason.LOCAL_USER_LEFT); }
Source:
public AdvancedFilterEditor(DataSetClientServices dataSetClientServices) { initWidget(uiBinder.createAndBindUi(this)); this.dataSetClientServices = dataSetClientServices; okButton.setType(ButtonType.PRIMARY); okButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { ok(); } }); }

Target:
public AdvancedFilterEditor(DataSetClientServices dataSetClientServices) { initWidget(uiBinder.createAndBindUi(this)); this.dataSetClientServices = dataSetClientServices; okButton.setType(ButtonType.PRIMARY); okButton.addClickHandler(event -> ok()); }
Source:
protected void drawStepContent() { super.drawStepContent(); setNextButtonEnabled(false); textField = new TextField(); textField.textProperty().addListener((observable, oldValue, newValue) -> { if ("".equals(newValue.trim())) { setNextButtonEnabled(false); } else { setNextButtonEnabled(true); } }); textField.setText(defaultValue); textField.setLayoutX(10); textField.setLayoutY(40); this.addToContentPane(textField); }

Target:
protected void drawStepContent() { super.drawStepContent(); setNextButtonEnabled(false); textField = new TextField(); textField.textProperty().addListener((observable, oldValue, newValue) -> { if (StringUtils.isBlank(newValue)) { setNextButtonEnabled(false); } else { setNextButtonEnabled(true); } }); textField.setText(defaultValue); textField.setLayoutX(10); textField.setLayoutY(40); this.addToContentPane(textField); }
Source:
private RelationalSymbolicValue create(Tree.Kind kind, SymbolicValue leftOperand, SymbolicValue rightOperand) { return (RelationalSymbolicValue) RelationalSymbolicValue.create(kind, leftOperand, rightOperand); }

Target:
private EqualitySymbolicValue create(Tree.Kind kind, SymbolicValue leftOperand, SymbolicValue rightOperand) { return (EqualitySymbolicValue) RelationalSymbolicValue.create(kind, leftOperand, rightOperand); }
Source:
public static CassandraKeyValueService create( MetricsManager metricsManager, CassandraKeyValueServiceConfig config, CassandraMutationTimestampProvider mutationTimestampProvider, CassandraClientPool clientPool) { return createOrShutdownClientPool(metricsManager, config, CassandraKeyValueServiceRuntimeConfig::getDefault, clientPool, null, mutationTimestampProvider, LoggerFactory.getLogger(CassandraKeyValueService.class), AtlasDbConstants.DEFAULT_INITIALIZE_ASYNC); }

Target:
public static CassandraKeyValueService create( MetricsManager metricsManager, CassandraKeyValueServiceConfig config, CassandraMutationTimestampProvider mutationTimestampProvider, CassandraClientPool clientPool) { return createOrShutdownClientPool(metricsManager, config, CassandraKeyValueServiceRuntimeConfig::getDefault, clientPool, Optional.empty(), mutationTimestampProvider, LoggerFactory.getLogger(CassandraKeyValueService.class), AtlasDbConstants.DEFAULT_INITIALIZE_ASYNC); }
Source:
public State getStateAs(Class<? extends State> typeClass) { State newState = null; if (function != null) { newState = function.getStateAs(getMembers(), typeClass); } if (newState == null && baseItem != null) { baseItem.setState(state); newState = baseItem.getStateAs(typeClass); } if (newState == null) { newState = super.getStateAs(typeClass); } return newState; }

Target:
public @Nullable State getStateAs(Class<? extends State> typeClass) { State newState = null; if (function != null) { newState = function.getStateAs(getStateMembers(getMembers()), typeClass); } if (newState == null && baseItem != null) { baseItem.setState(state); newState = baseItem.getStateAs(typeClass); } if (newState == null) { newState = super.getStateAs(typeClass); } return newState; }
Source:
public static Map<String, String> toMap(Properties properties) { Map<String, String> res = new HashMap<String, String>(); for (Property property : properties.getProperty()) { res.put(property.getName(), property.getValue()); } return res; }

Target:
public static Map<String, String> toMap(Properties properties) { Map<String, String> res = new HashMap<>(); for (Property property : properties.getProperties()) { res.put(property.getName(), property.getValue()); } return res; }
Source:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (!MediaType.TEXT_EVENT_STREAM_VALUE.equalsIgnoreCase(request.getHeader("Accept"))) { response.sendError(HttpStatus.NOT_ACCEPTABLE.value()); } else { response.setStatus(HttpStatus.OK.value()); response.setContentType(MediaType.TEXT_EVENT_STREAM_VALUE); response.setCharacterEncoding("UTF-8"); response.setHeader("Cache-control", "no-cache, no-store"); response.setHeader("Pragma", "no-cache"); response.setHeader("Expires", "-1"); response.setHeader("Allow", "GET, OPTIONS"); response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Headers", "*"); response.setHeader("Access-Control-Max-Age", "600"); response.flushBuffer(); final AsyncContext asyncContext = request.startAsync(); final Observable<String> observable = BootProgressBeanPostProcessor.getObservable() .observeOn(Schedulers.single()) .subscribeOn(Schedulers.io()) .filter(this::filterBeansByName) .map(this::getBeanDisplayName); final Disposable disposable = observable.subscribe(msg -> streamContent(msg, asyncContext.getResponse()), (e) -> { }, () -> complete(asyncContext)); asyncContext.addListener(new DisposeObservableAsyncListener(disposable)); } }

Target:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { if (!MediaType.TEXT_EVENT_STREAM_VALUE.equalsIgnoreCase(request.getHeader("Accept"))) { response.sendError(HttpStatus.NOT_ACCEPTABLE.value()); return; } response.setStatus(HttpStatus.OK.value()); response.setContentType(MediaType.TEXT_EVENT_STREAM_VALUE); response.setCharacterEncoding("UTF-8"); response.setHeader("Connection", "keep-alive"); response.setHeader("Cache-control", "no-cache, no-store, max-age=0, must-revalidate"); response.setHeader("Pragma", "no-cache"); response.setHeader("Expires", "0"); response.setHeader("Allow", "GET, OPTIONS"); response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Headers", "*"); response.setHeader("Access-Control-Max-Age", "600"); final AsyncContext asyncContext = request.startAsync(request, response); final Disposable disposable = BootProgressBeanPostProcessor.getProgressObservable() .doOnComplete(() -> { write("booted", "", asyncContext); asyncContext.getResponse().getWriter().flush(); asyncContext.complete(); }) .doOnError((e) -> { logger.error("An error occurred!", e); asyncContext.complete(); }) .subscribe(data -> write("booting", data, asyncContext)); asyncContext.addListener(new BootProgressAsyncListener(disposable)); } catch (Exception e) { logger.error("Failed to process request {}", request.getRequestURI(), e); response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value()); } }
Source:
IgnoreCondition create() { checkConditionType(); try { return createCondition(); } catch (RuntimeException re) { throw Throwables.propagate(re); } catch (Exception e) { throw new RuntimeException(e); } }

Target:
IgnoreCondition create() { checkConditionType(); try { return createCondition(); } catch (Exception re) { throw Throwables.propagate(re); } }
Source:
public void setUp() { ignoreTestDir = JGitTestUtil.getTestResourceFile("excludeTest"); assertTrue("Test resource directory is not a directory",ignoreTestDir.isDirectory()); try { repo = new Repository(ignoreTestDir); } catch (IOException e) { fail("IOException when creating repository at" + ignoreTestDir); } cache = new SimpleIgnoreCache(repo); initCache(); }

Target:
public void setUp() throws Exception { super.setUp(); ignoreTestDir = JGitTestUtil.getTestResourceFile("excludeTest"); assertTrue("Test resource directory is not a directory",ignoreTestDir.isDirectory()); db = createWorkRepository(); recursiveCopy(ignoreTestDir, db.getDirectory().getParentFile()); cache = new SimpleIgnoreCache(db); initCache(); }
Source:
private void raiseAlert(HttpMessage msg, int id, String evidence) { Alert alert = new Alert(getPluginId(), Alert.RISK_MEDIUM, Alert.CONFIDENCE_MEDIUM, getName()); alert.setDetail( this.getDescription(), msg.getRequestHeader().getURI().toString(), "", "", "", this.getSolution(), this.getReference(), evidence, 0, 0, msg); parent.raiseAlert(id, alert); }

Target:
private void raiseAlert(HttpMessage msg, int id, String evidence) { Alert alert = new Alert(getPluginId(), Alert.RISK_LOW, Alert.CONFIDENCE_LOW, getName()); alert.setDetail( this.getDescription(), msg.getRequestHeader().getURI().toString(), "", "", "", this.getSolution(), this.getReference(), evidence, 749, 0, msg); parent.raiseAlert(id, alert); }
Source:
public XWikiAttachment remove(int index) { XWikiAttachment removedAttachment = map.remove(this.list.get(index).getFilename()); if (removedAttachment != null) { removedAttachment = super.remove(index); document.setMetaDataDirty(true); } return removedAttachment; }

Target:
public XWikiAttachment remove(int index) { XWikiAttachment removedAttachment = map.remove(this.decorated().get(index).getFilename()); if (removedAttachment != null) { updatedMap(); } return removedAttachment; }
Source:
private void dismissKeyguard() { final ResolvableFuture<Void> future = ResolvableFuture.create(); KeyguardManager keyguardManager = getSystemService(KeyguardManager.class); keyguardManager.requestDismissKeyguard(this, new KeyguardManager.KeyguardDismissCallback() { @Override public void onDismissSucceeded() { future.set(null); } }); try { future.get(500, TimeUnit.MILLISECONDS); } catch (ExecutionException | InterruptedException | TimeoutException e) { Log.w("WebViewTestActivity", "Failed to dismiss keyguard"); } }

Target:
private void dismissKeyguard() { final ResolvableFuture<Void> future = ResolvableFuture.create(); KeyguardManager keyguardManager = getSystemService(KeyguardManager.class); keyguardManager.requestDismissKeyguard(this, new KeyguardManager.KeyguardDismissCallback() { @Override public void onDismissSucceeded() { future.set(null); } }); try { future.get(500, TimeUnit.MILLISECONDS); } catch (ExecutionException | InterruptedException | TimeoutException e) { Log.w("WebViewTestActivity", "Failed to dismiss keyguard", e); } }
Source:
private Predicate<Fragment> exportedJarFragment() { return new Predicate<Fragment>() { @Override public boolean apply(final Fragment input) { return input.isExported() && input.getValue().endsWith(".jar"); } }; }

Target:
private Predicate<Fragment> exportedJarFragment() { return new Predicate<Fragment>() { @Override public boolean apply(final Fragment input) { return input.isExported() && input.getValue().endsWith(JAR_EXT); } }; }
Source:
public StatusAdapter getStatusAdapter(JobInfo info) { if (map == null) { return null; } StatusAdapter statusAdapter = (StatusAdapter) map.remove(info); if (statusAdapter != null) statusAdapter.setProperty( IProgressConstants.NO_IMMEDIATE_ERROR_PROMPT_PROPERTY, Boolean.FALSE); return statusAdapter; }

Target:
public StatusAdapter getStatusAdapter(JobInfo info) { if (map == null) { return null; } StatusAdapter statusAdapter = (StatusAdapter) map.remove(info); if (statusAdapter != null) { statusAdapter.setProperty( IProgressConstants.NO_IMMEDIATE_ERROR_PROMPT_PROPERTY, Boolean.FALSE); } return statusAdapter; }
Source:
public <K, V, M> OutputStream<K, V, M> getOutputStream(String streamId, Function<? super M, ? extends K> keyExtractor, Function<? super M, ? extends V> msgExtractor) { if (keyExtractor == null || msgExtractor == null) { throw new IllegalArgumentException("Neither keyExtractor nor msgExtractor can be null for an output stream."); } return outStreams.computeIfAbsent(runner.getStreamSpec(streamId), streamSpec -> new OutputStreamInternalImpl<K, V, M>(this, streamSpec, keyExtractor, msgExtractor)); }

Target:
public <K, V, M> OutputStream<K, V, M> getOutputStream(String streamId, Function<? super M, ? extends K> keyExtractor, Function<? super M, ? extends V> msgExtractor) { if (keyExtractor == null) { throw new IllegalArgumentException("keyExtractor can't be null for an output stream."); } if (msgExtractor == null) { throw new IllegalArgumentException("msgExtractor can't be null for an output stream."); } return outStreams.computeIfAbsent(runner.getStreamSpec(streamId), streamSpec -> new OutputStreamInternalImpl<>(this, streamSpec, (Function<M, K>) keyExtractor, (Function<M, V>) msgExtractor)); }
Source:
public MoveDescription( final Collection<Unit> units, final Route route, final Map<Unit, Unit> unitsToTransports, final Map<Unit, Collection<Unit>> dependentUnits) { super(units); this.route = route; if (this.route == null) { throw new NullPointerException(); } this.unitsToTransports = unitsToTransports; if (this.unitsToTransports == null) { throw new NullPointerException(); } if (!dependentUnits.isEmpty()) { this.dependentUnits = new HashMap<>(); for (final Entry<Unit, Collection<Unit>> entry : dependentUnits.entrySet()) { this.dependentUnits.put(entry.getKey(), new HashSet<>(entry.getValue())); } } else { this.dependentUnits = Map.of(); } }

Target:
public MoveDescription( final Collection<Unit> units, final Route route, final Map<Unit, Unit> unitsToTransports, final Map<Unit, Collection<Unit>> dependentUnits) { super(Collections.unmodifiableCollection(units)); this.route = Preconditions.checkNotNull(route); this.unitsToTransports = Collections.unmodifiableMap(unitsToTransports); this.dependentUnits = Collections.unmodifiableMap( dependentUnits.entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, e -> Set.copyOf(e.getValue())))); }
Source:
private Iterable<Review> reviews(final Publisher contentPublisher, Set<org.atlasapi.media.entity.simple.Review> simpleReviews) { return simpleReviews.stream() .map(simpleReview -> { if (simpleReview.getPublisherDetails() != null && !getPublisher(simpleReview.getPublisherDetails()).equals(contentPublisher)) { throw new IllegalArgumentException("Review publisher must match content publisher"); } return Review.builder() .withLocale(Locale.forLanguageTag(simpleReview.getLanguage())) .withReview(simpleReview.getReview()) .withDate(simpleReview.getDate()) .withAuthor(simpleReview.getAuthor()) .withAuthorInitials(simpleReview.getAuthorInitials()) .withRating(simpleReview.getRating()) .withReviewType(simpleReview.getReviewType()) .build(); }) .collect(Collectors.toList()); }

Target:
private Iterable<Review> reviews( final Publisher contentPublisher, Set<org.atlasapi.media.entity.simple.Review> simpleReviews ) { return simpleReviews.stream() .map(simpleReview -> { if (simpleReview.getPublisherDetails() != null && !getPublisher(simpleReview.getPublisherDetails()).equals(contentPublisher)) { throw new IllegalArgumentException("Review publisher must match content publisher"); } return Review.builder() .withLocale(Locale.forLanguageTag(simpleReview.getLanguage())) .withReview(simpleReview.getReview()) .withDate(simpleReview.getDate()) .withAuthor(simpleReview.getAuthor()) .withAuthorInitials(simpleReview.getAuthorInitials()) .withRating(simpleReview.getRating()) .withReviewTypeKey(simpleReview.getReviewType().toKey()) .build(); }) .collect(MoreCollectors.toImmutableList()); }
Source:
public List<TriggeredNotification> calculate( List<? extends Person> subjects, Notification notification, OrchestrationManager manager) { List<TriggeredNotification> triggered = new ArrayList<>(); if (null != notification.getGoal().getApproved()) { for(Person p : subjects) { List<TriggeredNotification> t = NotificationCalculator.createTriggeredNotifications( notification, 0D, manager, p.getId()); if (null != t) { triggered.addAll(t); } } } if (triggered.isEmpty()) { return null; } else { return triggered; } }

Target:
public List<TriggeredNotification> calculate( List<? extends Person> subjects, Notification notification, OrchestrationManager manager) { List<TriggeredNotification> triggered = new ArrayList<>(); if (null != notification.getGoal().getApproved()) { for(Person p : subjects) { List<TriggeredNotification> t = NotificationCalculator.createTriggeredNotifications( notification, 0D, manager, p.getId()); if (null != t) { triggered.addAll(t); } } } return triggered.isEmpty() ? null : triggered; }
Source:
public TerminationData killJobs(List<JobId> jobIds) { jobIds.forEach(jobId -> jlogger.info(jobId, "killing job")); List<JobData> jobDatas = lockJobs(jobIds); if (jobDatas == null) { return null; } try { TaskResultImpl taskResult = null; JobStatus jobStatus = JobStatus.KILLED; Set<TaskId> tasksToUpdate = new HashSet<>(); TerminationData terminationData = TerminationData.newTerminationData(); for (JobData jobData : jobDatas) { JobId jobId = jobData.job.getId(); jobs.remove(jobId); terminationData.addJobToTerminate(jobId); InternalJob job = jobData.job; jlogger.info(job.getId(), "ending request"); for (Iterator<RunningTaskData> i = runningTasksData.values().iterator(); i.hasNext();) { RunningTaskData taskData = i.next(); if (taskData.getTask().getJobId().equals(jobId)) { i.remove(); taskData.getTask().setProgress(0); terminationData.addTaskData(job, taskData, TerminationData.TerminationStatus.ABORTED, taskResult); } } tasksToUpdate.addAll(job.failed(null, jobStatus)); } dbManager.killJobs(jobDatas.stream().map(jobData -> jobData.job).collect(Collectors.toList())); for (JobData jobData : jobDatas) { InternalJob job = jobData.job; updateTasksInSchedulerState(job, tasksToUpdate); SchedulerEvent event; if (job.getStatus() == JobStatus.PENDING) { event = SchedulerEvent.JOB_PENDING_TO_FINISHED; } else { event = SchedulerEvent.JOB_RUNNING_TO_FINISHED; } updateJobInSchedulerState(job, event); jlogger.info(job.getId(), "finished (" + jobStatus + ")"); jlogger.close(job.getId()); } return terminationData; } finally { jobDatas.forEach(JobData::unlock); } }

Target:
public TerminationData killJobs(List<JobId> jobIds) { jobIds.forEach(jobId -> jlogger.info(jobId, "killing job")); List<JobData> jobDatas = lockJobs(jobIds); if (jobDatas == null || jobDatas.isEmpty()) { return TerminationData.EMPTY; } try { TaskResultImpl taskResult = null; JobStatus jobStatus = JobStatus.KILLED; Set<TaskId> tasksToUpdate = new HashSet<>(); TerminationData terminationData = TerminationData.newTerminationData(); for (JobData jobData : jobDatas) { JobId jobId = jobData.job.getId(); jobs.remove(jobId); terminationData.addJobToTerminate(jobId); InternalJob job = jobData.job; jlogger.info(job.getId(), "ending request"); for (Iterator<RunningTaskData> i = runningTasksData.values().iterator(); i.hasNext();) { RunningTaskData taskData = i.next(); if (taskData.getTask().getJobId().equals(jobId)) { i.remove(); taskData.getTask().setProgress(0); terminationData.addTaskData(job, taskData, TerminationData.TerminationStatus.ABORTED, taskResult); } } tasksToUpdate.addAll(job.failed(null, jobStatus)); } dbManager.killJobs(jobDatas.stream().map(jobData -> jobData.job).collect(Collectors.toList())); for (JobData jobData : jobDatas) { InternalJob job = jobData.job; updateTasksInSchedulerState(job, tasksToUpdate); SchedulerEvent event; if (job.getStatus() == JobStatus.PENDING) { event = SchedulerEvent.JOB_PENDING_TO_FINISHED; } else { event = SchedulerEvent.JOB_RUNNING_TO_FINISHED; } updateJobInSchedulerState(job, event); jlogger.info(job.getId(), "finished (" + jobStatus + ")"); jlogger.close(job.getId()); } return terminationData; } finally { jobDatas.forEach(JobData::unlock); } }
Source:
private MessageElement readMessage(String documentation) { String name = readName(); MessageElement.Builder builder = MessageElement.builder() .setName(name) .setQualifiedName(prefix + name) .setDocumentation(documentation); String previousPrefix = prefix; prefix = prefix + name + "."; if (readChar() != '{') throw unexpected("expected '{'"); while (true) { String nestedDocumentation = readDocumentation(); if (peekChar() == '}') { pos++; break; } Object declared = readDeclaration(nestedDocumentation, Context.MESSAGE); if (declared instanceof FieldElement) { builder.addField((FieldElement) declared); } else if (declared instanceof OneOfElement) { builder.addOneOf((OneOfElement) declared); } else if (declared instanceof TypeElement) { builder.addType((TypeElement) declared); } else if (declared instanceof ExtensionsElement) { builder.addExtensions((ExtensionsElement) declared); } else if (declared instanceof OptionElement) { builder.addOption((OptionElement) declared); } else if (declared instanceof ExtendElement) { fileBuilder.addExtendDeclaration((ExtendElement) declared); } } prefix = previousPrefix; return builder.build(); }

Target:
private MessageElement readMessage(String documentation) { String name = readName(); MessageElement.Builder builder = MessageElement.builder() .name(name) .qualifiedName(prefix + name) .documentation(documentation); String previousPrefix = prefix; prefix = prefix + name + "."; if (readChar() != '{') throw unexpected("expected '{'"); while (true) { String nestedDocumentation = readDocumentation(); if (peekChar() == '}') { pos++; break; } Object declared = readDeclaration(nestedDocumentation, Context.MESSAGE); if (declared instanceof FieldElement) { builder.addField((FieldElement) declared); } else if (declared instanceof OneOfElement) { builder.addOneOf((OneOfElement) declared); } else if (declared instanceof TypeElement) { builder.addType((TypeElement) declared); } else if (declared instanceof ExtensionsElement) { builder.addExtensions((ExtensionsElement) declared); } else if (declared instanceof OptionElement) { builder.addOption((OptionElement) declared); } else if (declared instanceof ExtendElement) { fileBuilder.addExtendDeclaration((ExtendElement) declared); } } prefix = previousPrefix; return builder.build(); }
Source:
public void unwatchWithinMulti() { final String key = "foo"; final String val = "bar"; jedis.set(key, val); jedis.watch(key); List<String> exp = new ArrayList<>(); Transaction t = jedis.multi(); t.get(key); exp.add(val); t.unwatch(); exp.add("OK"); t.get(key); exp.add(val); List<Object> res = t.exec(); assertEquals(exp, res); }

Target:
public void unwatchWithinMulti() { final String key = "foo"; final String val = "bar"; jedis.set(key, val); jedis.watch(key); List<Object> exp = new ArrayList<>(); Transaction t = jedis.multi(); t.get(key); exp.add(val); t.unwatch(); exp.add("OK"); t.get(key); exp.add(val); List<Object> res = t.exec(); assertEquals(exp, res); }
Source:
protected InputStream loadResource(Uri uri, ContentResolver contentResolver) throws FileNotFoundException { if (ContactsContract.Contacts.CONTENT_URI.getHost().equals(uri.getHost()) && URI_MATCHER.match(uri) != UriMatcher.NO_MATCH) { return loadResourceFromContactUri(uri, contentResolver); } return contentResolver.openInputStream(uri); }

Target:
protected InputStream loadResource(Uri uri, ContentResolver contentResolver) throws FileNotFoundException { final int matchedUri = URI_MATCHER.match(uri); return loadResourceFromUri(uri, contentResolver, matchedUri); }
Source:
void verifySpace(int destination, String path, long length) throws StopRequestException { resetBytesDownloadedSinceLastCheckOnSpace(); File dir = null; if (path == null) { throw new IllegalArgumentException("path can't be null"); } switch (destination) { case DownloadsDestination.DESTINATION_CACHE_PARTITION: case DownloadsDestination.DESTINATION_CACHE_PARTITION_NOROAMING: case DownloadsDestination.DESTINATION_CACHE_PARTITION_PURGEABLE: dir = downloadDataDir; break; case DownloadsDestination.DESTINATION_EXTERNAL: dir = externalStorageDir; break; case DownloadsDestination.DESTINATION_SYSTEMCACHE_PARTITION: dir = systemCacheDir; break; case DownloadsDestination.DESTINATION_FILE_URI: if (path.startsWith(externalStorageDir.getPath())) { dir = externalStorageDir; } else if (path.startsWith(downloadDataDir.getPath())) { dir = downloadDataDir; } else if (path.startsWith(systemCacheDir.getPath())) { dir = systemCacheDir; } else if (path.startsWith(internalStorageDir.getPath())) { dir = internalStorageDir; } else { for (File aExternalStorageDir : externalStorageDirs) { if (aExternalStorageDir != null) { if (path.startsWith(aExternalStorageDir.getPath())) { dir = aExternalStorageDir; break; } } } } break; } if (dir == null) { throw new IllegalStateException("invalid combination of destination: " + destination + ", path: " + path); } findSpace(dir, length, destination); }

Target:
void verifySpace(int destination, String path, long length) throws StopRequestException { resetBytesDownloadedSinceLastCheckOnSpace(); File dir = null; if (path == null) { throw new IllegalArgumentException("path can't be null"); } switch (destination) { case DownloadsDestination.DESTINATION_CACHE_PARTITION: case DownloadsDestination.DESTINATION_CACHE_PARTITION_NOROAMING: case DownloadsDestination.DESTINATION_CACHE_PARTITION_PURGEABLE: dir = downloadDataDir; break; case DownloadsDestination.DESTINATION_EXTERNAL: dir = externalStorageDir; break; case DownloadsDestination.DESTINATION_SYSTEMCACHE_PARTITION: dir = systemCacheDir; break; case DownloadsDestination.DESTINATION_FILE_URI: if (path.startsWith(externalStorageDir.getPath())) { dir = externalStorageDir; } else if (path.startsWith(downloadDataDir.getPath())) { dir = downloadDataDir; } else if (path.startsWith(systemCacheDir.getPath())) { dir = systemCacheDir; } else if (path.startsWith(internalStorageDir.getPath())) { dir = internalStorageDir; } else { for (File anExternalStorageDir : externalStorageDirs) { if (anExternalStorageDir != null && path.startsWith(anExternalStorageDir.getPath()) { dir = anExternalStorageDir; break; } } } break; } if (dir == null) { throw new IllegalStateException("invalid combination of destination: " + destination + ", path: " + path); } findSpace(dir, length, destination); }
Source:
public void greetTest() { RestAssuredMockMvc.given() .contentType(ContentType.JSON) .param("The param", "Johan") .when() .get("/users/greet") .then() .statusCode(200) .body(containsString("hello, Johan")); }

Target:
public void greetTest() { given().contentType(ContentType.JSON) .param("name", "Johan") .when() .get("/users/greet") .then() .statusCode(200) .body(containsString("hello, Johan")); }
Source:
public void canCombatDamageHappen(AreaEffectCloudApplyEvent event) { if ( ! MUtil.isHarmfulPotion(event.getEntity().getBasePotionData().getType().getEffectType())) return; ProjectileSource projectileSource = event.getEntity().getSource(); if ( ! (projectileSource instanceof Entity)) return; Entity thrower = (Entity)projectileSource; List<LivingEntity> affectedList = new ArrayList<LivingEntity>(); for (LivingEntity affectedEntity : event.getAffectedEntities()) { EntityDamageByEntityEvent sub = new EntityDamageByEntityEvent(thrower, affectedEntity, EntityDamageEvent.DamageCause.CUSTOM, 0D); if (EngineCombat.get().canCombatDamageHappen(sub, false)) continue; affectedList.add(affectedEntity); } for (LivingEntity affectedEnt : affectedList) { event.getAffectedEntities().remove(affectedEnt); } }

Target:
public void canCombatDamageHappen(AreaEffectCloudApplyEvent event) { if ( ! MUtil.isHarmfulPotion(event.getEntity().getBasePotionData().getType().getEffectType())) return; ProjectileSource projectileSource = event.getEntity().getSource(); if ( ! (projectileSource instanceof Entity)) return; Entity thrower = (Entity)projectileSource; List<LivingEntity> affectedList = new ArrayList<LivingEntity>(); for (LivingEntity affectedEntity : event.getAffectedEntities()) { EntityDamageByEntityEvent sub = new EntityDamageByEntityEvent(thrower, affectedEntity, EntityDamageEvent.DamageCause.CUSTOM, 0D); if (EngineCombat.get().canCombatDamageHappen(sub, false)) continue; affectedList.add(affectedEntity); } event.getAffectedEntities().removeAll(affectedList); }
Source:
private static Type best(List<Type> minimalCandidates) { Collections.sort(minimalCandidates, new Comparator<Type>() { @Override public int compare(Type type, Type t1) { return type.name().compareTo(t1.name()); } }); Collections.sort(minimalCandidates, new Comparator<Type>() { @Override public int compare(Type type, Type t1) { Symbol.TypeSymbol typeSymbol = type.symbol(); Symbol.TypeSymbol t1Symbol = t1.symbol(); if (typeSymbol.isInterface() && t1Symbol.isInterface()) { return 0; } else if (typeSymbol.isInterface()) { return 1; } else if (t1Symbol.isInterface()) { return -1; } return 0; } }); return minimalCandidates.get(0); }

Target:
private static Type best(List<Type> minimalCandidates) { Collections.sort(minimalCandidates, new Comparator<Type>() { @Override public int compare(Type type, Type t1) { Symbol.TypeSymbol typeSymbol = type.symbol(); Symbol.TypeSymbol t1Symbol = t1.symbol(); if (typeSymbol.isInterface() && t1Symbol.isInterface()) { return type.name().compareTo(t1.name()); } else if (typeSymbol.isInterface()) { return 1; } else if (t1Symbol.isInterface()) { return -1; } return type.name().compareTo(t1.name()); } }); return minimalCandidates.get(0); }
Source:
private void startDataRegions(DataStorageConfiguration cfg) throws IgniteCheckedException { if (dataRegionsStarted) return; assert cfg != null; registerMetricsMBeans(cctx.gridConfig()); startDataRegions(); initPageMemoryDataStructures(cfg); dataRegionsStarted = true; DecimalFormat dblFmt = new DecimalFormat("#.##", DecimalFormatSymbols.getInstance(Locale.US)); if (log.isQuiet()) { U.quiet(false, "Data Regions Started: " + dataRegionMap.size()); U.quietMultipleLines(false, IgniteKernal.dataStorageReport(this, dblFmt, false)); } else if (log.isInfoEnabled()) { log.info("Data Regions Started: " + dataRegionMap.size()); log.info(IgniteKernal.dataStorageReport(this, dblFmt, false)); } }

Target:
private void startDataRegions(DataStorageConfiguration cfg) throws IgniteCheckedException { if (dataRegionsStarted) return; assert cfg != null; registerMetricsMBeans(cctx.gridConfig()); startDataRegions(); initPageMemoryDataStructures(cfg); dataRegionsStarted = true; if (log.isQuiet()) { U.quiet(false, "Data Regions Started: " + dataRegionMap.size()); U.quietMultipleLines(false, IgniteKernal.dataStorageReport(this, false)); } else if (log.isInfoEnabled()) { log.info("Data Regions Started: " + dataRegionMap.size()); log.info(IgniteKernal.dataStorageReport(this, false)); } }
Source:
private String getRunContext(final Run run) { if (run instanceof WorkflowRun) { List<? extends Action> actionList = ((WorkflowRun) run).getAllActions(); for (final Action currAction : actionList) { if (currAction instanceof CauseAction) { for (final Cause currCause : ((CauseAction) currAction).getCauses()) { if (currCause instanceof TeamPushCause) { return ((TeamPushCause) currCause).getRunContext(); } } } } } return DEFAULT_RUN_CONTEXT; }

Target:
private String getRunContext(final Run run) { List<? extends Action> actionList = run.getAllActions(); for (final Action currAction : actionList) { if (currAction instanceof CauseAction) { for (final Cause currCause : ((CauseAction) currAction).getCauses()) { if (currCause instanceof TeamPushCause) { return ((TeamPushCause) currCause).getRunContext(); } } } } return DEFAULT_RUN_CONTEXT; }
Source:
public void testTimeoutWasNotTriggered() throws IOException, ExecutionException, InterruptedException { FreeStyleProject project = j.createFreeStyleProject(); project.setDisplayName("Check timeout"); Builder step = new BuildStepWithTimeout(new FakeBuildStep(0), new QuickBuildTimeOutStrategy(500), null); project.getBuildersList().add(step); Future<FreeStyleBuild> future = project.scheduleBuild2(0, new Cause.UserIdCause()); FreeStyleBuild build = future.get(); assertTrue(IOUtils.toString(build.getLogReader()).contains("Test")); }

Target:
public void testTimeoutWasNotTriggered() throws Exception { final FreeStyleProject project = createProjectWithBuildStepWithTimeout(TINY_DELAY, null); final FreeStyleBuild build = project.scheduleBuild2(0, new Cause.UserIdCause()).get(); j.assertBuildStatusSuccess(build); j.assertLogContains("Test", build); }
Source:
public WritableComponentView(Composite parent, final WritableComponentProperty property, boolean displayName, final boolean isPreview) { super(parent, SWT.NONE); setLayout(new FillLayout(SWT.VERTICAL)); this.parent = parent; this.property = property; if (displayName) { propertyName = new Label(this, SWT.NONE); propertyName.setAlignment(SWT.CENTER); propertyName.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE)); propertyName.setFont(SWTResourceManager.getFont("Arial", 10, SWT.BOLD)); propertyName.setText(property.displayName()); } composite = new Composite(this, SWT.NONE); composite.setBackground(SWTResourceManager.getColor(SWT.COLOR_CYAN)); GridLayout glComposite = new GridLayout(1, false); glComposite.horizontalSpacing = 1; glComposite.marginWidth = 2; glComposite.verticalSpacing = 0; glComposite.marginHeight = 2; composite.setLayout(glComposite); text = new Text(composite, SWT.BORDER | SWT.RIGHT); text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); text.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); bindText(property); text.addFocusListener(new FocusListener() { @Override public void focusLost(FocusEvent e) { text.removeModifyListener(textModifyListener); } @Override public void focusGained(FocusEvent e) { text.addModifyListener(textModifyListener); } }); text.addListener(SWT.Traverse, new Listener() { @Override public void handleEvent(Event event) { if (event.detail == SWT.TRAVERSE_RETURN) { if (!isPreview) { sendValue(); } } } }); }

Target:
public WritableComponentView(Composite parent, final WritableComponentProperty property, boolean displayName, final boolean isPreview) { super(parent, SWT.NONE); setLayout(new FillLayout(SWT.VERTICAL)); this.parent = parent; this.property = property; if (displayName) { propertyName = new Label(this, SWT.NONE); propertyName.setAlignment(SWT.CENTER); propertyName.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE)); propertyName.setFont(SWTResourceManager.getFont("Arial", 10, SWT.BOLD)); propertyName.setText(property.displayName()); } composite = new Composite(this, SWT.NONE); composite.setBackground(SWTResourceManager.getColor(SWT.COLOR_CYAN)); GridLayout glComposite = new GridLayout(1, false); glComposite.horizontalSpacing = 1; glComposite.marginWidth = 2; glComposite.verticalSpacing = 0; glComposite.marginHeight = 2; composite.setLayout(glComposite); text = new Text(composite, SWT.BORDER | SWT.RIGHT); text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); text.setFont(SWTResourceManager.getFont("Arial", 9, SWT.NORMAL)); bindText(property); text.addListener(SWT.Traverse, new Listener() { @Override public void handleEvent(Event event) { if (event.detail == SWT.TRAVERSE_RETURN && !isPreview) { sendValue(); } } }); }
Source:
private long sendRequestTimeoutMillis() { int emitQueueSize = approximateBuffersToEmitCount.get(); if (emitQueueSize < 5) { return (long) (lastFillTimeMillis * config.httpTimeoutAllowanceFactor); } if (emitQueueSize < 10) { return (long) (lastFillTimeMillis * 0.9); } return (long) (lastFillTimeMillis * 0.5); }

Target:
private long sendRequestTimeoutMillis() { int emitQueueSize = approximateBuffersToEmitCount.get(); if (emitQueueSize < EMIT_QUEUE_THRESHOLD_1) { return (long) (lastFillTimeMillis * config.httpTimeoutAllowanceFactor); } if (emitQueueSize < EMIT_QUEUE_THRESHOLD_2) { return (long) (lastFillTimeMillis * EQUILIBRIUM_ALLOWANCE_FACTOR); } return (long) (lastFillTimeMillis * TIGHT_ALLOWANCE_FACTOR); }
Source:
private DevicePropertiesUtils mockDevicePropertiesUtils(String customDevPropSpec) { DevicePropertiesUtils mockedUtils = spy(new DevicePropertiesUtils()); doReturn(customDevPropSpec). when(mockedUtils) .getCustomDeviceProperties(eq(Version.v3_3)); doReturn(""). when(mockedUtils) .getCustomDeviceProperties(eq(Version.v3_2)); doReturn(new HashSet<Version>(Arrays.asList(Version.v3_2, Version.v3_3))). when(mockedUtils) .getSupportedClusterLevels(); try { mockedUtils.init(); } catch (InitializationException e) { e.printStackTrace(); } return mockedUtils; }

Target:
private DevicePropertiesUtils mockDevicePropertiesUtils(String customDevPropSpec) { DevicePropertiesUtils mockedUtils = spy(new DevicePropertiesUtils()); doReturn(customDevPropSpec). when(mockedUtils) .getCustomDeviceProperties(eq(Version.v3_3)); doReturn(""). when(mockedUtils) .getCustomDeviceProperties(eq(Version.v3_2)); doReturn(new HashSet<Version>(Arrays.asList(Version.v3_2, Version.v3_3))). when(mockedUtils) .getSupportedClusterLevels(); try { mockedUtils.init(); } catch (InitializationException ex) { log.error("Error initializing DevicePropertiesUtils instance", ex); } return mockedUtils; }