auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void generateInstallSection(StringBuilder buffer) { buffer.append("%install\n"); buffer.append("rm -rf %{buildroot}\n\n"); buffer.append("%if 0%{?with_python3}\n"); buffer.append("pushd %{py3dir}\n"); buffer.append("%{__python3} setup.py install --skip-build --root %{buildroot}\n"); buffer.append("popd\n"); buffer.append("%endif # with_python3\n\n"); buffer.append("%{__python} setup.py install --skip-build --root %{buildroot}\n\n\n"); }

Target:
private void generateInstallSection(StringBuilder buffer) { buffer.append("%install\n"); buffer.append("%if 0%{?with_python3}\n"); buffer.append("pushd %{py3dir}\n"); buffer.append("%{__python3} setup.py install --skip-build --root %{buildroot}\n"); buffer.append("popd\n"); buffer.append("%endif # with_python3\n\n"); buffer.append("%{__python} setup.py install --skip-build --root %{buildroot}\n\n\n"); }
Source:
private void loadSnapshot(SingleFileSnapshotInfo snapshot) throws IOException { if (snapshot == null) { LOG.info("No snapshot to load"); return; } LOG.info("Loading Snapshot {}", snapshot); final File snapshotFile = snapshot.getFile().getPath().toFile(); if (!snapshotFile.exists()) { LOG.error("The snapshot does not exist", snapshot); throw new FileNotFoundException( String.format("The snapshot file %s does not exist", snapshotFile.getPath())); } try { resetState(); setLastAppliedTermIndex(snapshot.getTermIndex()); install(snapshotFile); } catch (Exception e) { LOG.error("Failed to load snapshot {}", snapshot, e); throw e; } }

Target:
private void loadSnapshot(SingleFileSnapshotInfo snapshot) throws IOException { if (snapshot == null) { LOG.info("No snapshot to load"); return; } LOG.info("Loading Snapshot {}", snapshot); final File snapshotFile = snapshot.getFile().getPath().toFile(); if (!snapshotFile.exists()) { throw new FileNotFoundException( String.format("The snapshot file %s does not exist", snapshotFile.getPath())); } try { resetState(); setLastAppliedTermIndex(snapshot.getTermIndex()); install(snapshotFile); } catch (Exception e) { throw new IOException(String.format("Failed to load snapshot %s", snapshot), e); } }
Source:
private void restartServices(ClustersResourceApi clustersResourceApi) throws ApiException, CloudbreakException { List<String> serviceNames = getClusterServices(); ApiRestartClusterArgs restartClusterArgs = new ApiRestartClusterArgs(); restartClusterArgs.setRestartServiceNames(serviceNames); restartClusterArgs.setRedeployClientConfiguration(true); ApiCommand restartCommand = clustersResourceApi.restartCommand(stack.getName(), restartClusterArgs); PollingResult pollingResult = clouderaManagerPollingServiceProvider.startPollingCmServicesRestart(stack, apiClient, restartCommand.getId()); if (isExited(pollingResult)) { throw new CancellationException("Cluster was terminated while refreshing services."); } else if (isTimeout(pollingResult)) { throw new CloudbreakException("Timeout while was restarting services."); } }

Target:
private void restartServices(ClustersResourceApi clustersResourceApi) throws ApiException, CloudbreakException { ApiRestartClusterArgs restartClusterArgs = new ApiRestartClusterArgs(); restartClusterArgs.setRedeployClientConfiguration(true); ApiCommand restartCommand = clustersResourceApi.restartCommand(stack.getName(), restartClusterArgs); PollingResult pollingResult = clouderaManagerPollingServiceProvider.startPollingCmServicesRestart(stack, apiClient, restartCommand.getId()); if (isExited(pollingResult)) { throw new CancellationException("Cluster was terminated while restarting services."); } else if (isTimeout(pollingResult)) { throw new CloudbreakException("Timeout happened while restarting services."); } }
Source:
public GoGoDuck(Catalog catalog, String profile, String subset, String outputFile, Integer limit) { this(profile, subset, outputFile, limit); this.urlIndexInterface = new UrlIndexFeatureSource(this.userLog, catalog); }

Target:
public GoGoDuck(Catalog catalog, String profile, String subset, String outputFile, Integer limit) { this(profile, subset, outputFile, limit); this.indexReader = new FeatureSourceIndexReader(this.userLog, catalog); }
Source:
public void close() throws Exception { if (iterator instanceof CloseableIterator) { ((CloseableIterator) iterator).close(); } }

Target:
public void close() { CloseableIterator.closeIterator(iterator); }
Source:
public void init() { this.entityRewrite = EntityMap.getEntityMap( getPendingConnection().getVersion() ); this.displayName = name; switch ( getPendingConnection().getListener().getTabListType() ) { case "EMPTY": tabListHandler = new Global( this ); break; default: tabListHandler = new ServerUnique( this ); break; } Collection<String> g = bungee.getConfigurationAdapter().getGroups( name ); for ( String s : g ) { addGroups( s ); } }

Target:
public void init() { this.entityRewrite = EntityMap.getEntityMap( getPendingConnection().getVersion() ); this.displayName = name; switch ( getPendingConnection().getListener().getTabListType() ) { case "EMPTY": if( getPendingConnection().getVersion() < ProtocolConstants.MINECRAFT_SNAPSHOT ) { tabListHandler = new Empty(this); } else { tabListHandler = new EmptyNew(this); } break; default: tabListHandler = new ServerUnique( this ); break; } Collection<String> g = bungee.getConfigurationAdapter().getGroups( name ); for ( String s : g ) { addGroups( s ); } }
Source:
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException { if (isTwoFactorAuthenticationEnabled()) { if (!httpServletRequest.getRequestURI().contains(TwoFactorAuthenticationController.URI) && SecurityUtils.currentUserIsAuthenticated() && !httpServletRequest.getRequestURI() .toLowerCase() .equals(CHANGE_PASSWORD_URI.toLowerCase())) { if (!isUserTwoFactorAuthenticated() && !hasAuthenticatedMolgenisToken() && !isUserRecoveryAuthenticated()) { if (isTwoFactorAuthenticationEnforced() || userUsesTwoFactorAuthentication()) { if (twoFactorAuthenticationService.isConfiguredForUser()) { redirectStrategy.sendRedirect(httpServletRequest, httpServletResponse, TwoFactorAuthenticationController.URI + TwoFactorAuthenticationController.TWO_FACTOR_CONFIGURED_URI); return; } else { redirectStrategy.sendRedirect(httpServletRequest, httpServletResponse, TwoFactorAuthenticationController.URI + TwoFactorAuthenticationController.TWO_FACTOR_ACTIVATION_URI); return; } } } } } filterChain.doFilter(httpServletRequest, httpServletResponse); }

