auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void rename() { if ( isDirty() ) { view.showYesNoCancelPopup( CommonConstants.INSTANCE.Information(), Constants.INSTANCE.modelEditor_confirm_save_before_rename(), new Command() { @Override public void execute() { rename( true ); } }, new Command() { @Override public void execute() { rename( false ); } }, new Command() { @Override public void execute() { } } ); } else { rename( false ); } }

Target:
protected void rename() { if ( isDirty() ) { view.showYesNoCancelPopup( CommonConstants.INSTANCE.Information(), Constants.INSTANCE.modelEditor_confirm_save_before_rename(), new Command() { @Override public void execute() { rename( true ); } }, new Command() { @Override public void execute() { rename( false ); } } ); } else { rename( false ); } }
Source:
public void testRepeatedRolledBack() throws Exception { Xid xid = new CustomXid(654321); xaRes.start(xid, XAResource.TMNOFLAGS); xaRes.end(xid, XAResource.TMSUCCESS); xaRes.prepare(xid); xaRes.recover(XAResource.TMSTARTRSCAN); xaRes.rollback(xid); try { xaRes.rollback(xid); } catch (XAException xae) { assertEquals("Checking the errorCode is XAER_NOTA indicating the " + "xid does not exist.", XAException.XAER_NOTA, xae.errorCode ); } }

Target:
public void testRepeatedRolledBack() throws Exception { Xid xid = new CustomXid(654321); xaRes.start(xid, XAResource.TMNOFLAGS); xaRes.end(xid, XAResource.TMSUCCESS); xaRes.prepare(xid); xaRes.recover(XAResource.TMSTARTRSCAN); xaRes.rollback(xid); try { xaRes.rollback(xid); fail("Rollback was successful"); } catch (XAException xae) { assertEquals("Checking the errorCode is XAER_NOTA indicating the " + "xid does not exist.", XAException.XAER_NOTA, xae.errorCode ); } }
Source:
public static Set<URL> getResourceURLs(ResourceURLFilter filter) { try(URLClassLoader ucl = new URLClassLoader(new URL[] {(ClassLoader.getSystemClassLoader()).getResource("L10N")}, Resources.class.getClassLoader())) { Set<URL> collectedURLs = new HashSet<>(); for (URL url : ucl.getURLs()) { try { iterateEntry(new File(url.toURI()), filter, collectedURLs); } catch (URISyntaxException e) { LOGGER.debug(e.getMessage(), e); } } return collectedURLs; } catch (IOException e) { LOGGER.debug(e.getMessage(), e); } return null; }

Target:
public static Set<URL> getResourceURLs(ResourceURLFilter filter) { Set<URL> collectedURLs = new HashSet<>(); try(URLClassLoader ucl = new URLClassLoader(new URL[] {(ClassLoader.getSystemClassLoader()).getResource("L10N")}, Resources.class.getClassLoader())) { for (URL url : ucl.getURLs()) { try { iterateEntry(new File(url.toURI()), filter, collectedURLs); } catch (URISyntaxException e) { LOGGER.debug(e.getMessage(), e); } } return collectedURLs; } catch (IOException e) { LOGGER.debug(e.getMessage(), e); } return collectedURLs; }
Source:
public void ipSecListenSocket(Integer socketFd) { FileDescriptor fd = new FileDescriptor(); fd.setInt$(socketFd.intValue()); try { Os.listen(fd, 10); } catch (ErrnoException e) { Log.e("IpSec: Failed to listen on socket " + e.toString()); } }

Target:
public Boolean ipSecListenSocket(Integer socketFd) { FileDescriptor fd = new FileDescriptor(); fd.setInt$(socketFd.intValue()); try { Os.listen(fd, 10); return true; } catch (ErrnoException e) { Log.e("IpSec: Failed to listen on socket " + e.toString()); } return false; }
Source:
protected LightblueResponse callService(HttpRequestBase httpOperation) { String jsonOut; LOGGER.debug("Calling " + httpOperation); try { try (CloseableHttpClient httpClient = getLightblueHttpClient()) { httpOperation.setHeader("Content-Type", "application/json"); if (LOGGER.isDebugEnabled()) { try { LOGGER.debug("Request body: " + (EntityUtils.toString(((HttpEntityEnclosingRequestBase) httpOperation).getEntity()))); } catch (ClassCastException e) { LOGGER.debug("Request body: None"); } } try (CloseableHttpResponse httpResponse = httpClient.execute(httpOperation)) { HttpEntity entity = httpResponse.getEntity(); jsonOut = EntityUtils.toString(entity); LOGGER.debug("Response received from service" + jsonOut); return new LightblueResponse(jsonOut); } } } catch (IOException e) { LOGGER.error("There was a problem calling the lightblue service", e); return new LightblueResponse("{\"error\":\"There was a problem calling the lightblue service\"}"); } }

