auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void pingCorrectServer(Message clientMessage, DistributedMember targetServer, ServerConnection serverConnection) throws IOException { if (logger.isDebugEnabled()) { logger.debug("Received a Ping request from intended for {}. Forwarding the ping..."); } if (!serverConnection.getCache().getDistributionManager().isCurrentMember(targetServer)) { logger.warn("Unable to ping non-member for client {}", targetServer, serverConnection.getProxyID()); writeErrorResponse(clientMessage, MessageType.PING, serverConnection); serverConnection.setAsTrue(RESPONDED); } else { final DistributedPingMessage distributedPingMessage = new DistributedPingMessage(targetServer, serverConnection.getProxyID()); serverConnection.getCache().getDistributionManager().putOutgoing(distributedPingMessage); writeReply(clientMessage, serverConnection); } }

Target:
protected void pingCorrectServer(Message clientMessage, DistributedMember targetServer, ServerConnection serverConnection) throws IOException { if (logger.isDebugEnabled()) { logger.debug("Received a Ping request from intended for {}. Forwarding the ping...", serverConnection.getProxyID(), targetServer); } if (!serverConnection.getCache().getDistributionManager().isCurrentMember(targetServer)) { logger.warn("Unable to ping non-member for client {}", targetServer, serverConnection.getProxyID()); writeErrorResponse(clientMessage, MessageType.PING, serverConnection); serverConnection.setAsTrue(RESPONDED); } else { final DistributedPingMessage distributedPingMessage = new DistributedPingMessage(targetServer, serverConnection.getProxyID()); serverConnection.getCache().getDistributionManager().putOutgoing(distributedPingMessage); writeReply(clientMessage, serverConnection); } }
Source:
public TrainingParameters getParameters(String namespace) { TrainingParameters params = new TrainingParameters(); Map<String, Object> settings = getObjectSettings(namespace); for (Entry<String, Object> entry: settings.entrySet()) { final String key = entry.getKey(); final Object value = entry.getValue();; if (value instanceof Integer) { params.put(key, (Integer)value); } else if (value instanceof Double) { params.put(key, (Double)value); } else if (value instanceof Boolean) { params.put(key, (Boolean)value); } else { params.put(key, (String)value); } } return params; }

Target:
public TrainingParameters getParameters(String namespace) { TrainingParameters params = new TrainingParameters(); Map<String, Object> settings = getObjectSettings(namespace); for (Entry<String, Object> entry: settings.entrySet()) { String key = entry.getKey(); Object value = entry.getValue();; if (value instanceof Integer) { params.put(key, (Integer)value); } else if (value instanceof Double) { params.put(key, (Double)value); } else if (value instanceof Boolean) { params.put(key, (Boolean)value); } else { params.put(key, (String)value); } } return params; }
Source:
public boolean isInSameLabelUpdateEventGroup(TurboIssueEvent e) { long timeDiffMs = Math.abs(getDate().getTime() - e.getDate().getTime()); long timeDiffMin = TimeUnit.MILLISECONDS.toSeconds(timeDiffMs); return getActor().getLogin().equals(e.getActor().getLogin()) && timeDiffMin <= MAX_TIME_DIFF; }

Target:
public boolean isInSameLabelUpdateEventGroup(TurboIssueEvent e) { long timeDiffMs = Math.abs(getDate().getTime() - e.getDate().getTime()); long timeDiffSec = TimeUnit.MILLISECONDS.toSeconds(timeDiffMs); return getActor().getLogin().equals(e.getActor().getLogin()) && timeDiffSec <= MAX_TIME_DIFF; }
Source:
public Map<String, CustomizedView> getCustomizedView(String customizedStateType) { return _customizedViewCaches.get(customizedStateType).getCustomizedViewMap(); }

Target:
public Map<String, CustomizedView> getCustomizedView(String customizedStateType) { if (_customizedViewCaches.containsKey(customizedStateType)) { return _customizedViewCaches.get(customizedStateType).getCustomizedViewMap(); } throw new HelixException(String.format( "customizedStateType %s does not exist in customizedViewCaches.", customizedStateType)); }
Source:
public static int calculateAggregateEnvironmentScore(int soundScore, int temperatureScore, int humidityScore) { return (Math.round(0.25f * temperatureScore) + Math.round(0.25f * humidityScore) + Math.round(0.50f * soundScore)); }

Target:
public static int calculateAggregateEnvironmentScore(int soundScore, int temperatureScore, int humidityScore) { return Math.round((0.25f * temperatureScore) + (0.25f * humidityScore) + (0.50f * soundScore)); }
Source:
public void deleteAllAttributeAuthz(PerunSession sess, AttributeDefinition attribute) throws InternalErrorException { try { if (0 < jdbc.update("DELETE FROM attributes_authz WHERE attr_id=?", attribute.getId())) { log.debug("All attribute_authz were deleted for Attribute={}.", attribute); } } catch (RuntimeException ex) { throw new InternalErrorException(ex); } }

Target:
public void deleteAllAttributeAuthz(PerunSession sess, AttributeDefinition attribute) throws InternalErrorException { try { if (0 < jdbc.update("DELETE FROM attributes_authz WHERE attr_id=?", attribute.getId())) { log.debug("All attribute_authz were deleted for {}.", attribute); } } catch (RuntimeException ex) { throw new InternalErrorException(ex); } }
Source:
public void testOpenUrlInvalid() throws Exception { if (!PlatformUiUtil.hasInternalBrowser()) { System.err.println("Skipping GerritUrlHandlerTest.testOpenUrlInvalid() due to lack of browser support"); return; } if (System.getProperty("mylyn.gerrit.tests.skipBrowserTests") != null) { System.err.println("Skipping GerritUrlHandlerTest.testOpenUrlInvalid() to avoid browser crash"); return; } TaskRepository repository = GerritFixture.GERRIT_NON_EXISTANT.singleRepository(); EditorHandle handler = BrowserUtil.openUrl(activePage, repository.getUrl() + "/abc", 0); assertNotNull("Expected a browser instance, got: " + handler.getClass(), handler.getAdapter(IWebBrowser.class)); assertEquals(Status.OK_STATUS, handler.getStatus()); }

