auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void revokeReviewerPolicies(Context context, Item item) throws SQLException, AuthorizeException { Bundle originalBundle; try { originalBundle = itemService.getBundles(item, "ORIGINAL").get(0); } catch (IndexOutOfBoundsException ex) { originalBundle = null; } if (originalBundle != null) { for (Bitstream bitstream : originalBundle.getBitstreams()) { authorizeService.removeAllPoliciesByDSOAndType(context, bitstream, ResourcePolicy.TYPE_WORKFLOW); } authorizeService.removeAllPoliciesByDSOAndType(context, originalBundle, ResourcePolicy.TYPE_WORKFLOW); } authorizeService.removeAllPoliciesByDSOAndType(context, item, ResourcePolicy.TYPE_WORKFLOW); }

Target:
protected void revokeReviewerPolicies(Context context, Item item) throws SQLException, AuthorizeException { List<Bundle> bundles = item.getBundles(); for (Bundle originalBundle : bundles) { for (Bitstream bitstream : originalBundle.getBitstreams()) { authorizeService.removeAllPoliciesByDSOAndType(context, bitstream, ResourcePolicy.TYPE_WORKFLOW); } authorizeService.removeAllPoliciesByDSOAndType(context, originalBundle, ResourcePolicy.TYPE_WORKFLOW); } authorizeService.removeAllPoliciesByDSOAndType(context, item, ResourcePolicy.TYPE_WORKFLOW); }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); KazakApplication.injector().inject(this); setContentView(R.layout.activity_login); Firebase.setAndroidContext(this); if (savedInstanceState == null || !savedInstanceState.getBoolean(BUNDLE_NEED_NEW_CACHE)) { Log.v(TAG, "New LoginActivity created, clearing the login cache."); authRepository.clearLoginCache(); } mEmailView = (AutoCompleteTextView) findViewById(R.id.email); populateAutoComplete(); mPasswordView = (EditText) findViewById(R.id.password); mPasswordView.setOnEditorActionListener( new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) { if (id == R.id.login || id == EditorInfo.IME_NULL) { attemptLogin(); return true; } return false; } } ); Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button); mEmailSignInButton.setOnClickListener( new OnClickListener() { @Override public void onClick(View view) { attemptLogin(); } } ); mLoginFormView = findViewById(R.id.login_form); mProgressView = findViewById(R.id.login_progress); loginSubscriptions = new CompositeSubscription(); }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); KazakApplication.injector().inject(this); setContentView(R.layout.activity_login); contentRootView = (LinearLayout) findViewById(R.id.login_root_layout); if (savedInstanceState == null || !savedInstanceState.getBoolean(BUNDLE_NEED_NEW_CACHE)) { authRepository.clearLoginCache(); } emailView = (AutoCompleteTextView) findViewById(R.id.email); populateAutoComplete(); passwordView = (EditText) findViewById(R.id.password); passwordView.setOnEditorActionListener( new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) { if (id == R.id.login || id == EditorInfo.IME_NULL) { attemptLogin(); return true; } return false; } } ); Button signIn = (Button) findViewById(R.id.email_sign_in_button); signIn.setOnClickListener( new OnClickListener() { @Override public void onClick(@NonNull View view) { attemptLogin(); } } ); loginFormView = findViewById(R.id.login_form); progressView = findViewById(R.id.login_progress); }
Source:
private String getSerialNumber(byte[] bytes) { byte[] sn = new byte[10]; for (int i = 0; i < 10; i++) { sn[i] = (byte) bytes[i + 8]; } try { return new String(sn, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return ""; }

Target:
private String getSerialNumber(byte[] bytes) { byte[] sn = new byte[10]; for (int i = 0; i < 10; i++) { sn[i] = (byte) bytes[i + 8]; } try { return new String(sn, "UTF-8"); } catch (UnsupportedEncodingException e) { logger.debug("Cannot encode serial number from C message due to encoding issues."); } return ""; }
Source:
private DeferredSerialization dsOf(final ByteBuffer buf) { return new DeferredSerialization() { @Override public ByteBuffer serialize(final ByteBuffer outbuf) throws IOException { outbuf.put(buf); return null; } @Override public void cancel() @Override public int getSerializedSize() { return buf.remaining(); } }; }

Target:
private DeferredSerialization dsOf(final ByteBuffer buf) { return new DeferredSerialization() { @Override public void serialize(final ByteBuffer outbuf) throws IOException { outbuf.put(buf); } @Override public void cancel() @Override public int getSerializedSize() { return buf.remaining(); } }; }
Source:
private static <T> Optional<T> nullableOptional(Callable<T> callable) { if (!CDI_AVAILABLE) { return Optional.ofNullable(null); } T t; try { t = callable.call(); } catch (Throwable ex) { t = null; } return Optional.ofNullable(t); }

Target:
private static <T> Optional<T> nullableOptional(Callable<T> callable) { if (!CDI_AVAILABLE) { return Optional.empty(); } T t; try { t = callable.call(); } catch (Throwable ex) { t = null; } return Optional.ofNullable(t); }
Source:
public Boolean isBuildSuccessIndicated() { if (getStream() == null) return false; return getStream().contains(BUILD_SUCCESS); }

Target:
public boolean isBuildSuccessIndicated() { if (isErrorIndicated() || getStream() == null) { return false; } return getStream().contains(BUILD_SUCCESS); }
Source:
public void setUpZap() throws Exception { super.setUpZap(); Path xmlDir = Files.createDirectories( Paths.get(Constant.getZapHome(), JSFunctionPassiveScanner.FUNC_LIST_DIR)); Path testFile = xmlDir.resolve(JSFunctionPassiveScanner.FUNC_LIST_FILE); Files.write( testFile, Arrays.asList("# Test File", "bypassSecurityTrustScript", "trustAsHtml")); }

Target:
public void setUpZap() throws Exception { super.setUpZap(); Path xmlDir = Files.createDirectories( Paths.get(Constant.getZapHome(), JSFunctionPassiveScanner.FUNC_LIST_DIR)); Path testFile = xmlDir.resolve(JSFunctionPassiveScanner.FUNC_LIST_FILE); Files.write(testFile, Arrays.asList("# Test File", "bypassSecurityTrustHtml", "eval")); }
Source:
private void checkCachedCategories(PoiFiltersHelper poiFiltersHelper) { String fileName = resource.getFileName(); long lastModified = resource.getFileLastModified(); Pair<Long, Map<String, List<String>>> cache = poiFiltersHelper.getCacheByResourceName(fileName); if (cache == null || cache.first != null && cache.first != lastModified) { try { BinaryMapIndexReader reader = getOpenFile(); if (reader != null) { reader.initCategories(); List<BinaryMapPoiReaderAdapter.PoiRegion> regions = reader.getPoiIndexes(); for (BinaryMapPoiReaderAdapter.PoiRegion region : regions) { List<String> categories = region.getCategories(); List<List<String>> subCategories = region.getSubcategories(); for (int i = 0; i < categories.size(); i++) { PoiCategory poiCategory = poiTypes.getPoiCategoryByName(categories.get(i)); Set<String> filters = new HashSet<>(subCategories.get(i)); List<String> keys = poiCategory.getPoiTypesKeys(); filters.removeAll(keys); if (!filters.isEmpty()) { poiCategories.put(categories.get(i), new ArrayList<>(filters)); } } } if (cache == null) { poiFiltersHelper.insertCacheForResource(fileName, lastModified, poiCategories); } else { poiFiltersHelper.updateCacheForResource(fileName, lastModified, poiCategories); } } } catch (IOException e) { log.error("Error initializing categories ", e); } } else if (cache.second != null) { poiCategories = cache.second; } }

Target:
private void checkCachedCategories(PoiFiltersHelper poiFiltersHelper) { String fileName = resource.getFileName(); long lastModified = resource.getFileLastModified(); Pair<Long, Map<String, List<String>>> cache = poiFiltersHelper.getCacheByResourceName(fileName); if (cache == null || cache.first != null && cache.first != lastModified) { deltaPoiCategories = new HashMap<>(); try { BinaryMapIndexReader reader = getOpenFile(); if (reader != null) { reader.initCategories(); List<BinaryMapPoiReaderAdapter.PoiRegion> regions = reader.getPoiIndexes(); for (BinaryMapPoiReaderAdapter.PoiRegion region : regions) { calculateDeltaSubcategories(region); } if (cache == null) { poiFiltersHelper.insertCacheForResource(fileName, lastModified, deltaPoiCategories); } else { poiFiltersHelper.updateCacheForResource(fileName, lastModified, deltaPoiCategories); } } } catch (IOException e) { log.error("Error initializing categories ", e); } } else if (cache.second != null) { deltaPoiCategories = cache.second; } }
Source:
public void anotherMethod() { this.anonMethod(new AnonWithEmpty() { private int member; @Override public void fooEmpty() { this.member++; } }); }

Target:
public void anotherMethod() { this.anonMethod(new AnonWithEmpty() { private int member; public void fooEmpty() { this.member++; } }); }
Source:
public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_ISSUE_CREATE) { if (resultCode == Activity.RESULT_OK && data.hasExtra("issue")) { final Issue issue = (Issue) data.getSerializableExtra("issue"); mHandler.post(new Runnable() { @Override public void run() { if (mOpenFragment != null) { mOpenFragment.onItemClick(issue); } } }); } } else { super.onActivityResult(requestCode, resultCode, data); } }

