auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void addClientProperties(Client client, HashMap<String,Object> hashMapInstance, String entryId){ if (client == null){ return; } WMSProperties clientProps = client.getProperties(); String rtmpUrl, encoder,IP; rtmpUrl = clientProps.getPropertyStr(Constants.CLIENT_PROPERTY_CONNECT_URL); encoder = clientProps.getPropertyStr(Constants.CLIENT_PROPERTY_ENCODER); IP = client.getIp(); int port = client.getServerHostPort().getPort(); HashMap<String,Object> ClientPropertiesHash = new HashMap<>(); ClientPropertiesHash.put("rtmpUrl" , rtmpUrl); ClientPropertiesHash.put("encoder" , encoder); ClientPropertiesHash.put("IP" , IP); ClientPropertiesHash.put("port" , port); hashMapInstance.put("clientProperties", ClientPropertiesHash); logger.debug(httpSessionId + "[" + entryId + "] Add the following params: rtmpUrl "+ rtmpUrl + ", encoder " + encoder + ", IP " + IP + ", port " + port); }

Target:
private void addClientProperties(Client client, HashMap<String,Object> hashMapInstance, String entryId){ if (client == null){ return; } WMSProperties clientProps = client.getProperties(); if (clientProps == null){ logger.warn(httpSessionId + "[" + entryId + "] Can't get properties"); return; } String rtmpUrl, encoder,IP; rtmpUrl = clientProps.getPropertyStr(Constants.CLIENT_PROPERTY_CONNECT_URL); encoder = clientProps.getPropertyStr(Constants.CLIENT_PROPERTY_ENCODER); IP = client.getIp(); long pingRoundTripTime = client.getPingRoundTripTime(); double timeRunningSeconds = client.getTimeRunningSeconds(); HashMap<String,Object> ClientPropertiesHash = new HashMap<String,Object>(); ClientPropertiesHash.put("pingRoundTripTime" , pingRoundTripTime); ClientPropertiesHash.put("timeRunningSeconds" , timeRunningSeconds); ClientPropertiesHash.put("rtmpUrl" , rtmpUrl); ClientPropertiesHash.put("encoder" , encoder); ClientPropertiesHash.put("IP" , IP); hashMapInstance.put("clientProperties", ClientPropertiesHash); logger.debug(httpSessionId + "[" + entryId + "] Add the following params: rtmpUrl "+ rtmpUrl + ", encoder " + encoder + ", IP " + IP + ", port " + port); }
Source:
URI generateOutputFilename(final String id) { final FileInfo cfi = job.getFileInfo(currentFile); URI result = cfi.result.resolve(id + FILE_EXTENSION_DITA); URI temp = toURI(new File (result).getName()); if (id == null || new File(currentParsingFile.resolve(temp)).exists()) { final URI t = temp; result = cfi.result.resolve(generateFilename()); temp = toURI(new File (result).getName()); final FileInfo.Builder b = new FileInfo.Builder(cfi); final FileInfo fi = b .uri(temp) .result(result) .format(ATTR_FORMAT_VALUE_DITA) .build(); job.add(fi); conflictTable.put(currentParsingFile.resolve(temp), currentParsingFile.resolve(t)); } return currentParsingFile.resolve(temp); }

Target:
URI generateOutputFilename(final String id) { final FileInfo cfi = job.getFileInfo(stripFragment(currentParsingFile)); URI result = cfi.result.resolve(id + FILE_EXTENSION_DITA); URI temp = tempFileNameScheme.generateTempFileName(result); if (id == null || new File(job.tempDirURI.resolve(temp)).exists()) { final URI t = temp; result = cfi.result.resolve(generateFilename()); temp = tempFileNameScheme.generateTempFileName(result); final FileInfo.Builder b = new FileInfo.Builder(cfi); final FileInfo fi = b .uri(temp) .result(result) .format(ATTR_FORMAT_VALUE_DITA) .build(); job.add(fi); conflictTable.put(job.tempDirURI.resolve(temp), job.tempDirURI.resolve(t)); } return job.tempDirURI.resolve(temp); }
Source:
public void testRegisterTrialIsDeprecated() throws Exception { String[] cmd = { "unused" }; NuxeoLauncher launcher = NuxeoLauncher.createLauncher(cmd); try { launcher.registerTrial(); fail("Command \"register-trial\" did not raise exception."); } catch (UnsupportedOperationException e) { String msg = "This command is deprecated. To register for a free 30 day trial on Nuxeo Online Services," + " please visit <LINK_0>"; assertEquals(msg, e.getMessage()); } }

Target:
public void testRegisterTrialIsDeprecated() throws Exception { thrown.expect(UnsupportedOperationException.class); thrown.expectMessage("deprecated"); thrown.expectMessage("<LINK_0>"); NuxeoLauncher.createLauncher(new String[] { "register-trial" }).registerTrial(); }
Source:
public void tearDown() throws Exception { testContext = null; }

Target:
public void tearDown() throws Exception { testContext = null; super.tearDown(); }
Source:
public void setUpRefs() throws IOException { Map<String, Ref> refs = getRemoteRefs(); for (Map.Entry<String, Ref> entry : refs.entrySet()) { String pubsubRef = getPubSubRefFromLocal(remote, entry.getKey()); if (repository.getRef(pubsubRef) != null) continue; RefUpdate ru = repository.updateRef(pubsubRef); ru.setExpectedOldObjectId(ObjectId.zeroId()); ru.setNewObjectId(entry.getValue().getObjectId()); ru.update(); } }

Target:
public void setUpRefs() throws IOException { Set<String> existingRefs = new LinkedHashSet<String>( repository.getRefDatabase().getRefs( getPubSubRefFromLocal(remote, Constants.R_REFS)) .keySet()); Map<String, Ref> refs = getRemoteRefs(); for (Map.Entry<String, Ref> entry : refs.entrySet()) { String ref = entry.getKey(); String existingRef = ref.substring(Constants.R_REFS.length()); existingRefs.remove(existingRef); String pubsubRef = getPubSubRefFromLocal(remote, ref); if (repository.getRef(pubsubRef) != null) continue; RefUpdate ru = repository.updateRef(pubsubRef); ru.setExpectedOldObjectId(ObjectId.zeroId()); ru.setNewObjectId(entry.getValue().getObjectId()); ru.setRefLogMessage("pubsub setup", true); ru.update(); } for (String r : existingRefs) { String pubsubRef = getPubSubRefFromLocal( remote, Constants.R_REFS + r); if (repository.getRef(pubsubRef) == null) continue; RefUpdate ru = repository.updateRef(pubsubRef); ru.setForceUpdate(true); ru.delete(); } }
Source:
public PunchCommand() { this.setVerb("punch"); }