Target:
public void testOpenUrlInvalid() throws Exception { if (!PlatformUiUtil.hasInternalBrowser()) { System.err.println("Skipping GerritUrlHandlerTest.testOpenUrlInvalid() due to lack of browser support"); return; } if (CommonTestUtil.skipBrowserTests()) { System.err.println("Skipping GerritUrlHandlerTest.testOpenUrlInvalid() to avoid browser crash"); return; } TaskRepository repository = GerritFixture.GERRIT_NON_EXISTANT.singleRepository(); EditorHandle handler = BrowserUtil.openUrl(activePage, repository.getUrl() + "/abc", 0); assertNotNull("Expected a browser instance, got: " + handler.getClass(), handler.getAdapter(IWebBrowser.class)); assertEquals(Status.OK_STATUS, handler.getStatus()); }
Source:
public EntityModel<Integer> getMacsCount() { return macsCount; }

Target:
public EntityModel<Long> getMacsCount() { return macsCount; }
Source:
private File saveToFile(Bitmap bitmap) throws IOException { File root = null; String fileName = "map-export-image" + System.currentTimeMillis() + ".png"; root = Environment.getExternalStorageDirectory(); File fileDir = new File(root.getAbsolutePath() + "/ArcGIS/"); fileDir.mkdirs(); File file = new File(fileDir, fileName); FileOutputStream fos = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos); fos.flush(); fos.close(); return file; }

Target:
private File saveToFile(Bitmap bitmap) throws IOException { File root; File file = null; String fileName = "map-export-image" + System.currentTimeMillis() + ".png"; root = Environment.getExternalStorageDirectory(); File fileDir = new File(root.getAbsolutePath() + "/ArcGIS Export/"); boolean isDirectoryCreated=fileDir.exists(); if (!isDirectoryCreated) { isDirectoryCreated= fileDir.mkdirs(); } if(isDirectoryCreated) { file = new File(fileDir, fileName); FileOutputStream fos = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos); fos.flush(); fos.close(); } return file; }
Source:
public void getEntitiesWithinAABBForEntity(Entity exclude, AxisAlignedBB queryBox, @Nonnull List<Entity> out, Predicate<? super Entity> predicate) { int minCubeY = Coords.blockToCube(MathHelper.floor_double(queryBox.minY - World.MAX_ENTITY_RADIUS)); int maxCubeY = Coords.blockToCube(MathHelper.floor_double(queryBox.maxY + World.MAX_ENTITY_RADIUS)); for (int cubeY = minCubeY;cubeY < maxCubeY + 1;cubeY++) { Cube cube = getCube(cubeY); cube.getEntitiesWithinAABBForEntity(exclude, queryBox, out, predicate); } }

Target:
public void getEntitiesWithinAABBForEntity(Entity exclude, AxisAlignedBB queryBox, @Nonnull List<Entity> out, Predicate<? super Entity> predicate) { int minCubeY = Coords.blockToCube(MathHelper.floor_double(queryBox.minY - World.MAX_ENTITY_RADIUS)); int maxCubeY = Coords.blockToCube(MathHelper.floor_double(queryBox.maxY + World.MAX_ENTITY_RADIUS)); for (int cubeY = minCubeY;cubeY <= maxCubeY;cubeY++) { Cube cube = getCube(cubeY); cube.getEntitiesWithinAABBForEntity(exclude, queryBox, out, predicate); } }
Source:
CorfuRecord<V, M> getRecord(@Nonnull final String tableName, @Nullable final Timestamp timestamp, @Nonnull final K key) { try { txBegin(timestamp); return ((Table<K, V, M>) getTable(tableName)).get(key); } finally { txEnd(); } }

Target:
CorfuRecord<V, M> getRecord(@Nonnull final String tableName, @Nullable final Timestamp timestamp, @Nonnull final K key) { if (tableName == null) { throw new IllegalArgumentException("Query::getRecord needs a valid tableName"); } try { txBegin(timestamp); Table<K, V, M> table = getTable(tableName); return table.get(key); } finally { txEnd(); } }
Source:
public static <N extends Number> PropertyConstraint<N> inRange(final N minInclusive, final N maxInclusive) { return ConstraintFactory.fromPredicate( new Predicate<N>() { @Override public boolean test(N t) { return minInclusive.intValue() <= t.intValue() && maxInclusive.intValue() >= t.intValue(); } }, "Should be between " + minInclusive + " and " + maxInclusive ); }

Target:
public static <N extends Number & Comparable<N>> PropertyConstraint<N> inRange(final N minInclusive, final N maxInclusive) { return ConstraintFactory.fromPredicate( new Predicate<N>() { @Override public boolean test(N t) { return minInclusive.compareTo(t) >= 0 && maxInclusive.compareTo(t) <= 0; } }, "Should be between " + minInclusive + " and " + maxInclusive ); }
Source:
private Message getMessage(TopicPartition topicPartition, long offset, SimpleConsumer consumer) { LOG.debug("fetching message topic partition offset {}", topicPartition.getTopic(), topicPartition.getPartition(), offset); final int MAX_MESSAGE_SIZE_BYTES = mConfig.getMaxMessageSizeBytes(); final String clientName = getClientName(topicPartition); kafka.api.FetchRequest request = new FetchRequestBuilder().clientId(clientName) .addFetch(topicPartition.getTopic(), topicPartition.getPartition(), offset, MAX_MESSAGE_SIZE_BYTES) .build(); FetchResponse response = consumer.fetch(request); if (response.hasError()) { consumer.close(); throw new RuntimeException("Error fetching offset data. Reason: " + response.errorCode(topicPartition.getTopic(), topicPartition.getPartition())); } MessageAndOffset messageAndOffset = response.messageSet( topicPartition.getTopic(), topicPartition.getPartition()).iterator().next(); byte[] keyBytes = null; if (messageAndOffset.message().hasKey()) { ByteBuffer key = messageAndOffset.message().key(); keyBytes = new byte[key.limit()]; key.get(keyBytes); } byte[] payloadBytes = null; if (!messageAndOffset.message().isNull()) { ByteBuffer payload = messageAndOffset.message().payload(); payloadBytes = new byte[payload.limit()]; payload.get(payloadBytes); } Long timestamp = null; timestamp = messageAndOffset.message().timestamp(); return new Message(topicPartition.getTopic(), topicPartition.getPartition(), messageAndOffset.offset(), keyBytes, payloadBytes, timestamp); }