Target:
public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_ISSUE_CREATE) { if (resultCode == Activity.RESULT_OK && data.hasExtra("issue")) { Issue issue = (Issue) data.getSerializableExtra("issue"); Intent intent = IssueActivity.makeIntent(this, mRepoOwner, mRepoName, issue.getNumber()); startActivityForResult(intent, REQUEST_ISSUE_AFTER_CREATE); } } else if (requestCode == REQUEST_ISSUE_AFTER_CREATE) { super.onRefresh(); } else { super.onActivityResult(requestCode, resultCode, data); } }
Source:
@Test public void checkAbilityToChangeOutputStream() throws Exception { file = new File("test"); file.createNewFile(); stream = new FileOutputStream(file); service = buildDefaultService(); service.addOutPutStream(stream); service.start(); assertTrue(file.length() > 0); }

Target:
@Test public void checkAbilityToChangeOutputStream() throws Exception { testLogFile = new File("test"); testLogFile.createNewFile(); stream = new FileOutputStream(testLogFile); service = buildDefaultService(); service.addOutPutStream(stream); service.start(); assertThat(testLogFile.length(), greaterThan(0L)); }
Source:
public static void mongoInsertSubmission(final DB dbs, final String uniqueId, final String problemId, final String submissionId, final boolean experiment) { LOG.info("Inserting an experiment ", experiment); LOG.info("Database is ", dbs); LOG.info("Problem id: ", problemId); final DBRef myDbRef = new DBRef(dbs, experiment ? EXPERIMENT_COLLECTION : SOLUTION_COLLECTION, new ObjectId(problemId)); final DBCollection collection = dbs.getCollection(experiment ? EXPERIMENT_COLLECTION : SOLUTION_COLLECTION); final DBObject corsor = myDbRef.fetch(); LOG.info("corsor: {}", corsor); LOG.info("uniuq id: {}", uniqueId); final BasicDBObject queryObj = new BasicDBObject(experiment ? uniqueId : SOLUTION_ID, submissionId); if (corsor == null) { LOG.info("Creating a new instance to this old itemid"); queryObj.append(SELF_ID, new ObjectId(problemId)); collection.insert(queryObj); } else { LOG.info("adding a new submission to this old itemid"); collection.update(corsor, new BasicDBObject("$set", queryObj)); } }

Target:
public static void mongoInsertSubmission(final DB dbs, final String uniqueId, final String problemId, final String submissionId, final boolean experiment) { LOG.info("Inserting an experiment {}", experiment); LOG.info("Database is {}", dbs); LOG.info("Problem id: {}", problemId); final DBRef myDbRef = new DBRef(dbs, experiment ? EXPERIMENT_COLLECTION : SOLUTION_COLLECTION, new ObjectId(problemId)); final DBCollection collection = dbs.getCollection(experiment ? EXPERIMENT_COLLECTION : SOLUTION_COLLECTION); final DBObject corsor = myDbRef.fetch(); LOG.info("corsor: {}", corsor); LOG.info("uniuq id: {}", uniqueId); final BasicDBObject queryObj = new BasicDBObject(experiment ? uniqueId : SOLUTION_ID, submissionId); if (corsor == null) { LOG.info("Creating a new instance to this old itemid"); queryObj.append(SELF_ID, new ObjectId(problemId)); collection.insert(queryObj); } else { LOG.info("adding a new submission to this old itemid"); collection.update(corsor, new BasicDBObject("$set", queryObj)); } }
Source:
public void testCommandDelegatesToTmcLangs() throws Exception { new RunCheckStyle("somePath", tmcLangsMock).call(); verify(tmcLangsMock, times(1)).runCheckCodeStyle(eq(Paths.get("somePath"))); }