Target:
public PunchCommand() { this.setVerb("punche"); }
Source:
private Map<String, Object> buildStringKeyMap(ByteBuffer input) { int payloadSize = input.limit(); if (chars == null || chars.remaining() < payloadSize) { chars = CharBuffer.allocate(payloadSize); } final CoderResult coderResult = Charsets.UTF_8.newDecoder() .onMalformedInput(CodingErrorAction.REPLACE) .onUnmappableCharacter(CodingErrorAction.REPLACE) .decode(input, chars, true); Map<String, Object> theMap; if (coderResult.isUnderflow()) { chars.flip(); try { theMap = parseString(chars.toString()); } finally { chars.clear(); } } else { throw new FormattedException.Builder() .withErrorCode(FormattedException.ErrorCode.UNPARSABLE_ROW) .withMessage(String.format("Failed with CoderResult[%s]", coderResult)) .build(); } return theMap; }

Target:
private Map<String, Object> buildStringKeyMap(ByteBuffer input) { int payloadSize = input.remaining(); if (chars == null || chars.remaining() < payloadSize) { chars = CharBuffer.allocate(payloadSize); } final CoderResult coderResult = Charsets.UTF_8.newDecoder() .onMalformedInput(CodingErrorAction.REPLACE) .onUnmappableCharacter(CodingErrorAction.REPLACE) .decode(input, chars, true); Map<String, Object> theMap; if (coderResult.isUnderflow()) { chars.flip(); try { theMap = parseString(chars.toString()); } finally { chars.clear(); } } else { throw new FormattedException.Builder() .withErrorCode(FormattedException.ErrorCode.UNPARSABLE_ROW) .withMessage(String.format("Failed with CoderResult[%s]", coderResult)) .build(); } return theMap; }
Source:
public ChangeDetail abandon(String reviewId, int patchSetId, final String message, IProgressMonitor monitor) throws GerritException { final PatchSet.Id id = new PatchSet.Id(new Change.Id(id(reviewId)), patchSetId); if (hasJsonRpcApi(monitor)) { return execute(monitor, new Operation<ChangeDetail>() { @Override public void execute(IProgressMonitor monitor) throws GerritException { getChangeManageService(monitor).abandonChange(id, message, this); } }); } else { final String uri = "/a/changes/" + id.getParentKey().get() + "/abandon"; ChangeDetailX preAbandoned = getChangeDetail(id.getParentKey().get(), monitor); executePostRestRequest(uri, new AbandonInput(message), ChangeInfo.class, null , monitor); ChangeDetailX postAbandoned = getChangeDetail(id.getParentKey().get(), monitor); if (postAbandoned.getApprovals().isEmpty()) { postAbandoned.setApprovals(preAbandoned.getApprovals()); } if (postAbandoned.getApprovalTypes().isEmpty()) { postAbandoned.setApprovalTypes(preAbandoned.getApprovalTypes()); } return postAbandoned; } }

Target:
public ChangeDetail abandon(String reviewId, int patchSetId, final String message, IProgressMonitor monitor) throws GerritException { final PatchSet.Id id = new PatchSet.Id(new Change.Id(id(reviewId)), patchSetId); if (hasJsonRpcApi(monitor)) { return execute(monitor, new Operation<ChangeDetail>() { @Override public void execute(IProgressMonitor monitor) throws GerritException { getChangeManageService(monitor).abandonChange(id, message, this); } }); } else { final String uri = "/a/changes/" + id.getParentKey().get() + "/abandon"; executePostRestRequest(uri, new AbandonInput(message), ChangeInfo.class, null , monitor); return getChangeDetail(id.getParentKey().get(), monitor); } }
Source:
public boolean canProcess(Map<String, Serializable> params) { try { File file = (File) FILE_PARAM.lookUp(params); String indexPath = (String) INDEX_PARAM.lookUp(params); String dsPath = (String) DS_PARAM.lookUp(params); AncillaryFileManager ancilaryFileManager = new AncillaryFileManager(file, indexPath, dsPath); DataStoreConfiguration datastoreConfig = ancilaryFileManager.getDatastoreConfiguration(); return datastoreConfig.getDatastoreSpi().canProcess(datastoreConfig.getParams()); } catch (NoSuchAlgorithmException | JAXBException | IOException e) { } return false; }

Target:
public boolean canProcess(Map<String, Serializable> params) { try { File file = (File) FILE_PARAM.lookUp(params); String indexPath = (String) INDEX_PARAM.lookUp(params); String dsPath = (String) DS_PARAM.lookUp(params); AncillaryFileManager ancilaryFileManager = new AncillaryFileManager(file, indexPath, dsPath); DataStoreConfiguration datastoreConfig = ancilaryFileManager.getDatastoreConfiguration(); return datastoreConfig.getDatastoreSpi().canProcess(datastoreConfig.getParams()); } catch (NoSuchAlgorithmException | JAXBException | IOException e) { return false; } }
Source:
public static TupleDomainFilter toBigintValues(long[] values, boolean nullAllowed) { long min = values[0]; long max = values[0]; for (int i = 1; i < values.length; i++) { min = Math.min(min, values[i]); max = Math.max(max, values[i]); } if ((max - min) > Integer.MAX_VALUE || ((max - min) / values.length) > 192) { return BigintValuesUsingHashTable.of(min, max, values, nullAllowed); } else { return BigintValuesUsingBitmask.of(min, max, values, nullAllowed); } }