Target:
private Message getMessage(TopicPartition topicPartition, long offset, SimpleConsumer consumer) { LOG.debug("fetching message topic partition offset {}", topicPartition.getTopic(), topicPartition.getPartition(), offset); final int MAX_MESSAGE_SIZE_BYTES = mConfig.getMaxMessageSizeBytes(); final String clientName = getClientName(topicPartition); kafka.api.FetchRequest request = new FetchRequestBuilder().clientId(clientName) .addFetch(topicPartition.getTopic(), topicPartition.getPartition(), offset, MAX_MESSAGE_SIZE_BYTES) .build(); FetchResponse response = consumer.fetch(request); if (response.hasError()) { consumer.close(); throw new RuntimeException("Error fetching offset data. Reason: " + response.errorCode(topicPartition.getTopic(), topicPartition.getPartition())); } MessageAndOffset messageAndOffset = response.messageSet( topicPartition.getTopic(), topicPartition.getPartition()).iterator().next(); byte[] keyBytes = null; if (messageAndOffset.message().hasKey()) { ByteBuffer key = messageAndOffset.message().key(); keyBytes = new byte[key.limit()]; key.get(keyBytes); } byte[] payloadBytes = null; if (!messageAndOffset.message().isNull()) { ByteBuffer payload = messageAndOffset.message().payload(); payloadBytes = new byte[payload.limit()]; payload.get(payloadBytes); } Long timestamp = null; if (mConfig.useKafkaTimestamp()) { timestamp = messageAndOffset.message().timestamp(); } return new Message(topicPartition.getTopic(), topicPartition.getPartition(), messageAndOffset.offset(), keyBytes, payloadBytes, timestamp); }
Source:
public void stop(int batchSize) { if (!isProfiling) { return; } verify(previousTimestamp != NOT_INITALIZED, "start() is not called"); verify(batchSize > 0, "batchSize must be positive"); long now = System.nanoTime(); long delta = NANOSECONDS.toMillis(now - previousTimestamp); meanExecutionTime = (meanExecutionTime * samples + delta) / (samples + 1); samples += batchSize; if (samples >= rowsToProfile) { isProfiling = false; if (meanExecutionTime < expensiveFunctionThresholdMillis) { isExpressionExpensive = false; } } previousTimestamp = NOT_INITALIZED; }

Target:
public void stop(int batchSize) { verify(previousTimestamp != NOT_INITALIZED, "start() is not called"); verify(batchSize > 0, "batchSize must be positive"); long now = ticker.read(); long delta = now - previousTimestamp; totalExecutionTimeNanos += delta; samples += batchSize; if ((totalExecutionTimeNanos / samples) < expensiveExpressionThresholdNanos) { isExpressionExpensive = false; } previousTimestamp = NOT_INITALIZED; }
Source:
public void testOpenMRSProviderDataSourceAndCreateEncounterAction() throws InterruptedException, IOException, ParseException, ConceptNameAlreadyInUseException { Long taskID = createProviderTestTask(); activateTrigger(); waitForTaskExecution(taskID); deleteTask(taskID); checkIfProviderWasCreatedProperly(); }

Target:
public void testOpenMRSProviderDataSourceAndCreateEncounterAction() throws InterruptedException, IOException, ParseException, ConceptNameAlreadyInUseException { Long taskID = createProviderTestTask(); activateTrigger(); assertTrue(waitForTaskExecution(taskID)); checkIfProviderWasCreatedProperly(); }
Source:
public static ImmutableList<Struct> getStructsOrderedList(final Ds3ApiSpec spec) throws ParseException { final ImmutableList.Builder<Struct> orderedStructsBuilder = ImmutableList.builder(); final Queue<Struct> allStructs = new LinkedList(getAllStructs(spec).asList()); final ImmutableSet.Builder<String> existingTypesBuilder = ImmutableSet.builder(); int skippedStructsCount = 0; while (!allStructs.isEmpty()) { final int allStructsSize = allStructs.size(); final Struct structEntry = allStructs.peek(); if (orderedStructsBuilder.build().contains(structEntry)) { continue; } if (StructHelper.isPrimitive(structEntry) || StructHelper.containsExistingStructs(structEntry, existingTypesBuilder.build())) { existingTypesBuilder.add(StructHelper.getResponseTypeName(structEntry.getName())); orderedStructsBuilder.add(allStructs.remove()); } else { allStructs.add(allStructs.remove()); } if (allStructsSize == allStructs.size()) { skippedStructsCount++; if (skippedStructsCount == allStructsSize) { LOG.warn("Unable to progress on remaining structs, aborting!"); LOG.warn(" Remaining structs[" + allStructs.size() + "]"); for (final Struct struct : allStructs) { LOG.warn(" " + struct.getName()); } break; } } } return orderedStructsBuilder.build(); }

Target:
public static ImmutableList<Struct> getStructsOrderedList(final Ds3ApiSpec spec) throws ParseException { final ImmutableList.Builder<Struct> orderedStructsBuilder = ImmutableList.builder(); final Queue<Struct> allStructs = new LinkedList(getAllStructs(spec)); final Set<String> existingTypes = new HashSet<>(); int skippedStructsCount = 0; while (!allStructs.isEmpty()) { final int allStructsSize = allStructs.size(); final Struct structEntry = allStructs.remove(); if (existingTypes.contains(structEntry)) { LOG.warn("Skipping structEntry " + structEntry.getName()); continue; } if (StructHelper.isPrimitive(structEntry) || containsExistingStructs(structEntry, existingTypes)) { existingTypes.add(StructHelper.getResponseTypeName(structEntry.getName())); orderedStructsBuilder.add(structEntry); } else { allStructs.add(structEntry); } if (allStructsSize == allStructs.size()) { skippedStructsCount++; if (skippedStructsCount == allStructsSize) { LOG.warn("Unable to progress on remaining structs, aborting!"); LOG.warn(" Remaining structs[" + allStructs.size() + "]"); for (final Struct struct : allStructs) { LOG.warn(" " + struct.getName()); } break; } } } return orderedStructsBuilder.build(); }
Source:
public void init() { super.init(); _setupUI(); }