Target:
protected LightblueResponse callService(HttpRequestBase httpOperation) { String jsonOut; LOGGER.debug("Calling " + httpOperation); try { try (CloseableHttpClient httpClient = getLightblueHttpClient()) { httpOperation.setHeader("Content-Type", "application/json"); if (LOGGER.isDebugEnabled()) { try { LOGGER.debug("Request body: " + (EntityUtils.toString(((HttpEntityEnclosingRequestBase) httpOperation).getEntity()))); } catch (ClassCastException e) { LOGGER.debug("Request body: None"); } } long t1 = new Date().getTime(); try (CloseableHttpResponse httpResponse = httpClient.execute(httpOperation)) { HttpEntity entity = httpResponse.getEntity(); jsonOut = EntityUtils.toString(entity); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Response received from service: " + jsonOut); long t2 = new Date().getTime(); LOGGER.debug("Call took "+(t2-t1)+"ms"); } return new LightblueResponse(jsonOut, mapper); } } } catch (IOException e) { LOGGER.error("There was a problem calling the lightblue service", e); return new LightblueResponse("{\"error\":\"There was a problem calling the lightblue service\"}", mapper); } }
Source:
private void unregisterServices(Thing thing) { ThingUID thingUID = thing.getUID(); Set<ServiceRegistration<?>> serviceRegs = this.thingHandlerServices.remove(thingUID); if (serviceRegs != null) { for (ServiceRegistration<?> serviceReg : serviceRegs) { serviceReg.unregister(); } } }

Target:
private void unregisterServices(Thing thing) { ThingUID thingUID = thing.getUID(); Set<ServiceRegistration<?>> serviceRegs = this.thingHandlerServices.remove(thingUID); if (serviceRegs != null) { for (ServiceRegistration<?> serviceReg : serviceRegs) { ThingHandlerService service = (ThingHandlerService) getBundleContext() .getService(serviceReg.getReference()); serviceReg.unregister(); if (service != null) { service.deactivate(); } } } }
Source:
public void setIDSupplier(ToLongFunction<E> supplier) { this.idSupplier = supplier; nodeMap = new LongObjectHashMap<>(this.size); Iterator iterator = (Iterator)iterator(); try { while (iterator.hasNext()) { E value = iterator.next(); Node<E> position = iterator.last; putID(value, position); } } finally { iterator.close(); } }

Target:
public void setIDSupplier(ToLongFunction<E> supplier) { this.idSupplier = supplier; nodeMap = newLongHashMap(); try (Iterator iterator = (Iterator) iterator()) { while (iterator.hasNext()) { E value = iterator.next(); Node<E> position = iterator.last; putID(value, position); } } }
Source:
public int hashCode() { return Objects.hash(getBucket(), getPath()); }

Target:
public int hashCode() { return Objects.hash(bucket, path); }
Source:
private Optional<String> formatPlanNodeStatsAndCost(PlanNode node) { PlanNodeStatsEstimate stats = estimatedStatsAndCosts.getStats().getOrDefault(node.getId(), PlanNodeStatsEstimate.unknown()); PlanNodeCostEstimate cost = estimatedStatsAndCosts.getCosts().getOrDefault(node.getId(), UNKNOWN_COST); if (stats.isOutputRowCountUnknown() || cost.equals(UNKNOWN_COST)) { return Optional.empty(); } return Optional.of(String.format("{rows: %s (%s), cpu: %s, memory: %s, network: %s}", formatAsLong(stats.getOutputRowCount()), formatEstimateAsDataSize(stats.getOutputSizeInBytes(node.getOutputSymbols(), types)), formatDouble(cost.getCpuCost()), formatDouble(cost.getMemoryCost()), formatDouble(cost.getNetworkCost()))); }

Target:
private Optional<String> formatPlanNodeStatsAndCost(PlanNode node) { PlanNodeStatsEstimate stats = estimatedStatsAndCosts.getStats().getOrDefault(node.getId(), PlanNodeStatsEstimate.unknown()); PlanNodeCostEstimate cost = estimatedStatsAndCosts.getCosts().getOrDefault(node.getId(), PlanNodeCostEstimate.unknown()); if (stats.isOutputRowCountUnknown() || cost.equals(PlanNodeCostEstimate.unknown())) { return Optional.empty(); } return Optional.of(String.format("{rows: %s (%s), cpu: %s, memory: %s, network: %s}", formatAsLong(stats.getOutputRowCount()), formatEstimateAsDataSize(stats.getOutputSizeInBytes(node.getOutputSymbols(), types)), formatDouble(cost.getCpuCost()), formatDouble(cost.getMemoryCost()), formatDouble(cost.getNetworkCost()))); }
Source:
private static void ensureSameTenant(Iterable<Event> events) { checkNotNull(events); final Set<TenantId> tenants = FluentIterable.from(events) .transform(new Function<Event, TenantId>() { @Override public TenantId apply( @Nullable Event event) { checkNotNull(event); return getTenantId(event); } }) .toSet(); checkArgument(tenants.size() == 1, DIFFERENT_TENANT_ERROR_TEMPLATE, tenants); }

Target:
private static void ensureSameTenant(Iterable<Event> events) { checkNotNull(events); final Set<TenantId> tenants = FluentIterable.from(events) .transform(new Function<Event, TenantId>() { @Override public TenantId apply( @Nullable Event event) { checkNotNull(event); return getTenantId(event); } }) .toSet(); checkArgument(tenants.size() == 1, TENANT_MISMATCH_ERROR_MSG, tenants); }
Source:
private void startMetricsService() { if (state != State.STARTING) { return; } LOG.info("Initializing metrics service"); connectionAttempts++; try { session = createSession(); } catch (Throwable t) { Throwable rootCause = Throwables.getRootCause(t); LOG.warn("Could not connect to Cassandra cluster - assuming its not up yet", rootCause); long delay = 1 + ((connectionAttempts - 1) % 4); LOG.warn("[{}] Retrying connecting to Cassandra cluster in [{}]s...", connectionAttempts, delay); lifecycleExecutor.schedule(this::startMetricsService, delay, SECONDS); return; } SchemaManager schemaManager = new SchemaManager(session); try { if (Boolean.parseBoolean(resetDb)) { schemaManager.dropKeyspace(keyspace); } schemaManager.createSchema(keyspace); session.execute("USE " + keyspace); LOG.info("Using a key space of '{}'", keyspace); metricsService.startUp(session); LOG.info("Metrics service started"); state = State.STARTED; } catch (Throwable t) { LOG.error("An error occurred trying to connect to the Cassandra cluster", t); state = State.FAILED; } }

Target:
private void startMetricsService() { if (state != State.STARTING) { return; } LOG.info("Initializing metrics service"); connectionAttempts++; try { session = createSession(); } catch (Throwable t) { Throwable rootCause = Throwables.getRootCause(t); LOG.warn("Could not connect to Cassandra cluster - assuming its not up yet", rootCause); long delay = 1 + ((connectionAttempts - 1) % 4); LOG.warn("[{}] Retrying connecting to Cassandra cluster in [{}]s...", connectionAttempts, delay); lifecycleExecutor.schedule(this::startMetricsService, delay, SECONDS); return; } try { metricsService.startUp(session, keyspace, Boolean.parseBoolean(resetDb)); LOG.info("Metrics service started"); state = State.STARTED; } catch (Throwable t) { LOG.error("An error occurred trying to connect to the Cassandra cluster", t); state = State.FAILED; } finally { if (state != State.STARTED) { try { metricsService.shutdown(); } catch (Throwable ignore) { } } } }
Source:
private Pod newPod() { return new PodBuilder() .withNewMetadata() .withName("che-plugin-broker") .endMetadata() .withNewSpec() .withRestartPolicy("Never") .endSpec() .build(); }

Target:
private Pod newPod() { return new PodBuilder() .withNewMetadata() .withName(BROKERS_POD_NAME) .endMetadata() .withNewSpec() .withRestartPolicy("Never") .endSpec() .build(); }
Source:
public Builder withRequest(ReadRowsRequest request) { this.request = request; return this; }

Target:
public Builder withRequest(ReadRowsRequest request) { this.request = request; this.scan = null; return this; }
Source:
public void onRebindLocationFailed(Location location, Exception e) { Exceptions.propagateIfFatal(e); String errmsg = "problem rebinding location "+(location == null ? null : location.getId()+" ("+location+")"); rebindLocationFailures.put(location, new IllegalStateException(errmsg, e)); onErrorImpl(errmsg, e); }

Target:
public void onRebindLocationFailed(Location location, Exception e) { Exceptions.propagateIfFatal(e); String errmsg = "problem rebinding location "+location.getId()+" ("+location+")"; exceptions.add(new IllegalStateException(errmsg, e)); onErrorImpl(errmsg, e); }
Source:
public default LocalDate selectDateOrSame(LocalDate inputDate, SequenceDate sequenceDate) { DateSequence seq = sequenceDate.isFullSequence() ? this : baseSequence(); return sequenceDate.selectDate(inputDate, seq, true); }

Target:
public default LocalDate selectDateOrSame(LocalDate inputDate, SequenceDate sequenceDate) { return sequenceDate.selectDate(inputDate, this, true); }
Source:
public void authenticateAndOpen(SeleniumWebDriver driver) throws Exception { String dashboardUrlPath = dashboardUrl.get().toString(); driver.get(dashboardUrlPath); entrance.login(owner); waitUntilTextPresentInUrl(driver, dashboardUrlPath + "#/"); driver.get(factoryUrl); }

Target:
public void authenticateAndOpen(SeleniumWebDriver driver) throws Exception { driver.get(dashboardUrl.get().toString()); entrance.login(owner); driver.get(factoryUrl); }
Source:
private void flushData(final Partition.PartitionKey pk, final SortedMap<Long, String> data, final Optional<String> metadata) { try { final String evt = EventStream.createStreamEvent( pk.partition, String.valueOf(offsets.get(pk).getSentOffset()), new ArrayList<>(data.values()), metadata); getOut().streamData(evt.getBytes(EventStream.UTF8)); } catch (final IOException e) { getLog().error("Failed to write data to output.", e); shutdownGracefully("Failed to write data to output"); } }

Target:
private void flushData(final Partition.PartitionKey pk, final SortedMap<Long, String> data, final Optional<String> metadata) { try { final String offset = String.valueOf(offsets.get(pk).getSentOffset()); final String batch = serializeBatch(pk, offset, new ArrayList<>(data.values()), metadata); getOut().streamData(batch.getBytes(EventStream.UTF8)); } catch (final IOException e) { getLog().error("Failed to write data to output.", e); shutdownGracefully("Failed to write data to output"); } }
Source:
private void lockTemplateInDb() { TransactionSupport.executeInNewTransaction(() -> { getCompensationContext().snapshotEntityStatus(getVmTemplate()); vmTemplateDao.updateStatus(getVmTemplate().getId(), VmTemplateStatus.Locked); getDiskImages().forEach(diskImage -> { getCompensationContext().snapshotEntityStatus(diskImage.getImage()); diskImage.setImageStatus(ImageStatus.LOCKED); ImagesHandler.updateImageStatus(diskImage.getImageId(), ImageStatus.LOCKED); }); getCompensationContext().stateChanged(); return null; }); }

Target:
private void lockTemplateInDb() { VmTemplateHandler.lockVmTemplateInTransaction(getVmTemplateId(), getCompensationContext()); }
Source:
public void elasticsearchOssImage() throws IOException { try (ElasticsearchContainer container = new ElasticsearchContainer( DockerImageName .parse("docker.elastic.co/elasticsearch/elasticsearch-oss") .withTag(ELASTICSEARCH_VERSION) .asCompatibleSubstituteFor("docker.elastic.co/elasticsearch/elasticsearch") ) ) { container.start(); Response response = getClient(container).performRequest(new Request("GET", "/")); assertThat(response.getStatusLine().getStatusCode(), is(200)); assertThrows("We should not have /_xpack endpoint with an OSS License", ResponseException.class, () -> getClient(container).performRequest(new Request("GET", "/_xpack/"))); } }

Target:
public void elasticsearchOssImage() throws IOException { try (ElasticsearchContainer container = new ElasticsearchContainer( DockerImageName .parse("docker.elastic.co/elasticsearch/elasticsearch-oss") .withTag(ELASTICSEARCH_VERSION) ) ) { container.start(); Response response = getClient(container).performRequest(new Request("GET", "/")); assertThat(response.getStatusLine().getStatusCode(), is(200)); assertThrows("We should not have /_xpack endpoint with an OSS License", ResponseException.class, () -> getClient(container).performRequest(new Request("GET", "/_xpack/"))); } }
Source:
private void readOffset() throws ConnectException { String path = FileUtils.topicDirectory(url, topicsDir, tp.topic()); CommittedFileFilter filter = new TopicPartitionCommittedFileFilter(tp); FileStatus fileStatusWithMaxOffset = FileUtils.fileStatusWithMaxOffset( storage, new Path(path), filter ); if (fileStatusWithMaxOffset != null) { offset = FileUtils.extractOffset(fileStatusWithMaxOffset.getPath().getName()) + 1; committedOffset = offset; } }

Target:
private void readOffset() throws ConnectException { String path = FileUtils.topicDirectory(url, topicsDir, tp.topic()); CommittedFileFilter filter = new TopicPartitionCommittedFileFilter(tp); FileStatus fileStatusWithMaxOffset = FileUtils.fileStatusWithMaxOffset( storage, new Path(path), filter ); if (fileStatusWithMaxOffset != null) { committedOffset = FileUtils.extractOffset(fileStatusWithMaxOffset.getPath().getName()); offset = committedOffset + 1; } }
Source:
public void start(final Environment env) { startThread(new CommandRunnable() { @Override public void run() throws Exception { if (!currentUser.getCapabilities().canCreateProject()) { String msg = String.format( "fatal: %s does not have \"Create Project\" capability.", currentUser.getUserName()); throw new UnloggedFailure(BaseCommand.STATUS_NOT_ADMIN, msg); } parseCommandLine(); if (projectName == null) { throw new UnloggedFailure(1, "Error: Project name is required."); } try { final CreateProjectArgs args = new CreateProjectArgs(); args.setProjectName(projectName); args.ownerIds = ownerIds; args.newParent = newParent; args.permissionsOnly = permissionsOnly; args.projectDescription = projectDescription; args.submitType = submitType; args.contributorAgreements = contributorAgreements; args.signedOffBy = signedOffBy; args.contentMerge = contentMerge; args.changeIdRequired = requireChangeID; args.branch = branch; args.createEmptyCommit = createEmptyCommit; final CreateProject createProject = CreateProjectFactory.create(args); createProject.createProject(); } catch (ProjectCreationFailedException err) { throw new UnloggedFailure(1, "fatal: " + err.getMessage(), err); } } }); }

Target:
public void start(final Environment env) { startThread(new CommandRunnable() { @Override public void run() throws Exception { if (!currentUser.getCapabilities().canCreateProject()) { String msg = String.format( "fatal: %s does not have \"Create Project\" capability.", currentUser.getUserName()); throw new UnloggedFailure(BaseCommand.STATUS_NOT_ADMIN, msg); } parseCommandLine(); if (projectName == null) { throw new UnloggedFailure(1, "fatal: Project name is required."); } try { final CreateProjectArgs args = new CreateProjectArgs(); args.setProjectName(projectName); args.ownerIds = ownerIds; args.newParent = newParent; args.permissionsOnly = permissionsOnly; args.projectDescription = projectDescription; args.submitType = submitType; args.contributorAgreements = contributorAgreements; args.signedOffBy = signedOffBy; args.contentMerge = contentMerge; args.changeIdRequired = requireChangeID; args.branch = branch; args.createEmptyCommit = createEmptyCommit; final CreateProject createProject = CreateProjectFactory.create(args); createProject.createProject(); } catch (ProjectCreationFailedException err) { throw new UnloggedFailure(1, "fatal: " + err.getMessage(), err); } } }); }
Source:
public String version() { return "0.1.4.3"; }

Target:
public String version() { return "0.1.4.6"; }
Source:
private Socket enableTlsOnSocket(Socket socket) { if (socket != null && (socket instanceof SSLSocket)) { ((SSLSocket) socket).setEnabledProtocols(new String[]{"MonkeyBalls"}); } return socket; }

Target:
private Socket enableTlsOnSocket(Socket socket) { if (socket != null && (socket instanceof SSLSocket)) { ((SSLSocket) socket).setEnabledProtocols(PROTOCOLS_TLS_1_2_ONLY); } return socket; }
Source:
public void addPostShouldSetModificationDateToPostCreationDate() throws InterruptedException { Topic topic = createTopic(); DateTime prevDate = topic.getModificationDate(); Thread.sleep(25); Post post = new Post(); post.setCreationDate(new DateTime()); topic.addPost(post); assertEquals(topic.getModificationDate(), post.getCreationDate()); assertFalse(prevDate.equals(topic.getModificationDate())); }

Target:
public void addPostShouldSetModificationDateToPostCreationDate() throws InterruptedException { Topic topic = createTopic(); DateTime prevDate = topic.getModificationDate(); Post post = new Post(); post.setCreationDate(new DateTime().plusDays(1)); topic.addPost(post); assertEquals(topic.getModificationDate(), post.getCreationDate()); assertFalse(prevDate.equals(topic.getModificationDate())); }
Source:
public static void createServer() throws Exception { server = SshServer.setUpDefaultServer(); server.setPasswordAuthenticator((username, password, session) -> true); server.setPort(0); server.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(new File("hostkey.ser"))); server.setSubsystemFactories(Collections.<NamedFactory<Command>>singletonList(new SftpSubsystemFactory())); server.setFileSystemFactory( new VirtualFileSystemFactory(Paths.get(remoteTemporaryFolder.getRoot().getAbsolutePath()))); server.start(); port = server.getPort(); }

Target:
public static void createServer() throws Exception { server = SshServer.setUpDefaultServer(); server.setPasswordAuthenticator((username, password, session) -> true); server.setPort(0); server.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(new File("hostkey.ser"))); server.setSubsystemFactories(Collections.<NamedFactory<Command>>singletonList(new SftpSubsystemFactory())); server.setFileSystemFactory(new VirtualFileSystemFactory(remoteTemporaryFolder.getRoot().toPath())); server.start(); port = server.getPort(); }
Source:
switch(4) { case 4 : break; default: switch(5) { case 5 : break; case 6 : default: break; } break; }