Target:
public static TupleDomainFilter toBigintValues(long[] values, boolean nullAllowed) { long min = values[0]; long max = values[0]; for (int i = 1; i < values.length; i++) { min = Math.min(min, values[i]); max = Math.max(max, values[i]); } if ((max - min + 1) > Integer.MAX_VALUE || ((max - min + 1) / values.length) > 192) { return BigintValuesUsingHashTable.of(min, max, values, nullAllowed); } return BigintValuesUsingBitmask.of(min, max, values, nullAllowed); }
Source:
public void shouldRetrieveOverridingCredentialFromProject() throws Exception { Folder f = r.jenkins.createProject(Folder.class, "folder1"); UsernamePasswordCredentialsImpl credentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, ID, DESCRIPTION, USERNAME, PASSWORD); getFolderStore(f).addCredentials(Domain.global(), credentials); Credential overridingCredentialProvided = new Credential(null, "", null, credentials.getId(), null, true); DeployitNotifier.DeployitDescriptor descriptor = new DeployitNotifier.DeployitDescriptor(); DeployitNotifier notifierSpy = Mockito.spy(new DeployitNotifier("AdminGlobal1", "app1", null, null, null, null, false, null, overridingCredentialProvided)); doReturn(descriptor).when(notifierSpy).getDescriptor(); doReturn(overridingCredentialProvided).when(notifierSpy).getOverridingCredential(); FreeStyleProject freeStyleProjectSpy = Mockito.spy(new FreeStyleProject(f, "folder1/proj1")); freeStyleProjectSpy.addPublisher(notifierSpy); DescribableList<Publisher, Descriptor<Publisher>> publisherListMock = Mockito.mock(DescribableList.class); doReturn(notifierSpy).when(publisherListMock).get(any(DeployitNotifier.DeployitDescriptor.class)); doReturn(publisherListMock).when(freeStyleProjectSpy).getPublishersList(); Credential overridingCredential = RepositoryUtils.retrieveOverridingCredentialFromProject(freeStyleProjectSpy); assertEquals(USERNAME, overridingCredential.getUsername()); assertEquals(PASSWORD, overridingCredential.getPassword().getPlainText()); }

Target:
public void shouldRetrieveOverridingCredentialFromProject() throws Exception { Folder f = r.jenkins.createProject(Folder.class, "folder1"); UsernamePasswordCredentialsImpl credentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, ID, DESCRIPTION, USERNAME, PASSWORD); getFolderStore(f).addCredentials(Domain.global(), credentials); Credential overridingCredentialProvided = new Credential(null, "", null, credentials.getId(), null, true); DeployitNotifier.DeployitDescriptor descriptor = new DeployitNotifier.DeployitDescriptor(); DeployitNotifier notifierSpy = spy(new DeployitNotifier("AdminGlobal1", "app1", null, null, null, null, false, null, overridingCredentialProvided)); doReturn(descriptor).when(notifierSpy).getDescriptor(); doReturn(overridingCredentialProvided).when(notifierSpy).getOverridingCredential(); FreeStyleProject freeStyleProjectSpy = spy(new FreeStyleProject(f, "folder1/proj1")); freeStyleProjectSpy.addPublisher(notifierSpy); DescribableList<Publisher, Descriptor<Publisher>> publisherListMock = Mockito.mock(DescribableList.class); doReturn(notifierSpy).when(publisherListMock).get(any(DeployitNotifier.DeployitDescriptor.class)); doReturn(publisherListMock).when(freeStyleProjectSpy).getPublishersList(); Credential overridingCredential = RepositoryUtils.retrieveOverridingCredentialFromProject(freeStyleProjectSpy); assertEquals(USERNAME, overridingCredential.getUsername()); assertEquals(PASSWORD, overridingCredential.getPassword().getPlainText()); }
Source:
public synchronized Uri insert(Uri uri, ContentValues initialValues) { SqlArguments args = new SqlArguments(uri); synchronized (mLock) { SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final long rowId = db.insert(args.table, null, initialValues); if (rowId <= 0) return null; uri = ContentUris.withAppendedId(uri, rowId); sendNotify(uri); return uri; } }

Target:
public Uri insert(Uri uri, ContentValues initialValues) { SqlArguments args = new SqlArguments(uri); synchronized (mLock) { SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final long rowId = db.insert(args.table, null, initialValues); if (rowId <= 0) return null; uri = ContentUris.withAppendedId(uri, rowId); sendNotify(uri); return uri; } }
Source:
public void initialize(Context context, InitializationCompleteCallback initializationCompleteCallback, List<MediationConfiguration> mediationConfigurations) { if (VungleInitializer.getInstance().isInitialized()) { initializationCompleteCallback.onInitializationSucceeded(); return; } if (!(context instanceof Activity)) { initializationCompleteCallback.onInitializationFailed("Vungle SDK requires an " + "Activity context to initialize"); return; } HashSet<String> appIDs = new HashSet<>(); for (MediationConfiguration configuration: mediationConfigurations) { Bundle serverParameters = configuration.getServerParameters(); String appIDFromServer = serverParameters.getString(KEY_APP_ID); if (!TextUtils.isEmpty(appIDFromServer)) { appIDs.add(appIDFromServer); } } int count = appIDs.size(); if (count > 0) { String appID = appIDs.iterator().next(); if (count > 1) { String logMessage = String.format("Multiple '%s' entries found: %s. " + "Using '%s' to initialize the Vungle SDK.", KEY_APP_ID, appIDs.toString(), appID); Log.w(TAG, logMessage); } mInitializationCallback = initializationCompleteCallback; mAdapterId = REWARDED + String.valueOf(sCounter); sCounter++; VungleInitializer.getInstance().initialize(appID, context.getApplicationContext(), mAdapterId, VungleMediationAdapter.this); } else { initializationCompleteCallback.onInitializationFailed("Initialization failed: " + "Missing or Invalid App ID."); } }

Target:
public void initialize(Context context, InitializationCompleteCallback initializationCompleteCallback, List<MediationConfiguration> mediationConfigurations) { if (VungleInitializer.getInstance().isInitialized()) { initializationCompleteCallback.onInitializationSucceeded(); return; } if (!(context instanceof Activity)) { initializationCompleteCallback.onInitializationFailed("Vungle SDK requires an " + "Activity context to initialize"); return; } HashSet<String> appIDs = new HashSet<>(); for (MediationConfiguration configuration: mediationConfigurations) { Bundle serverParameters = configuration.getServerParameters(); String appIDFromServer = serverParameters.getString(KEY_APP_ID); if (!TextUtils.isEmpty(appIDFromServer)) { appIDs.add(appIDFromServer); } } int count = appIDs.size(); if (count > 0) { String appID = appIDs.iterator().next(); if (count > 1) { String logMessage = String.format("Multiple '%s' entries found: %s. " + "Using '%s' to initialize the Vungle SDK.", KEY_APP_ID, appIDs.toString(), appID); Log.w(TAG, logMessage); } mInitializationCallback = initializationCompleteCallback; VungleInitializer.getInstance().initialize(appID, context.getApplicationContext(), VungleMediationAdapter.this); } else { initializationCompleteCallback.onInitializationFailed("Initialization failed: " + "Missing or Invalid App ID."); } }
Source:
public void backpressure() { MulticastProcessor<Integer> mp = MulticastProcessor.create(16, false); mp.start(); for (int i = 0; i < 10; i++) { mp.onNext(i); } mp.onComplete(); mp.test(0) .assertEmpty() .requestMore(1) .assertValues(0) .assertNotComplete() .requestMore(2) .assertValues(0, 1, 2) .assertNotComplete() .requestMore(3) .assertValues(0, 1, 2, 3, 4, 5) .assertNotComplete() .requestMore(4) .assertResult(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); }