Target:
public void init() { super.init(); removeAllComponents(); _msgCon = new MessageContainer(TimeUnit.SECONDS.toMillis(60)); _msgCon.clearMessages(); QLBuilder facultyQB=_facultyMemberDao.getAllFacultyQB(); int size = facultyQB.getQueryResolver().list().size(); if(size<=0) { _msgCon.sendNotification(new Message(NotificationType.ERROR,getLocaleContext().getLocalizedText(FacultyMemberListUILOK .ERROR_INFO()))); return; } final Label title = new Label(FacultyMemberListUILOK.TITLE()); title.setHTMLElement(HTMLElement.h1); Container imageCon=new Container(); add(Container.of("prop-mainCon", Container.of("top", title),imageCon)); List<FacultyMemberProfile> facultyMembers=facultyQB.getQueryResolver().list(); for(FacultyMemberProfile facultyMember:facultyMembers) { final PushButton nameLink = new PushButton(); nameLink.setLabel(new LocalizedText(facultyMember.getSlug())); nameLink.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ev) { String slug = nameLink.getLabel().getText(getLocaleContext()).toString(); _slug = _facultyMemberDao.getFacultyMemberProfile(slug).getSlug(); Response response = Event.getResponse(); response.redirect(response.createURL(_contentBuilder.getDetailInfoPage()).addParameter("slug", _slug)); } }); if(facultyMember.getPicture()!=null) { Image image= null; try { image = new Image(ImageResource.getResource(facultyMember.getPicture(), 80, 90)); } catch (IOException e) { _logger.error("Something is wrong when get the picture!", e); } ImageComponent imageCom=new ImageComponent(image); imageCon.add(Container.of("prop-image", Container.of("prop-imageCom",imageCom), Container.of("prop-name",nameLink))); } else { imageCon.add(Container.of("prop-image", Container.of("prop-nameLink", nameLink))); } } }
Source:
public Update(Map<String, Object> properties, MetricUnit unit) { super(properties); this.unit = unit == null ? MetricUnit.NONE : unit; }

Target:
public Update(Map<String, Object> properties, MetricUnit unit) { super(properties); this.unit = unit; }
Source:
@Override protected void setUp() throws Exception { Assert.assertSame("abc", "abc"); Assert.assertSame(tmpStr1.intern(), new String(tmpStr1).intern()); Assert.assertSame(long1 + long1, long1 + long1); }

Target:
@Override protected void setUp() throws Exception { Assert.assertSame("abc", "abc"); Assert.assertNotSame("abc" , new String("abc")); Assert.assertSame("abc", "abc".intern()); Assert.assertSame("abc", new String("abc").intern()); Assert.assertSame(long1 + long1, long1 + long1); }
Source:
public void query_explain_multipleIndexes_missingIndexName() { StubMappingScope scope = indexManager.createScope( otherIndexManager ); LuceneSearchQuery<DocumentReference> query = scope.query().extension( LuceneExtension.get() ) .where( f -> f.id().matching( FIRST_ID ) ) .toQuery(); Assertions.assertThatThrownBy( () -> query.explain( FIRST_ID ) ) .isInstanceOf( SearchException.class ) .hasMessageContaining( "explain(String id) cannot be used when the query targets multiple mapped types" ) .hasMessageContaining( TYPE_NAME ) .hasMessageContaining( OTHER_TYPE_NAME ); }

Target:
public void query_explain_multipleIndexes_missingIndexName() { StubMappingScope scope = indexManager.createScope( otherIndexManager ); LuceneSearchQuery<DocumentReference> query = scope.query().extension( LuceneExtension.get() ) .where( f -> f.id().matching( FIRST_ID ) ) .toQuery(); Assertions.assertThatThrownBy( () -> query.explain( FIRST_ID ) ) .isInstanceOf( SearchException.class ) .hasMessageContaining( "explain(String id) cannot be used when the query targets multiple mapped types" ) .hasMessageContaining( "pass one of [" + TYPE_NAME + ", " + OTHER_TYPE_NAME + "]" ); }
Source:
private <P extends VdsIdVDSCommandParametersBase> FutureVDSCommand createFutureCommand(FutureVDSCommandType commandType, P parameters) { try { Class<FutureVDSCommand> type = (Class<FutureVDSCommand>) Class.forName(commandType.getFullyQualifiedClassName()); Constructor<FutureVDSCommand> constructor = ReflectionUtils.findConstructor(type, parameters.getClass()); if (constructor != null) { return constructor.newInstance(new Object[] { parameters }); } } catch (Exception e) { if (e.getCause() != null) { log.error("CreateCommand failed", e.getCause()); throw new RuntimeException(e.getCause().getMessage(), e.getCause()); } log.error("CreateCommand failed", e); } return null; }

Target:
private <P extends VdsIdVDSCommandParametersBase> FutureVDSCommand createFutureCommand(FutureVDSCommandType commandType, P parameters) { try { Class<FutureVDSCommand> type = (Class<FutureVDSCommand>) Class.forName(commandType.getFullyQualifiedClassName()); Constructor<FutureVDSCommand> constructor = ReflectionUtils.findConstructor(type, parameters.getClass()); if (constructor != null) { return constructor.newInstance(new Object[] { parameters }); } } catch (Exception e) { if (e.getCause() != null) { log.error("CreateFutureCommand failed", e.getCause()); throw new RuntimeException(e.getCause().getMessage(), e.getCause()); } log.error("CreateFutureCommand failed", e); } return null; }
Source:
public void facet_on_created_at() { SearchOptions searchOptions = fixtureForCreatedAtFacet(); Map<String, Long> createdAt = index.search(newQueryBuilder() .createdBefore(DateUtils.parseDateTime("2016-01-01T00:00:00+0100")).build(), searchOptions).getFacets().get("createdAt"); assertThat(createdAt).containsOnly( entry("2011-01-01T00:00:00+0000", 10L), entry("2012-01-01T00:00:00+0000", 0L), entry("2013-01-01T00:00:00+0000", 0L), entry("2014-01-01T00:00:00+0000", 50L), entry("2015-01-01T00:00:00+0000", 10L)); }

Target:
public void facet_on_created_at() { SearchOptions searchOptions = fixtureForCreatedAtFacet(); Builder query = newQueryBuilder().createdBefore(DateUtils.parseDateTime("2016-01-01T00:00:00+0100")); Map<String, Long> createdAt = new Facets(underTest.search(query.build(), searchOptions)).get("createdAt"); assertThat(createdAt).containsOnly( entry("2011-01-01T00:00:00+0000", 10L), entry("2012-01-01T00:00:00+0000", 0L), entry("2013-01-01T00:00:00+0000", 0L), entry("2014-01-01T00:00:00+0000", 50L), entry("2015-01-01T00:00:00+0000", 10L)); }
Source:
public String duplicateProject(Integer itemId) { this.itemId = 0; try { this.myProjekt = serviceManager.getProjectService().duplicateProject(itemId); return redirectToEdit("?faces-redirect=true"); } catch (DAOException e) { logger.error(e.getMessage()); FacesContext facesContext = FacesContext.getCurrentInstance(); FacesMessage facesMessage = new FacesMessage("ERROR: Unable to duplicate selected project!"); facesContext.addMessage(null, facesMessage); return null; } }