Target:
switch(4) { case 4 : break; default: switch(5) { case 5 : break; case 6 : break; case 7 : break; default: break; } break; }
Source:
private long insertBootstrapStartRow(Connection connection, String db, String table, String whereClause, Long totalRows) throws SQLException { LOGGER.info("inserting bootstrap start row"); String sql = null; if ( whereClause != null ) { sql = "insert into `bootstrap` (database_name, table_name, where_clause, total_rows) values(?, ?, ?, ?)"; } else { sql = "insert into `bootstrap` (database_name, table_name, total_rows) values(?, ?, ?)"; } PreparedStatement preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); preparedStatement.setString(1, db); preparedStatement.setString(2, table); if ( whereClause != null ) { preparedStatement.setString(3, whereClause); preparedStatement.setLong(4, totalRows); } else { preparedStatement.setLong(3, totalRows); } preparedStatement.execute(); ResultSet generatedKeys = preparedStatement.getGeneratedKeys(); generatedKeys.next(); return generatedKeys.getLong(1); }

Target:
private long insertBootstrapStartRow(Connection connection, String db, String table, String whereClause, Long totalRows) throws SQLException { LOGGER.info("inserting bootstrap start row"); String sql = null; sql = "insert into `bootstrap` (database_name, table_name, where_clause, total_rows) values(?, ?, ?, ?)"; PreparedStatement preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); preparedStatement.setString(1, db); preparedStatement.setString(2, table); preparedStatement.setString(3, whereClause); preparedStatement.setLong(4, totalRows); preparedStatement.execute(); ResultSet generatedKeys = preparedStatement.getGeneratedKeys(); generatedKeys.next(); return generatedKeys.getLong(1); }
Source:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { super.doGet(request, response); String target = request.getPathInfo(); String uri = request.getRequestURI(); try { if (uri != null && uri.endsWith("help.htm")) { target = HELP_HTM; } else if (uri != null && "/".equals(uri)){ target = INDEX_HTM; } URL url = VoltDB.class.getResource("dbmonitor" + target); if (url == null) { String msg = "404: Resource not found.\n"; response.setContentType("text/plain;charset=utf-8"); response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.getWriter().print(msg); return; } InputStream is = VoltDB.class.getResourceAsStream("dbmonitor" + target); if (target.endsWith(INDEX_HTM) || target.endsWith(HELP_HTM)) { response.setContentType(HTML_CONTENT_TYPE); response.setStatus(HttpServletResponse.SC_OK); OutputStream os = response.getOutputStream(); BufferedInputStream bis = new BufferedInputStream(is); int c = -1; while ((c = bis.read()) != -1) { os.write(c); } } else { String msg = "404: Resource not found.\n"; response.setContentType("text/plain;charset=utf-8"); response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.getWriter().print(msg); } } catch (Exception ex) { m_log.info("Not servicing url: " + target + " Details: " + ex.getMessage()); } }