Target:
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException { if (isUserShouldTwoFactorAuthenticate() && currentUserIsAuthenticated() && isNotProtected( httpServletRequest.getRequestURI()) && isInsufficientlyAuthenticated()) { redirectToTwoFactorAuthenticationController(httpServletRequest, httpServletResponse); } else { filterChain.doFilter(httpServletRequest, httpServletResponse); } }
Source:
public AzkabanWebServer(final Props props, final Server server, final ExecutorManager executorManager, final ProjectManager projectManager, final TriggerManager triggerManager, final MetricsManager metricsManager, final MetricRegistry metricRegistry, final SessionCache sessionCache, final UserManager userManager, final ScheduleManager scheduleManager, final VelocityEngine velocityEngine) { this.props = requireNonNull(props); this.server = requireNonNull(server); this.executorManager = requireNonNull(executorManager); this.projectManager = requireNonNull(projectManager); this.triggerManager = requireNonNull(triggerManager); this.metricsManager = requireNonNull(metricsManager); this.registry = requireNonNull(metricRegistry); this.sessionCache = requireNonNull(sessionCache); this.userManager = requireNonNull(userManager); this.scheduleManager = requireNonNull(scheduleManager); this.velocityEngine = requireNonNull(velocityEngine); loadBuiltinCheckersAndActions(); final String triggerPluginDir = props.getString("trigger.plugin.dir", "plugins/triggers"); loadPluginCheckersAndActions(triggerPluginDir); if (props.containsKey(DEFAULT_TIMEZONE_ID)) { final String timezone = props.getString(DEFAULT_TIMEZONE_ID); System.setProperty("user.timezone", timezone); TimeZone.setDefault(TimeZone.getTimeZone(timezone)); DateTimeZone.setDefault(DateTimeZone.forID(timezone)); logger.info("Setting timezone to " + timezone); } configureMBeanServer(); }

Target:
public AzkabanWebServer(final Props props, final Server server, final ExecutorManager executorManager, final ProjectManager projectManager, final TriggerManager triggerManager, final MetricsManager metricsManager, final MetricRegistry metricRegistry, final SessionCache sessionCache, final UserManager userManager, final ScheduleManager scheduleManager, final VelocityEngine velocityEngine) { this.props = requireNonNull(props, "props is null."); this.server = requireNonNull(server, "server is null."); this.executorManager = requireNonNull(executorManager, "executorManager is null."); this.projectManager = requireNonNull(projectManager, "projectManager is null."); this.triggerManager = requireNonNull(triggerManager, "triggerManager is null."); this.metricsManager = requireNonNull(metricsManager, "metricsManager is null."); this.registry = requireNonNull(metricRegistry, "metricRegistry is null."); this.sessionCache = requireNonNull(sessionCache, "sessionCache is null."); this.userManager = requireNonNull(userManager, "userManager is null."); this.scheduleManager = requireNonNull(scheduleManager, "scheduleManager is null."); this.velocityEngine = requireNonNull(velocityEngine, "velocityEngine is null."); loadBuiltinCheckersAndActions(); final String triggerPluginDir = props.getString("trigger.plugin.dir", "plugins/triggers"); loadPluginCheckersAndActions(triggerPluginDir); if (props.containsKey(DEFAULT_TIMEZONE_ID)) { final String timezone = props.getString(DEFAULT_TIMEZONE_ID); System.setProperty("user.timezone", timezone); TimeZone.setDefault(TimeZone.getTimeZone(timezone)); DateTimeZone.setDefault(DateTimeZone.forID(timezone)); logger.info("Setting timezone to " + timezone); } configureMBeanServer(); }
Source:
public void onOpenDataFile(OpenDataFileEvent event) { final String dataFilePath = event.getFile().getPath(); if (dataFilePath.endsWith(".rds")) { globalDisplay_.promptForText( "Load R Object", "Load '" + dataFilePath + "' into an R object named:", FilePathUtils.fileNameSansExtension(dataFilePath), new ProgressOperationWithInput<String>() { @Override public void execute(String input, ProgressIndicator indicator) { if (!RegexUtil.isSyntacticRIdentifier(input)) input = "`" + input.replaceAll("`", "\\\\`") + "`"; consoleDispatcher_.executeCommand( input + " <- readRDS", dataFilePath); indicator.onCompleted(); } }); } else { globalDisplay_.showYesNoMessage(GlobalDisplay.MSG_QUESTION, "Confirm Load RData", "Do you want to load the R data file \"" + dataFilePath + "\" " + "into the global environment?", new ProgressOperation() { public void execute(ProgressIndicator indicator) { consoleDispatcher_.executeCommand( "load", FileSystemItem.createFile(dataFilePath)); indicator.onCompleted(); } }, true); } }

Target:
public void onOpenDataFile(OpenDataFileEvent event) { final String dataFilePath = event.getFile().getPath(); if (Pattern.create("[.]rds$", "i").test(dataFilePath)) { globalDisplay_.promptForText( "Load R Object", "Load '" + dataFilePath + "' into an R object named:", FilePathUtils.fileNameSansExtension(dataFilePath), new ProgressOperationWithInput<String>() { @Override public void execute(String input, ProgressIndicator indicator) { if (!RegexUtil.isSyntacticRIdentifier(input)) input = "`" + input.replaceAll("`", "\\\\`") + "`"; consoleDispatcher_.executeCommand( input + " <- readRDS", dataFilePath); indicator.onCompleted(); } }); } else { globalDisplay_.showYesNoMessage(GlobalDisplay.MSG_QUESTION, "Confirm Load RData", "Do you want to load the R data file \"" + dataFilePath + "\" " + "into the global environment?", new ProgressOperation() { public void execute(ProgressIndicator indicator) { consoleDispatcher_.executeCommand( "load", FileSystemItem.createFile(dataFilePath)); indicator.onCompleted(); } }, true); } }
Source:
private void moveJobToAddressModeTaskQueue() { if (!addressModeOn) { return; } taskQueuer.scheduleAdminEmailPreparationInAddressMode(emailId, addressReceiverListString); statusToAdmin += "<br/>" + "Receipient: " + addressReceiverListString; statusToUser.add(new StatusMessage("Email will be sent within an hour to " + addressReceiverListString, StatusMessageColor.SUCCESS)); }