Target:
public String duplicateProject(Integer itemId) { setLocked(false); this.itemId = 0; try { this.myProjekt = serviceManager.getProjectService().duplicateProject(itemId); return redirectToEdit("?faces-redirect=true"); } catch (DAOException e) { logger.error(e.getMessage()); FacesContext facesContext = FacesContext.getCurrentInstance(); FacesMessage facesMessage = new FacesMessage(Helper.getTranslation("unableToDuplicateProject")); facesContext.addMessage(null, facesMessage); return null; } }
Source:
void hierarchicalPropagateImprovement(VolcanoPlanner planner, RelMetadataQuery mq, RelSubset subset, RelNode rel, Set<RelSubset> activeSet) { Stack<Pair<RelNode, RelSubset>> propagateStack = new Stack<>(); subset.push(rel, propagateStack); while (!propagateStack.empty()) { Pair<RelNode, RelSubset> one = propagateStack.remove(0); one.getValue() .propagateCostImprovements0(planner, mq, one.getKey(), activeSet, propagateStack); } }

Target:
void hierarchicalPropagateImprovement(VolcanoPlanner planner, RelMetadataQuery mq, RelSubset subset, RelNode rel, Set<RelSubset> activeSet) { ArrayDeque<Pair<RelNode, RelSubset>> propagateQueue = new ArrayDeque<>(); subset.push(rel, propagateQueue); while (!propagateQueue.isEmpty()) { Pair<RelNode, RelSubset> first = propagateQueue.remove(); first.getValue() .propagateCostImprovements0(planner, mq, first.getKey(), activeSet, propagateQueue); } }
Source:
private AggregationNode computeCounts(UnionNode sourceNode, List<Symbol> originalColumns, List<Symbol> markers, List<Symbol> aggregationOutputs) { ImmutableMap.Builder<Symbol, Aggregation> aggregations = ImmutableMap.builder(); for (int i = 0; i < markers.size(); i++) { Symbol output = aggregationOutputs.get(i); aggregations.put(output, new Aggregation( new FunctionCall(QualifiedName.of("count"), ImmutableList.of(markers.get(i).toSymbolReference())), COUNT_AGGREGATION, Optional.empty())); } return new AggregationNode(idAllocator.getNextId(), sourceNode, aggregations.build(), AggregationNode.singleGroupingSet(originalColumns), ImmutableList.of(), Step.SINGLE, Optional.empty(), Optional.empty()); }

Target:
private AggregationNode computeCounts(UnionNode sourceNode, List<Symbol> originalColumns, List<Symbol> markers, List<Symbol> aggregationOutputs) { ImmutableMap.Builder<Symbol, Aggregation> aggregations = ImmutableMap.builder(); for (int i = 0; i < markers.size(); i++) { Symbol output = aggregationOutputs.get(i); aggregations.put(output, new Aggregation( new FunctionCall(QualifiedName.of("count"), ImmutableList.of(markers.get(i).toSymbolReference())), COUNT_AGGREGATION, Optional.empty())); } return new AggregationNode(idAllocator.getNextId(), sourceNode, aggregations.build(), singleGroupingSet(originalColumns), ImmutableList.of(), Step.SINGLE, Optional.empty(), Optional.empty()); }
Source:
public void stopStatisticCollector() { if (collectingStats.compareAndSet(true, false)) { task.cancel(false); task = null; } }

Target:
public synchronized void stopStatisticCollector() { if (task != null) { task.cancel(false); task = null; } }
Source:
public void init() { model = editorFixture.getModel(); assertNotNull("The model cannot be null", model); profile = model.getAppliedProfile(PROFILE_NAME); assertEquals("Profile is not the one Expected", PROFILE_NAME, profile.getName()); simpleClass = model.getMember(SIMPLE_CLASS_NAME); assertTrue("The element is a Class", simpleClass instanceof Class); assertEquals("Element is not the one expected", SIMPLE_CLASS_NAME, simpleClass.getName()); stereotypedClass = model.getMember(STEREOTYPED_CLASS_NAME); assertTrue("The element is a Class", simpleClass instanceof Class); assertEquals("Element is not the one expected", STEREOTYPED_CLASS_NAME, stereotypedClass.getName()); for (Iterator<Comment> iterator = model.getOwnedComments().iterator(); iterator.hasNext();) { Comment comment = iterator.next(); if (comment.getBody() == null) { emptyCommment = comment; } else { commment = comment; } } templateSignature = model.getOwnedTemplateSignature(); assertNotNull("The template signature must exist", templateSignature); templateParameter = templateSignature.getParameters().get(0); assertNotNull("The template parameters must exist", templateParameter); }

Target:
public void init() { model = editorFixture.getModel(); assertNotNull("The model cannot be null", model); profile = model.getAppliedProfile(PROFILE_NAME); assertEquals("Profile is not the one Expected", PROFILE_NAME, profile.getName()); simpleClass = model.getMember(SIMPLE_CLASS_NAME); assertTrue("The element is not a Class", simpleClass instanceof Class); assertEquals("Element is not the one expected", SIMPLE_CLASS_NAME, simpleClass.getName()); stereotypedClass = model.getMember(STEREOTYPED_CLASS_NAME); assertTrue("The element is not a Class", stereotypedClass instanceof Class); assertEquals("Element is not the one expected", STEREOTYPED_CLASS_NAME, stereotypedClass.getName()); for (Iterator<Comment> iterator = model.getOwnedComments().iterator(); iterator.hasNext();) { Comment comment = iterator.next(); if (comment.getBody() == null) { emptyCommment = comment; } else { commment = comment; } } templateSignature = model.getOwnedTemplateSignature(); assertNotNull("The template signature must exist", templateSignature); templateParameter = templateSignature.getParameters().get(0); assertNotNull("The template parameters must exist", templateParameter); }
Source:
public void propertyChange(PropertyChangeEvent event) { Repository repo = historyPage.getCurrentRepo(); if (repo == null) { if (UIPreferences.RESOURCEHISTORY_SHOW_FIRST_PARENT_ONLY_DEFAULT .equals(event.getProperty())) { applyNewState(historyPage.store.getBoolean( UIPreferences.RESOURCEHISTORY_SHOW_FIRST_PARENT_ONLY_DEFAULT)); } return; } String repoSepcificKey = getRepositorySpecificFirstParentPreferenceKey( repo); if (UIPreferences.RESOURCEHISTORY_SHOW_FIRST_PARENT_ONLY_DEFAULT .equals(event.getProperty())) { if (!historyPage.store.contains(repoSepcificKey)) { applyNewState(historyPage.store.getBoolean( UIPreferences.RESOURCEHISTORY_SHOW_FIRST_PARENT_ONLY_DEFAULT)); } } if (P_REPOSITORY.equals(event.getProperty())) { applyNewState(historyPage.isShowFirstParentOnly()); } }