Target:
public void backpressure() { MulticastProcessor<Integer> mp = MulticastProcessor.create(16, false); mp.start(); for (int i = 0; i < 10; i++) { mp.onNext(i); } mp.onComplete(); mp.test(0) .assertEmpty() .requestMore(1) .assertValuesOnly(0) .requestMore(2) .assertValuesOnly(0, 1, 2) .requestMore(3) .assertValuesOnly(0, 1, 2, 3, 4, 5) .requestMore(4) .assertResult(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); }
Source:
public IFormPage getPreviousPage(IFormPage current) { int i = pages.indexOf(current); if (i > -1) { ListIterator<? extends Object> it = pages.listIterator(i); while (it.hasPrevious()) { Object prev = it.previous(); if (prev instanceof CommonActivityExplorerPage) { String pageID = ((CommonActivityExplorerPage)prev).getId(); IConfigurationElement pageConfigurationElement = ActivityExplorerExtensionManager.getConfigurationElement(pageID); if (pageConfigurationElement != null) { Image imageOn = ActivityExplorerExtensionManager.getImageOn(pageConfigurationElement); Image imageOff = ActivityExplorerExtensionManager.getImageOff(pageConfigurationElement); if (imageOn != null || imageOff != null) { return (IFormPage) prev; } } } } } return null; }

Target:
public IFormPage getPreviousPage(IFormPage current) { int i = pages.indexOf(current); if (i > -1) { ListIterator<? extends Object> it = pages.listIterator(i); while (it.hasPrevious()) { Object prev = it.previous(); if (prev instanceof ActivityExplorerPage) { ActivityExplorerPage previousPage = (ActivityExplorerPage)prev; if (previousPage.getHeaderImageOff() != null || previousPage.getHeaderImageOn() != null) { return previousPage; } } } } return null; }
Source:
public DiffEntry getAndReset() { if (captured == null) { throw new NullPointerException(); } final DiffEntry retVal = captured; captured = null; return retVal; }

Target:
public DiffEntry getAndReset() { if (captured == null) { throw new NullPointerException("Cannot get DiffEntry when none was captured."); } final DiffEntry retVal = captured; captured = null; return retVal; }
Source:
public void deleteAllCategories(final String siteId, User user) { ArrayList<CategoryPill.Data> categories = getCategoriesFromSite(siteId, user); for (CategoryPill.Data category : categories) { PageObjectLogging.logInfo("Deleting category: " + category.getName()); deleteCategory(siteId, category); } }

Target:
public void deleteAllCategories(final String siteId, User user) { List<CategoryPill.Data> categories = getCategoriesFromSite(siteId, user); for (CategoryPill.Data category : categories) { PageObjectLogging.logInfo("Deleting category: " + category.getName()); deleteCategory(siteId, category); } }
Source:
public void should_return_failed_future_if_reloading_not_supported() { DefaultDriverConfigLoader loader = new DefaultDriverConfigLoader(() -> ConfigFactory.parseString(configSource.get())) { @Override public boolean supportsReloading() { return false; } }; CompletionStage<Boolean> stage = loader.reload(); assertThatStage(stage) .isFailed( t -> assertThat(t) .isInstanceOf(UnsupportedOperationException.class) .hasMessage( "This instance of DefaultDriverConfigLoader does not support reloading")); }

Target:
public void should_return_failed_future_if_reloading_not_supported() { DefaultDriverConfigLoader loader = new DefaultDriverConfigLoader(() -> ConfigFactory.parseString(configSource.get()), false); assertThat(loader.supportsReloading()).isFalse(); CompletionStage<Boolean> stage = loader.reload(); assertThatStage(stage) .isFailed( t -> assertThat(t) .isInstanceOf(UnsupportedOperationException.class) .hasMessage( "This instance of DefaultDriverConfigLoader does not support reloading")); }
Source:
public boolean retainAll(Collection<?> c) { for (XWikiAttachment x : this.list) { if (!((Collection<? extends XWikiAttachment>) (c)).contains(x)) remove(x); } return true; }

Target:
public boolean retainAll(Collection<?> c) { boolean changed = false; Collection<XWikiAttachment> values = map.values(); for (XWikiAttachment x : values) { if (!c.contains(x)) { map.remove(x.getFilename()); changed = true; } } if (changed) { updatedMap(); } return changed; }
Source:
void shutdown() { try { retryExecutor.shutdownNow(); } catch (Exception ignore) { } }

Target:
void shutdown() { try { if (retryExecutor != null) { retryExecutor.shutdownNow(); } } catch (Exception ignore) { } }
Source:
private static void serializePrimitive(Type type, BlockBuilder builder, Object object) { requireNonNull(builder, "builder is null"); if (object == null) { builder.appendNull(); return; } if (type.equals(BOOLEAN)) { type.writeBoolean(builder, (Boolean) object); } else if (type.equals(BIGINT)) { type.writeLong(builder, Long.valueOf(String.valueOf(object))); } else if (type.equals(DOUBLE)) { type.writeDouble(builder, (Double) object); } else if (type.equals(INTEGER)) { type.writeLong(builder, Long.valueOf(String.valueOf(object))); } else if (type.equals(VARCHAR)) { type.writeSlice(builder, utf8Slice(String.valueOf(object))); } else if (type.equals(VARBINARY)) { type.writeSlice(builder, utf8Slice(String.valueOf(object))); } else { throw new RuntimeException("Unknown primitive type: " + type.getDisplayName()); } }