Target:
private void moveJobToAddressModeTaskQueue() { if (!addressModeOn) { return; } taskQueuer.scheduleAdminEmailPreparationInAddressMode(emailId, addressReceiverListString); statusToAdmin += "<br/>" + "Recipient: " + addressReceiverListString; statusToUser.add(new StatusMessage("Email will be sent within an hour to " + addressReceiverListString, StatusMessageColor.SUCCESS)); }
Source:
public PatchSet getBasePatchSet(ChangeEdit edit) throws IOException, InvalidChangeOperationException { Change change = edit.getChange(); Repository repo = gitManager.openRepository(change.getProject()); try { RevWalk rw = new RevWalk(repo); ObjectInserter inserter = repo.newObjectInserter(); try { RevCommit editCommit = rw.parseCommit(edit.getRef().getObjectId()); return getBasePatchSet(edit, editCommit); } finally { inserter.release(); rw.release(); } } finally { repo.close(); } }

Target:
public PatchSet getBasePatchSet(ChangeEdit edit) throws IOException, InvalidChangeOperationException { Change change = edit.getChange(); Repository repo = gitManager.openRepository(change.getProject()); try { RevWalk rw = new RevWalk(repo); try { return getBasePatchSet(edit, rw.parseCommit( edit.getRef().getObjectId())); } finally { rw.release(); } } finally { repo.close(); } }
Source:
public void returnsMessage() throws Exception { final Response mock = new Response("A message", Status.OK); Assert.assertEquals(Status.OK, mock.status()); }

Target:
public void returnsMessage() throws Exception { final Response response = new Response("A message", Status.OK); MatcherAssert.assertThat( response.status(), Matchers.equalTo(Status.OK) ); }
Source:
private boolean applyTypedFilter(Instance instance) { for (String type : this.typeFilters.keySet()) { if (instance.getDefinition().getName().getLocalPart().equals(type + "Type")) { for (Filter innerFilter : this.typeFilters.get(type)) { if (innerFilter.match(instance)) return true; } return false; } } return true; }

Target:
private boolean applyTypedFilter(Instance instance) { for (String type : this.typeFilters.keySet()) { if (checkType(instance.getDefinition(), type)) { for (Filter innerFilter : this.typeFilters.get(type)) { if (innerFilter.match(instance)) return true; } return false; } } return false; }
Source:
double getExistingEditorWidth() { double existingWidth = DMNGridColumn.DEFAULT_WIDTH; final GridCell<?> cell = model.getRow(0).getCells().get(0); if (cell != null) { final GridCellValue<?> value = cell.getValue(); if (value instanceof ExpressionCellValue) { final ExpressionCellValue ecv = (ExpressionCellValue) value; final Optional<BaseExpressionGrid> editor = ecv.getValue(); if (editor.isPresent()) { final BaseExpressionGrid beg = editor.get(); existingWidth = Math.max(existingWidth, beg.getWidth() + beg.getPadding() * 2); existingWidth = Math.max(existingWidth, beg.getMinimumWidth() + beg.getPadding() * 2); } } } return existingWidth; }

Target:
double getExistingEditorWidth() { double existingWidth = DMNGridColumn.DEFAULT_WIDTH; final GridCell<?> cell = model.getRow(0).getCells().get(0); if (cell != null) { final GridCellValue<?> value = cell.getValue(); if (value instanceof ExpressionCellValue) { final ExpressionCellValue ecv = (ExpressionCellValue) value; final Optional<BaseExpressionGrid> editor = ecv.getValue(); if (editor.isPresent()) { final BaseExpressionGrid beg = editor.get(); existingWidth = Collections.max(Arrays.asList(existingWidth, beg.getWidth() + beg.getPadding() * 2, beg.getMinimumWidth() + beg.getPadding() * 2)); } } } return existingWidth; }
Source:
public boolean performNextOperation(int completedChildCount) { if (getParameters().getStage() == CopyStage.DEST_CREATION) { updateStage(CopyStage.DATA_COPY); if (getParameters().isCollapse()) { CopyDataCommandParameters parameters = new CopyDataCommandParameters(getParameters().getStoragePoolId(), buildImageLocationInfo(getParameters().getDestDomain(), getParameters().getDestImageGroupId(), getParameters().getDestinationImageId()), buildImageLocationInfo(getParameters().getSrcDomain(), getParameters().getImageGroupID(), getParameters().getImageId()), true); parameters.setEndProcedure(EndProcedure.COMMAND_MANAGED); parameters.setParentCommand(getActionType()); parameters.setParentParameters(getParameters()); runInternalAction(VdcActionType.CopyData, parameters); } else { CopyImageGroupVolumesDataCommandParameters p = new CopyImageGroupVolumesDataCommandParameters( getParameters().getStoragePoolId(), getParameters().getSrcDomain(), getParameters().getImageGroupID(), getParameters().getDestDomain(), getActionType(), getParameters() ); p.setEndProcedure(EndProcedure.COMMAND_MANAGED); runInternalAction(VdcActionType.CopyImageGroupVolumesData, p); } return true; } return false; }

Target:
public boolean performNextOperation(int completedChildCount) { if (getParameters().getStage() == CopyStage.DEST_CREATION) { updateStage(CopyStage.DATA_COPY); if (getParameters().isCollapse()) { CopyDataCommandParameters parameters = new CopyDataCommandParameters(getParameters().getStoragePoolId(), buildImageLocationInfo(getParameters().getSrcDomain(), getParameters().getImageGroupID(), getParameters().getImageId()), buildImageLocationInfo(getParameters().getDestDomain(), getParameters().getDestImageGroupId(), getParameters().getDestinationImageId()), true); parameters.setEndProcedure(EndProcedure.COMMAND_MANAGED); parameters.setParentCommand(getActionType()); parameters.setParentParameters(getParameters()); runInternalAction(VdcActionType.CopyData, parameters); } else { CopyImageGroupVolumesDataCommandParameters p = new CopyImageGroupVolumesDataCommandParameters( getParameters().getStoragePoolId(), getParameters().getSrcDomain(), getParameters().getImageGroupID(), getParameters().getDestDomain(), getActionType(), getParameters() ); p.setEndProcedure(EndProcedure.COMMAND_MANAGED); runInternalAction(VdcActionType.CopyImageGroupVolumesData, p); } return true; } return false; }
Source:
public void textBoxKeyPress(final TextBoxWidget tbwe) { if (getDataObject() != null) { _ignoreChanges = true; try { if (tbwe == getPosAngleTextBox()) { final double defaultPositionAngle = 0.0; getDataObject().setPosAngleDegrees(tbwe.getDoubleValue(defaultPositionAngle)); } else if (tbwe == getExposureTimeTextBox()) { final double expTime = tbwe.getDoubleValue(getDefaultExposureTime()); final double expTimeAdj = isForceIntegerExposureTime() ? Math.floor(expTime) : expTime; getDataObject().setExposureTime(expTimeAdj); } else if (tbwe == getCoaddsTextBox()) { final int defaultCoadds = 1; getDataObject().setCoadds(tbwe.getIntegerValue(defaultCoadds)); } } finally { _ignoreChanges = false; } } }

