auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void processKey(KeyCacheObject key) throws IgniteCheckedException { assert nonNull(key); while (true) { try { checkCancelled(); GridCacheEntryEx entry = cctx.cache().entryEx(key); try { entry.updateIndex(rowFilter, clo, indexCacheStat); } finally { entry.touch(); } break; } catch (GridDhtInvalidPartitionException ignore) { break; } catch (GridCacheEntryRemovedException ignored) { } } }

Target:
private void processKey(KeyCacheObject key) throws IgniteCheckedException { assert nonNull(key); while (true) { try { checkCancelled(); GridCacheEntryEx entry = cctx.cache().entryEx(key); try { entry.updateIndex(wrappedClo); } finally { entry.touch(); } break; } catch (GridDhtInvalidPartitionException ignore) { break; } catch (GridCacheEntryRemovedException ignored) { } } }
Source:
public Disk(DataNode dataNode, JSONObject jsonObject, ClusterMapConfig clusterMapConfig) throws JSONException { if (logger.isTraceEnabled()) { logger.trace("Disk " + jsonObject.toString()); } this.dataNode = dataNode; this.mountPath = jsonObject.getString("mountPath"); try { ResourceStatePolicyFactory resourceStatePolicyFactory = Utils .getObj(clusterMapConfig.clusterMapResourceStatePolicyFactory, this, HardwareState.valueOf(jsonObject.getString("hardwareState")), clusterMapConfig); this.diskStatePolicy = resourceStatePolicyFactory.getResourceStatePolicy(); } catch (Exception e) { logger.error("Error during start {}", e); throw new InstantiationError("Error during start " + e); } this.capacityInBytes = jsonObject.getLong("capacityInBytes"); validate(); }

Target:
public Disk(DataNode dataNode, JSONObject jsonObject, ClusterMapConfig clusterMapConfig) throws JSONException { if (logger.isTraceEnabled()) { logger.trace("Disk " + jsonObject.toString()); } this.dataNode = dataNode; this.mountPath = jsonObject.getString("mountPath"); try { ResourceStatePolicyFactory resourceStatePolicyFactory = Utils .getObj(clusterMapConfig.clusterMapResourceStatePolicyFactory, this, HardwareState.valueOf(jsonObject.getString("hardwareState")), clusterMapConfig); this.diskStatePolicy = resourceStatePolicyFactory.getResourceStatePolicy(); } catch (Exception e) { logger.error("Error creating resource state policy when instantiating a disk " + e); throw new IllegalStateException("Error creating resource state policy when instantiating a disk: " + mountPath, e); } this.capacityInBytes = jsonObject.getLong("capacityInBytes"); validate(); }
Source:
public ConsumerDTO clone() { ConsumerDTO copy = super.clone(); OwnerDTO owner = this.getOwner(); copy.owner = owner != null ? (OwnerDTO) owner.clone() : null; EnvironmentDTO environment = this.getEnvironment(); copy.environment = environment != null ? (EnvironmentDTO) environment.clone() : null; Map<String, String> facts = this.getFacts(); copy.facts = facts != null ? new HashMap<String, String>(facts) : null; Set<ConsumerInstalledProductDTO> installedProducts = this.getInstalledProducts(); if (installedProducts != null) { copy.installedProducts = new HashSet<ConsumerInstalledProductDTO>(); for (ConsumerInstalledProductDTO installedProduct: installedProducts) { copy.installedProducts.add(installedProduct.clone()); } } Set<CapabilityDTO> capabilities = this.getCapabilities(); if (capabilities != null) { copy.capabilities = new HashSet<CapabilityDTO>(); for (CapabilityDTO capabilityDTO: capabilities) { copy.capabilities.add(capabilityDTO.clone()); } } HypervisorIdDTO hypervisorId = this.getHypervisorId(); copy.hypervisorId = hypervisorId != null ? (HypervisorIdDTO) hypervisorId.clone() : null; Set<String> contentTags = this.getContentTags(); copy.contentTags = contentTags != null ? new HashSet<String>(contentTags) : null; ConsumerTypeDTO type = this.getType(); copy.type = type != null ? (ConsumerTypeDTO) type.clone() : null; CertificateDTO cert = this.getIdCert(); copy.idCert = cert != null ? (CertificateDTO) cert.clone() : null; return copy; }

Target:
public ConsumerDTO clone() { ConsumerDTO copy = super.clone(); copy.owner = owner != null ? owner.clone() : null; copy.environment = environment != null ? environment.clone() : null; copy.setFacts(this.getFacts()); copy.setInstalledProducts(this.getInstalledProducts()); copy.setCapabilities(this.getCapabilities()); copy.hypervisorId = hypervisorId != null ? hypervisorId.clone() : null; copy.setContentTags(this.getContentTags()); copy.type = type != null ? type.clone() : null; copy.idCert = idCert != null ? idCert.clone() : null; return copy; }
Source:
private void startWebMetrics() throws Exception { final MetricRegistry registry = SERVICE_PROVIDER.getInstance(MetricsManager.class) .getRegistry(); MetricsUtility .addGauge("JETTY-NumIdleThreads", registry, this.queuedThreadPool::getIdleThreads); MetricsUtility.addGauge("JETTY-NumTotalThreads", registry, this.queuedThreadPool::getThreads); MetricsUtility.addGauge("JETTY-NumQueueSize", registry, this.queuedThreadPool::getQueueSize); MetricsUtility .addGauge("WEB-NumQueuedFlows", registry, this.executorManager::getQueuedFlowSize); MetricsUtility .addGauge("WEB-NumRunningFlows", registry, () -> this.executorManager.getRunningFlows().size()); logger.info("starting reporting Web Server Metrics"); SERVICE_PROVIDER.getInstance(MetricsManager.class).startReporting("AZ-WEB", this.props); }

Target:
private void startWebMetrics() throws Exception { MetricsUtility .addGauge("JETTY-NumIdleThreads", this.registry, this.queuedThreadPool::getIdleThreads); MetricsUtility .addGauge("JETTY-NumTotalThreads", this.registry, this.queuedThreadPool::getThreads); MetricsUtility .addGauge("JETTY-NumQueueSize", this.registry, this.queuedThreadPool::getQueueSize); MetricsUtility .addGauge("WEB-NumQueuedFlows", this.registry, this.executorManager::getQueuedFlowSize); MetricsUtility .addGauge("WEB-NumRunningFlows", this.registry, () -> this.executorManager.getRunningFlows().size()); logger.info("starting reporting Web Server Metrics"); this.metricsManager.startReporting("AZ-WEB", this.props); }
Source:
public static <T> Comparator<Tag<T>> tagIdComparator() { return Comparator.nullsFirst(Comparator.<Tag<T>, ResourceLocation>comparing(Tag::getId, Comparator.nullsFirst(Comparator.naturalOrder()))); }