Target:
public void propertyChange(PropertyChangeEvent event) { Repository repo = historyPage.getCurrentRepo(); final String prefKey = UIPreferences.RESOURCEHISTORY_SHOW_FIRST_PARENT_ONLY_DEFAULT; if (repo == null) { if (prefKey.equals(event.getProperty())) { applyNewState(historyPage.store.getBoolean(prefKey)); } return; } String repoSpecificKey = getRepoSpecificKey(repo, prefKey); if (prefKey.equals(event.getProperty())) { if (!historyPage.store.contains(repoSpecificKey)) { applyNewState(historyPage.store.getBoolean(prefKey)); } } if (P_REPOSITORY.equals(event.getProperty())) { applyNewState(historyPage.isShowFirstParentOnly()); } }
Source:
public Object execute(ExecutionEvent event) throws ExecutionException { IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); if (window == null) { return null; } IWorkbenchPage page = window.getActivePage(); IWorkbenchPart part = page.getActivePart(); if (!(part instanceof FilterView)) { return null; } FilterView v = (FilterView) part; ITmfFilterTreeNode sel = v.getSelection(); if (sel == null) { sel = v.getFilterRoot(); } ITmfFilterTreeNode objectToPaste = FilterEditUtils.getTransferedTreeNode(); objectToPaste = objectToPaste.clone(); sel.addChild(objectToPaste); v.refresh(); v.setSelection(objectToPaste); return null; }

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); if (window == null) { return null; } IWorkbenchPage page = window.getActivePage(); IWorkbenchPart part = page.getActivePart(); if (!(part instanceof FilterView)) { return null; } FilterView v = (FilterView) part; ITmfFilterTreeNode sel = v.getSelection(); if (sel == null) { sel = v.getFilterRoot(); } ITmfFilterTreeNode objectToPaste = FilterEditUtils.getTransferredTreeNode(); objectToPaste = objectToPaste.clone(); sel.addChild(objectToPaste); v.refresh(); v.setSelection(objectToPaste); return null; }
Source:
public void dispose() { }

Target:
public void dispose() { fSyncLock.lock(); try { BuildThread buildThread = fBuildThread; if (buildThread != null) { buildThread.cancel(); } } finally { fSyncLock.unlock(); } }
Source:
public final void doGenerateAndDownload(StaplerRequest req, StaplerResponse rsp) throws ServletException, IOException, Descriptor.FormException { Jenkins.get().checkPermission(Jenkins.ADMINISTER); LOGGER.fine("Preparing response..."); rsp.setContentType("application/zip"); JSONObject json = req.getSubmittedForm(); if (!json.has("components")) { rsp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } LOGGER.fine("Parsing request..."); List<ObjectComponent<T>> components = new ArrayList<>(parseRequest(req)); rsp.addHeader("Content-Disposition", "inline; filename=" + SupportPlugin.getBundleFileName() + ";"); try { SupportPlugin.setRequesterAuthentication(Jenkins.getAuthentication()); try (ACLContext old = ACL.as(ACL.SYSTEM)) { SupportPlugin.writeBundle(rsp.getOutputStream(), components, new ComponentVisitor() { @Override public <C extends Component> void visit(Container container, C component) { ((ObjectComponent<T>)component).addContents(container, object); } }); } catch (IOException e) { LOGGER.log(Level.WARNING, e.getMessage(), e); } finally { SupportPlugin.clearRequesterAuthentication(); } } finally { LOGGER.fine("Response completed"); } }

Target:
public final void doGenerateAndDownload(StaplerRequest req, StaplerResponse rsp) throws ServletException, IOException, Descriptor.FormException { Jenkins.get().checkPermission(Jenkins.ADMINISTER); LOGGER.fine("Preparing response..."); rsp.setContentType("application/zip"); JSONObject json = req.getSubmittedForm(); if (json == null || !json.has("components")) { rsp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } LOGGER.fine("Parsing request..."); List<ObjectComponent<T>> components = new ArrayList<>(parseRequest(req)); rsp.addHeader("Content-Disposition", "inline; filename=" + SupportPlugin.getBundleFileName() + ";"); try { SupportPlugin.setRequesterAuthentication(Jenkins.getAuthentication()); try (ACLContext old = ACL.as(ACL.SYSTEM)) { SupportPlugin.writeBundle(rsp.getOutputStream(), components, new ComponentVisitor() { @Override public <C extends Component> void visit(Container container, C component) { ((ObjectComponent<T>)component).addContents(container, object); } }); } catch (IOException e) { LOGGER.log(Level.WARNING, e.getMessage(), e); } finally { SupportPlugin.clearRequesterAuthentication(); } } finally { LOGGER.fine("Response completed"); } }
Source:
public void testProviderUnavailableCreate() throws SourceUnavailableException { MockEventProcessor eventAdmin = new MockEventProcessor(); MockMemoryProvider provider = new MockMemoryProvider("Provider", "Provider", "v1.0", "DDF", new HashSet<>(), false, null); CatalogFramework framework = createDummyCatalogFramework(provider, storageProvider, eventAdmin, false); List<Metacard> metacards = new ArrayList<>(); MetacardImpl newCard = new MetacardImpl(); newCard.setId(null); metacards.add(newCard); CreateRequest create = new CreateRequestImpl(metacards); try { framework.create(create); } catch (IngestException e) { fail(); } }