Target:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { super.doGet(request, response); String target = request.getPathInfo(); final String uri = request.getRequestURI(); final String msg = "404: Resource not found.\n"; try { if (uri != null && uri.endsWith("help.htm")) { target = HELP_HTM; } else if (uri != null && "/".equals(uri)){ target = INDEX_HTM; } URL url = VoltDB.class.getResource("dbmonitor" + target); if (url == null) { response.setContentType("text/plain;charset=utf-8"); response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.getWriter().print(msg); return; } InputStream is = VoltDB.class.getResourceAsStream("dbmonitor" + target); if (target.endsWith(INDEX_HTM) || target.endsWith(HELP_HTM)) { response.setContentType(HTML_CONTENT_TYPE); response.setStatus(HttpServletResponse.SC_OK); OutputStream os = response.getOutputStream(); BufferedInputStream bis = new BufferedInputStream(is); int c = -1; while ((c = bis.read()) != -1) { os.write(c); } } else { response.setContentType("text/plain;charset=utf-8"); response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.getWriter().print(msg); } } catch (Exception ex) { rateLimitedLogWarn("Not servicing url: %s Details: ", target, ex.getMessage()); response.setContentType("text/plain;charset=utf-8"); response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.getWriter().print(msg); } }
Source:
public Resource loadResource(IStorage storage, Map<?, ?> options) { InputStream stream = null; Resource resource = null; try { URI uri = createURIFor(storage); resource = createResource(uri); if (!(storage instanceof File)) { stream = storage.getContents(); resource.load(stream, options); } else { resource.load(options); } } catch (IOException e) { } catch (CoreException e) { } catch (WrappedException e) { } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { } } } return resource; }