Target:
public static <T> Comparator<Tag<T>> tagIdComparator() { return Comparator.comparing(Tag::getId); }
Source:
public void setFluxUnits(YUnit newUnit) throws UnitsException { if (specValues == null) return; if (fluxValues != null) { setFluxValues(units.convertY(fluxValues, specValues, fluxUnits, specUnits, newUnit)); } if (originalFluxValues != null) { setOriginalFluxValues(units.convertY(originalFluxValues, specValues, fluxUnits, specUnits, newUnit)); } if (fluxErrValues != null) { setFluxErrValues(units.convertY(fluxErrValues, specValues, fluxUnits, specUnits, newUnit)); } if (fluxErrValuesLo != null) { setFluxErrValuesLo(units.convertY(fluxErrValuesLo, specValues, fluxUnits, specUnits, newUnit)); } if (fluxErrValuesHi != null) { setFluxErrValuesHi(units.convertY(fluxErrValuesLo, specValues, fluxUnits, specUnits, newUnit)); } fluxUnits = newUnit; for (int i=0; i<this.getColumnCount(); i++) { if (StringUtils.contains(getColumnInfo(i).getUtype(), "flux")) getColumnInfo(i).setUnitString(newUnit.toString()); } }

Target:
public void setFluxUnits(YUnit newUnit) throws UnitsException { if (specValues == null) return; setFluxValues(units.convertY(fluxValues, specValues, fluxUnits, specUnits, newUnit)); setOriginalFluxValues(units.convertY(originalFluxValues, specValues, fluxUnits, specUnits, newUnit)); setFluxErrValues(units.convertY(fluxErrValues, specValues, fluxUnits, specUnits, newUnit)); setFluxErrValuesLo(units.convertY(fluxErrValuesLo, specValues, fluxUnits, specUnits, newUnit)); setFluxErrValuesHi(units.convertY(fluxErrValuesLo, specValues, fluxUnits, specUnits, newUnit)); fluxUnits = newUnit; for (int i=0; i<this.getColumnCount(); i++) { if (StringUtils.contains(getColumnInfo(i).getUtype(), "flux")) getColumnInfo(i).setUnitString(newUnit.toString()); } }
Source:
default boolean isNull() { throw new UnsupportedOperationException("DimensionSelector cannot be operated as numeric ColumnValueSelector" + this.getClass()); }

Target:
default boolean isNull() { return false; }
Source:
public void deleteAll(){ getHibernateTemplate().deleteAll(getHibernateTemplate().find( "from KeyValue")); }

Target:
public void deleteAll(){ getHibernateTemplate().bulkUpdate("delete from KeyValue"); }
Source:
public void dragOver(DropTargetDragEvent dragEvent) { NlDropEvent event = new NlDropEvent(dragEvent); Point location = event.getLocation(); myLastMouseX = location.x; myLastMouseY = location.y; ScreenView screenView = mySurface.getScreenView(myLastMouseX, myLastMouseY); if (screenView != null && myCurrentInteraction instanceof DragDropInteraction) { DragDropInteraction interaction = (DragDropInteraction)myCurrentInteraction; assert interaction.getTransferItem() != null; interaction.update(myLastMouseX, myLastMouseY, myLastStateMask); DragType dragType = event.getDropAction() == DnDConstants.ACTION_COPY ? DragType.COPY : DragType.MOVE; interaction.setType(dragType); NlModel model = screenView.getModel(); InsertType insertType = model.determineInsertType(dragType, interaction.getTransferItem(), true ); event.accept(insertType.isCreate() ? DnDConstants.ACTION_COPY : event.getDropAction()); } else { event.reject(); } }

Target:
public void dragOver(DropTargetDragEvent dragEvent) { NlDropEvent event = new NlDropEvent(dragEvent); Point location = event.getLocation(); myLastMouseX = location.x; myLastMouseY = location.y; ScreenView screenView = mySurface.getScreenView(myLastMouseX, myLastMouseY); if (screenView != null && myCurrentInteraction instanceof DragDropInteraction) { DragDropInteraction interaction = (DragDropInteraction)myCurrentInteraction; interaction.update(myLastMouseX, myLastMouseY, myLastStateMask); DragType dragType = event.getDropAction() == DnDConstants.ACTION_COPY ? DragType.COPY : DragType.MOVE; interaction.setType(dragType); NlModel model = screenView.getModel(); InsertType insertType = model.determineInsertType(dragType, interaction.getTransferItem(), true ); event.accept(insertType.isCreate() ? DnDConstants.ACTION_COPY : event.getDropAction()); } else { event.reject(); } }
Source:
public void executeTask() throws MojoExecutionException, MojoFailureException { if (serverId == null) { File currentProperties = Server.checkCurrentDirForServer(); if (currentProperties != null) serverId = currentProperties.getName(); } serverId = wizard.promptForExistingServerIdIfMissing(serverId); Server server = loadValidatedServer(serverId); port = Integer.valueOf(server.getPort()); String message = "Set server port or use default from parameters"; this.requestPortChnage(message, server); serverHelper = new ServerHelper(wizard); this.validatePort(); wizard.showMessage(String.format("Using %s", port)); server.setParam("tomcat.port", String.valueOf(port)); server.save(); File serverPath = server.getServerDirectory(); serverPath.mkdirs(); File userDir = new File(System.getProperty("user.dir")); if (Project.hasProject(userDir)) { Project config = Project.loadProject(userDir); if (config.isOpenmrsModule()) { String artifactId = config.getArtifactId(); String groupId = config.getGroupId(); String version = config.getVersion(); if ((artifactId != null) && (groupId != null) && version != null) { getLog().info("OpenMRS module detected, installing before run..."); Deploy deployer = new Deploy(this); deployer.deployModule(serverPath.getName(), groupId, artifactId, version); } } } if (server.hasWatchedProjects()) { new Build(this, serverId).executeTask(); } if (Boolean.FALSE.equals(fork)) { new RunTomcat(serverId, port, mavenSession, mavenProject, pluginManager, wizard).execute(); } else { runInFork(server); } }