Target:
public void testCommandDelegatesToTmcLangs() throws Exception { new RunCheckStyle("somePath", tmcLangsMock).call(); verify(tmcLangsMock).runCheckCodeStyle(eq(Paths.get("somePath"))); }
Source:
private void persistParameter(T value) { String memento = MementoUtils.encodeStringIntoMemento(value.toString()); IEclipsePreferences store = MulticoreVisualizerUIPlugin.getEclipsePreferenceStore(); if (memento != null) { store.put(m_storeKey, memento); try { store.flush(); } catch (BackingStoreException e) { e.printStackTrace(); } } }

Target:
private void persistParameter(T value) { String memento = MementoUtils.encodeStringIntoMemento(value.toString()); if (memento != null) { IEclipsePreferences store = MulticoreVisualizerUIPlugin.getEclipsePreferenceStore(); store.put(m_storeKey, memento); try { store.flush(); } catch (BackingStoreException e) { e.printStackTrace(); } } }
Source:
protected String fixEntryName(String entryName){ if(entryName.indexOf('\\') > 0) { return entryName.replace('\\', CompressedHelper.SEPARATOR_CHAR); } else { return entryName; } }

Target:
protected String fixEntryName(String entryName){ if(entryName.indexOf('\\') > 0) { return entryName.replaceAll("\\\\", CompressedHelper.SEPARATOR); } else { return entryName; } }
Source:
public void testSshProtoHostWithEmptyPortAndPath() throws Exception { final String str = "ssh://example.com:/path"; URIish u = new URIish(str); assertEquals("ssh", u.getScheme()); assertTrue(u.isRemote()); assertEquals("/path", u.getRawPath()); assertEquals("/path", u.getPath()); assertEquals("example.com", u.getHost()); assertEquals(-1, u.getPort()); assertEquals("ssh://example.com:/path", u.toString()); assertEquals("ssh://example.com:/path", u.toASCIIString()); assertEquals(u, new URIish(str)); }

Target:
public void testSshProtoHostWithEmptyPortAndPath() throws Exception { final String str = "ssh://example.com:/path"; URIish u = new URIish(str); assertEquals("ssh", u.getScheme()); assertTrue(u.isRemote()); assertEquals("/path", u.getRawPath()); assertEquals("/path", u.getPath()); assertEquals("example.com", u.getHost()); assertEquals(-1, u.getPort()); assertEquals("ssh://example.com/path", u.toString()); assertEquals("ssh://example.com/path", u.toASCIIString()); assertEquals(u, new URIish(str)); assertEquals(u, new URIish("ssh://example.com/path")); }
Source:
public int hashCode() { int hash = 5; hash = 79 * hash + (this.path != null ? this.path.hashCode() : 0); return hash; }

Target:
public int hashCode() { return this.path.hashCode(); }
Source:
public void execute(String userName) { FollowModeManager currentFollowModeManager = followModeManager; User userToFollow = findUser(userName); if (currentFollowModeManager == null) { return; } User currentlyFollowedUser = followModeManager.getFollowedUser(); if ((currentlyFollowedUser != null && !currentlyFollowedUser.equals(userToFollow)) || (currentlyFollowedUser == null && userToFollow != null)) { currentFollowModeManager.follow(userToFollow); } actionPerformed(); }

Target:
public void execute(String userName) { FollowModeManager currentFollowModeManager = followModeManager; User userToFollow = findUser(userName); if (currentFollowModeManager == null) { return; } currentFollowModeManager.follow(userToFollow); actionPerformed(); }
Source:
public static UserFactory getInstance() { if (instance == null) { Realm realm = Realm.getInstance(configuration); RealmLog.error("TTT " + realm.getPath()); UserFactoryStore store = realm.where(UserFactoryStore.class).findFirst(); if (store == null || store.getUserName() == null) { throw new IllegalStateException("Current user has not been set. Call resetInstance() first."); } instance = new UserFactory(store.getUserName()); realm.close(); } return instance; }

Target:
public static synchronized UserFactory getInstance() { if (instance == null) { Realm realm = Realm.getInstance(configuration); UserFactoryStore store = realm.where(UserFactoryStore.class).findFirst(); if (store == null || store.getUserName() == null) { throw new IllegalStateException("Current user has not been set. Call resetInstance() first."); } instance = new UserFactory(store.getUserName()); realm.close(); } RealmLog.debug("UserFactory.getInstance, the default user is " + instance.userName + " ."); return instance; }
Source:
private void endDefaultOperations() { endUnlockOps(); if (getParameters().getBaseTemplateId() != null) { for (Guid vmId : getVmDAO().getVmIdsForVersionUpdate(getParameters().getBaseTemplateId())) { UpdateVmVersionParameters params = new UpdateVmVersionParameters(vmId); params.setSessionId(getParameters().getSessionId()); params.setTransactionScopeOption(TransactionScopeOption.RequiresNew); getBackend().runInternalAction(VdcActionType.UpdateVmVersion, params); } } }

Target:
private void endDefaultOperations() { endUnlockOps(); if (getParameters().getBaseTemplateId() != null) { String jobId = SchedulerUtilQuartzImpl.getInstance().scheduleAOneTimeJob(this, "onTimerHandleVdsRecovering", new Class[0], new Object[0], 0, TimeUnit.SECONDS); updateVmsJobIdMap.put(getParameters().getBaseTemplateId(), jobId); } }
Source:
public Function<Locale, Text> apply(String translationId) { return locale -> { final Map<Locale, Text> translations = getTranslations(translationId); final Text result = translations.get(locale); if (result == null) { return this.translationFallback.apply(locale, translations); } else { return result; } }; }

Target:
public Function<Locale, Text> apply(String translationId) { checkNotNull(translationId, "translationId"); return locale -> getTranslation(translationId, locale); }
Source:
public FileWatcher startWatching(Collection<String> paths, double latency, FileWatcherCallback callback) { if (paths.isEmpty()) { return FileWatcher.EMPTY; } FunctionResult result = new FunctionResult(); FileWatcher watch = startWatching(paths.toArray(new String[0]), latency, callback, result); if (result.isFailed()) { throw new NativeException("Failed to start watch. Reason: " + result.getMessage()); } return watch; }