Target:
public Resource loadResource(IStorage storage, Map<?, ?> options) { InputStream stream = null; Resource resource = null; try { resource = createResource(createURIFor(storage)); stream = storage.getContents(); resource.load(stream, options); } catch (IOException e) { } catch (CoreException e) { } catch (WrappedException e) { } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { } } } return resource; }
Source:
private void receivePublish(SubscribedRepository repo) throws IOException { final String remote = repo.getRemote(); ReceivePack rp = new ReceivePack(repo.getRepository()) { @Override protected void validateCommands() { for (ReceiveCommand c : getAllCommands()) c.setName(SubscribedRepository.getPubSubRefFromLocal( remote, c.getRefName())); super.validateCommands(); } }; rp.setExpectDataAfterPackFooter(true); rp.setBiDirectionalPipe(false); rp.setAdvertisedRefs(repo.getPubSubRefs(), null); try { rp.receive(in, out, null); } finally { rp.unlockPack(); } }

Target:
private void receivePublish(SubscribedRepository repo) throws IOException { ReceivePublishedPack rp = new ReceivePublishedPack( repo.getRepository(), repo.getRemote()); rp.setExpectDataAfterPackFooter(true); rp.setAdvertisedRefs(repo.getPubSubRefs(), null); rp.receive(in); }
Source:
private IncrementalBuildResults addResource( final Path resource, final InputStream inputStream ) { synchronized ( kieFileSystem ) { checkNotNull( "resource", resource ); if ( !Files.isRegularFile( resource ) ) { return new IncrementalBuildResults( projectGAV ); } checkAFullBuildHasBeenPerformed(); final IncrementalBuildResults results = new IncrementalBuildResults( projectGAV ); final BuildValidationHelper validator = getBuildValidationHelper( resource ); if ( validator != null ) { final List<ValidationMessage> addedValidationMessages = validator.validate( Paths.convert( resource ) ); results.addAllAddedMessages( convertValidationMessages( addedValidationMessages ) ); results.addAllRemovedMessages( convertValidationMessages( nonKieResourceValidationHelperMessages.remove( resource ) ) ); nonKieResourceValidationHelpers.put( resource, validator ); nonKieResourceValidationHelperMessages.put( resource, addedValidationMessages ); } final String destinationPath = destinationPath( resource ); final Resource inputStreamResource = KieServices.Factory.get().getResources().newInputStreamResource( new BufferedInputStream( inputStream ) ); kieFileSystem.write( destinationPath, inputStreamResource ); addJavaClass( resource ); handles.put( getBaseFileName( destinationPath ), Paths.convert( resource ) ); buildIncrementally( results, destinationPath( resource ) ); return results; } }