Target:
public void testProviderUnavailableCreate() throws SourceUnavailableException { MockEventProcessor eventAdmin = new MockEventProcessor(); MockMemoryProvider provider = new MockMemoryProvider( PROVIDER, PROVIDER, PROVIDER_VERSION, "DDF", new HashSet<>(), false, null); CatalogFramework framework = createDummyCatalogFramework(provider, storageProvider, eventAdmin, false); List<Metacard> metacards = new ArrayList<>(); MetacardImpl newCard = new MetacardImpl(); newCard.setId(null); metacards.add(newCard); CreateRequest create = new CreateRequestImpl(metacards); try { framework.create(create); } catch (IngestException e) { fail(); } }
Source:
public void testDisableSlowConsumerReconnectWithKilled() throws Exception { ClientSessionFactory sf = createSessionFactory(locator); ClientSession session = addClientSession(sf.createSession(false, true, true, false)); session.createQueue(QUEUE, QUEUE, null, false); ClientProducer producer = addClientProducer(session.createProducer(QUEUE)); final int numMessages = 25; for (int i = 0; i < numMessages; i++) { producer.send(createTextMessage(session, "m" + i)); } ClientConsumer consumer = addClientConsumer(session.createConsumer(QUEUE)); session.start(); Thread.sleep(3000); RemotingService service = server.getRemotingService(); Set<RemotingConnection> connections = service.getConnections(); assertEquals(true, connections.isEmpty()); if (sf instanceof ClientSessionFactoryImpl) { int reconnectAttemps = ((ClientSessionFactoryImpl)sf).getReconnectAttempts(); assertEquals(0, reconnectAttemps); } else { throw new ActiveMQException(); } }

Target:
public void testDisableSlowConsumerReconnectWithKilled() throws Exception { ClientSessionFactory sf = createSessionFactory(locator); ClientSession session = addClientSession(sf.createSession(false, true, true, false)); session.createQueue(QUEUE, QUEUE, null, false); ClientProducer producer = addClientProducer(session.createProducer(QUEUE)); final int numMessages = 25; for (int i = 0; i < numMessages; i++) { producer.send(createTextMessage(session, "m" + i)); } ClientConsumer consumer = addClientConsumer(session.createConsumer(QUEUE)); session.start(); Thread.sleep(3000); RemotingService service = server.getRemotingService(); Set<RemotingConnection> connections = service.getConnections(); assertTrue(connections.isEmpty()); if (sf instanceof ClientSessionFactoryImpl) { int reconnectAttemps = ((ClientSessionFactoryImpl)sf).getReconnectAttempts(); assertEquals(0, reconnectAttemps); } else { fail("ClientSessionFactory is not the instance of ClientSessionFactoryImpl"); } }
Source:
public int compare(Method o1, Method o2) { return o2.getParameterTypes().length - o1.getParameterTypes().length; }

Target:
public int compare(Method o1, Method o2) { return Integer.compare(o2.getParameterTypes().length, o1.getParameterTypes().length); }
Source:
private static boolean isSimilar(Object expected, Object actual) { logger.debug("Comparing EXPECTED and ACTUAL {}", expected, actual); if (expected instanceof String && actual instanceof String) { return expected.equals(ANY_VALUE) || expected.equals(actual); } else if (expected instanceof Number && actual instanceof Number) { return expected.getClass() == actual.getClass() && expected.equals(actual); } else if (expected instanceof JSONObject && actual instanceof JSONObject) { return areJsonObjectsSimilarEnough((JSONObject) expected, (JSONObject) actual); } return false; }

Target:
private static boolean isSimilar(Object expected, Object actual) { logger.debug("Comparing expected and actual {}", expected, actual); if (expected instanceof String && actual instanceof String) { return expected.equals(ANY_VALUE) || expected.equals(actual); } else if (expected instanceof Number && actual instanceof Number) { return expected.getClass() == actual.getClass() && expected.equals(actual); } else if (expected instanceof JSONObject && actual instanceof JSONObject) { return areJsonObjectsSimilarEnough((JSONObject) expected, (JSONObject) actual); } return false; }
Source:
private boolean isAddAccessEnabled() { boolean returnValue; try { if (SystemGroup.OseeAccessAdmin.isCurrentUserMember()) { returnValue = true; } else if (policyTableViewer.getAccessControlList().size() > 0) { returnValue = AccessControlManager.hasPermission(accessControlledObject, PermissionEnum.FULLACCESS); } else { returnValue = true; } } catch (OseeCoreException ex) { OseeLog.log(Activator.class, Level.SEVERE, ex); returnValue = false; } return returnValue; }

Target:
private boolean isAddAccessEnabled() { boolean returnValue; try { if (!SystemGroup.OseeAccessAdmin.isCurrentUserMember() && policyTableViewer.getAccessControlList().size() > 0) { returnValue = AccessControlManager.hasPermission(accessControlledObject, PermissionEnum.FULLACCESS); } else { returnValue = true; } } catch (OseeCoreException ex) { OseeLog.log(Activator.class, Level.SEVERE, ex); returnValue = false; } return returnValue; }
Source:
private final List<Expression> extractNodes = extractNode() ? Collections.<Expression>singletonList(PrefixFunction.this) : Collections.<Expression>emptyList(); private final KeyPart childPart; PrefixKeyPart(KeyPart childPart) { this.childPart = childPart; }

Target:
Collections.<Expression>singletonList(PrefixFunction.this) : Collections.<Expression>emptyList(); private final KeyPart childPart; PrefixKeyPart(KeyPart childPart) { this.childPart = childPart; }
Source:
public void setMirroringEnabled(boolean value) { fMirroringEnabled = value; }

Target:
public final void setMirroringEnabled(boolean value) { fMirroringEnabled = value; }
Source:
private String getErrorMessage( List<MissingEntry> missingEntries ) { StringBuilder entries = new StringBuilder(); for ( MissingEntry entry : missingEntries ) { if ( missingEntries.indexOf( entry ) == missingEntries.size() - 1 ) { entries.append( "- " + entry.getName() + " - " + entry.getMissingPluginId() + "\n\n" ); } else { entries.append( "- " + entry.getName() + " - " + entry.getMissingPluginId() + "\n" ); } } return BaseMessages.getString( PKG, "MissingEntryDialog.MissingJobEntries", entries.toString() ); }