Target:
public void textBoxKeyPress(final TextBoxWidget tbwe) { if (getDataObject() != null) { _ignoreChanges = true; try { if (tbwe == getPosAngleTextBox()) { final double defaultPositionAngle = 0.0; getDataObject().setPosAngleDegrees(tbwe.getDoubleValue(defaultPositionAngle)); } else if (tbwe == getExposureTimeTextBox()) { final double expTime = tbwe.getDoubleValue(getDefaultExposureTime()); getDataObject().setExposureTime(expTime); } else if (tbwe == getCoaddsTextBox()) { final int defaultCoadds = 1; getDataObject().setCoadds(tbwe.getIntegerValue(defaultCoadds)); } } finally { _ignoreChanges = false; } } }
Source:
public ValueMatcher makeValueMatcher(final LongColumnSelector selector, final String value) { Long matchVal = DimensionHandlerUtils.convertObjectToLong(value); if (matchVal == null) { matchVal = DimensionHandlerUtils.getIntegralFromFloatString(value); } if (matchVal == null) { return BooleanValueMatcher.of(false); } final long matchValLong = matchVal; return new ValueMatcher() { @Override public boolean matches() { return selector.get() == matchValLong; } }; }

Target:
public ValueMatcher makeValueMatcher(final LongColumnSelector selector, final String value) { final Long matchVal = DimensionHandlerUtils.convertObjectToLong(value); if (matchVal == null) { return BooleanValueMatcher.of(false); } final long matchValLong = matchVal; return new ValueMatcher() { @Override public boolean matches() { return selector.get() == matchValLong; } }; }
Source:
protected List<String> getModules() { return ImmutableList.of("+", "Data.List", "Data.Maybe", "Data.Either"); }

Target:
protected List<String> getModules() { return ImmutableList.of("CLaSH.Prelude", "Data.List", "Data.Maybe", "Data.Either"); }
Source:
public static void afterClass() throws IOException, OperationException, TimeoutException, InterruptedException { operations.removeIfExists(serviceAddress); Administration administration = new Administration(client); administration.restartIfRequired(); administration.reloadIfRequired(); }

Target:
public static void afterClass() throws IOException, OperationException, TimeoutException, InterruptedException { try { operations.removeIfExists(serviceAddress); Administration administration = new Administration(client); administration.reloadIfRequired(); } finally { client.close(); } }
Source:
private void updateGtidSet(Event event) { EventHeader eventHeader = event.getHeader(); if (eventHeader.getEventType() == EventType.GTID) { GtidEventData gtidEventData = (GtidEventData) unwrapEventData(event.getData()); currentGtid = gtidEventData.getGtid(); } else if ( gtidSet != null ) { if (eventHeader.getEventType() == EventType.XID) { addGtidToSet(currentGtid); } else if ( eventHeader.getEventType() == EventType.QUERY) { QueryEventData qed = (QueryEventData) unwrapEventData(event.getData()); String sql = qed.getSql(); if ( sql != null && sql.toUpperCase().startsWith("COMMIT") ) { addGtidToSet(currentGtid); } } } }

Target:
private void updateGtidSet(Event event) { synchronized (gtidSetAccessLock) { if (gtidSet == null) { return; } } EventHeader eventHeader = event.getHeader(); if (eventHeader.getEventType() == EventType.GTID) { GtidEventData gtidEventData = (GtidEventData) unwrapEventData(event.getData()); currentGtid = gtidEventData.getGtid(); return; } switch(eventHeader.getEventType()) { case XID: addGtidToSet(currentGtid); inGTIDTransaction = false; break; case QUERY: QueryEventData qed = (QueryEventData) unwrapEventData(event.getData()); String sql = qed.getSql(); if (sql == null) { break; } sql = sql.toUpperCase(); if (sql.startsWith("BEGIN")) { inGTIDTransaction = true; } else if (sql.startsWith("COMMIT")) { addGtidToSet(currentGtid); inGTIDTransaction = false; } else if (!inGTIDTransaction) { addGtidToSet(currentGtid); } default: } }
Source:
public void http_url_exist_and_is_modified() throws Exception { stubFor(get(urlEqualTo("/exist.txt")).willReturn( aResponse().withStatus(200).withHeader("Content-Type", "text/plain").withHeader("Last-Modified", "Mon, 11 Jun 2007 18:53:14 GMT").withBody("exists"))); String url = "<LINK_0>" + wireMockRule.port() + "/exist.txt"; UrlResource res = new UrlResource(url); assertThat(res.exists(), is(true)); assertThat(res.lastModified(), greaterThan(0L)); try { File file = res.getFile(); fail("File should not exist: " + file); } catch (FileNotFoundException e) { } InputStream in = res.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IoUtils.copy(in, baos); String actual = new String(baos.toByteArray(), StandardCharsets.UTF_8); String expected = "exists"; assertThat(actual, is(expected)); }

Target:
public void http_url_exist_and_is_modified() throws Exception { stubFor(get(urlEqualTo("/exist.txt")).willReturn( aResponse().withStatus(200).withHeader("Content-Type", "text/plain").withHeader("Last-Modified", "Mon, 11 Jun 2007 18:53:14 GMT").withBody("exists"))); String url = "<LINK_0>" + wireMockRule.port() + "/exist.txt"; UrlResource res = new UrlResource(url); assertThat(res.exists(), is(true)); assertThat(res.lastModified(), greaterThan(0L)); try { File file = res.getFile(); fail("File should not exist: " + file); } catch (FileNotFoundRuntimeException e) { } InputStream in = res.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IoUtils.copy(in, baos); String actual = new String(baos.toByteArray(), StandardCharsets.UTF_8); String expected = "exists"; assertThat(actual, is(expected)); }
Source:
public Response queryUserTasksByVariables(@Context HttpHeaders headers, String payload, @ApiParam(value = "optional pagination - at which page to start, defaults to 0 (meaning first)", required = false) @QueryParam("page") @DefaultValue("0") Integer page, @ApiParam(value = "optional pagination - size of the result, defaults to 10", required = false) @QueryParam("pageSize") @DefaultValue("10") Integer pageSize) { Header conversationIdHeader = buildConversationIdHeader("", context, headers); Variant v = getVariant(headers); try { String type = getContentType(headers); ProcessInstanceUserTaskWithVariablesList taskVariableSummaryList = runtimeDataServiceBase.queryUserTasksByVariables(payload, type, new QueryContext(page * pageSize, pageSize)); logger.debug("Returning result of process instance search: {}", taskVariableSummaryList); return createCorrectVariant(taskVariableSummaryList, headers, Response.Status.OK, conversationIdHeader); } catch (Exception e) { logger.error("Unexpected error during processing {}", e.getMessage(), e); return internalServerError(errorMessage(e), v, conversationIdHeader); } }