Target:
private IncrementalBuildResults addResource( final Path resource, final InputStream inputStream ) { synchronized ( kieFileSystem ) { checkNotNull( "resource", resource ); if ( !Files.isRegularFile( resource ) ) { return new IncrementalBuildResults( projectGAV ); } checkAFullBuildHasBeenPerformed(); final IncrementalBuildResults results = new IncrementalBuildResults( projectGAV ); final BuildValidationHelper validator = getBuildValidationHelper( resource ); if ( validator != null ) { final List<ValidationMessage> addedValidationMessages = validator.validate( Paths.convert( resource ) ); results.addAllAddedMessages( convertValidationMessages( addedValidationMessages ) ); results.addAllRemovedMessages( convertValidationMessages( nonKieResourceValidationHelperMessages.remove( resource ) ) ); nonKieResourceValidationHelpers.put( resource, validator ); nonKieResourceValidationHelperMessages.put( resource, addedValidationMessages ); } addNewResource( resource, inputStream ); buildIncrementally( results, destinationPath( resource ) ); return results; } }
Source:
private void refreshGeoRepDataInCluster(VDSGroup cluster) { if (!supportsGlusterGeoRepFeature(cluster)) { return; } List<GlusterGeoRepSession> sessions = getSessionsForCluster(cluster); if (sessions == null) { log.debugFormat("No sessions returned for cluster {0} from CLI, nothing to do", cluster.getName()); return; } for (GlusterGeoRepSession session: sessions) { session.setMasterVolumeId(getVolumeId(cluster, session.getMasterVolumeName())); updateGeoRepStatus(session); if (getGeoRepDao().getById(session.getId()) == null) { getGeoRepDao().save(session); } else { getGeoRepDao().updateSession(session); } getGeoRepDao().saveOrUpdateDetailsInBatch(session.getSessionDetails()); } }

Target:
private void refreshGeoRepDataInCluster(VDSGroup cluster) { if (!supportsGlusterGeoRepFeature(cluster)) { return; } Map<Guid, GlusterGeoRepSession> sessionsMap = getSessionsForCluster(cluster); if (sessionsMap == null) { log.debugFormat("Error in retrieving sessions for cluster {0} from CLI, nothing to do", cluster.getName()); return; } removeDeletedSessions(cluster.getId(), sessionsMap); for (GlusterGeoRepSession session : sessionsMap.values()) { GlusterVolumeEntity masterVolume = getVolume(cluster, session.getMasterVolumeName()); if (masterVolume == null) { log.infoFormat("Could not find corresponding volume for geo-rep session {0} and volume {1}", session.getSessionKey(), session.getMasterVolumeName()); } else { session.setMasterVolumeId(masterVolume.getId()); } updateGeoRepStatus(masterVolume, session); if (getGeoRepDao().getById(session.getId()) == null) { log.debugFormat("detected new geo-rep session {0} for volume {1}", session.getSessionKey(), session.getMasterVolumeName()); getGeoRepDao().save(session); logGeoRepMessage(AuditLogType.GLUSTER_GEOREP_SESSION_DETECTED_FROM_CLI, cluster.getId(), session); } else { getGeoRepDao().updateSession(session); } getGeoRepDao().saveOrUpdateDetailsInBatch(session.getSessionDetails()); } }
Source:
private ResponseCallback release(int streamId, ChannelHandlerContext ctx) { LOG.trace("[{}] Releasing stream id {}", logPrefix, streamId); ResponseCallback responseCallback; if (!abortingAllRequests) { responseCallback = MoreObjects.firstNonNull(inFlight.remove(streamId), orphaned.remove(streamId)); } else { responseCallback = orphaned.remove(streamId); } orphanedSize = orphaned.size(); streamIds.release(streamId); if (closingGracefully && inFlight.isEmpty()) { LOG.debug("[{}] Done handling the last pending query, closing channel", logPrefix); ctx.channel().close(); } return responseCallback; }

Target:
private void release(int streamId, ChannelHandlerContext ctx) { LOG.trace("[{}] Releasing stream id {}", logPrefix, streamId); if (inFlight.remove(streamId) != null) { if (closingGracefully && inFlight.isEmpty()) { LOG.debug("[{}] Done handling the last pending query, closing channel", logPrefix); ctx.channel().close(); } } else if (orphaned.remove(streamId) != null) { orphanedSize = orphaned.size(); } streamIds.release(streamId); }
Source:
public ScriptHelper uniqueSshConnection() { setFlag("unique", Identifiers.makeRandomBase64Id(32)); return this; }

Target:
public ScriptHelper uniqueSshConnection() { setFlag(SshMachineLocation.UNIQUE_ID, Identifiers.makeRandomBase64Id(32)); return this; }
Source:
public void reopenCase(String caseId, String containerId, String caseDefinitionId, String payload, String marshallingType) { containerId = context.getContainer(containerId, LatestContainerLocator.get()).getContainerId(); CaseDefinition caseDef = caseRuntimeDataService.getCase(containerId, caseDefinitionId); if( caseDef == null ) { throw new IllegalStateException("Unable to find case '" + caseDefinitionId + "' in container " + containerId); } logger.debug("About to unmarshal data from payload: '{}'", payload); Map<String, Object> data = marshallerHelper.unmarshal(containerId, payload, marshallingType, Map.class); caseService.reopenCase(caseId, containerId, caseDefinitionId, data); logger.debug("Case successfully reopened", caseId); }

Target:
public void reopenCase(String caseId, String containerId, String caseDefinitionId, String payload, String marshallingType) { containerId = context.getContainer(containerId, new ByCaseIdContainerLocator(caseId)).getContainerId(); CaseDefinition caseDef = caseRuntimeDataService.getCase(containerId, caseDefinitionId); if( caseDef == null ) { throw new IllegalStateException("Unable to find case '" + caseDefinitionId + "' in container " + containerId); } logger.debug("About to unmarshal data from payload: '{}'", payload); Map<String, Object> data = marshallerHelper.unmarshal(containerId, payload, marshallingType, Map.class); caseService.reopenCase(caseId, containerId, caseDefinitionId, data); logger.debug("Case successfully reopened", caseId); }
Source:
public void test_no_usages() throws Exception { highlight("<?php $a = 1; "); checkNoSymbolExists(1, 7); checkSymbolExistence(1, 8, true); checkSymbolExistence(1, 9, true); checkNoSymbolExists(1, 10); checkSymbolReferences(1, 8, new LinkedList<>()); }