Target:
private static void serializePrimitive(Type type, BlockBuilder builder, Object object) { requireNonNull(builder, "builder is null"); if (object == null) { builder.appendNull(); return; } if (type.equals(BOOLEAN)) { type.writeBoolean(builder, (Boolean) object); } else if (type.equals(BIGINT)) { type.writeLong(builder, Long.valueOf(String.valueOf(object))); } else if (type.equals(DOUBLE)) { type.writeDouble(builder, Double.valueOf(String.valueOf(object))); } else if (type.equals(INTEGER)) { type.writeLong(builder, Integer.valueOf(String.valueOf(object))); } else if (type.equals(VARCHAR)) { type.writeSlice(builder, utf8Slice(String.valueOf(object))); } else if (type.equals(VARBINARY)) { type.writeSlice(builder, utf8Slice(String.valueOf(object))); } else { throw new IllegalArgumentException("Unknown primitive type: " + type.getDisplayName()); } }
Source:
public final void init(final FilterConfig filterConfig) throws ServletException { if (!isIgnoreInitConfiguration()) { setServerName(getPropertyFromInitParams(filterConfig, "serverName", null)); logger.trace("Loading serverName property: {}", this.serverName); setService(getPropertyFromInitParams(filterConfig, "service", null)); logger.trace("Loading service property: {}", this.service); setArtifactParameterName(getPropertyFromInitParams(filterConfig, "artifactParameterName", "ticket")); logger.trace("Loading artifact parameter name property: {}", this.artifactParameterName); setServiceParameterName(getPropertyFromInitParams(filterConfig, "serviceParameterName", "service")); logger.trace("Loading serviceParameterName property: ", this.serviceParameterName); setEncodeServiceUrl(parseBoolean(getPropertyFromInitParams(filterConfig, "encodeServiceUrl", "true"))); logger.trace("Loading encodeServiceUrl property: {}", this.encodeServiceUrl); final String ignorePattern = getPropertyFromInitParams(filterConfig, "ignorePattern", null); if (ignorePattern != null) { setIgnorePattern(Pattern.compile(ignorePattern)); logger.trace("Loading ignorePattern property: {}", this.ignorePattern.pattern()); } initInternal(filterConfig); } init(); }

Target:
public final void init(final FilterConfig filterConfig) throws ServletException { if (!isIgnoreInitConfiguration()) { setServerName(getPropertyFromInitParams(filterConfig, "serverName", null)); logger.trace("Loading serverName property: {}", this.serverName); setService(getPropertyFromInitParams(filterConfig, "service", null)); logger.trace("Loading service property: {}", this.service); setArtifactParameterName(getPropertyFromInitParams(filterConfig, "artifactParameterName", "ticket")); logger.trace("Loading artifact parameter name property: {}", this.artifactParameterName); setServiceParameterName(getPropertyFromInitParams(filterConfig, "serviceParameterName", "service")); logger.trace("Loading serviceParameterName property: ", this.serviceParameterName); setEncodeServiceUrl(parseBoolean(getPropertyFromInitParams(filterConfig, "encodeServiceUrl", "true"))); logger.trace("Loading encodeServiceUrl property: {}", this.encodeServiceUrl); initInternal(filterConfig); } init(); }
Source:
public void testIterator() throws Exception { final int blockCount = 3; RocksBlockStore blockStore = new RocksBlockStore(mFolder.newFolder().getAbsolutePath()); for (int i = 0; i < blockCount; i++) { blockStore.putBlock(i, Block.BlockMeta.newBuilder().setLength(i).build()); } Iterator<BlockStore.Block> iter = blockStore.iterator(); for (int i = 0; i < blockCount; i++) { assertTrue(iter.hasNext()); BlockStore.Block block = iter.next(); assertEquals(i, block.getId()); assertEquals(i, block.getMeta().getLength()); } }

Target:
public void testIterator() throws Exception { final int blockCount = 3; RocksBlockStore blockStore = new RocksBlockStore(mFolder.newFolder().getAbsolutePath()); for (int i = 0; i < blockCount; i++) { blockStore.putBlock(i, Block.BlockMeta.newBuilder().setLength(i).build()); } Iterator<BlockStore.Block> iter = blockStore.iterator(); for (int i = 0; i < blockCount; i++) { assertTrue(iter.hasNext()); BlockStore.Block block = iter.next(); assertEquals(i, block.getId()); assertEquals(i, block.getMeta().getLength()); } assertFalse(iter.hasNext()); }
Source:
public DataFormatChooserValues() { super( DataFormat.AVRO, DataFormat.BINARY, DataFormat.DATAGRAM, DataFormat.DELIMITED, DataFormat.JSON, DataFormat.LOG, DataFormat.PROTOBUF, DataFormat.SDC_JSON, DataFormat.TEXT, DataFormat.XML, DataFormat.SAS ); }

Target:
public DataFormatChooserValues() { super( DataFormat.AVRO, DataFormat.BINARY, DataFormat.DATAGRAM, DataFormat.DELIMITED, DataFormat.JSON, DataFormat.LOG, DataFormat.PROTOBUF, DataFormat.SDC_JSON, DataFormat.TEXT, DataFormat.XML ); }
Source:
private void apply(TaskAdded event) { getBuilder().setDescription(TASK_DESCRIPTION).build(); }

Target:
private void apply(TaskAdded event) { getBuilder().setDescription(TASK_DESCRIPTION); }
Source:
private void setupAllMetrics() { dbConnectionMeter = MetricsUtility.addMeter("DB-Connection-meter", registry); flowFailMeter = MetricsUtility.addMeter("flow-fail-meter", registry); MetricsUtility.addGauge("OOM-waiting-job-meter", registry, OOMWaitingJobCount::get); MetricsUtility.addGauge("dbConnectionTime", registry, dbConnectionTime::get); }

Target:
private void setupAllMetrics() { dbConnectionMeter = MetricsUtility.addMeter("DB-Connection-meter", registry); flowFailMeter = MetricsUtility.addMeter("flow-fail-meter", registry); MetricsUtility.addGauge("OOM-waiting-job-count", registry, OOMWaitingJobCount::get); MetricsUtility.addGauge("dbConnectionTime", registry, dbConnectionTime::get); }
Source:
public void start(Listener<RespT> responseListener, Metadata headers) { super.start( new ForwardingClientCallListener.SimpleForwardingClientCallListener<RespT>( responseListener) { @Override public void onClose(Status status, Metadata trailers) { try { networkTime.stop(); throw new IllegalStateException(); } catch (RuntimeException e) { logger.atWarning().withCause(e).log("Failed to stop networkTime"); } super.onClose(status, trailers); } }, headers); }

Target:
public void start(Listener<RespT> responseListener, Metadata headers) { super.start( new ForwardingClientCallListener.SimpleForwardingClientCallListener<RespT>( responseListener) { @Override public void onClose(Status status, Metadata trailers) { try { networkTime.stop(); } catch (RuntimeException e) { logger.atWarning().withCause(e).log("Failed to stop networkTime"); } super.onClose(status, trailers); } }, headers); }
Source:
public static String user(DataContext root) { return java.util.Optional.ofNullable((String) DataContext.Variable.USER.get(root)) .orElse("sa"); }