Target:
public Response queryUserTasksByVariables(@Context HttpHeaders headers, String payload, @ApiParam(value = "optional pagination - at which page to start, defaults to 0 (meaning first)", required = false) @QueryParam("page") @DefaultValue("0") Integer page, @ApiParam(value = "optional pagination - size of the result, defaults to 10", required = false) @QueryParam("pageSize") @DefaultValue("10") Integer pageSize) { Header conversationIdHeader = buildConversationIdHeader("", context, headers); Variant v = getVariant(headers); try { String type = getContentType(headers); ProcessInstanceUserTaskWithVariablesList taskVariableSummaryList = runtimeDataServiceBase.queryUserTasksByVariables(payload, type, new QueryContext(page * pageSize, pageSize)); logger.debug("Returning result of process tasks search: {}", taskVariableSummaryList); return createCorrectVariant(taskVariableSummaryList, headers, Response.Status.OK, conversationIdHeader); } catch (Exception e) { logger.error("Unexpected error during processing {}", e.getMessage(), e); return internalServerError(errorMessage(e), v, conversationIdHeader); } }
Source:
public RunIdGenerator(CoordinationUtils coordinationUtils, MetadataStore metadataStore) { Preconditions.checkNotNull(coordinationUtils, "CoordinationUtils cannot be null"); Preconditions.checkNotNull(metadataStore, "MetadataStore cannot be null"); this.coordinationUtils = coordinationUtils; this.metadataStore = metadataStore; this.clusterMembership = coordinationUtils.getClusterMembership(); if (clusterMembership == null) { throw new SamzaException("Failed to create utils for run id generation"); } }

Target:
public RunIdGenerator(CoordinationUtils coordinationUtils, MetadataStore metadataStore) { Preconditions.checkNotNull(coordinationUtils, "CoordinationUtils cannot be null"); Preconditions.checkNotNull(metadataStore, "MetadataStore cannot be null"); this.coordinationUtils = coordinationUtils; this.metadataStore = metadataStore; this.clusterMembership = coordinationUtils.getClusterMembership(); Preconditions.checkNotNull(this.clusterMembership, "Failed to create utils for run id generation"); }
Source:
public Folder getFolder() { return this.folder; }

Target:
protected Folder getFolder() { return this.folder; }
Source:
public BenchmarkSuite( BenchmarkSuiteInfo suiteInfo, List<BenchmarkQuery> queries) { this.suiteInfo = requireNonNull(suiteInfo, "SuiteInfo is null"); this.queryMap = new HashMap(); for (BenchmarkQuery query : queries) { queryMap.put(query.getName(), query); } }

Target:
public BenchmarkSuite( BenchmarkSuiteInfo suiteInfo, List<BenchmarkQuery> queries) { this.suiteInfo = requireNonNull(suiteInfo, "SuiteInfo is null"); this.queries = queries.stream() .collect(toImmutableMap(BenchmarkQuery::getName, identity())); }
Source:
public JSONObject toJSONObject() { JSONObject mainObj = new JSONObject(); try { mainObj.put("notification_enabled", notificationEnabled); mainObj.put("push_disabled", pushDisabled); mainObj.put("subscribed", subscribed); mainObj.put("user_id", userId); mainObj.put("push_token", pushToken); mainObj.put("email_user_id", emailUserId); mainObj.put("email_address", emailAddress); } catch (Throwable t) { t.printStackTrace(); } return mainObj; }

Target:
public JSONObject toJSONObject() { JSONObject mainObj = new JSONObject(); try { mainObj.put("areNotificationsEnabled", areNotificationsEnabled); mainObj.put("isPushDisabled", pushDisabled); mainObj.put("isSubscribed", subscribed); mainObj.put("userId", userId); mainObj.put("pushToken", pushToken); mainObj.put("emailUserId", emailUserId); mainObj.put("emailAddress", emailAddress); } catch (Throwable t) { t.printStackTrace(); } return mainObj; }
Source:
private void flushAndMakeCheckpoints() { synchronized (DatastreamEventProducerImpl.this) { _transportProvider.flush(); if (_checkpointPolicy == CheckpointPolicy.DATASTREAM) { _checkpointProvider.commit(_latestCheckpoints); } _safeCheckpoints.putAll(_latestCheckpoints); } }

Target:
private void flushAndMakeCheckpoints() throws DatastreamException { synchronized (DatastreamEventProducerImpl.this) { if (!_pendingCheckpoint) { return; } try { LOG.info(String.format("Flush started, tasks = [%s].", _taskDesc)); _transportProvider.flush(); LOG.info("Flush ended."); } catch (Throwable t) { throw new DatastreamException(String.format("Flush failed, tasks = [%s].", _taskDesc), t); } if (_checkpointPolicy == CheckpointPolicy.DATASTREAM) { try { LOG.info(String.format("Checkpoint commit started, tasks = [%s].", _taskDesc)); _checkpointProvider.commit(_latestCheckpoints); LOG.info("Commit ended."); } catch (Throwable t) { throw new DatastreamException(String.format("Checkpoint commit failed, tasks = [%s].", _taskDesc), t); } } _safeCheckpoints.putAll(_latestCheckpoints); _pendingCheckpoint = false; LOG.debug("Safe checkpoints: " + _latestCheckpoints); } }
Source:
private VDSReturnValue handleVdsResult(VDSReturnValue result) { if (!StringUtils.isEmpty(result.getExceptionString())) { VdcBLLException exp; if (result.getVdsError() != null) { exp = new VdcBLLException(result.getVdsError().getCode(), result.getExceptionString()); } else { exp = new VdcBLLException(VdcBllErrors.ENGINE, result.getExceptionString()); } throw exp; } return result; }