Target:
public void executeTask() throws MojoExecutionException, MojoFailureException { if (serverId == null) { File currentProperties = Server.checkCurrentDirForServer(); if (currentProperties != null) serverId = currentProperties.getName(); } serverId = wizard.promptForExistingServerIdIfMissing(serverId); Server server = loadValidatedServer(serverId); port = (System.getProperty("port") != null ? Integer.valueOf(System.getProperty("port")) : Integer.valueOf(server.getPort())); serverHelper = new ServerHelper(wizard); this.validatePort(); wizard.showMessage(String.format("Using %s", port)); server.setParam("tomcat.port", String.valueOf(port)); server.save(); File serverPath = server.getServerDirectory(); serverPath.mkdirs(); File userDir = new File(System.getProperty("user.dir")); if (Project.hasProject(userDir)) { Project config = Project.loadProject(userDir); if (config.isOpenmrsModule()) { String artifactId = config.getArtifactId(); String groupId = config.getGroupId(); String version = config.getVersion(); if ((artifactId != null) && (groupId != null) && version != null) { getLog().info("OpenMRS module detected, installing before run..."); Deploy deployer = new Deploy(this); deployer.deployModule(serverPath.getName(), groupId, artifactId, version); } } } if (server.hasWatchedProjects()) { new Build(this, serverId).executeTask(); } if (Boolean.FALSE.equals(fork)) { new RunTomcat(serverId, port, mavenSession, mavenProject, pluginManager, wizard).execute(); } else { runInFork(server); } }
Source:
private void checkNewRepositoryParameters(IProcess2 process, Set<String> names) { ContextManagerHelper helper = new ContextManagerHelper(process.getContextManager()); Set<ContextItem> contextItemList = helper.getContextItems(); ContextItem item = (ContextItem) result.getParameter(); if (contextItemList.contains(item)) { ContextType contextType = getDefaultContextType(item); for (String paramName : names) { ContextParameterType contextParameterType = ContextUtils.getContextParameterTypeByName(contextType, paramName); helper.addContextParameterType(contextParameterType); } } String remark = result.getRemark(); if (remark != null && remark.endsWith(UpdatesConstants.CONTEXT_MODE)) { ConnectionContextHelper.showContextGroupDialog(process, item, process.getContextManager(), names); } }

Target:
private void checkNewRepositoryParameters(IProcess2 process, Set<String> names) { ContextManagerHelper helper = new ContextManagerHelper(process.getContextManager()); Set<ContextItem> contextItemList = helper.getContextItems(); ContextItem item = (ContextItem) result.getParameter(); if (contextItemList.contains(item)) { ContextType contextType = getDefaultContextType(item); for (String paramName : names) { ContextParameterType contextParameterType = ContextUtils.getContextParameterTypeByName(contextType, paramName); helper.addContextParameterType(contextParameterType); } } String remark = result.getRemark(); ConnectionContextHelper.showContextGroupDialog(process, item, process.getContextManager(), names, remark != null && remark.endsWith(UpdatesConstants.CONTEXT_MODE)); }
Source:
public void testBlockLogoffAfterLogon() throws Exception { int freePort = AvailablePortFinder.getNextAvailable(); ServerThread serverThread = new ServerThread(freePort); try { serverThread.setDaemon(true); serverThread.start(); serverThread.waitForInitialization(); SessionID clientSessionID = new SessionID(FixVersions.BEGINSTRING_FIX42, "TW", "ISLD"); SessionSettings settings = getClientSessionSettings(clientSessionID, freePort); ClientApplication clientApplication = new ClientApplication(); final SocketInitiator initiator = new SocketInitiator(clientApplication, new MemoryStoreFactory(), settings, new DefaultMessageFactory()); try { clientApplication.stopAfterLogon(initiator); clientApplication.setUpLogonExpectation(); initiator.start(); assertFalse("wrong logon status", initiator.isLoggedOn()); assertEquals("wrong # of session", 1, initiator.getManagedSessions().size()); } finally { initiator.stop(); } } finally { serverThread.interrupt(); serverThread.join(); } }

Target:
public void testBlockLogoffAfterLogon() throws Exception { int freePort = AvailablePortFinder.getNextAvailable(); ServerThread serverThread = new ServerThread(freePort); try { serverThread.setDaemon(true); serverThread.start(); serverThread.waitForInitialization(); SessionID clientSessionID = new SessionID(FixVersions.BEGINSTRING_FIX42, "TW", "ISLD"); SessionSettings settings = getClientSessionSettings(clientSessionID, freePort); ClientApplication clientApplication = new ClientApplication(); final SocketInitiator initiator = new SocketInitiator(clientApplication, new MemoryStoreFactory(), settings, new DefaultMessageFactory()); try { clientApplication.stopAfterLogon(initiator); clientApplication.setUpLogonExpectation(); initiator.block(); assertFalse("wrong logon status", initiator.isLoggedOn()); assertEquals("wrong # of session", 1, initiator.getManagedSessions().size()); } finally { initiator.stop(); } } finally { serverThread.interrupt(); serverThread.join(); } }
Source:
public ToneMappingNode(Context context) { screenGrabber = context.get(ScreenGrabber.class); DisplayResolutionDependentFBOs displayResolutionDependentFBOs = context.get(DisplayResolutionDependentFBOs.class); FBO toneMappingFbo = requiresFBO(new FBOConfig(TONE_MAPPING_FBO, FULL_SCALE, FBO.Type.HDR), displayResolutionDependentFBOs); addDesiredStateChange(new BindFbo(toneMappingFbo)); addDesiredStateChange(new SetViewportToSizeOf(toneMappingFbo)); addDesiredStateChange(new EnableMaterial(TONE_MAPPING_MATERIAL)); toneMappingMaterial = getMaterial(TONE_MAPPING_MATERIAL); int textureSlot = 0; addDesiredStateChange(new SetInputTextureFromFbo(textureSlot, displayResolutionDependentFBOs.get(INITIAL_POST_FBO), ColorTexture, displayResolutionDependentFBOs, TONE_MAPPING_MATERIAL, "texScene")); }