Target:
public void test_no_usages() throws Exception { highlight("<?php $a = 1; "); checkNoSymbolExists(1, 7); checkSymbolExistence(1, 8); checkSymbolExistence(1, 9); checkNoSymbolExists(1, 10); checkSymbolReferences(1, 8, new LinkedList<>()); }
Source:
public DataElementMetadata extract(Element element) throws InvalidElementException { if (element.getKind() != ElementKind.CLASS) { throw new InvalidElementException( "Element must be class, found " + element.toString() ); } AnnotatedElement helper = new AnnotatedElement(element, elementUtils); if (!helper.hasAnnotation(DataElement.class)) { throw new InvalidElementException( "Element is not annotated with DataElement" ); } Fields fields = new Fields(); fields.collect(DefaultFields.get()); fields.collect(extractFields(element)); return DataElementMetadata.builder() .name(extractName(helper)) .packageName(extractPackageName(element)) .fields(fields) .build(); }

Target:
public DataElementMetadata extract(Element element) throws InvalidElementException { if (element.getKind() != ElementKind.CLASS) { throw new InvalidElementException( "Element must be class, found " + element.toString() ); } if (!hasAnnotation(element, DataElement.class)) { throw new InvalidElementException( "Element is not annotated with DataElement" ); } Fields fields = new Fields(); fields.collect(DefaultFields.get()); fields.collect(extractFields(element)); DataElementMetadata data = DataElementMetadata.builder() .name(extractName(element)) .packageName(extractPackageName(element)) .fields(fields) .build(); return data; }
Source:
public boolean equals( final Object obj ) { if( obj instanceof AESharedItemStack ) { final AESharedItemStack other = (AESharedItemStack) obj; Preconditions.checkState( this.itemStack.getCount() == 1, "ItemStack#getCount() has to be 1" ); Preconditions.checkArgument( other.getDefinition().getCount() != 1, "ItemStack#getCount() has to be 1" ); if( this.itemStack == other.itemStack ) { return true; } return ItemStack.areItemStacksEqual( this.itemStack, other.itemStack ); } return false; }

Target:
public boolean equals( final Object obj ) { if( obj instanceof AESharedItemStack ) { final AESharedItemStack other = (AESharedItemStack) obj; Preconditions.checkState( this.itemStack.getCount() == 1, "ItemStack#getCount() has to be 1" ); Preconditions.checkArgument( other.getDefinition().getCount() == 1, "ItemStack#getCount() has to be 1" ); if( this.itemStack == other.itemStack ) { return true; } return ItemStack.areItemStacksEqual( this.itemStack, other.itemStack ); } return false; }
Source:
public static List<String> getAggregateFunctionInputVariables(final String formula, final boolean isWrapped) { final List<String> aggregateInputVariables = new ArrayList<>(); final String agggregateRegex = "(?i)" + DerivedVariableUtils.AGGREGATE_FUNCTIONS + "\\((\\{\\{(\\w+)}})(,[\\s]?\\{\\{(\\w+)}})*\\)"; Pattern aggregatePattern = Pattern.compile(agggregateRegex); Matcher aggregateMatcher = aggregatePattern.matcher(formula); while (aggregateMatcher.find()) { final String aggregateString = aggregateMatcher.group(); final String aggregateInputRegex = "(\\{\\{\\w+}})"; final Pattern aggregateInputPattern = Pattern.compile(aggregateInputRegex); final Matcher aggregateInputMatcher = aggregateInputPattern.matcher(aggregateString); while(aggregateInputMatcher.find()) { String inputVariable = aggregateInputMatcher.group().replaceAll("(\\{)","").replaceAll("}",""); inputVariable = isWrapped? DerivedVariableUtils.wrapTerm(inputVariable) : inputVariable; aggregateInputVariables.add(inputVariable); } } return aggregateInputVariables; }

Target:
public static List<String> getAggregateFunctionInputVariables(final String formula, final boolean isWrapped) { final List<String> aggregateInputVariables = new ArrayList<>(); Pattern aggregatePattern = Pattern.compile(AGGREGATE_REGEX); Matcher aggregateMatcher = aggregatePattern.matcher(formula); while (aggregateMatcher.find()) { final String aggregateString = aggregateMatcher.group(); final Pattern aggregateInputPattern = Pattern.compile(AGGREGATE_INPUT_REGEX); final Matcher aggregateInputMatcher = aggregateInputPattern.matcher(aggregateString); while(aggregateInputMatcher.find()) { String inputVariable = aggregateInputMatcher.group().replaceAll("(\\{)","").replaceAll("}",""); inputVariable = isWrapped? DerivedVariableUtils.wrapTerm(inputVariable) : inputVariable; aggregateInputVariables.add(inputVariable); } } return aggregateInputVariables; }
Source:
public static void marshallIntCollection(Collection<Integer> collection, ObjectOutput out) throws IOException { final int size = collection == null ? NULL_VALUE : collection.size(); marshallInt(out, size); if (size <= 0) { return; } for (Integer integer : collection) { out.writeInt(integer); } }

Target:
public static void marshallIntCollection(Collection<Integer> collection, ObjectOutput out) throws IOException { final int size = collection == null ? NULL_VALUE : collection.size(); marshallSize(out, size); if (size <= 0) { return; } for (Integer integer : collection) { out.writeInt(integer); } }
Source:
public void testEndOfYearDates() { Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); cal.clear(); cal.set(2015, 11, 30, 12, 0, 0); Date date = cal.getTime(); assertEquals("30/12/2015", TimeHelper.formatDate(TimeHelper.convertDateToLocalDateTime(date))); assertEquals("Wed, 30 Dec, 2015", TimeHelper.formatDateForSessionsForm(TimeHelper.convertDateToLocalDateTime(date))); assertEquals("Wed, 30 Dec 2015, 12:00 NOON", TimeHelper.formatTime12H(TimeHelper.convertDateToLocalDateTime(date))); assertEquals("Wed, 30 Dec 2015, 12:00 NOON UTC+0000", TimeHelper.formatDateTimeForSessions( TimeHelper.convertDateToInstant(date), ZoneId.of("UTC"))); assertEquals("30 Dec 12:00 NOON", TimeHelper.formatDateTimeForInstructorHomePage( TimeHelper.convertDateToLocalDateTime(date))); }