Target:
public static String user(DataContext root) { return Objects.requireNonNull(DataContext.Variable.USER.get(root)); }
Source:
public ResultSetMapper mapperFor(Class type, StatementContext ctx) { Map<String, Object> attributes = ctx.getAttributes(); Boolean bypassCache = attributes.containsKey("bypassMappingRegistryCache") ? (Boolean) ctx.getAttribute("bypassMappingRegistryCache") : Boolean.FALSE; if (cache.containsKey(type)) { ResultSetMapper mapper = cache.get(type); if (mapper != null) { return mapper; } } for (ResultSetMapperFactory factory : factories) { if (factory.accepts(type, ctx)) { ResultSetMapper mapper = factory.mapperFor(type, ctx); if (!bypassCache.booleanValue()) { cache.put(type, mapper); } return mapper; } } if (BUILT_IN_MAPPERS.accepts(type, ctx)) { ResultSetMapper mapper = BUILT_IN_MAPPERS.mapperFor(type, ctx); cache.put(type, mapper); return mapper; } throw new DBIException("No mapper registered for " + type.getName()) {}; }

Target:
public ResultSetMapper mapperFor(Class type, StatementContext ctx) { Boolean bypassCache = Boolean.valueOf(String.valueOf(ctx.getAttribute("bypassMappingRegistryCache"))); if (cache.containsKey(type)) { ResultSetMapper mapper = cache.get(type); if (mapper != null) { return mapper; } } for (ResultSetMapperFactory factory : factories) { if (factory.accepts(type, ctx)) { ResultSetMapper mapper = factory.mapperFor(type, ctx); if (!bypassCache.booleanValue()) { cache.put(type, mapper); } return mapper; } } if (BUILT_IN_MAPPERS.accepts(type, ctx)) { ResultSetMapper mapper = BUILT_IN_MAPPERS.mapperFor(type, ctx); cache.put(type, mapper); return mapper; } throw new DBIException("No mapper registered for " + type.getName()) {}; }
Source:
public byte[] toByteArray() { if (isOpCode()) { checkState(data == null); return new byte[]{ (byte) opcode }; } else if (data != null) { ArrayList<Byte> res = new ArrayList<>(); if (opcode < OP_PUSHDATA1) { checkState(data.length == opcode); res.add((byte) opcode); } else if (opcode == OP_PUSHDATA1) { checkState(data.length <= 0xFF); res.add((byte) OP_PUSHDATA1); res.add((byte) data.length); } else if (opcode == OP_PUSHDATA2) { checkState(data.length <= 0xFFFF); res.add((byte) OP_PUSHDATA2); res.add((byte) (0xFF & data.length)); res.add((byte) (0xFF & (data.length >> 8))); } else if (opcode == OP_PUSHDATA4) { checkState(data.length <= Script.MAX_SCRIPT_ELEMENT_SIZE); res.add((byte) OP_PUSHDATA4); res.add((byte) (0xFF & data.length)); res.add((byte) (0xFF & (data.length >> 8))); res.add((byte) (0xFF & (data.length >> 16))); res.add((byte) (0xFF & (data.length >> 24))); } else { throw new RuntimeException("Unimplemented"); } return Bytes.concat(Bytes.toArray(res), data); } else { return new byte[] { (byte) opcode }; } }

Target:
public byte[] toByteArray() { ByteArrayOutputStream stream = new ByteArrayOutputStream(); try { write(stream); } catch (IOException e) { throw new RuntimeException(e); } return stream.toByteArray(); }
Source:
public void testApplicationIdContainsSpace() { IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> new HttpLogOptions().setApplicationId("AppId 78912345")); assertEquals(thrown.getMessage(), "'applicationId' must not contain a space."); }

Target:
public void testApplicationIdContainsSpace() { IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> new HttpLogOptions().setApplicationId("AppId 78912345")); }
Source:
public static Properties defaultProperties() { Properties properties = BaseHttpApiMetadata.defaultProperties(); properties.setProperty(Constants.PROPERTY_MAX_RETRIES, "5"); properties.setProperty(ShipyardProperties.SHIPYARD_CREDENTIAL, "<remote-service-key-given-by-shipyard-cli>"); return properties; }

Target:
public static Properties defaultProperties() { return BaseHttpApiMetadata.defaultProperties(); }
Source:
public void setUp() throws Exception { Logger.getLogger(ConcurStandardAccountingExtractValidationServiceImpl.class).setLevel(Level.DEBUG); concurStandardAccountingExtractService = new ConcurStandardAccountingExtractValidationServiceImpl(); double[] debits = {100.75, -50.45}; double[] credits = {50.45}; file = ConcurStandardAccountingExtractFileFixture.buildConcurStandardAccountingExtractFile(debits, credits); }

Target:
public void setUp() throws Exception { Logger.getLogger(ConcurStandardAccountingExtractValidationServiceImpl.class).setLevel(Level.DEBUG); concurStandardAccountingValidationService = new ConcurStandardAccountingExtractValidationServiceImpl(); KualiDecimal[] debits = {new KualiDecimal(100.75), new KualiDecimal(-50.45)}; KualiDecimal[] credits = {}; file = ConcurStandardAccountingExtractFileFixture.buildConcurStandardAccountingExtractFile(debits, credits); }
Source:
private String convertMapToString(ModelNode modelNode) { StringBuffer sb = new StringBuffer(); String[] ss = strip(modelNode.asString().trim(), '{', '}').split(","); boolean first = true; for (String s : ss) { if (first) { first = false; } else { sb.append(","); } String[] entry = s.split("=>"); sb.append(strip(entry[0].trim(), '"', '"') + ":" + strip(entry[1].trim(), '"', '"')); } return sb.toString(); }

Target:
private String convertMapToString(ModelNode modelNode) { StringBuilder sb = new StringBuilder(); boolean first = true; for (String key : modelNode.keys()) { ModelNode value = modelNode.get(key); if (first) { first = false; } else { sb.append(","); } sb.append(key + ":" + value.asString()); } return sb.toString(); }
Source:
LauncherDiscoveryRequest buildRequest(Bundle bundle) { List<DiscoverySelector> selectors = new ArrayList<>(baseSelectors.size() + 1); selectors.add(BundleSelector.selectBundle(bundle)); return LauncherDiscoveryRequestBuilder.request() .configurationParameter(BundleEngine.CHECK_UNRESOLVED, unresolved) .selectors(selectors) .build(); }