Target:
private VDSReturnValue handleVdsResult(VDSReturnValue result) { if (StringUtils.isNotEmpty(result.getExceptionString())) { VdcBLLException exp; if (result.getVdsError() != null) { exp = new VdcBLLException(result.getVdsError().getCode(), result.getExceptionString()); } else { exp = new VdcBLLException(VdcBllErrors.ENGINE, result.getExceptionString()); } throw exp; } return result; }
Source:
public List<Tree.Kind> nodesToVisit() { ArrayList<Tree.Kind> nodesToVisit = new ArrayList<>(super.nodesToVisit()); nodesToVisit.add(Tree.Kind.CLASS); nodesToVisit.add(Tree.Kind.ASSIGNMENT); nodesToVisit.add(Tree.Kind.STATIC_INITIALIZER); return nodesToVisit; }

Target:
public List<Tree.Kind> nodesToVisit() { List<Tree.Kind> nodesToVisit = new ArrayList<>(super.nodesToVisit()); nodesToVisit.add(Tree.Kind.CLASS); nodesToVisit.add(Tree.Kind.ASSIGNMENT); nodesToVisit.add(Tree.Kind.STATIC_INITIALIZER); return nodesToVisit; }
Source:
public ResultSummary process(Fixture fixture) throws IOException { SummarizingResultRecorder resultRecorder = new SummarizingResultRecorder(); resultRecorder.setSpecificationDescription(fixture.getSpecificationDescription()); getSpecification(fixture).process(evaluatorFactory.createEvaluator(fixture.getFixtureObject()), resultRecorder, fixture); return resultRecorder; }

Target:
public ResultSummary process(Fixture fixture) throws IOException { SummarizingResultRecorder resultRecorder = new SummarizingResultRecorder(); Evaluator evaluator = evaluatorFactory.createEvaluator(fixture); getSpecification().process(evaluator, resultRecorder, fixture); return resultRecorder; }
Source:
public Aggregation toDruidAggregation( final String name, final RowSignature rowSignature, final List<Aggregation> existingAggregations, final Project project, final AggregateCall aggregateCall, final DimFilter filter ) { final RexNode rexNode = Expressions.fromFieldAccess( rowSignature, project, Iterables.getOnlyElement(aggregateCall.getArgList()) ); final RowExtraction rex = Expressions.toRowExtraction( rowSignature.getRowOrder(), rexNode ); if (rex == null) { return null; } final AggregatorFactory aggregatorFactory; if (rowSignature.getColumnType(rex.getColumn()) == ValueType.COMPLEX) { aggregatorFactory = new HyperUniquesAggregatorFactory(name, rex.getColumn()); } else { final SqlTypeName sqlTypeName = rexNode.getType().getSqlTypeName(); final ValueType outputType = RowSignature.getValueTypeForSqlTypeName(sqlTypeName); if (outputType == null) { throw new ISE("Cannot translate sqlTypeName[%s] to Druid type for field[%s]", sqlTypeName, name); } final DimensionSpec dimensionSpec = rex.toDimensionSpec(rowSignature, null, null); if (dimensionSpec == null) { return null; } aggregatorFactory = new CardinalityAggregatorFactory(name, ImmutableList.of(dimensionSpec), false); } return Aggregation.createFinalizable( ImmutableList.<AggregatorFactory>of(aggregatorFactory), null, new PostAggregatorFactory() { @Override public PostAggregator factorize(String outputName) { return new HyperUniqueFinalizingPostAggregator(outputName, name); } } ).filter(filter); }

Target:
public Aggregation toDruidAggregation( final String name, final RowSignature rowSignature, final List<Aggregation> existingAggregations, final Project project, final AggregateCall aggregateCall, final DimFilter filter ) { final RexNode rexNode = Expressions.fromFieldAccess( rowSignature, project, Iterables.getOnlyElement(aggregateCall.getArgList()) ); final RowExtraction rex = Expressions.toRowExtraction( rowSignature.getRowOrder(), rexNode ); if (rex == null) { return null; } final AggregatorFactory aggregatorFactory; if (rowSignature.getColumnType(rex.getColumn()) == ValueType.COMPLEX) { aggregatorFactory = new HyperUniquesAggregatorFactory(name, rex.getColumn()); } else { final SqlTypeName sqlTypeName = rexNode.getType().getSqlTypeName(); final ValueType outputType = Calcites.getValueTypeForSqlTypeName(sqlTypeName); if (outputType == null) { throw new ISE("Cannot translate sqlTypeName[%s] to Druid type for field[%s]", sqlTypeName, name); } final DimensionSpec dimensionSpec = rex.toDimensionSpec(rowSignature, null, ValueType.STRING); if (dimensionSpec == null) { return null; } aggregatorFactory = new CardinalityAggregatorFactory(name, ImmutableList.of(dimensionSpec), false); } return Aggregation.createFinalizable( ImmutableList.<AggregatorFactory>of(aggregatorFactory), null, new PostAggregatorFactory() { @Override public PostAggregator factorize(String outputName) { return new HyperUniqueFinalizingPostAggregator(outputName, name); } } ).filter(filter); }
Source:
protected void setup( Mapper<ImmutableBytesWritable, Result, ImmutableBytesWritable, Put>.Context context) throws java.io.IOException, InterruptedException { Configuration myConf = context.getConfiguration(); jobHistoryByIdService = new JobHistoryByIdService(myConf); appVersionService = new AppVersionService(myConf); rawService = new JobHistoryRawService(myConf); keyCount = 0; String attemptid = context.getTaskAttemptID().toString(); if (attemptid != null) { isThisAttemptTheFirst = (attemptid.endsWith("0") ? true : false); } }

Target:
protected void setup( Mapper<ImmutableBytesWritable, Result, ImmutableBytesWritable, Put>.Context context) throws java.io.IOException, InterruptedException { Configuration myConf = context.getConfiguration(); jobHistoryByIdService = new JobHistoryByIdService(myConf); appVersionService = new AppVersionService(myConf); rawService = new JobHistoryRawService(myConf); keyCount = 0; String attemptid = context.getTaskAttemptID().toString(); if (attemptid != null) { isThisAttemptTheFirst = attemptid.endsWith("0"); } }
Source:
public BakingActionResult checkActionIsApplicableInState(State state, String[] params) { BakingActionResult superResult = super.checkActionIsApplicableInState(state, params); if (!superResult.getIsSuccess()) { return superResult; } ObjectInstance agent = state.getObject(params[0]); String spaceName = params[1]; ObjectInstance spaceInstance = state.getObject(spaceName); if (!SpaceFactory.isSwitchable(spaceInstance)) { return BakingActionResult.failure(spaceName + " cannot be turned on/off"); } return BakingActionResult.success(); }