Target:
public FileWatcher startWatching(Collection<String> paths, double latency, FileWatcherCallback callback) { if (paths.isEmpty()) { return FileWatcher.EMPTY; } FunctionResult result = new FunctionResult(); FileWatcher watcher = startWatching(paths.toArray(new String[0]), latency, callback, result); if (result.isFailed()) { throw new NativeException("Failed to start watching. Reason: " + result.getMessage()); } return watcher; }
Source:
public List<BrooklinMetricInfo> getMetricInfos() { List<BrooklinMetricInfo> metrics = new ArrayList<>(); metrics.add(new BrooklinMeterInfo(buildMetricName(NUM_TASK_RESTARTS))); return Collections.unmodifiableList(metrics); }

Target:
public List<BrooklinMetricInfo> getMetricInfos() { List<BrooklinMetricInfo> metrics = new ArrayList<>(); metrics.add(new BrooklinGaugeInfo(buildMetricName(_metricsPrefix, NUM_TASK_RESTARTS))); return Collections.unmodifiableList(metrics); }
Source:
private void send(LanguageServer server, String filePath, FileChangeType changeType) { DidChangeWatchedFilesParams params = new DidChangeWatchedFilesParams( Collections.singletonList(new FileEvent(prefixURI(filePath), changeType))); LOG.debug("sending " + changeType + " to LS: " + filePath); server.getWorkspaceService().didChangeWatchedFiles(params); }

Target:
private void send(LanguageServer server, String filePath, FileChangeType changeType) { DidChangeWatchedFilesParams params = new DidChangeWatchedFilesParams( Collections.singletonList(new FileEvent(prefixURI(filePath), changeType))); LOG.debug("sending to LS: {}", changeType, filePath); server.getWorkspaceService().didChangeWatchedFiles(params); }
Source:
public void testHumanTaskListener() { KieSession ksession = createKSession(HUMAN_TASK_LISTENER); AtomicBoolean triggered = new AtomicBoolean(false); TaskLifeCycleEventListener listener = new DefaultTaskEventListener() { @Override public void afterTaskActivatedEvent(TaskEvent event) { triggered.set(true); } }; RuntimeEngine engine = getRuntimeEngine(); TaskService taskService = engine.getTaskService(); ((EventService<TaskLifeCycleEventListener>) taskService).registerTaskEventListener(listener); ProcessInstance pi = ksession.startProcess(HUMAN_TASK_LISTENER_ID); long processInstanceId = pi.getId(); List<Long> idList = taskService.getTasksByProcessInstanceId(processInstanceId); for (long taskId : idList) { taskService.start(taskId, "john"); taskService.complete(taskId, "john", emptyMap()); } assertTrue("Task should have triggered the event", triggered.get()); ksession.abortProcessInstance(processInstanceId); assertProcessInstanceAborted(processInstanceId); }

Target:
public void testHumanTaskListener() { KieSession ksession = createKSession(HUMAN_TASK_LISTENER); MutableInt triggered = new MutableInt(0); TaskLifeCycleEventListener listener = new DefaultTaskEventListener() { @Override public void afterTaskActivatedEvent(TaskEvent event) { triggered.increment(); } }; RuntimeEngine engine = getRuntimeEngine(); TaskService taskService = engine.getTaskService(); ((EventService<TaskLifeCycleEventListener>) taskService).registerTaskEventListener(listener); ProcessInstance pi = ksession.startProcess(HUMAN_TASK_LISTENER_ID); long processInstanceId = pi.getId(); List<Long> idList = taskService.getTasksByProcessInstanceId(processInstanceId); for (long taskId : idList) { taskService.start(taskId, "john"); taskService.complete(taskId, "john", emptyMap()); } assertEquals((int) 2, (int) triggered.getValue()); ksession.abortProcessInstance(processInstanceId); assertProcessInstanceAborted(processInstanceId); }
Source:
public DefaultContentDescriptor(String description, boolean mandatory) { this(description, mandatory, null); }

Target:
public DefaultContentDescriptor(String description, boolean mandatory) { this(description, mandatory, String.class); }
Source:
protected Command<GraphCommandExecutionContext, RuleViolation> newGraphCommand(final AbstractCanvasHandler context) { return new AbstractGraphCommand() { @Override protected CommandResult<RuleViolation> check(final GraphCommandExecutionContext context) { return GraphCommandResultBuilder.SUCCESS; } @Override public CommandResult<RuleViolation> execute(final GraphCommandExecutionContext context) { final int ocIndex = uiColumnIndex - DecisionTableUIModelMapperHelper.ROW_INDEX_COLUMN_COUNT - dtable.getInput().size(); dtable.getOutput().add(ocIndex, outputClause); dtable.getRule().forEach(rule -> { final LiteralExpression le = new LiteralExpression(); le.setText(OUTPUT_CLAUSE_DEFAULT_VALUE); rule.getOutputEntry().add(ocIndex, le); }); return GraphCommandResultBuilder.SUCCESS; } @Override public CommandResult<RuleViolation> undo(final GraphCommandExecutionContext context) { final int clauseIndex = dtable.getOutput().indexOf(outputClause); dtable.getRule().forEach(rule -> rule.getOutputEntry().remove(clauseIndex)); dtable.getOutput().remove(outputClause); return GraphCommandResultBuilder.SUCCESS; } }; }