Target:
public ToneMappingNode(Context context) { screenGrabber = context.get(ScreenGrabber.class); DisplayResolutionDependentFBOs displayResolutionDependentFBOs = context.get(DisplayResolutionDependentFBOs.class); FBO toneMappingFbo = requiresFBO(new FBOConfig(TONE_MAPPING_FBO_URI, FULL_SCALE, FBO.Type.HDR), displayResolutionDependentFBOs); addDesiredStateChange(new BindFbo(toneMappingFbo)); addDesiredStateChange(new SetViewportToSizeOf(toneMappingFbo)); addDesiredStateChange(new EnableMaterial(TONE_MAPPING_MATERIAL_URN)); toneMappingMaterial = getMaterial(TONE_MAPPING_MATERIAL_URN); int textureSlot = 0; addDesiredStateChange(new SetInputTextureFromFbo(textureSlot, INITIAL_POST_FBO_URI, ColorTexture, displayResolutionDependentFBOs, TONE_MAPPING_MATERIAL_URN, "texScene")); }
Source:
void reportInternal(ReportPoint point) { try { validatePoint(point, validationConfig); } catch (DeltaCounterValueException e) { discardedCounterSupplier.get().inc(); return; } receivedPointLag.update(Clock.now() - point.getTimestamp()); if (point.getValue() instanceof Histogram && recompressor != null) { Histogram histogram = (Histogram) point.getValue(); point.setValue(recompressor.apply(histogram)); } if (point.getValue() instanceof Histogram) { histogramTagCount.update(point.getAnnotations().size()); } else { pointTagCount.update(point.getAnnotations().size()); } final String strPoint = serializer.apply(point); getTask().add(strPoint); getReceivedCounter().inc(); if (validItemsLogger != null) validItemsLogger.info(strPoint); }

Target:
void reportInternal(ReportPoint point) { receivedTagCount.update(point.getAnnotations().size()); try { validatePoint(point, validationConfig); } catch (DeltaCounterValueException e) { discardedCounterSupplier.get().inc(); return; } receivedPointLag.update(Clock.now() - point.getTimestamp()); if (point.getValue() instanceof Histogram && recompressor != null) { Histogram histogram = (Histogram) point.getValue(); point.setValue(recompressor.apply(histogram)); } final String strPoint = serializer.apply(point); getTask().add(strPoint); getReceivedCounter().inc(); if (validItemsLogger != null) validItemsLogger.info(strPoint); }
Source:
public long getStartTimeoutMillis() { long currentTimeMillis = System.currentTimeMillis(); long deadLine = startTimeMillis + workspaceStartTimeoutMillis; long timeout = deadLine - currentTimeMillis; return timeout < 0 ? 0 : timeout; }

Target:
public long getStartTimeoutMillis() { long deadLine = startTimeMillis + workspaceStartTimeoutMillis; long timeout = deadLine - System.currentTimeMillis(); return Math.max(0, timeout); }
Source:
public void testExecuteBatchPreparedStatement() throws Exception { try (Connection conn = DriverManager.getConnection(connectionStr)) { PreparedStatement stmt = conn.prepareStatement("insert into test (id, string_field) values (?, ?)"); stmt.setInt(1, 2); stmt.setString(2, "foo"); stmt.addBatch(); stmt.setInt(1, 3); stmt.setString(2, "bar"); stmt.addBatch(); stmt.setInt(1, 4); stmt.setString(2, "baz"); stmt.addBatch(); int[] results = stmt.executeBatch(); assertArrayEquals(new int[]{1, 1, 1}, results); conn.createStatement().execute("refresh table test"); ResultSet resultSet = conn.createStatement().executeQuery("select count(*) from test"); assertThat(resultSet.next(), is(true)); assertThat(resultSet.getLong(1), is(4L)); } }

Target:
public void testExecuteBatchPreparedStatement() throws Exception { try (Connection conn = DriverManager.getConnection(connectionString)) { PreparedStatement stmt = conn.prepareStatement("insert into test (id) values (?)"); stmt.setInt(1, 2); stmt.addBatch(); stmt.setInt(1, 4); stmt.addBatch(); int[] results = stmt.executeBatch(); assertArrayEquals(new int[]{1, 1}, results); conn.createStatement().execute("refresh table test"); ResultSet resultSet = conn.createStatement().executeQuery("select count(*) from test"); assertThat(resultSet.next(), is(true)); assertThat(resultSet.getLong(1), is(2L)); } }
Source:
public String toString() { StringBuilder builder = new StringBuilder(); builder.append(getName()) .append(" {id=") .append(getId()) .append(", vdsId=") .append(getVdsId()) .append(", name=") .append(getName()) .append(", macAddress=") .append(getMacAddress()) .append(", networkName=") .append(getNetworkName()) .append(", bondName=") .append(getBondName()) .append(", bootProtocol=") .append(getBootProtocol()) .append(", address=") .append(getAddress()) .append(", subnet=") .append(getSubnet()) .append(", gateway=") .append(getGateway()) .append(", mtu=") .append(getMtu()) .append(", bridged=") .append(isBridged()) .append(", speed=") .append(getSpeed()) .append(", type=") .append(getType()) .append(", networkImplementationDetails=") .append(getNetworkImplementationDetails()) .append("]"); return builder.toString(); }

Target:
public String toString() { StringBuilder builder = new StringBuilder(); builder.append(getName()) .append(" {id=") .append(getId()) .append(", vdsId=") .append(getVdsId()) .append(", name=") .append(getName()) .append(", macAddress=") .append(getMacAddress()) .append(", networkName=") .append(getNetworkName()) .append(", bondName=") .append(getBondName()) .append(", bootProtocol=") .append(getBootProtocol()) .append(", address=") .append(getAddress()) .append(", subnet=") .append(getSubnet()) .append(", gateway=") .append(getGateway()) .append(", mtu=") .append(getMtu()) .append(", bridged=") .append(isBridged()) .append(", speed=") .append(getSpeed()) .append(", type=") .append(getType()) .append(", networkImplementationDetails=") .append(getNetworkImplementationDetails()) .append("}"); return builder.toString(); }
Source:
public WebElement findElement(SearchContext context) { for (By by : bys) { WebElement element = getSearchingFunction(by).apply(context); if (element != null) { return element; } } throw new NoSuchElementException("Cannot locate an element using " + toString()); }

Target:
public WebElement findElement(SearchContext context) { return bys.stream() .map(by -> getSearchingFunction(by).apply(context)) .filter(Optional::isPresent) .map(Optional::get) .findFirst() .orElseThrow(() -> new NoSuchElementException("Cannot locate an element using " + toString())); }
Source:
public AuthUser authenticate(final AuthRequest request) throws AuthException { List<AuthUser> authUsers = Lists.newArrayList(); List<AuthException> authExs = Lists.newArrayList(); for (AuthBackend backend : authBackends) { try { authUsers.add(checkNotNull(backend.authenticate(request))); } catch (MissingCredentialsException ex) { } catch (AuthException ex) { authExs.add(ex); } } if (authExs.isEmpty() && authUsers.isEmpty()) { throw new MissingCredentialsException(); } else if (authExs.isEmpty() && authUsers.size() == 1) { return authUsers.get(0); } else if (authExs.size() == 1 && authUsers.isEmpty()) { throw authExs.get(0); } String msg = String.format("Multiple AuthBackends attempted to handle request:" + " authUsers=%s authExs=%s", authUsers, authExs); throw new AuthException(msg); }