Target:
private String getErrorMessage( List<MissingEntry> missingEntries ) { StringBuilder entries = new StringBuilder(); for ( MissingEntry entry : missingEntries ) { entries.append( "- " + entry.getName() + " - " + entry.getMissingPluginId() + "\n" ); if ( missingEntries.indexOf( entry ) == missingEntries.size() - 1 ) { entries.append( '\n' ); } } return BaseMessages.getString( PKG, "MissingEntryDialog.MissingJobEntries", entries.toString() ); }
Source:
private IAction createHierarchicalAction() { IAction action = new Action(Messages.ControlFlowView_hierarchicalViewLabel, IAction.AS_RADIO_BUTTON) { @Override public void run() { ITmfTrace parentTrace = getTrace(); fFlatTraces.remove(parentTrace); for (ITmfTrace trace : TmfTraceManager.getTraceSet(parentTrace)) { final ITmfStateSystem ss = TmfStateSystemAnalysisModule.getStateSystem(trace, KernelAnalysisModule.ID); List<ControlFlowEntry> currentRootList = getEntryList(ss).stream().filter(e -> e instanceof ControlFlowEntry).map(e -> (ControlFlowEntry) e).collect(Collectors.toList()); addEntriesToHierarchicalTree(currentRootList, parentTrace, ss); refresh(); } } }; action.setChecked(true); action.setToolTipText(Messages.ControlFlowView_hierarchicalViewToolTip); action.setImageDescriptor(Activator.getDefault().getImageDescripterFromPath(IControlflowImageConstants.IMG_UI_HIERARCHICAL_VIEW)); return action; }

Target:
private IAction createHierarchicalAction() { IAction action = new Action(Messages.ControlFlowView_hierarchicalViewLabel, IAction.AS_RADIO_BUTTON) { @Override public void run() { ITmfTrace parentTrace = getTrace(); synchronized (fFlatTraces) { fFlatTraces.remove(parentTrace); for (ITmfTrace trace : TmfTraceManager.getTraceSet(parentTrace)) { final ITmfStateSystem ss = TmfStateSystemAnalysisModule.getStateSystem(trace, KernelAnalysisModule.ID); List<ControlFlowEntry> currentRootList = getEntryList(ss).stream().filter(e -> e instanceof ControlFlowEntry).map(e -> (ControlFlowEntry) e).collect(Collectors.toList()); addEntriesToHierarchicalTree(currentRootList, parentTrace, ss); } } refresh(); } }; action.setChecked(true); action.setToolTipText(Messages.ControlFlowView_hierarchicalViewToolTip); return action; }
Source:
private static String readUrl(String urlString) throws Exception { BufferedReader reader = null; try { URL url = new URL(urlString); reader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buffer = new StringBuffer(); int read; char[] chars = new char[1024]; while ((read = reader.read(chars)) != -1) buffer.append(chars, 0, read); return buffer.toString(); } finally { if (reader != null) reader.close(); } }

Target:
private static String readUrl(String urlString) throws Exception { URL url = new URL(urlString); try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()))) { StringBuffer buffer = new StringBuffer(); int read; char[] chars = new char[1024]; while ((read = reader.read(chars)) != -1) buffer.append(chars, 0, read); return buffer.toString(); } }
Source:
public boolean equals(final Object obj) { if (!(obj instanceof DueDateAmountMap)) { return false; } return innerMap.equals(obj); }

Target:
public boolean equals(final Object obj) { return obj instanceof DueDateAmountMap && innerMap.equals(obj); }
Source:
public void findByNullSchema() throws Exception { context.turnOffAuthorisationSystem(); getClient().perform(get("/api/core/metadatafields/search/bySchema")) .andExpect(status().isUnprocessableEntity()); }

Target:
public void findByNullSchema() throws Exception { getClient().perform(get("/api/core/metadatafields/search/bySchema")) .andExpect(status().isUnprocessableEntity()); }
Source:
public List<Contentlet> getRelatedContentFromIndex(Contentlet contentlet,Relationship rel, boolean pullByParent, User user, boolean respectFrontendRoles) throws DotDataException, DotSecurityException { try { return getRelatedContentESQuery(contentlet, rel, user, respectFrontendRoles, pullByParent); } catch (Exception e){ final String errorMessage = "Unable to look up related content for contentlet with identifier " + contentlet.getIdentifier(); if (e instanceof SearchPhaseExecutionException || e .getCause() instanceof SearchPhaseExecutionException) { Logger.warnAndDebug(ESContentletAPIImpl.class, errorMessage + ". An empty list will be returned", e); return Collections.emptyList(); } throw new DotDataException(errorMessage, e); } }

Target:
public List<Contentlet> getRelatedContentFromIndex(Contentlet contentlet,Relationship rel, boolean pullByParent, User user, boolean respectFrontendRoles) throws DotDataException, DotSecurityException { try { return getRelatedContentESQuery(contentlet, rel, user, respectFrontendRoles, pullByParent); } catch (Exception e){ final String errorMessage = "Unable to look up related content for contentlet with identifier " + contentlet.getIdentifier() + ". Relationship Name: " + rel.getRelationTypeValue(); if (e instanceof SearchPhaseExecutionException || e .getCause() instanceof SearchPhaseExecutionException) { Logger.warnAndDebug(ESContentletAPIImpl.class, errorMessage + ". An empty list will be returned", e); return Collections.emptyList(); } throw new DotDataException(errorMessage, e); } }
Source:
public <T> Provider<T> scope(final Key<T> key, final Provider<T> unscopedProvider) { return new Provider<T>() { @Override public T get() { CacheableContext cacheableContext = cacheableContextProvider.get(); String resourcePath = resourcePathProvider.get(); T unscoped = unscopedProvider.get(); T scoped = cacheableContext.putIfAbsent(resourcePath, key, unscoped); return scoped == null ? unscoped : scoped; } }; }

Target:
public <T> Provider<T> scope(final Key<T> key, final Provider<T> unscopedProvider) { return new Provider<T>() { @SuppressWarnings("unchecked") @Override public T get() { CacheableContext cacheableContext = cacheableContextProvider.get(); String resourcePath = resourcePathProvider.get(); CacheableContextKey contextKey = new CacheableContextKey(resourcePath, key); T value = (T) cacheableContext.get(contextKey); if (value == null) { value = unscopedProvider.get(); cacheableContext.put(contextKey, value); } return value; } }; }