Target:
protected Command<GraphCommandExecutionContext, RuleViolation> newGraphCommand(final AbstractCanvasHandler context) { return new AbstractGraphCommand() { @Override protected CommandResult<RuleViolation> check(final GraphCommandExecutionContext context) { return GraphCommandResultBuilder.SUCCESS; } @Override public CommandResult<RuleViolation> execute(final GraphCommandExecutionContext context) { final int clauseIndex = uiColumnIndex - DecisionTableUIModelMapperHelper.ROW_INDEX_COLUMN_COUNT - dtable.getInput().size(); dtable.getOutput().add(clauseIndex, outputClause); dtable.getRule().forEach(rule -> { final LiteralExpression le = new LiteralExpression(); le.setText(OUTPUT_CLAUSE_DEFAULT_VALUE); rule.getOutputEntry().add(clauseIndex, le); }); return GraphCommandResultBuilder.SUCCESS; } @Override public CommandResult<RuleViolation> undo(final GraphCommandExecutionContext context) { final int clauseIndex = dtable.getOutput().indexOf(outputClause); dtable.getRule().forEach(rule -> rule.getOutputEntry().remove(clauseIndex)); dtable.getOutput().remove(outputClause); return GraphCommandResultBuilder.SUCCESS; } }; }
Source:
private ActionListener<SearchResponse> expiredSnapshotsListener(String jobId, long deleteAllBeforeMs, ActionListener<Boolean> listener) { return new ActionListener<>() { @Override public void onResponse(SearchResponse searchResponse) { long nextToKeepMs = deleteAllBeforeMs; try { List<JobSnapshotId> snapshotIds = new ArrayList<>(); for (SearchHit hit : searchResponse.getHits()) { String timestamp = stringFieldValueOrNull(hit, ModelSnapshot.TIMESTAMP.getPreferredName()); if (timestamp == null) { continue; } Long timestampMs = TimeUtils.parseToEpochMs(timestamp); if (timestampMs >= nextToKeepMs) { do { nextToKeepMs += MS_IN_ONE_DAY; } while (timestampMs >= nextToKeepMs); continue; } JobSnapshotId idPair = new JobSnapshotId( stringFieldValueOrNull(hit, Job.ID.getPreferredName()), stringFieldValueOrNull(hit, ModelSnapshotField.SNAPSHOT_ID.getPreferredName())); if (idPair.hasNullValue() == false) { snapshotIds.add(idPair); } } deleteModelSnapshots(new VolatileCursorIterator<>(snapshotIds), listener); } catch (Exception e) { onFailure(e); } } @Override public void onFailure(Exception e) { listener.onFailure(new ElasticsearchException("[" + jobId + "] Search for expired snapshots failed", e)); } }; }

Target:
private ActionListener<SearchResponse> expiredSnapshotsListener(String jobId, long deleteAllBeforeMs, ActionListener<Boolean> listener) { return new ActionListener<>() { @Override public void onResponse(SearchResponse searchResponse) { long nextToKeepMs = deleteAllBeforeMs; try { List<JobSnapshotId> snapshotIds = new ArrayList<>(); for (SearchHit hit : searchResponse.getHits()) { String timestamp = stringFieldValueOrNull(hit, ModelSnapshot.TIMESTAMP.getPreferredName()); if (timestamp == null) { LOGGER.warn("Model snapshot document has a null timestamp field", hit.getId()); continue; } long timestampMs = TimeUtils.parseToEpochMs(timestamp); if (timestampMs >= nextToKeepMs) { do { nextToKeepMs += MS_IN_ONE_DAY; } while (timestampMs >= nextToKeepMs); continue; } JobSnapshotId idPair = new JobSnapshotId( stringFieldValueOrNull(hit, Job.ID.getPreferredName()), stringFieldValueOrNull(hit, ModelSnapshotField.SNAPSHOT_ID.getPreferredName())); if (idPair.hasNullValue() == false) { snapshotIds.add(idPair); } } deleteModelSnapshots(new VolatileCursorIterator<>(snapshotIds), listener); } catch (Exception e) { onFailure(e); } } @Override public void onFailure(Exception e) { listener.onFailure(new ElasticsearchException("[" + jobId + "] Search for expired snapshots failed", e)); } }; }
Source:
public void test() { CommitStatusUpdater.updateCommitStatus(build, taskListener, BuildState.success, STAGE); verify(client).changeBuildStatus(Integer.toString(PROJECT_ID), REVISION, BuildState.success, null, STAGE, Jenkins.getInstance().getRootUrl() + BUILD_URL + BUILD_URL_REDIRECT, null); }

Target:
public void test() { CommitStatusUpdater.updateCommitStatus(build, taskListener, BuildState.success, STAGE); verify(client).changeBuildStatus(Integer.toString(PROJECT_ID), REVISION, BuildState.success, null, STAGE, DisplayURLProvider.get().getRunURL(build), null); }
Source:
private DataSetReference.Builder createBasicMetadata(ResultProtos.Result sourceResult, DataSetReference.Builder metaBuilder) { if (sourceResult.hasMetadata()) { handleTitles(sourceResult.getMetadata().getTitleList(), metaBuilder); handleDescription(sourceResult.getMetadata().getDescriptionList(), metaBuilder); handlePublisher(sourceResult.getMetadata().getPublisher(), metaBuilder); handleYear(sourceResult.getMetadata().getDateofacceptance(), metaBuilder); handleFormats(sourceResult.getMetadata().getFormatList(), metaBuilder); handleResourceType(sourceResult.getMetadata(), metaBuilder); } return metaBuilder; }

Target:
private void createBasicMetadata(ResultProtos.Result sourceResult, DataSetReference.Builder metaBuilder) { if (sourceResult.hasMetadata()) { handleTitles(sourceResult.getMetadata().getTitleList(), metaBuilder); handleDescription(sourceResult.getMetadata().getDescriptionList(), metaBuilder); handlePublisher(sourceResult.getMetadata().getPublisher(), metaBuilder); handleYear(sourceResult.getMetadata().getDateofacceptance(), metaBuilder); handleFormats(sourceResult.getMetadata().getFormatList(), metaBuilder); handleResourceType(sourceResult.getMetadata(), metaBuilder); } }
Source:
boolean removeStorage(DatanodeStorageInfo storage) { int dnIndex = findStorageInfo(storage); if (dnIndex < 0) { return false; } int lastNode = numNodes()-1; setStorageInfo(dnIndex, getStorageInfo(lastNode)); setStorageInfo(lastNode, null); if (storage.getStorageType() == StorageType.PROVIDED && !hasProvidedStorages()) { hasProvidedStorage = false; } return true; }

Target:
boolean removeStorage(DatanodeStorageInfo storage) { int dnIndex = findStorageInfo(storage); if (dnIndex < 0) { return false; } int lastNode = numNodes()-1; setStorageInfo(dnIndex, getStorageInfo(lastNode)); setStorageInfo(lastNode, null); return true; }
Source:
public void modal_curtains_close_correctly() { openTestURL(); openModalWindow(); new Actions(getDriver()) .moveToElement(findElement(By.className("v-window-header"))) .clickAndHold().sendKeys(Keys.ESCAPE).perform(); verifyCurtainsNotPresent(); openModalWindow(); new Actions(getDriver()) .moveToElement(findElement(By.className("v-window-resizebox"))) .clickAndHold().sendKeys(Keys.ESCAPE).perform(); verifyCurtainsNotPresent(); }