Target:
public AuthUser authenticate(final AuthRequest request) throws AuthException { List<AuthUser> authUsers = Lists.newArrayList(); List<AuthException> authExs = Lists.newArrayList(); for (AuthBackend backend : authBackends) { try { authUsers.add(checkNotNull(backend.authenticate(request))); } catch (MissingCredentialsException ex) { } catch (AuthException ex) { authExs.add(ex); } } if (authExs.isEmpty()) { return authUsers.get(0); } else if (authExs.size() == 1) { throw authExs.get(0); } else if (authExs.isEmpty() && authUsers.isEmpty()) { throw new MissingCredentialsException(); } String msg = String.format("Multiple AuthBackends attempted to handle request:" + " authUsers=%s authExs=%s", authUsers, authExs); throw new AuthException(msg); }
Source:
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (totalItemCount < mPreviousTotalItemCount) { mCurrentPage = mStartingPageIndex; mPreviousTotalItemCount = totalItemCount; if (totalItemCount == 0) { mLoading = true; } } if (mLoading && (totalItemCount > mPreviousTotalItemCount)) { mLoading = false; mPreviousTotalItemCount = totalItemCount; mCurrentPage++; } if (!mLoading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + mVisibleThreshold)) { mLoading = onLoadMore(mCurrentPage + 1, totalItemCount); } }

Target:
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (totalItemCount < mPreviousTotalItemCount) { mCurrentPage = mStartingPageIndex; mPreviousTotalItemCount = totalItemCount; if (totalItemCount == 0) { mLoading = true; } } if (mLoading && (totalItemCount > mPreviousTotalItemCount)) { mLoading = false; mPreviousTotalItemCount = totalItemCount; mCurrentPage++; } if (!mLoading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + mVisibleThreshold)) { mLoading = onLoadMore(mCurrentPage + 1); } }
Source:
private static void checkSensitiveArgument(RegularArgument regularArgument, SubscriptionContext ctx) { if (regularArgument.expression().is(Tree.Kind.NAME)) { Symbol symbol = ((Name) regularArgument.expression()).symbol(); if (symbol == null) { return; } List<Usage> bindingUsages = symbol.usages().stream().filter(Usage::isBindingUsage).collect(Collectors.toList()); if (bindingUsages.size() == 1) { Usage bindingUsage = bindingUsages.get(0); if (bindingUsage.kind().equals(Usage.Kind.ASSIGNMENT_LHS)) { AssignmentStatement assignmentStatement = (AssignmentStatement) TreeUtils.firstAncestorOfKind(bindingUsage.tree(), Tree.Kind.ASSIGNMENT_STMT); if (assignmentStatement.assignedValue().is(Tree.Kind.STRING_LITERAL, Tree.Kind.NUMERIC_LITERAL)) { ctx.addIssue(regularArgument, PREDICTABLE_SALT_MESSAGE).secondary(assignmentStatement, null); } } } } if (regularArgument.expression().is(Tree.Kind.STRING_LITERAL)) { ctx.addIssue(regularArgument, PREDICTABLE_SALT_MESSAGE); } }

Target:
private static void checkSensitiveArgument(RegularArgument regularArgument, SubscriptionContext ctx) { if (regularArgument.expression().is(Tree.Kind.NAME)) { Expression expression = Expressions.singleAssignedValue((Name) regularArgument.expression()); if (expression == null) { return; } if (expression.is(Tree.Kind.STRING_LITERAL)) { AssignmentStatement assignmentStatement = (AssignmentStatement) TreeUtils.firstAncestorOfKind(expression, Tree.Kind.ASSIGNMENT_STMT); ctx.addIssue(regularArgument, PREDICTABLE_SALT_MESSAGE).secondary(assignmentStatement, null); } } if (regularArgument.expression().is(Tree.Kind.STRING_LITERAL)) { ctx.addIssue(regularArgument, PREDICTABLE_SALT_MESSAGE); } }
Source:
private static Metadata deserialize(byte[] blob) { try { return new ObjectMapper().readValue(blob, Metadata.class); } catch (IOException e) { throw new RuntimeException(e); } }

Target:
private static Metadata deserialize(byte[] blob) { try { return MAPPER.readValue(blob, Metadata.class); } catch (IOException e) { throw new RuntimeException(e); } }
Source:
public User updateUser(User user, Map<String, Boolean> requiredAttributes, List<String> allSimpleMultiValuedAttributes) throws CharonException, BadRequestException, NotFoundException { if (user.getId() == null) { throw new NotFoundException("No user found with the id : " + user.getId()); } inMemoryUserList.replace(user.getId(), user); return (User) CopyUtil.deepCopy(user); }

Target:
public User updateUser(User user, Map<String, Boolean> requiredAttributes, List<String> allSimpleMultiValuedAttributes) throws CharonException, BadRequestException, NotFoundException { if (StringUtils.isEmpty(user.getId())) { throw new NotFoundException("No user found. User id is empty."); } inMemoryUserList.replace(user.getId(), user); return (User) CopyUtil.deepCopy(user); }
Source:
public void setZabState(ZabState zabState) { this.zabState.set(zabState); LOG.info("Peer state changed: " + getDetailedPeerState()); }

Target:
public void setZabState(ZabState zabState) { this.zabState.set(zabState); LOG.info("Peer state changed: {}", getDetailedPeerState()); }
Source:
public void returnsGreatestPunchedTimeBeforeTimestampEvenIfNotAssociatedWithGreatestEligibleTimestamp() { puncherStore.put(TIMESTAMP_BETWEEN_1_AND_2, WALL_CLOCK_BETWEEN_2_AND_3); assertThat(puncherStore.getMillisForTimestamp(TIMESTAMP_2)) .isEqualTo(WALL_CLOCK_BETWEEN_2_AND_3) .isNotEqualTo(WALL_CLOCK_2); }