Target:
LauncherDiscoveryRequest buildRequest(Bundle bundle) { List<DiscoverySelector> selectors = new ArrayList<>(baseSelectors.size() + 1); selectors.addAll(baseSelectors); selectors.add(BundleSelector.selectBundle(bundle)); return LauncherDiscoveryRequestBuilder.request() .configurationParameter(BundleEngine.CHECK_UNRESOLVED, unresolved) .selectors(selectors) .build(); }
Source:
public boolean handleClick(int x, int y, int k) { return this.inputField.mouseClicked(x,y,k); }

Target:
public boolean handleClick(int x, int y, int k) { if (k == 1 && x >= this.x && x < this.x + width && y >= this.y && y < y + height) setText(""); return mouseClicked(x, y, k); }
Source:
public static URLNotification parseXML(final InputStream message) throws Exception{ parser.parse(message); return parser.getNotification(); }

Target:
public static URLNotification parseXML(final InputStream message) throws Exception{ URLNotificationParser parser = new URLNotificationParser(); parser.parse(message); return parser.getNotification(); }
Source:
void addCellToPutMutation(Put put, byte[] family, byte[] column, long ts, byte[] value) throws Exception { byte[] rowKey = put.getRow(); Cell cell = new KeyValue(rowKey, family, column, ts, KeyValue.Type.Put, value); put.add(cell); }

Target:
void addCellToPutMutation(Put put, byte[] family, byte[] column, long ts, byte[] value) throws Exception { byte[] rowKey = put.getRow(); Cell cell = CellUtil.createCell(rowKey, family, column, ts, KeyValue.Type.Put.getCode(), value); put.add(cell); }
Source:
public void removeJson(MessageContext synCtx, SynapsePath jsonPath) throws IOException, PathNotFoundException { SynapseJsonPath synapseJsonPath = (SynapseJsonPath) jsonPath; Axis2MessageContext axis2smc = (Axis2MessageContext) synCtx; org.apache.axis2.context.MessageContext axis2MessageCtx = axis2smc.getAxis2MessageContext(); String jsonPathString = synapseJsonPath.toString(); jsonPathString = jsonPathString.substring(10, jsonPathString.length() - 1); if (jsonPathString.equals("$") || jsonPathString.equals("$.")) { JsonUtil.getNewJsonPayload(axis2MessageCtx, "", true, true); } else { String jsonString = IOUtils.toString(JsonUtil.getJsonPayload(axis2MessageCtx)); if (!StringUtils.isEmpty(jsonString)) { String result = jsonString; DocumentContext doc = JsonPath.parse(result); doc.delete(synapseJsonPath.getJsonPath()); result = doc.jsonString(); JsonUtil.getNewJsonPayload(axis2MessageCtx, result, true, true); } } }

Target:
public void removeJson(MessageContext synCtx, SynapsePath jsonPath) throws IOException, PathNotFoundException { SynapseJsonPath synapseJsonPath = (SynapseJsonPath) jsonPath; Axis2MessageContext axis2smc = (Axis2MessageContext) synCtx; org.apache.axis2.context.MessageContext axis2MessageCtx = axis2smc.getAxis2MessageContext(); String jsonPathString = synapseJsonPath.toString(); jsonPathString = jsonPathString.substring(10, jsonPathString.length() - 1); String[] jsonPathArray = jsonPathString.split(","); String jsonString = IOUtils.toString(JsonUtil.getJsonPayload(axis2MessageCtx)); String result = jsonString; if (jsonPathArray.length > 0) { for (String path : jsonPathArray) { if (path.equals("$") || path.equals("$.")) { JsonUtil.getNewJsonPayload(axis2MessageCtx, "", true, true); result = ""; } else { DocumentContext doc = JsonPath.parse(result); doc.delete(path); result = doc.jsonString(); } } JsonUtil.getNewJsonPayload(axis2MessageCtx, result, true, true); } }
Source:
protected void AddVmTemplateImages() { Guid vmSnapshotId = Guid.NewGuid(); for (DiskImage diskImage : mImages) { CreateImageTemplateParameters createParams = new CreateImageTemplateParameters(diskImage.getImageId(), getVmTemplateId(), getVmTemplateName(), getVmId()); createParams.setStorageDomainId(diskImage.getStorageIds().get(0)); createParams.setVmSnapshotId(vmSnapshotId); createParams.setEntityId(getParameters().getEntityId()); createParams.setDestinationStorageDomainId(diskInfoDestinationMap.get(diskImage.getId()) .getStorageIds() .get(0)); createParams.setDiskAlias(diskInfoDestinationMap.get(diskImage.getId()).getDiskAlias()); createParams.setParentParameters(getParameters()); if (getParameters().getDiskInfoDestinationMap() != null && getParameters().getDiskInfoDestinationMap().get(diskImage.getId()) != null) { createParams.setQuotaId(getParameters().getDiskInfoDestinationMap().get(diskImage.getId()).getQuotaId() != null ? getParameters().getDiskInfoDestinationMap().get(diskImage.getId()).getQuotaId() : null); } else { createParams.setQuotaId(diskImage.getQuotaId()); } VdcReturnValueBase retValue = Backend.getInstance().runInternalAction( VdcActionType.CreateImageTemplate, createParams, ExecutionHandler.createDefaultContexForTasks(getExecutionContext())); if (!retValue.getSucceeded()) { throw new VdcBLLException(retValue.getFault().getError(), retValue.getFault().getMessage()); } getReturnValue().getTaskIdList().addAll(retValue.getInternalTaskIdList()); newDiskImages.add((DiskImage) retValue.getActionReturnValue()); } }