Target:
public void modal_curtains_close_correctly() { openTestURL(); openModalWindow(); new Actions(getDriver()) .moveToElement(findHeaderElement()) .clickAndHold().moveByOffset(1, 1).perform(); assertTrue(isElementPresent(By.className("v-window-draggingCurtain"))); new Actions(getDriver()).sendKeys(findHeaderElement(), Keys.ESCAPE) .release().perform(); verifyCurtainsNotPresent(); openModalWindow(); new Actions(getDriver()) .moveToElement(findResizingElement()) .clickAndHold().moveByOffset(1, 1).perform(); assertTrue(isElementPresent(By.className("v-window-resizingCurtain"))); new Actions(getDriver()).sendKeys(findResizingElement(), Keys.ESCAPE) .release().perform(); verifyCurtainsNotPresent(); }
Source:
private boolean canDoSnapshot(VM vm) { boolean canSnapshot = true; if(!isLiveSnapshotEnabled() && !ImagesHandler.isVmDown(vm)) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_DATA_CENTER_VERSION_DOESNT_SUPPORT_LIVE_SNAPSHOT); canSnapshot = false; } return canSnapshot; }

Target:
private boolean canDoSnapshot(VM vm) { if (!isLiveSnapshotEnabled() && !ImagesHandler.isVmDown(vm)) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_DATA_CENTER_VERSION_DOESNT_SUPPORT_LIVE_SNAPSHOT); return false; } return true; }
Source:
public boolean set(String path, T data, int expectVersion, int options) { String clientPath = path; String serverPath = prependChroot(clientPath); Cache<T> cache = getCache(serverPath); boolean success = false; try { if (cache != null) { cache.lockWrite(); ZkBaseDataAccessor<T>.AccessResult result = _baseAccessor.doSet(_zkclient, serverPath, data, expectVersion, options); success = result._retCode == RetCode.OK; updateCache(cache, result._pathCreated, success, serverPath, data, result._stat); } else { success = _baseAccessor.set(serverPath, data, expectVersion, options); } } catch (Exception e) { } finally { if (cache != null) { cache.unlockWrite(); } } return success; }

Target:
public boolean set(String path, T data, int expectVersion, int options) { String clientPath = path; String serverPath = prependChroot(clientPath); Cache<T> cache = getCache(serverPath); boolean success = false; try { if (cache != null) { cache.lockWrite(); ZkBaseDataAccessor<T>.AccessResult result = _baseAccessor.doSet(serverPath, data, expectVersion, options); success = result._retCode == RetCode.OK; updateCache(cache, result._pathCreated, success, serverPath, data, result._stat); } else { success = _baseAccessor.set(serverPath, data, expectVersion, options); } } catch (Exception e) { } finally { if (cache != null) { cache.unlockWrite(); } } return success; }
Source:
private ClientConnection getConnection() throws IOException { ClientConnection connection = activeConnections.get(inetSocketAddressCache.get(target)); if (connection != null) { return connection; } AddressProvider addressProvider = currentClusterContext.getAddressProvider(); Address address = null; try { address = addressProvider.translate(target); } catch (Exception e) { logger.warning("Failed to translate addresses via address provider: " + e.getMessage()); } if (address == null) { throw new NullPointerException("Address Provider " + addressProvider.getClass() + " could not translate address " + target); } return createSocketConnection(address); }

Target:
private ClientConnection getConnection() throws IOException { ClientConnection connection = activeConnections.get(inetSocketAddressCache.get(target)); if (connection != null) { return connection; } AddressProvider addressProvider = currentClusterContext.getAddressProvider(); Address address = null; try { address = addressProvider.translate(target); } catch (Exception e) { logger.warning("Failed to translate address " + target + " via address provider " + e.getMessage()); } if (address == null) { throw new NullPointerException("Address Provider " + addressProvider.getClass() + " could not translate address " + target); } return createSocketConnection(address); }
Source:
protected int doWork() { IOUtil.assertFileIsReadable(VCF); IOUtil.assertFileIsWritable(OUTPUT); VCFFileReader vcfFileReader = new VCFFileReader(VCF, false); CloseableIterator<VariantContext> variants = vcfFileReader.iterator(); try { final IlluminaAdpcFileWriter adpcFileWriter = new IlluminaAdpcFileWriter(OUTPUT); final List<IlluminaAdpcRecord> adpcRecordList = new ArrayList<>(); while (variants.hasNext()) { final VariantContext context = variants.next(); final float gcScore = getFloatAttribute(context, InfiniumVcfFields.GC_SCORE); for (final Genotype genotype : context.getGenotypes()) { final IlluminaGenotype illuminaGenotype = getIlluminaGenotype(genotype, context); final short rawXIntensity = getShortAttribute(genotype, InfiniumVcfFields.X); final short rawYIntensity = getShortAttribute(genotype, InfiniumVcfFields.Y); final float normalizedXIntensity = getFloatAttribute(genotype, InfiniumVcfFields.NORMX); final float normalizedYIntensity = getFloatAttribute(genotype, InfiniumVcfFields.NORMY); final IlluminaAdpcRecord record = new IlluminaAdpcRecord(rawXIntensity, rawYIntensity, normalizedXIntensity, normalizedYIntensity, gcScore, illuminaGenotype); adpcRecordList.add(record); } } adpcFileWriter.write(adpcRecordList); } catch (IOException e) { log.error(e); return 1; } return 0; }