Target:
public void returnsGreatestPunchedTimeBeforeTimestampEvenIfNotAssociatedWithGreatestEligibleTimestamp() { puncherStore = initializePuncherStore(PUNCHER_HISTORY_WITH_CLOCK_DRIFT); assertThat(puncherStore.getMillisForTimestamp(TIMESTAMP_2)) .isEqualTo(WALL_CLOCK_2) .isNotEqualTo(WALL_CLOCK_1); }
Source:
public int run() throws IOException { Preconditions.checkArgument(samplePaths != null && !samplePaths.isEmpty(), "Sample CSV path is required"); Preconditions.checkArgument(samplePaths.size() == 1, "Only one CSV sample can be given"); Preconditions.checkArgument(linesToSample > 0, "At least one row must be sampled"); if (header != null) { noHeader = true; } CSVProperties props = new CSVProperties.Builder() .delimiter(delimiter) .escape(escape) .quote(quote) .header(header) .hasHeader(!noHeader) .linesToSkip(linesToSkip) .linesToSample(linesToSample) .charset(charsetName) .build(); Set<String> required = ImmutableSet.of(); if (requiredFields != null) { required = ImmutableSet.copyOf(requiredFields); } String sampleSchema = CSVUtil .inferNullableSchema( recordName, open(samplePaths.get(0)), props, required) .toString(!minimize); output(sampleSchema, console, outputPath); return 0; }

Target:
public int run() throws IOException { Preconditions.checkArgument(samplePaths != null && !samplePaths.isEmpty(), "Sample CSV path is required"); Preconditions.checkArgument(samplePaths.size() == 1, "Only one CSV sample can be given"); Preconditions.checkArgument(numRecords > 0, "At least one row must be sampled"); if (header != null) { noHeader = true; } CSVProperties props = new CSVProperties.Builder() .delimiter(delimiter) .escape(escape) .quote(quote) .header(header) .hasHeader(!noHeader) .linesToSkip(linesToSkip) .charset(charsetName) .build(); Set<String> required = ImmutableSet.of(); if (requiredFields != null) { required = ImmutableSet.copyOf(requiredFields); } String sampleSchema = CSVUtil .inferNullableSchema( recordName, open(samplePaths.get(0)), props, required, numRecords) .toString(!minimize); output(sampleSchema, console, outputPath); return 0; }
Source:
public List<Facility> getFacilitiesByHostName(PerunSession sess, String hostname) throws InternalErrorException { Utils.checkPerunSession(sess); List<Facility> facilities = getFacilitiesManagerBl().getFacilitiesByHostName(sess, hostname); if (!facilities.isEmpty()) { Iterator<Facility> facilityByHostname = facilities.iterator(); while(facilityByHostname.hasNext()) { if(!AuthzResolver.isAuthorized(sess, Role.FACILITYADMIN, facilityByHostname.next()) && !AuthzResolver.isAuthorized(sess, Role.PERUNOBSERVER)) { facilityByHostname.remove(); } } } return facilities; }

Target:
public List<Facility> getFacilitiesByHostName(PerunSession sess, String hostname) throws InternalErrorException { Utils.checkPerunSession(sess); List<Facility> facilities = getFacilitiesManagerBl().getFacilitiesByHostName(sess, hostname); if (AuthzResolver.isAuthorized(sess, Role.PERUNOBSERVER)) { return facilities; } if (!facilities.isEmpty()) { Iterator<Facility> facilityByHostname = facilities.iterator(); while(facilityByHostname.hasNext()) { if(!AuthzResolver.isAuthorized(sess, Role.FACILITYADMIN, facilityByHostname.next())) { facilityByHostname.remove(); } } } return facilities; }
Source:
public static void stopSyncServer() throws Exception { Request request = new Request.Builder() .url(STOP_SERVER) .build(); Response response; int attempts = 3; while (attempts > 0) { attempts--; try { response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); return; } catch (SocketTimeoutException e) { RealmLog.error("HTTP test server did not respond to /stop in time. Retrying."); } } throw new IllegalStateException("Failed to stop ROS."); }

Target:
public static void stopSyncServer() throws Exception { Request request = new Request.Builder() .url(STOP_SERVER) .build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); }
Source:
public UserDTO updateUserCreatedOnBuddyRequest(UUID id, String tempPassword, UserDTO userResource) { User originalUserEntity = getEntityByID(id); if (!originalUserEntity.isCreatedOnBuddyRequest()) { throw new YonaException("User is not created on buddy request"); } UserEncryptedEntitySet retrievedEntitySet = retrieveUserEncryptedData(originalUserEntity, tempPassword); return saveUserEncryptedDataWithNewPassword(retrievedEntitySet, userResource); }

Target:
public UserDTO updateUserCreatedOnBuddyRequest(UUID id, String tempPassword, UserDTO userResource) { User originalUserEntity = getEntityByID(id); if (!originalUserEntity.isCreatedOnBuddyRequest()) { throw new IllegalArgumentException("User is not created on buddy request"); } EncryptedUserData retrievedEntitySet = retrieveUserEncryptedData(originalUserEntity, tempPassword); return saveUserEncryptedDataWithNewPassword(retrievedEntitySet, userResource); }
Source:
public BoltMessageLog( FileSystemAbstraction fileSystem, File logFile, Executor executor ) throws IOException { RotatingFileOutputStreamSupplier outputStreamSupplier = new RotatingFileOutputStreamSupplier( fileSystem, logFile, ROTATION_THRESHOLD_BYTES, ROTATION_DELAY_MS, MAX_ARCHIVES, executor ); FormattedLog formattedLog = FormattedLog.withUTCTimeZone().toOutputStream( outputStreamSupplier ); formattedLog.setLevel( Level.DEBUG ); this.inner = formattedLog; }