Target:
public BakingActionResult checkActionIsApplicableInState(State state, String[] params) { BakingActionResult superResult = super.checkActionIsApplicableInState(state, params); if (!superResult.getIsSuccess()) { return superResult; } ObjectInstance agent = state.getObject(params[0]); String spaceName = params[1]; ObjectInstance spaceInstance = state.getObject(spaceName); if (!SpaceFactory.isSwitchable(spaceInstance)) { return BakingActionResult.failure(spaceName + " does not have the capability to be turned on/off"); } return BakingActionResult.success(); }
Source:
public CompletableFuture<Optional<Integer>> getSize(Multihash hash) { return Futures.of(map(hash, h -> { GetObjectRequest get = new GetObjectRequest(bucket, folder + hashToKey(hash)); Histogram.Timer readTimer = readTimerLog.labels(h.toString()).startTimer(); try (S3Object res = s3Client.getObject(get)) { return Optional.of((int)res.getObjectMetadata().getContentLength()); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } finally { readTimer.observeDuration(); } }, e -> Optional.empty())); }

Target:
public CompletableFuture<Optional<Integer>> getSize(Multihash hash) { return Futures.of(map(hash, h -> { GetObjectRequest get = new GetObjectRequest(bucket, folder + hashToKey(hash)); Histogram.Timer readTimer = readTimerLog.labels("size").startTimer(); try (S3Object res = s3Client.getObject(get)) { return Optional.of((int)res.getObjectMetadata().getContentLength()); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } finally { readTimer.observeDuration(); } }, e -> Optional.empty())); }
Source:
public void testButtonVisibilityForMusicFile() throws Throwable { Uri uri = Uri.parse("android.resource://" + mContext.getPackageName() + "/" + R.raw.test_music); final MediaItem uriMediaItem = createTestMediaItem2(uri); final CountDownLatch latch = new CountDownLatch(3); final MediaController controller = createController(new MediaController.ControllerCallback() { @Override public void onCurrentMediaItemChanged(@NonNull MediaController controller, @Nullable MediaItem item) { latch.countDown(); } }); mActivityRule.runOnUiThread(new Runnable() { @Override public void run() { mVideoView.setMediaItem(uriMediaItem); } }); assertTrue(latch.await(WAIT_TIME_MS, TimeUnit.MILLISECONDS)); onView(withId(R.id.subtitle)).check(matches(not(isCompletelyDisplayed()))); }

Target:
public void testButtonVisibilityForMusicFile() throws Throwable { Uri uri = Uri.parse("android.resource://" + mContext.getPackageName() + "/" + R.raw.test_music); final MediaItem uriMediaItem = createTestMediaItem2(uri); final CountDownLatch latch = new CountDownLatch(1); final MediaController controller = createController(new MediaController.ControllerCallback() { @NonNull @Override public SessionResult onCustomCommand(@NonNull MediaController controller, @NonNull SessionCommand command, @Nullable Bundle args) { if (command.getCustomAction() == MediaControlView.EVENT_UPDATE_TRACK_STATUS) { latch.countDown(); } return new SessionResult(SessionResult.RESULT_SUCCESS, null); } }); mActivityRule.runOnUiThread(new Runnable() { @Override public void run() { mVideoView.setMediaItem(uriMediaItem); } }); assertTrue(latch.await(WAIT_TIME_MS, TimeUnit.MILLISECONDS)); onView(withId(R.id.subtitle)).check(matches(not(isCompletelyDisplayed()))); }
Source:
public void testMarshallAccount() throws Exception { ImmutableSerializationContext ctx = createContext(); Account account = new Account(); account.setId(1); account.setDescription("test account"); account.setCurrencies(new Account.Currency[]{Account.Currency.BRL}); Date creationDate = new Date(); account.setCreationDate(creationDate); List<byte[]> blurb = new ArrayList<>(); blurb.add(new byte[0]); blurb.add(new byte[]{1, 2, 3}); account.setBlurb(blurb); byte[] bytes = ProtobufUtil.toByteArray(ctx, account); Account decoded = ProtobufUtil.fromByteArray(ctx, bytes, Account.class); assertEquals(1, decoded.getId()); assertEquals("test account", decoded.getDescription()); assertEquals(creationDate, decoded.getCreationDate()); assertNotNull(decoded.getBlurb()); assertEquals(2, decoded.getBlurb().size()); assertEquals(0, decoded.getBlurb().get(0).length); assertEquals(3, decoded.getBlurb().get(1).length); assertArrayEquals(new byte[]{1, 2, 3}, decoded.getBlurb().get(1)); }

Target:
public void testMarshallAccount() throws Exception { ImmutableSerializationContext ctx = createContext(); Account account = new Account(); account.setId(1); account.setDescription("test account"); account.setCurrencies(new Account.Currency[]{Account.Currency.BRL}); Date creationDate = new Date(); account.setCreationDate(creationDate); List<byte[]> blurb = new ArrayList<>(); blurb.add(new byte[0]); blurb.add(new byte[]{1, 2, 3}); account.setBlurb(blurb); byte[] bytes = ProtobufUtil.toByteArray(ctx, account); Account decoded = ProtobufUtil.fromByteArray(ctx, bytes, Account.class); assertEquals(1, decoded.getId()); assertEquals("test account", decoded.getDescription()); assertEquals(creationDate, decoded.getCreationDate()); assertNotNull(decoded.getBlurb()); assertEquals(2, decoded.getBlurb().size()); assertEquals(0, decoded.getBlurb().get(0).length); assertEquals(3, decoded.getBlurb().get(1).length); assertArrayEquals(new byte[]{1, 2, 3}, decoded.getBlurb().get(1)); assertArrayEquals(new Account.Currency[]{Account.Currency.BRL}, decoded.getCurrencies()); }
Source:
public void testSetEnumNameProperty() { Assertions.assertThrows(IllegalStateException.class, () -> { JavaBeanDescriptor descriptor = new JavaBeanDescriptor(long.class.getName(), JavaBeanDescriptor.TYPE_PRIMITIVE); descriptor.setEnumNameProperty(JavaBeanDescriptor.class.getName()); }); JavaBeanDescriptor descriptor1 = new JavaBeanDescriptor(JavaBeanDescriptor.class.getName(), JavaBeanDescriptor.TYPE_ENUM); String oldValue1 = descriptor1.setEnumNameProperty(JavaBeanDescriptor.class.getName()); Assertions.assertNull(oldValue1); String oldValue2 = descriptor1.setEnumNameProperty(JavaBeanDescriptor.class.getName()); Assertions.assertEquals(oldValue2, descriptor1.getEnumPropertyName()); }