Target:
protected int doWork() { IOUtil.assertFileIsReadable(VCF); IOUtil.assertFileIsWritable(OUTPUT); VCFFileReader vcfFileReader = new VCFFileReader(VCF, false); try (CloseableIterator<VariantContext> variants = vcfFileReader.iterator(); IlluminaAdpcFileWriter adpcFileWriter = new IlluminaAdpcFileWriter(OUTPUT)) { final List<IlluminaAdpcFileWriter.Record> adpcRecordList = new ArrayList<>(); while (variants.hasNext()) { final VariantContext context = variants.next(); final float gcScore = getFloatAttribute(context, InfiniumVcfFields.GC_SCORE); for (final Genotype genotype : context.getGenotypes()) { final IlluminaGenotype illuminaGenotype = getIlluminaGenotype(genotype, context); final short rawXIntensity = getShortAttribute(genotype, InfiniumVcfFields.X); final short rawYIntensity = getShortAttribute(genotype, InfiniumVcfFields.Y); final float normalizedXIntensity = getFloatAttribute(genotype, InfiniumVcfFields.NORMX); final float normalizedYIntensity = getFloatAttribute(genotype, InfiniumVcfFields.NORMY); final IlluminaAdpcFileWriter.Record record = new IlluminaAdpcFileWriter.Record(rawXIntensity, rawYIntensity, normalizedXIntensity, normalizedYIntensity, gcScore, illuminaGenotype); adpcRecordList.add(record); } } adpcFileWriter.write(adpcRecordList); } catch (Exception e) { log.error(e); return 1; } return 0; }
Source:
public void readVectors(ColumnVector[] vectors, MessageType[] columnSchemas, long current, long total) { for (int i = 0 ; i < columnSchemas.length; i++) { MessageType schema = columnSchemas[i]; State state = getState(schema); readVector(state.column, vectors[i], current, total); } }

Target:
protected void readVectors(ColumnVector[] vectors, MessageType[] columnSchemas, long current, long total) { for (int i = 0 ; i < columnSchemas.length; i++) { MessageType schema = columnSchemas[i]; State state = getState(schema); readVector(state.column, vectors[i], current, total); } }
Source:
public void filter(ContainerRequestContext requestContext) throws IOException { if (requestContext.getHeaderString(TENANT_HEADER_NAME) != null) { requestContext.abortWith(Response.status(Response.Status.BAD_REQUEST) .type(APPLICATION_JSON_TYPE) .entity(new ApiError(TENANT_HEADER_NOT_ALLOWED)) .build()); } else if (!checkPersona()) { requestContext.abortWith(Response.status(Response.Status.BAD_REQUEST) .type(APPLICATION_JSON_TYPE) .entity(new ApiError(MISSING_TENANT_MSG)) .build()); } else { requestContext.getHeaders().putSingle(TENANT_HEADER_NAME, persona.get().getId()); } }

Target:
public void filter(ContainerRequestContext requestContext) throws IOException { String path = requestContext.getUriInfo().getPath(); if (path.startsWith("/db") || path.startsWith("/status") || path.equals("/")) { return; } if (requestContext.getHeaderString(TENANT_HEADER_NAME) != null) { requestContext.abortWith(Response.status(Response.Status.BAD_REQUEST) .type(APPLICATION_JSON_TYPE) .entity(new ApiError(TENANT_HEADER_NOT_ALLOWED)) .build()); } else if (!checkPersona()) { requestContext.abortWith(Response.status(Response.Status.BAD_REQUEST) .type(APPLICATION_JSON_TYPE) .entity(new ApiError(MISSING_TENANT_MSG)) .build()); } else { requestContext.getHeaders().putSingle(TENANT_HEADER_NAME, persona.get().getId()); } }
Source:
public LdapProviderType retrieveLdapProviderType(String domain) { Attributes attributes = getDomainAttributes(LdapProviderType.general, domain); if (attributes != null) { if (attributes.get(ADRootDSEAttributes.domainControllerFunctionality.name()) != null) { return LdapProviderType.activeDirectory; } else if (attributes.get(RHDSRootDSEAttributes.netscapemdsuffix.name()) != null) { return LdapProviderType.rhds; } else { return LdapProviderType.ipa; } } else { return LdapProviderType.general; } }

Target:
public LdapProviderType retrieveLdapProviderType(String domain) { LdapProviderType retVal = LdapProviderType.general; Attributes attributes = getDomainAttributes(LdapProviderType.general, domain); if (attributes != null) { if (attributes.get(ADRootDSEAttributes.domainControllerFunctionality.name()) != null) { retVal = LdapProviderType.activeDirectory; } else if (attributes.get(RHDSRootDSEAttributes.netscapemdsuffix.name()) != null) { retVal = LdapProviderType.rhds; } else if (attributes.get(IPARootDSEAttributes.namingContexts.name()) != null) { retVal = LdapProviderType.ipa; } } return retVal; }
Source:
public void itCanFireWorkFailureEvent() throws Exception { int initCount = DummyPostCommitEventListener.handledCount(); int initEvtCount = DummyPostCommitEventListener.eventCount(); int initSyncEvntCount = WorkFailureEventListener.getCount(); service.schedule(new SleepAndFailWork(0)); assertTrue(service.awaitCompletion(getDurationMillis(), TimeUnit.MILLISECONDS)); assertEquals(1 + initSyncEvntCount, WorkFailureEventListener.getCount()); eventService.waitForAsyncCompletion(); assertEquals(1 + initCount, DummyPostCommitEventListener.handledCount()); assertEquals(1 + initEvtCount, DummyPostCommitEventListener.eventCount()); }

Target:
public void itCanFireWorkFailureEvent() throws Exception { int initCount = DummyPostCommitEventListener.handledCount(); int initEvtCount = DummyPostCommitEventListener.eventCount(); int initSyncEvntCount = WorkFailureEventListener.getCount(); service.schedule(new SleepAndFailWork(0)); assertTrue(service.awaitCompletion(6000, TimeUnit.MILLISECONDS)); assertEquals(1 + initSyncEvntCount, WorkFailureEventListener.getCount()); eventService.waitForAsyncCompletion(); assertEquals(1 + initCount, DummyPostCommitEventListener.handledCount()); assertEquals(1 + initEvtCount, DummyPostCommitEventListener.eventCount()); }
Source:
public Collection<File> listItems( final Repository repository, final File repositoryBaseDir, final ResourceStoreRequest request, final File target ) throws ItemNotFoundException, LocalStorageException { if ( target.isDirectory() ) { List<File> result = new ArrayList<File>(); File[] files = target.listFiles( new FileFilter() { @Override public boolean accept( File pathname ) { return !pathname.getName().endsWith( HIDDEN_TARGET_SUFFIX ); } } ); if ( files != null ) { for ( int i = 0; i < files.length; i++ ) { if ( files[i].isFile() || files[i].isDirectory() ) { String newPath = ItemPathUtils.concatPaths( request.getRequestPath(), files[i].getName() ); request.pushRequestPath( newPath ); result.add( retrieveItem( repository, repositoryBaseDir, request, files[i] ) ); request.popRequestPath(); } } } else { getLogger().warn( "Cannot list directory in repository {}, path \"{}\"", RepositoryStringUtils.getHumanizedNameString( repository ), target.getAbsolutePath() ); throw new LocalStorageException( "Cannot list directory in repository " + repository + ", path " + target.getAbsolutePath() ); } return result; } else if ( target.isFile() ) { return null; } else { throw new ItemNotFoundException( request, repository ); } }