Target:
protected void AddVmTemplateImages() { Guid vmSnapshotId = Guid.NewGuid(); for (DiskImage diskImage : mImages) { CreateImageTemplateParameters createParams = new CreateImageTemplateParameters(diskImage.getImageId(), getVmTemplateId(), getVmTemplateName(), getVmId()); createParams.setStorageDomainId(diskImage.getStorageIds().get(0)); createParams.setVmSnapshotId(vmSnapshotId); createParams.setEntityId(getParameters().getEntityId()); createParams.setDestinationStorageDomainId(diskInfoDestinationMap.get(diskImage.getId()) .getStorageIds() .get(0)); createParams.setDiskAlias(diskInfoDestinationMap.get(diskImage.getId()).getDiskAlias()); createParams.setParentParameters(getParameters()); createParams.setQuotaId(getQuotaIdForDisk(diskImage)); VdcReturnValueBase retValue = Backend.getInstance().runInternalAction( VdcActionType.CreateImageTemplate, createParams, ExecutionHandler.createDefaultContexForTasks(getExecutionContext())); if (!retValue.getSucceeded()) { throw new VdcBLLException(retValue.getFault().getError(), retValue.getFault().getMessage()); } getReturnValue().getTaskIdList().addAll(retValue.getInternalTaskIdList()); newDiskImages.add((DiskImage) retValue.getActionReturnValue()); } }
Source:
public List<ChePlugin> getTooling(RuntimeIdentity runtimeID, Collection<PluginMeta> pluginsMeta) throws InfrastructureException { String workspaceId = runtimeID.getWorkspaceId(); CompletableFuture<Void> startFuture = new CompletableFuture<>(); CompletableFuture<List<ChePlugin>> toolingFuture = new CompletableFuture<>(); KubernetesNamespace kubernetesNamespace = factory.create(workspaceId); E brokerEnvironment = brokerEnvironmentFactory.create(pluginsMeta, runtimeID); environmentProvisioner.provision(brokerEnvironment, runtimeID); ListenBrokerEvents listenBrokerEvents = getListenEventPhase(workspaceId, startFuture, toolingFuture); PrepareStorage prepareStorage = getPrepareStoragePhase(workspaceId, brokerEnvironment); WaitBrokerResult waitBrokerResult = getWaitBrokerPhase(toolingFuture); DeployBroker deployBroker = getDeployBrokerPhase( runtimeID.getWorkspaceId(), kubernetesNamespace, brokerEnvironment, startFuture); listenBrokerEvents.then(prepareStorage).then(deployBroker).then(waitBrokerResult); return listenBrokerEvents.execute(); }

Target:
public List<ChePlugin> getTooling(RuntimeIdentity runtimeID, Collection<PluginMeta> pluginsMeta) throws InfrastructureException { String workspaceId = runtimeID.getWorkspaceId(); CompletableFuture<List<ChePlugin>> toolingFuture = new CompletableFuture<>(); KubernetesNamespace kubernetesNamespace = factory.create(workspaceId); E brokerEnvironment = brokerEnvironmentFactory.create(pluginsMeta, runtimeID); environmentProvisioner.provision(brokerEnvironment, runtimeID); ListenBrokerEvents listenBrokerEvents = getListenEventPhase(workspaceId, toolingFuture); PrepareStorage prepareStorage = getPrepareStoragePhase(workspaceId, brokerEnvironment); WaitBrokerResult waitBrokerResult = getWaitBrokerPhase(toolingFuture); DeployBroker deployBroker = getDeployBrokerPhase( runtimeID.getWorkspaceId(), kubernetesNamespace, brokerEnvironment, toolingFuture); listenBrokerEvents.then(prepareStorage).then(deployBroker).then(waitBrokerResult); return listenBrokerEvents.execute(); }
Source:
public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException { player = args.length < 2 ? getCommandSenderAsPlayer(sender) : getPlayer(server, sender, args[0]); uuid = PlayerHelper.getUUIDFromPlayer(player).toString(); network = NetworkHelper.getSoulNetwork(uuid); }

Target:
public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException { if (args.length == 1 && (args[0].equals("?") || args[0].equals("help"))) { sender.sendMessage(new TextComponentTranslation(getHelp())); return; } player = args.length < 2 ? getCommandSenderAsPlayer(sender) : getPlayer(server, sender, args[0]); uuid = PlayerHelper.getUUIDFromPlayer(player).toString(); network = NetworkHelper.getSoulNetwork(uuid); subExecute(server, sender, args); }
Source:
public Optional<RepositoryId> getLastViewedRepository() { if (sessionConfig.getLastViewedRepository().isEmpty()) { return Optional.empty(); } else { RepositoryId repositoryId = RepositoryId.createFromId(sessionConfig.getLastViewedRepository()); if (repositoryId == null) { return Optional.empty(); } else { return Optional.of(repositoryId); } } }

Target:
public Optional<RepositoryId> getLastViewedRepository() { if (sessionConfig.getLastViewedRepository().isEmpty()) { return Optional.empty(); } RepositoryId repositoryId = RepositoryId.createFromId(sessionConfig.getLastViewedRepository()); if (repositoryId == null) { return Optional.empty(); } return Optional.of(repositoryId); }
Source:
public void rightClickAir(GlowPlayer player, ItemStack holding) { Iterator<Block> itr = new BlockIterator(player, 5); Block target = null; while (itr.hasNext()) { target = itr.next(); if (target.getType() != Material.AIR) { break; } } if (target != null) { BlockFace face = BlockFace.SELF; Material type = target.getType(); Material replaceWith; if (type == Material.WATER || type == Material.STATIONARY_WATER) { replaceWith = Material.WATER_BUCKET; } else if (type == Material.LAVA || type == Material.STATIONARY_LAVA) { replaceWith = Material.LAVA_BUCKET; } else { return; } if (target.getState().getRawData() != 8) { return; } PlayerBucketFillEvent bucketFill = EventFactory.onPlayerBucketFill(player, target, face, holding.getType(), holding); if (bucketFill.isCancelled()) { return; } if (player.getGameMode() != GameMode.CREATIVE) { if (holding.getAmount() == 1) { holding.setType(replaceWith); } else { holding.setAmount(holding.getAmount() - 1); player.getInventory().addItem(new ItemStack(replaceWith)); } } target.setType(Material.AIR); } }

Target:
public void rightClickAir(GlowPlayer player, ItemStack holding) { Iterator<Block> itr = new BlockIterator(player, 5); Block target = null; Block previousTarget = null; BlockType targetBlockType = null; boolean validTarget = false; while (itr.hasNext()) { previousTarget = target; target = itr.next(); targetBlockType = ItemTable.instance().getBlock(target.getType()); if (targetBlockType != null && targetBlockType instanceof BlockLiquid) { if (((BlockLiquid)targetBlockType).isCollectible((GlowBlockState) target.getState())) { validTarget = true; break; } } } if (target != null && validTarget == true) { BlockFace face; if (previousTarget != null) { face = target.getFace(previousTarget); } else { face = BlockFace.SELF; } Material replaceWith = ((BlockLiquid) targetBlockType).getBucketType(); PlayerBucketFillEvent bucketFill = EventFactory.onPlayerBucketFill(player, target, face, holding.getType(), holding); if (bucketFill.isCancelled()) { return; } if (player.getGameMode() != GameMode.CREATIVE) { if (holding.getAmount() == 1) { holding.setType(replaceWith); } else { holding.setAmount(holding.getAmount() - 1); player.getInventory().addItem(new ItemStack(replaceWith)); } } target.setType(Material.AIR); } }