Target:
public void testEndOfYearDates() { LocalDateTime ldt = LocalDateTime.of(2015, Month.DECEMBER, 30, 12, 0); assertEquals("30/12/2015", TimeHelper.formatDate(ldt)); assertEquals("Wed, 30 Dec, 2015", TimeHelper.formatDateForSessionsForm(ldt)); assertEquals("Wed, 30 Dec 2015, 12:00 NOON", TimeHelper.formatTime12H(ldt)); assertEquals("Wed, 30 Dec 2015, 12:00 NOON UTC+0000", TimeHelper.formatDateTimeForSessions(ldt.toInstant(ZoneOffset.UTC), ZoneId.of("UTC"))); assertEquals("30 Dec 12:00 NOON", TimeHelper.formatDateTimeForInstructorHomePage(ldt)); }
Source:
public LoadBlockDefinitionResults loadBlockDefinitions() { logger.info("Loading Blocks..."); LoadBlockDefinitionResults result = new LoadBlockDefinitionResults(); for (AssetUri blockDefUri : Assets.list(AssetType.BLOCK_DEFINITION)) { try (ModuleContext.ContextSpan ignored = ModuleContext.setContext(blockDefUri.getModuleName())) { JsonElement rawJson = readJson(blockDefUri); if (rawJson != null) { JsonObject blockDefJson = rawJson.getAsJsonObject(); if (blockDefJson.has("template") && blockDefJson.get("template").getAsBoolean()) { continue; } logger.debug("Loading {}", blockDefUri); BlockDefinition blockDef = createBlockDefinition(inheritData(blockDefUri, blockDefJson)); if (isShapelessBlockFamily(blockDef)) { result.shapelessDefinitions.add(new FreeformFamily(new BlockUri(blockDefUri.getModuleName(), blockDefUri.getAssetName()), blockDef.categories)); } else { if (blockDef.liquid) { blockDef.rotation = null; blockDef.shapes.clear(); blockDef.shape = trimmedLoweredShape.getURI().toSimpleString(); } if (blockDef.shapes.isEmpty()) { BlockFamilyFactory familyFactory = blockFamilyFactoryRegistry.getBlockFamilyFactory(blockDef.rotation); result.families.add(familyFactory.createBlockFamily(this, blockDefUri, blockDef, blockDefJson)); } else { result.families.addAll(processMultiBlockFamily(blockDefUri, blockDef)); } } } } catch (JsonParseException | NullPointerException e) { logger.error("Failed to load block '{}'", blockDefUri, e); } catch (Exception e) { logger.error("Error loading block {}", blockDefUri, e); } } result.shapelessDefinitions.addAll(loadAutoBlocks()); return result; }

Target:
public LoadBlockDefinitionResults loadBlockDefinitions() { logger.info("Loading Blocks..."); LoadBlockDefinitionResults result = new LoadBlockDefinitionResults(); for (AssetUri blockDefUri : Assets.list(AssetType.BLOCK_DEFINITION)) { try (ModuleContext.ContextSpan ignored = ModuleContext.setContext(blockDefUri.getModuleName())) { JsonElement rawJson = readJson(blockDefUri); if (rawJson != null) { JsonObject blockDefJson = rawJson.getAsJsonObject(); if (blockDefJson.has("template") && blockDefJson.get("template").getAsBoolean()) { continue; } logger.debug("Loading {}", blockDefUri); BlockDefinition blockDef = createBlockDefinition(inheritData(blockDefUri, blockDefJson)); if (isShapelessBlockFamily(blockDef)) { result.shapelessDefinitions.add(new FreeformFamily(new BlockUri(blockDefUri.getModuleName(), blockDefUri.getAssetName()), blockDef.categories)); } else { if (blockDef.liquid) { blockDef.rotation = null; blockDef.shapes.clear(); blockDef.shape = trimmedLoweredShape.getURI().toSimpleString(); } if (blockDef.shapes.isEmpty()) { BlockFamilyFactory familyFactory = blockFamilyFactoryRegistry.getBlockFamilyFactory(blockDef.rotation); result.families.add(familyFactory.createBlockFamily(this, blockDefUri, blockDef, blockDefJson)); } else { result.families.addAll(processMultiBlockFamily(blockDefUri, blockDef)); } } } } catch (Exception e) { logger.error("Error loading block {}", blockDefUri, e); } } result.shapelessDefinitions.addAll(loadAutoBlocks()); return result; }
Source:
public void initialize(String directoryProviderName, Properties properties, BuildContext context) { this.properties = properties; this.directoryProviderName = directoryProviderName; sourceDir = DirectoryProviderHelper.getSourceDirectoryPath( directoryProviderName, properties, true ); log.debugf( "Source directory: %s", sourceDir ); indexDir = DirectoryHelper.getVerifiedIndexPath( directoryProviderName, properties, true ); log.debugf( "Index directory: %s", indexDir ); try { indexName = indexDir.toString(); directory = DirectoryProviderHelper.createFSIndex( indexDir, properties, context.getServiceManager() ); } catch (IOException e) { throw new SearchException( "Unable to initialize index: " + directoryProviderName, e ); } copyChunkSize = DirectoryProviderHelper.getCopyBufferSize( directoryProviderName, properties ); current = 0; }

Target:
public void initialize(String directoryProviderName, Properties properties, BuildContext context) { this.properties = properties; this.directoryProviderName = directoryProviderName; sourceDir = DirectoryProviderHelper.getSourceDirectoryPath( directoryProviderName, properties, true ); log.debugf( "Source directory: %s", sourceDir ); indexDir = DirectoryHelper.getVerifiedIndexPath( directoryProviderName, properties, true ).normalize(); log.debugf( "Index directory: %s", indexDir ); try { directory = DirectoryProviderHelper.createFSIndex( indexDir, properties, context.getServiceManager() ); } catch (IOException e) { throw new SearchException( "Unable to initialize index: " + directoryProviderName, e ); } DirectoryProviderHelper.getCopyBufferSize( directoryProviderName, properties ); current = 0; }
Source:
public boolean offer( PooledConnection pooledConnection ) { boolean offer = queue.offer( pooledConnection ); if ( offer ) { acquiredConnections.remove( pooledConnection ); } return offer; }

Target:
public boolean offer( PooledConnection pooledConnection ) { acquiredConnections.remove( pooledConnection ); boolean offer = queue.offer( pooledConnection ); if (!offer) { pooledConnection.dispose(); } if (isTerminating.get()) { PooledConnection poll = queue.poll(); if (poll != null) { poll.dispose(); } } return offer; }