Target:
public Collection<File> listItems( final Repository repository, final File repositoryBaseDir, final ResourceStoreRequest request, final File target ) throws ItemNotFoundException, LocalStorageException { if ( target.isDirectory() ) { List<File> result = new ArrayList<File>(); File[] files = target.listFiles( new FileFilter() { @Override public boolean accept( File pathname ) { return !pathname.getName().endsWith( HIDDEN_TARGET_SUFFIX ); } } ); if ( files != null ) { for ( int i = 0; i < files.length; i++ ) { if ( files[i].isFile() || files[i].isDirectory() ) { String newPath = ItemPathUtils.concatPaths( request.getRequestPath(), files[i].getName() ); request.pushRequestPath( newPath ); result.add( retrieveItem( repository, repositoryBaseDir, request, files[i] ) ); request.popRequestPath(); } } } else { throw new LocalStorageException( "Cannot list directory in repository " + repository + ", path " + target.getAbsolutePath() ); } return result; } else if ( target.isFile() ) { return null; } else { throw new ItemNotFoundException( request, repository ); } }
Source:
public boolean existsUser(String username) { try { for (String serviceName : securityManager.listUserGroupServices()) { if (securityManager.loadUserGroupService(serviceName).getUserByUsername(username) != null) { return true; } } for (String roleServiceName : securityManager.listRoleServices()) { if (securityManager.loadRoleService(roleServiceName).getRolesForUser(username) != null && !securityManager.loadRoleService(roleServiceName).getRolesForUser(username).isEmpty()) { return true; } } } catch (IOException e) { logger.log(Level.WARNING, e.getMessage(), e); } return false; }

Target:
public boolean existsUser(String username) { try { for (String serviceName : securityManager.listUserGroupServices()) { if (securityManager.loadUserGroupService(serviceName).getUserByUsername(username) != null) { return true; } } for (String roleServiceName : securityManager.listRoleServices()) { SortedSet<GeoServerRole> userRoles = securityManager.loadRoleService(roleServiceName).getRolesForUser(username); if (userRoles != null && !userRoles.isEmpty()) { return true; } } } catch (IOException e) { logger.log(Level.WARNING, e.getMessage(), e); } return false; }
Source:
public void verifyVideoWidth(int widthDesired) { waitForElementByElement(withInputField); int width = Integer.parseInt(withInputField.getAttribute("value")); Assertion.assertNumber( widthDesired, width, "video width is " + width + " should be " + widthDesired); PageObjectLogging.log("verifyVideoWidth", "video width verified", true); }

Target:
public void verifyVideoWidth(int widthDesired) { waitForElementByElement(widthInputField); int width = Integer.parseInt(widthInputField.getAttribute("value")); Assertion.assertEquals( widthDesired, width); PageObjectLogging.log("verifyVideoWidth", "video width verified", true); }
Source:
protected void render() { FormRenderingContext context = dynamicFormModelGenerator.getContextForModel(fieldCopy); if (context != null) { FormEditorRenderingContext renderingContext = new FormEditorRenderingContext(helper.getPath()); renderingContext.setRootForm(context.getRootForm()); renderingContext.getAvailableForms().putAll(context.getAvailableForms()); renderingContext.setModel(fieldCopy); doRender(helper, renderingContext); } else { propertiesService.call(new RemoteCallback<FormEditorRenderingContext>() { @Override public void callback(FormEditorRenderingContext renderingContext) { renderingContext.setModel(fieldCopy); renderingContext.setParentContext(helper.getCurrentRenderingContext()); doRender(helper, renderingContext); } }).getFieldPropertiesRenderingContext(fieldCopy, helper.getPath()); } }

Target:
protected void render() { FormRenderingContext context = dynamicFormModelGenerator.getContextForModel(fieldCopy); if (context != null) { FormEditorRenderingContext renderingContext = new FormEditorRenderingContext(helper.getPath()); renderingContext.setRootForm(context.getRootForm()); renderingContext.getAvailableForms().putAll(context.getAvailableForms()); renderingContext.setModel(fieldCopy); doRender(helper, renderingContext); } }
Source:
public static SimpleFeature toFeature(JSONObject json, SimpleFeatureBuilder builder) throws JSONException { String type = json.getString(GeoJSON.TYPE); if (!GeoJSON.FEATURE.equals(type)) { throw new IllegalArgumentException("type was not " + GeoJSON.FEATURE); } if (builder == null) { builder = getBuilder(json); } builder.reset(); JSONObject geometry = json.optJSONObject(GeoJSON.GEOMETRY); if (geometry != null) { builder.set("geom", toGeometry(geometry)); } JSONObject properties = json.optJSONObject(GeoJSON.PROPERTIES); if (properties != null) { @SuppressWarnings("unchecked") Iterator<String> keys = properties.keys(); while (keys.hasNext()) { String name = keys.next(); Object value = properties.get(name); builder.set(name, value); } } String id = json.optString(GeoJSON.ID); return builder.buildFeature(id); }

Target:
public static SimpleFeature toFeature(JSONObject json, SimpleFeatureBuilder builder) throws JSONException { String type = json.getString(GeoJSON.TYPE); if (!GeoJSON.FEATURE.equals(type)) { throw new IllegalArgumentException("type was not " + GeoJSON.FEATURE); } if (builder == null) { builder = getBuilder(json); } builder.reset(); JSONObject geometry = json.optJSONObject(GeoJSON.GEOMETRY); if (geometry != null) { builder.set(GEOM_ATTRIBUTE, toGeometry(geometry)); } JSONObject properties = json.optJSONObject(GeoJSON.PROPERTIES); if (properties != null) { @SuppressWarnings("unchecked") Iterator<String> keys = properties.keys(); while (keys.hasNext()) { String name = keys.next(); Object value = properties.get(name); builder.set(name, value); } } String id = json.optString(GeoJSON.ID); return builder.buildFeature(id); }