Target:
public void testSetEnumNameProperty() { Assertions.assertThrows(IllegalStateException.class, () -> { JavaBeanDescriptor descriptor = new JavaBeanDescriptor(long.class.getName(), JavaBeanDescriptor.TYPE_PRIMITIVE); descriptor.setEnumNameProperty(JavaBeanDescriptor.class.getName()); }); JavaBeanDescriptor descriptor = new JavaBeanDescriptor(JavaBeanDescriptor.class.getName(), JavaBeanDescriptor.TYPE_ENUM); String oldValueOrigin = descriptor.setEnumNameProperty(JavaBeanDescriptor.class.getName()); Assertions.assertNull(oldValueOrigin); String oldValueNext = descriptor.setEnumNameProperty(JavaBeanDescriptor.class.getName()); Assertions.assertEquals(oldValueNext, descriptor.getEnumPropertyName()); }
Source:
private void setAssertionNameIdQualifierAndFormat( NameID assertionNameId, @Nullable String nameIdFormatPolicy, @Nullable String spNameQualifierPolicy, Response response) { if (StringUtils.isNotEmpty(spNameQualifierPolicy)) { assertionNameId.setSPNameQualifier(spNameQualifierPolicy); } if (StringUtils.isNotEmpty(nameIdFormatPolicy)) { switch (nameIdFormatPolicy) { case NameID.UNSPECIFIED: break; case NameID.PERSISTENT: break; case NameID.TRANSIENT: break; case NameID.X509_SUBJECT: LOGGER.warn("Specifying the \"X509Subject\" NameIDPolicy Format is not fully supported."); if (!NameID.X509_SUBJECT.equals(assertionNameId.getFormat())) { throw new UnsupportedOperationException( "The \"X509Subject\" NameID could not be retrieved."); } break; case NameID.EMAIL: LOGGER.warn("Specifying the \"Email\" NameIDPolicy Format is not fully supported."); assertionNameId.setValue(resolveEmail(response)); break; case NameID.WIN_DOMAIN_QUALIFIED: case NameID.KERBEROS: case NameID.ENTITY: default: throw new UnsupportedOperationException( String.format( "The NameIDPolicy Format of value %s is not supported.", nameIdFormatPolicy)); } } assertionNameId.setFormat(nameIdFormatPolicy); }

Target:
private void setAssertionNameIdQualifierAndFormat( NameID assertionNameId, @Nullable String nameIdFormatPolicy, @Nullable String spNameQualifierPolicy, Response response) { if (StringUtils.isNotEmpty(spNameQualifierPolicy)) { assertionNameId.setSPNameQualifier(spNameQualifierPolicy); } if (StringUtils.isNotEmpty(nameIdFormatPolicy)) { switch (nameIdFormatPolicy) { case NameID.UNSPECIFIED: return; case NameID.PERSISTENT: break; case NameID.X509_SUBJECT: LOGGER.warn("Specifying the \"X509Subject\" NameIDPolicy Format is not fully supported."); if (!NameID.X509_SUBJECT.equals(assertionNameId.getFormat())) { throw new UnsupportedOperationException( "The \"X509Subject\" NameID could not be retrieved."); } break; case NameID.EMAIL: LOGGER.warn("Specifying the \"Email\" NameIDPolicy Format is not fully supported."); assertionNameId.setValue(resolveEmail(response, assertionNameId)); break; case NameID.TRANSIENT: case NameID.WIN_DOMAIN_QUALIFIED: case NameID.KERBEROS: case NameID.ENTITY: default: throw new UnsupportedOperationException( String.format( "The NameIDPolicy Format of value %s is not supported.", nameIdFormatPolicy)); } assertionNameId.setFormat(nameIdFormatPolicy); } }
Source:
public void onBlockPlace(final BlockPlaceEvent event) { final ItemStack is = LocationUtil.convertBlockToItem(event.getBlockPlaced()); if (is == null) { return; } if (is.getType() == MaterialUtil.SPAWNER && event.getItemInHand().getType() == MaterialUtil.SPAWNER) { final BlockState blockState = event.getBlockPlaced().getState(); if (blockState instanceof CreatureSpawner) { final CreatureSpawner spawner = (CreatureSpawner) blockState; final EntityType type = ess.getSpawnerProvider().getEntityType(event.getItemInHand()); final Mob mob = Mob.fromBukkitType(type); if (type != null && mob != null) { String mobName = mob.name().toLowerCase(Locale.ENGLISH); if (ess.getUser(event.getPlayer()).isAuthorized("essentials.spawnerconvert." + mobName)) { spawner.setSpawnedType(type); spawner.update(); } } } } final User user = ess.getUser(event.getPlayer()); if (user.hasUnlimited(is) && user.getBase().getGameMode() == GameMode.SURVIVAL) { class UnlimitedItemSpawnTask implements Runnable { @Override public void run() { user.getBase().getInventory().addItem(is); user.getBase().updateInventory(); } } ess.scheduleSyncDelayedTask(new UnlimitedItemSpawnTask()); } }

Target:
public void onBlockPlace(final BlockPlaceEvent event) { final ItemStack is = LocationUtil.convertBlockToItem(event.getBlockPlaced()); if (is == null) { return; } if (is.getType() == MaterialUtil.SPAWNER && event.getItemInHand() != null && event.getPlayer() != null && event.getItemInHand().getType() == MaterialUtil.SPAWNER) { final BlockState blockState = event.getBlockPlaced().getState(); if (blockState instanceof CreatureSpawner) { final CreatureSpawner spawner = (CreatureSpawner) blockState; final EntityType type = ess.getSpawnerProvider().getEntityType(event.getItemInHand()); if (type != null && Mob.fromBukkitType(type) != null) { if (ess.getUser(event.getPlayer()).isAuthorized("essentials.spawnerconvert." + Mob.fromBukkitType(type).name().toLowerCase(Locale.ENGLISH))) { spawner.setSpawnedType(type); spawner.update(); } } } } final User user = ess.getUser(event.getPlayer()); if (user.hasUnlimited(is) && user.getBase().getGameMode() == GameMode.SURVIVAL) { class UnlimitedItemSpawnTask implements Runnable { @Override public void run() { user.getBase().getInventory().addItem(is); user.getBase().updateInventory(); } } ess.scheduleSyncDelayedTask(new UnlimitedItemSpawnTask()); } }