Target:
public BoltMessageLog( FileSystemAbstraction fileSystem, File logFile, Executor executor ) throws IOException { RotatingFileOutputStreamSupplier outputStreamSupplier = new RotatingFileOutputStreamSupplier( fileSystem, logFile, ROTATION_THRESHOLD_BYTES, ROTATION_DELAY_MS, MAX_ARCHIVES, executor ); DateFormat iso8601DateFormat = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.SSSZ" ); FormattedLog formattedLog = FormattedLog.withUTCTimeZone().withDateFormat( iso8601DateFormat ) .toOutputStream( outputStreamSupplier ); formattedLog.setLevel( Level.DEBUG ); this.inner = formattedLog; }
Source:
public String getDimmer(String number) { String content = HttpUtil.executeUrl(GET, createURL() + "/" + XML_PATH + "?" + SUFFIX_PASSWORD + getPassword(), this.timeOut); content = XmlUtils.getContentOfElement(content, SUFFIX_DIMMER + number); double calc = Math.round(Double.parseDouble(XmlUtils.getContentOfElement(content, "Value"))/2.54); String string_value = String.valueOf((int)calc); return string_value; }

Target:
public String getDimmer(String number) { String URL = createURL() + "/" + XML_PATH + "?" + SUFFIX_PASSWORD + getPassword(); String content = HttpUtil.executeUrl(GET, URL, this.timeOut); content = XmlUtils.getContentOfElement(content, SUFFIX_DIMMER + number); double dimmer_value = Double.parseDouble(XmlUtils.getContentOfElement(content, "Value")); double calc = Math.round(dimmer_value/2.54); String string_value = String.valueOf((int)calc); return string_value; }
Source:
private Sorting.Direction convertDirection(Sort.Direction direction) { if (direction.toString().equalsIgnoreCase("desc")) { return Sorting.Direction.DESC; } else { return Sorting.Direction.ASC; } }

Target:
private Sorting.Direction convertDirection(Sort.Direction direction) { if (direction != null) { if (direction == Sort.Direction.DESC) { return Sorting.Direction.DESC; } else { return Sorting.Direction.ASC; } } else { return defaultDirection; } }
Source:
public InputStream readTemplatePath() { determineMessageFormat(); try { if (messageFormat == MessageFormat.CUSTOM) { return new FileInputStream(new File(templatePath)); } else { return getClass().getResourceAsStream(messageFormat.jarPath); } } catch (IOException e) { throw new RuntimeException("Failed to read template in subscription " + name + ": " + e.getMessage(), e); } }

Target:
public InputStream readTemplatePath() { messageFormat = determineMessageFormat(); log.info("Using message format: to process artifacts for subscription: {}", messageFormat, name); try { if (messageFormat == MessageFormat.CUSTOM) { return new FileInputStream(new File(templatePath)); } else if (messageFormat.jarPath != null){ return getClass().getResourceAsStream(messageFormat.jarPath); } } catch (IOException e) { throw new RuntimeException("Failed to read template in subscription " + name, e); } return null; }
Source:
Mono<PhoneNumberSearch>> createSearchActivationOperation(CreateSearchOptions options) { return (pollingContext) -> { Mono<PhoneNumberSearch> response = createSearch(options).flatMap(createSearchResponse -> { String searchId = createSearchResponse.getSearchId(); PhoneNumberSearch phoneNumberSearch = new PhoneNumberSearch().setSearchId(searchId); return Mono.just(phoneNumberSearch); }); return response; }; }

Target:
createSearchActivationOperation(CreateSearchOptions options) { return (pollingContext) -> { Mono<PhoneNumberSearch> response = createSearch(options).flatMap(createSearchResponse -> { String searchId = createSearchResponse.getSearchId(); Mono<PhoneNumberSearch> phoneNumberSearch = getSearchById(searchId); return phoneNumberSearch; }); return response; }; }
Source:
public boolean canFlipToNextPage() { boolean canFlip = true; if (!validatePage() || fileName.getText().equals("")) { canFlip = false; this.setErrorMessage(Messages.PapyrusProjectCreationPage_page_incorrect_desc + this.getProjectName().toLowerCase()); } IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects(); for (IProject iproject : projects) { if (this.getProjectName().equalsIgnoreCase(iproject.getName())) { canFlip = false; this.setErrorMessage(Messages.PapyrusProjectCreationPage_page_same_case_desc + this.getProjectName().toLowerCase()); } } return canFlip; }

Target:
public boolean canFlipToNextPage() { boolean canFlip = true; if (!validatePage() || fileName.getText().equals("")) { canFlip = false; this.setErrorMessage(Messages.PapyrusProjectCreationPage_page_incorrect_desc + this.getProjectName().toLowerCase()); } IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects(); if (canFlip != false) { for (IProject iproject : projects) { if (this.getProjectName().equalsIgnoreCase(iproject.getName())) { canFlip = false; this.setErrorMessage(Messages.PapyrusProjectCreationPage_page_same_case_desc + iproject.getName()); break; } } } return canFlip; }
Source:
protected String[][] formatTableContents() { final ImmutableList.Builder<String[]> builder = ImmutableList.builder(); for (final Contents content : contents) { final String[] arrayEntry = new String[6]; arrayEntry[0] = nullGuard(content.getKey()); arrayEntry[1] = nullGuard(Long.toString(content.getSize())); arrayEntry[2] = nullGuard(content.getOwner().getDisplayName()); arrayEntry[3] = nullGuardFromDate(content.getLastModified(), DATE_FORMAT); arrayEntry[4] = nullGuard(content.getETag()); arrayEntry[5] = nullGuard(content.getVersionId().toString()); builder.add(arrayEntry); } final ImmutableList<String[]> contentStrings = builder.build(); return contentStrings.toArray(new String[contentStrings.size()][]); }

Target:
protected String[][] formatTableContents() { final ImmutableList.Builder<String[]> builder = ImmutableList.builder(); for (final Contents content : contents) { final String[] arrayEntry = new String[6]; arrayEntry[0] = nullGuard(content.getKey()); arrayEntry[1] = nullGuard(Long.toString(content.getSize())); arrayEntry[2] = nullGuard(content.getOwner().getDisplayName()); arrayEntry[3] = nullGuardFromDate(content.getLastModified(), DATE_FORMAT); arrayEntry[4] = nullGuard(content.getETag()); arrayEntry[5] = nullGuard(content.getVersionId()); builder.add(arrayEntry); } final ImmutableList<String[]> contentStrings = builder.build(); return contentStrings.toArray(new String[contentStrings.size()][]); }
Source:
private ZonedDateTime getExpiryDateForAwaitingCaptureRequest() { int chargeExpiryWindowSeconds = FORTY_EIGHT_HOURS; if (StringUtils.isNotBlank(System.getenv(AWAITING_DELAY_CAPTURE_EXPIRY_WINDOW))) { chargeExpiryWindowSeconds = Integer.parseInt(System.getenv(AWAITING_DELAY_CAPTURE_EXPIRY_WINDOW)); } logger.debug("Charge expiry window size in seconds: " + chargeExpiryWindowSeconds); return ZonedDateTime.now().minusSeconds(chargeExpiryWindowSeconds); }

Target:
private ZonedDateTime getExpiryDateForAwaitingCaptureRequest() { int chargeExpiryWindowSeconds = FORTY_EIGHT_HOURS; if (StringUtils.isNotBlank(System.getenv(AWAITING_DELAY_CAPTURE_EXPIRY_WINDOW))) { chargeExpiryWindowSeconds = Integer.parseInt(System.getenv(AWAITING_DELAY_CAPTURE_EXPIRY_WINDOW)); } logger.debug("Charge expiry window size for awaiting_delay_capture in seconds: " + chargeExpiryWindowSeconds); return ZonedDateTime.now().minusSeconds(chargeExpiryWindowSeconds); }
Source:
public Boolean hasModifierProperty(@NotNull PsiModifierList modifierList, @NotNull String name) { final PsiElement parent = modifierList.getParent(); if (parent instanceof PsiLocalVariable && isVal((PsiLocalVariable) parent)) { return PsiModifier.FINAL.equals(name) ? Boolean.TRUE : null; } return null; }

Target:
public Boolean hasModifierProperty(@NotNull PsiModifierList modifierList, @NotNull String name) { final PsiElement parent = modifierList.getParent(); if (PsiModifier.FINAL.equals(name) && parent instanceof PsiLocalVariable && isVal((PsiLocalVariable) parent)) { return Boolean.TRUE; } return null; }
Source:
private Set<List<JavaFileScannerContext.Location>> flowFromYields(ExplodedGraph.Edge edge) { Set<MethodYield> methodYields = edge.yields(); if (methodYields.isEmpty()) { return ImmutableSet.of(ImmutableList.of()); } List<Integer> argumentIndices = correspondingArgumentIndices(symbolicValues, edge.parent); MethodInvocationTree mit = (MethodInvocationTree) edge.parent.programPoint.syntaxTree(); List<JavaFileScannerContext.Location> passedArgumentsMessages = flowsForPassedArguments(argumentIndices, mit); List<JavaFileScannerContext.Location> changingNameArgumentsMessages = flowsForArgumentsChangingName(argumentIndices, mit); SymbolicValue returnSV = edge.child.programState.peekValue(); if (symbolicValues.contains(returnSV)) { argumentIndices.add(-1); } if (argumentIndices.isEmpty()) { return ImmutableSet.of(ImmutableList.of()); } return methodYields.stream() .map(y -> y.flow(argumentIndices, domains)) .flatMap(Set::stream) .map(flowFromYield -> { ImmutableList.Builder<JavaFileScannerContext.Location> result = ImmutableList.builder(); result.addAll(flowFromYield); if (!flowFromYield.isEmpty()) { result .addAll(changingNameArgumentsMessages) .addAll(passedArgumentsMessages); } return result.build(); }) .collect(Collectors.toSet()); }

Target:
private Set<List<JavaFileScannerContext.Location>> flowFromYields(ExplodedGraph.Edge edge) { Set<MethodYield> methodYields = edge.yields(); if (methodYields.isEmpty()) { return ImmutableSet.of(); } List<Integer> argumentIndices = correspondingArgumentIndices(symbolicValues, edge.parent); MethodInvocationTree mit = (MethodInvocationTree) edge.parent.programPoint.syntaxTree(); List<JavaFileScannerContext.Location> passedArgumentsMessages = flowsForPassedArguments(argumentIndices, mit); List<JavaFileScannerContext.Location> changingNameArgumentsMessages = flowsForArgumentsChangingName(argumentIndices, mit); SymbolicValue returnSV = edge.child.programState.peekValue(); if (symbolicValues.contains(returnSV)) { argumentIndices.add(-1); } if (argumentIndices.isEmpty()) { return ImmutableSet.of(); } return methodYields.stream() .map(y -> y.flow(argumentIndices, domains)) .flatMap(Set::stream) .filter(f -> !f.isEmpty()) .map(flowFromYield -> ImmutableList.<JavaFileScannerContext.Location>builder() .addAll(flowFromYield) .addAll(changingNameArgumentsMessages) .addAll(passedArgumentsMessages) .build()) .collect(Collectors.toSet()); }
Source:
public void testDictIdSeeker() throws Exception { IntBuffer dimConversions = ByteBuffer.allocateDirect(3 * Ints.BYTES).asIntBuffer(); dimConversions.put(0); dimConversions.put(2); dimConversions.put(4); IndexMerger.DictIdSeeker dictIdSeeker = new IndexMerger.DictIdSeeker((IntBuffer) dimConversions.asReadOnlyBuffer().rewind()); Assert.assertEquals(0, dictIdSeeker.seek(0)); Assert.assertEquals(-1, dictIdSeeker.seek(1)); Assert.assertEquals(1, dictIdSeeker.seek(2)); try { dictIdSeeker.seek(1); } catch (ISE ise) { Assert.assertTrue("Only support access in order", true); } Assert.assertEquals(-1, dictIdSeeker.seek(3)); Assert.assertEquals(2, dictIdSeeker.seek(4)); Assert.assertEquals(-1, dictIdSeeker.seek(5)); }

Target:
public void testDictIdSeeker() throws Exception { IntBuffer dimConversions = ByteBuffer.allocateDirect(3 * Ints.BYTES).asIntBuffer(); dimConversions.put(0); dimConversions.put(2); dimConversions.put(4); IndexMerger.DictIdSeeker dictIdSeeker = new IndexMerger.DictIdSeeker((IntBuffer) dimConversions.asReadOnlyBuffer().rewind()); Assert.assertEquals(0, dictIdSeeker.seek(0)); Assert.assertEquals(-1, dictIdSeeker.seek(1)); Assert.assertEquals(1, dictIdSeeker.seek(2)); try { dictIdSeeker.seek(5); Assert.fail("Only support access in order"); } catch (ISE ise) { Assert.assertTrue("Only support access in order", true); } Assert.assertEquals(-1, dictIdSeeker.seek(3)); Assert.assertEquals(2, dictIdSeeker.seek(4)); Assert.assertEquals(-1, dictIdSeeker.seek(5)); }
Source:
public void test_validateLotNotesLists_throwsException() { try { this.errors = new MapBindingResult(new HashMap<String, String>(), String.class.getName()); this.inventoryCommonValidator.validateLotNotes(Collections.singletonList(""), errors); } catch (ApiRequestValidationException e) { assertThat(Arrays.asList(e.getErrors().get(0).getCodes()), hasItem("lot.input.list.notes.null.or.empty")); } }

Target:
public void test_validateLotNotesLists_throwsException() { try { this.errors = new MapBindingResult(new HashMap<String, String>(), String.class.getName()); this.inventoryCommonValidator.validateLotNotes(Collections.singletonList(""), this.errors); } catch (final ApiRequestValidationException e) { assertThat(Arrays.asList(e.getErrors().get(0).getCodes()), hasItem("lot.input.list.notes.null.or.empty")); } }