auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public GuidePostsCache(ConnectionQueryServices queryServices, Configuration config) { this.queryServices = Objects.requireNonNull(queryServices); final int statsCacheThreadPoolSize = config.getInt( QueryServices.STATS_CACHE_THREAD_POOL_SIZE, QueryServicesOptions.DEFAULT_STATS_CACHE_THREAD_POOL_SIZE); executor = Executors.newFixedThreadPool(statsCacheThreadPoolSize); final long statsUpdateFrequency = config.getLong( QueryServices.STATS_UPDATE_FREQ_MS_ATTRIB, QueryServicesOptions.DEFAULT_STATS_UPDATE_FREQ_MS); final long maxTableStatsCacheSize = config.getLong( QueryServices.STATS_MAX_CACHE_SIZE, QueryServicesOptions.DEFAULT_STATS_MAX_CACHE_SIZE); final boolean isStatsEnabled = config.getBoolean(STATS_COLLECTION_ENABLED, DEFAULT_STATS_COLLECTION_ENABLED) && config.getBoolean(STATS_ENABLED_ATTRIB, true); PhoenixStatsCacheLoader cacheLoader = new PhoenixStatsCacheLoader( isStatsEnabled ? new StatsLoaderImpl() : new EmptyStatsLoader(), executor); cache = CacheBuilder.newBuilder() .refreshAfterWrite(statsUpdateFrequency, TimeUnit.MILLISECONDS) .maximumWeight(maxTableStatsCacheSize) .weigher(new Weigher<GuidePostsKey, GuidePostsInfo>() { @Override public int weigh(GuidePostsKey key, GuidePostsInfo info) { return info.getEstimatedSize(); } }) .removalListener(new PhoenixStatsCacheRemovalListener()) .build(cacheLoader); }

Target:
public GuidePostsCache(ConnectionQueryServices queryServices, Configuration config) { this.queryServices = Objects.requireNonNull(queryServices); final long statsUpdateFrequency = config.getLong( QueryServices.STATS_UPDATE_FREQ_MS_ATTRIB, QueryServicesOptions.DEFAULT_STATS_UPDATE_FREQ_MS); final long maxTableStatsCacheSize = config.getLong( QueryServices.STATS_MAX_CACHE_SIZE, QueryServicesOptions.DEFAULT_STATS_MAX_CACHE_SIZE); final boolean isStatsEnabled = config.getBoolean(STATS_COLLECTION_ENABLED, DEFAULT_STATS_COLLECTION_ENABLED); PhoenixStatsCacheLoader cacheLoader = new PhoenixStatsCacheLoader( isStatsEnabled ? new StatsLoaderImpl() : new EmptyStatsLoader(), config); cache = CacheBuilder.newBuilder() .refreshAfterWrite(statsUpdateFrequency, TimeUnit.MILLISECONDS) .maximumWeight(maxTableStatsCacheSize) .weigher(new Weigher<GuidePostsKey, GuidePostsInfo>() { @Override public int weigh(GuidePostsKey key, GuidePostsInfo info) { return info.getEstimatedSize(); } }) .removalListener(new PhoenixStatsCacheRemovalListener()) .build(cacheLoader); }
Source:
public void onClose(Session session, CloseReason reason) { synchronized(close) { close.notify(); } listener.onClose(); }

Target:
public void onClose(Session session, CloseReason reason) { synchronized(close) { this.session = null; close.notify(); } listener.onClose(); }
Source:
public View onCreateView( @NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.camera_controller_view, container, false); mPreviewView = view.findViewById(R.id.preview_view); mCameraController.setPreviewView(mPreviewView); if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) { mCameraController.bindToLifecycle(CameraControllerFragment.this); } return view; }

Target:
public View onCreateView( @NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.camera_controller_view, container, false); mPreviewView = view.findViewById(R.id.preview_view); mCameraController.setPreviewView(mPreviewView); if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) { mCameraController.bindToLifecycle(getContext(), CameraControllerFragment.this); } return view; }
Source:
public static <T> Matcher<Async<T>> result(final Matcher<? super T> valueMatcher) { return new TypeSafeDiagnosingMatcher<Async<T>>() { @Override protected boolean matchesSafely(Async<T> item, Description mismatchDescription) { AsyncResult<T> result = getResult(item); switch (result.state) { case SUCCEEDED: if (valueMatcher.matches(result.value)) { return true; } else { mismatchDescription.appendText("result "); valueMatcher.describeMismatch(result.value, mismatchDescription); return false; } case FAILED: mismatchDescription.appendText("failed with exception " + result.error); return false; case UNFINISHED: mismatchDescription.appendText("isn't finished yet"); return false; } return false; } @Override public void describeTo(Description description) { description.appendText("a successful async which result ").appendDescriptionOf(valueMatcher); } }; }

Target:
public static <T> Matcher<Async<T>> result(final Matcher<? super T> valueMatcher) { return new TypeSafeDiagnosingMatcher<Async<T>>() { @Override protected boolean matchesSafely(Async<T> item, Description mismatchDescription) { AsyncResult<T> result = getResult(item); switch (result.state) { case SUCCEEDED: if (valueMatcher.matches(result.value)) { return true; } else { mismatchDescription.appendText("result "); valueMatcher.describeMismatch(result.value, mismatchDescription); return false; } case FAILED: mismatchDescription.appendText("failed with exception: "); mismatchDescription.appendValue(result.error); return false; case UNFINISHED: mismatchDescription.appendText("isn't finished yet"); return false; } return false; } @Override public void describeTo(Description description) { description.appendText("a successful async which result ").appendDescriptionOf(valueMatcher); } }; }
Source:
public MatrixTransformation(Request data) { this.data = data; }

Target:
MatrixTransformation(Request data) { this.data = data; }
Source:
public ListenableFuture<Map<Cell, byte[]>> getAsync(TableReference tableRef, Set<Cell> cells) { if (cells.isEmpty()) { return Futures.immediateFuture(ImmutableMap.of()); } Set<Cell> toLoad = Sets.newHashSet(); ImmutableMap.Builder<Cell, byte[]> cacheHitMapBuilder = ImmutableMap.builder(); for (Cell cell : cells) { byte[] val = getCachedCellIfPresent(tableRef, cell); if (val != null) { if (val.length > 0) { cacheHitMapBuilder.put(cell, val); } } else { toLoad.add(cell); } } ImmutableMap<Cell, byte[]> cacheHit = cacheHitMapBuilder.build(); return Futures.transform(super.getAsync(tableRef, toLoad), loaded -> { cacheLoadedCells(tableRef, toLoad, loaded); return ImmutableMap.<Cell, byte[]>builder() .putAll(loaded.entrySet()) .putAll(cacheHit.entrySet()) .build(); }, MoreExecutors.directExecutor()); }

Target:
public ListenableFuture<Map<Cell, byte[]>> getAsync(TableReference tableRef, Set<Cell> cells) { return getWithLoader(tableRef, cells, super::getAsync); }
Source:
public Configuration getEffectiveConfiguration(String[] args) throws CliArgsException { final CommandLine commandLine = cli.parseCommandLineOptions(args, true); final Configuration effectiveConfiguration = new Configuration(baseConfiguration); effectiveConfiguration.addAll(cli.toConfiguration(commandLine)); effectiveConfiguration.set(DeploymentOptions.TARGET, KubernetesSessionClusterExecutor.NAME); return effectiveConfiguration; }

Target:
Configuration getEffectiveConfiguration(String[] args) throws CliArgsException { final CommandLine commandLine = cli.parseCommandLineOptions(args, true); final Configuration effectiveConfiguration = new Configuration(baseConfiguration); effectiveConfiguration.addAll(cli.toConfiguration(commandLine)); effectiveConfiguration.set(DeploymentOptions.TARGET, KubernetesSessionClusterExecutor.NAME); return effectiveConfiguration; }
Source:
protected void emitResults() throws Exception { while ((resultTuple = pythonFunctionRunner.pollResult()) != null) { emitResult(); } }

Target:
protected void emitResults() throws Exception { Tuple2<byte[], Integer> resultTuple; while ((resultTuple = pythonFunctionRunner.pollResult()) != null) { emitResult(resultTuple); } }
Source:
public void insertLocator(Locator locator) throws IOException { Timer.Context timer = Instrumentation.getWriteTimerContext(CassandraModel.CF_METRICS_LOCATOR_NAME); try { MutationBatch mutationBatch = AstyanaxIO.getKeyspace().prepareMutationBatch(); AstyanaxWriter.getInstance().insertLocator(locator, mutationBatch); mutationBatch.execute(); } catch (Exception e) { throw new IOException(e); } finally { if ( timer != null ) { timer.stop(); } } }

Target:
public void insertLocator(Locator locator) throws IOException { Timer.Context timer = Instrumentation.getWriteTimerContext(CassandraModel.CF_METRICS_LOCATOR_NAME); try { MutationBatch mutationBatch = AstyanaxIO.getKeyspace().prepareMutationBatch(); AstyanaxWriter.getInstance().insertLocator(locator, mutationBatch); mutationBatch.execute(); } catch (Exception e) { throw new IOException(e); } finally { timer.stop(); } }
Source:
public List<Condition> getActiveConditions(Patient patient) { if(log.isInfoEnabled()){ log.info("Getting active conditions with patient " + patient); } return conditionDAO.getActiveConditions(patient); }

Target:
public List<Condition> getActiveConditions(Patient patient) { return conditionDAO.getActiveConditions(patient); }
Source:
public void removeBrokerConnection(MqttBrokerConnection connection) { synchronized (brokerConnections) { brokerConnections.remove(connection.getName(), connection); for (MqttBrokersObserver o : brokersObservers) { o.brokerRemoved(connection); } } }

Target:
public void removeBrokerConnection(MqttBrokerConnection connection) { synchronized (brokerConnections) { if (brokerConnections.remove(connection.getName().toLowerCase(), connection)) { for (MqttBrokersObserver o : brokersObservers) { o.brokerRemoved(connection); } } } }
Source:
public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; if (v == null) { v = View.inflate(context, R.layout.nav_drawer_item_view, null); } NavDrawerItem item = this.getItem(position); ((TextView)v.findViewById(R.id.drawer_text)).setText(item.text); ((ImageView)v.findViewById(R.id.drawer_icon)).setImageResource(item.iconResource); TextView subtext = ((TextView)v.findViewById(R.id.drawer_subtext)); if (item.subtext != null && !"".equals(item.subtext)) { subtext.setText(item.subtext); subtext.setVisibility(View.VISIBLE); } else { subtext.setVisibility(View.GONE); } return v; }

Target:
public @NonNull View getView(int position, View convertView, ViewGroup parent) { View v = convertView; if (v == null) { v = View.inflate(context, R.layout.nav_drawer_item_view, null); } NavDrawerItem item = this.getItem(position); if (item != null) { ((TextView)v.findViewById(R.id.drawer_text)).setText(item.text); ((ImageView)v.findViewById(R.id.drawer_icon)).setImageResource(item.iconResource); TextView subtext = ((TextView)v.findViewById(R.id.drawer_subtext)); if (item.subtext != null && !"".equals(item.subtext)) { subtext.setText(item.subtext); subtext.setVisibility(View.VISIBLE); } else { subtext.setVisibility(View.GONE); } } return v; }
Source:
protected void fireContentEditorFieldEvent(ContentEditorFieldEvent e) { EventListener[] listeners = m_listenerList.getListeners(ContentEditorFieldListener.class); if (listeners != null && listeners.length > 0) { for (int i = 0; i < listeners.length; i++) { ((ContentEditorFieldListener) listeners[i]).contentEditorFieldChanged(e); } } }

Target:
protected void fireContentEditorFieldEvent(ContentEditorFieldEvent e) { EventListener[] listeners = m_listenerList.getListeners(ContentEditorFieldListener.class); if (listeners == null) { return; } for (EventListener listener : listeners) { ((ContentEditorFieldListener) listener).contentEditorFieldChanged(e); } }
Source:
public Optional<AnnotationLayer> getLayer(Project aProject, long aLayerId) { AnnotationLayer layer = getLayer(aLayerId); if (layer != null && Objects.equals(layer.getProject().getId(), aProject.getId())) { return Optional.empty(); } return Optional.ofNullable(layer); }

Target:
public Optional<AnnotationLayer> getLayer(Project aProject, long aLayerId) { AnnotationLayer layer = getLayer(aLayerId); if (layer != null && !Objects.equals(layer.getProject().getId(), aProject.getId())) { return Optional.empty(); } return Optional.ofNullable(layer); }
Source:
public void setCookieMaxAge(int cookieMaxAge) { Assert.isTrue(cookieMaxAge != 0, "cookieMaxAge is not zero"); this.cookieMaxAge = cookieMaxAge; }

Target:
public void setCookieMaxAge(int cookieMaxAge) { Assert.isTrue(cookieMaxAge != 0, "cookieMaxAge cannot be zero"); this.cookieMaxAge = cookieMaxAge; }
Source:
public PlanNode optimize(PlanNode plan, Session session, Map<Symbol, Type> types, SymbolAllocator symbolAllocator, PlanNodeIdAllocator idAllocator) { if (!SystemSessionProperties.isNewOptimizerEnabled(session) && !legacyRules.isEmpty()) { for (PlanOptimizer optimizer : legacyRules) { plan = optimizer.optimize(plan, session, symbolAllocator.getTypes(), symbolAllocator, idAllocator); } return plan; } Memo memo = new Memo(idAllocator, plan); Lookup lookup = Lookup.from(memo::resolve); Matcher matcher = DEFAULT_MATCHER; Duration timeout = SystemSessionProperties.getOptimizerTimeout(session); Context context = new Context(memo, lookup, idAllocator, symbolAllocator, System.nanoTime(), timeout.toMillis(), session); exploreGroup(memo.getRootGroup(), context, matcher); return memo.extract(); }

Target:
public PlanNode optimize(PlanNode plan, Session session, Map<Symbol, Type> types, SymbolAllocator symbolAllocator, PlanNodeIdAllocator idAllocator) { if (!SystemSessionProperties.isNewOptimizerEnabled(session) && !legacyRules.isEmpty()) { for (PlanOptimizer optimizer : legacyRules) { plan = optimizer.optimize(plan, session, symbolAllocator.getTypes(), symbolAllocator, idAllocator); } return plan; } Memo memo = new Memo(idAllocator, plan); Lookup lookup = Lookup.from(memo::resolve); Matcher matcher = new PlanNodeMatcher(lookup); Duration timeout = SystemSessionProperties.getOptimizerTimeout(session); Context context = new Context(memo, lookup, idAllocator, symbolAllocator, System.nanoTime(), timeout.toMillis(), session); exploreGroup(memo.getRootGroup(), context, matcher); return memo.extract(); }
Source:
public List<SolrInputDocument> add(List<Metacard> metacards, boolean forceAutoCommit) throws IOException, SolrServerException, MetacardCreationException { if (metacards == null || metacards.isEmpty()) { return Collections.emptyList(); } List<SolrInputDocument> docs = new ArrayList<>(); for (Metacard metacard : metacards) { docs.add(getSolrInputDocument(metacard)); } if (!forceAutoCommit) { client.add(docs); } else { softCommit(docs); } return docs; }

Target:
public List<SolrInputDocument> add(List<Metacard> metacards, boolean forceAutoCommit) throws IOException, SolrServerException, MetacardCreationException { if (CollectionUtils.isEmpty(metacards)) { return Collections.emptyList(); } List<SolrInputDocument> docs = new ArrayList<>(); for (Metacard metacard : metacards) { docs.add(getSolrInputDocument(metacard)); } if (!forceAutoCommit) { client.add(docs); } else { softCommit(docs); } return docs; }
Source:
private void dispatch(ExecutionReference reference, ExecutableFlow exflow, Executor choosenExecutor) throws ExecutorManagerException { exflow.setUpdateTime(System.currentTimeMillis()); callExecutorServer(exflow, choosenExecutor, ConnectorParams.EXECUTE_ACTION); executorLoader.assignExecutor(choosenExecutor.getId(), exflow.getExecutionId()); reference.setExecutor(choosenExecutor); runningFlows.put(exflow.getExecutionId(), new Pair<ExecutionReference, ExecutableFlow>(reference, exflow)); logger.info(String.format( "Successfully dispatched exec %d with error count %d", exflow.getExecutionId(), reference.getNumErrors())); }

Target:
private void dispatch(ExecutionReference reference, ExecutableFlow exflow, Executor choosenExecutor) throws ExecutorManagerException { exflow.setUpdateTime(System.currentTimeMillis()); executorLoader.assignExecutor(choosenExecutor.getId(), exflow.getExecutionId()); try { callExecutorServer(exflow, choosenExecutor, ConnectorParams.EXECUTE_ACTION); } catch (ExecutorManagerException ex) { logger.error("Rolling back executor assignment for execution id:" + exflow.getExecutionId(), ex); executorLoader.unassignExecutor(exflow.getExecutionId()); throw new ExecutorManagerException(ex); } reference.setExecutor(choosenExecutor); runningFlows.put(exflow.getExecutionId(), new Pair<ExecutionReference, ExecutableFlow>(reference, exflow)); logger.info(String.format( "Successfully dispatched exec %d with error count %d", exflow.getExecutionId(), reference.getNumErrors())); }
Source:
public void testNoSequenceAlterations() { assertEquals(VariantType.NO_SEQUENCE_ALTERATION, VariantClassifier.getVariantClassification("NOVARIATION", "", 6)); assertNotEquals(VariantType.NO_SEQUENCE_ALTERATION, VariantClassifier.getVariantClassification("NOVAR", "", 6)); }

Target:
public void testNoSequenceAlterations() { assertEquals(VariantType.NO_SEQUENCE_ALTERATION, VariantClassifier.getVariantClassification("NOVARIATION", "", 6)); assertNotEquals(VariantType.NO_SEQUENCE_ALTERATION, VariantClassifier.getVariantClassification("NOVAR", "", 6)); assertEquals(VariantType.NO_SEQUENCE_ALTERATION, VariantClassifier.getVariantClassification("", "", 6)); assertEquals(VariantType.NO_SEQUENCE_ALTERATION, VariantClassifier.getVariantClassification("NOVARIATION", "NOVARIATION", 6)); }
Source:
private void addPreferenceChangeListener() { IPreferencesService preferencesService = Platform.getPreferencesService(); fileWalkerConcurrencyLevel = preferencesService.getInt(ResourcesPlugin.PI_RESOURCES, ResourcesPlugin.PREF_NIO2_REFRESH_FILE_WALKER_CONCURRENCY_LEVEL, PreferenceInitializer.PREF_NIO2_REFRESH_FILE_WALKER_CONCURRENCY_LEVEL_DEFAULT, null); }

Target:
private void addPreferenceChangeListener() { IPreferencesService preferencesService = Platform.getPreferencesService(); IEclipsePreferences pref = (IEclipsePreferences) preferencesService.getRootNode().node(InstanceScope.SCOPE).node(ResourcesPlugin.PI_RESOURCES); if (pref != null) { pref.addPreferenceChangeListener(this); } fileWalkerConcurrencyLevel = pref.getInt(ResourcesPlugin.PREF_NIO2_REFRESH_FILE_WALKER_CONCURRENCY_LEVEL, PreferenceInitializer.PREF_NIO2_REFRESH_FILE_WALKER_CONCURRENCY_LEVEL_DEFAULT); }
Source:
public void getNotModifiedBlobAndVerify(String blobId) throws Exception { JSONObject headers = new JSONObject(); SimpleDateFormat dateFormat = new SimpleDateFormat(RestUtils.HTTP_DATE_FORMAT, Locale.ENGLISH); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); Date date = new Date(System.currentTimeMillis()); String dateStr = dateFormat.format(date); headers.put(RestUtils.Headers.IF_MODIFIED_SINCE, dateStr); RestRequest restRequest = createRestRequest(RestMethod.GET, blobId, headers, null); MockRestResponseChannel restResponseChannel = new MockRestResponseChannel(); doOperation(restRequest, restResponseChannel); assertEquals("Unexpected response status", ResponseStatus.NotModified, restResponseChannel.getStatus()); assertTrue("No Date header", restResponseChannel.getHeader(RestUtils.Headers.DATE) != null); assertNull("No Last-Modified header expected", restResponseChannel.getHeader("Last-Modified")); assertNull(RestUtils.Headers.BLOB_SIZE + " should have been null ", restResponseChannel.getHeader(RestUtils.Headers.BLOB_SIZE)); assertNull("Content-Type should have been null", restResponseChannel.getHeader(RestUtils.Headers.CONTENT_TYPE)); assertEquals("No content expected as blob is not modified", 0, restResponseChannel.getResponseBody().length); assertEquals("Accept-Ranges not set correctly", "bytes", restResponseChannel.getHeader(RestUtils.Headers.ACCEPT_RANGES)); assertNull("Content-Range header should not be set", restResponseChannel.getHeader(RestUtils.Headers.CONTENT_RANGE)); }

Target:
public void getNotModifiedBlobAndVerify(String blobId) throws Exception { JSONObject headers = new JSONObject(); SimpleDateFormat dateFormat = new SimpleDateFormat(RestUtils.HTTP_DATE_FORMAT, Locale.ENGLISH); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); Date date = new Date(System.currentTimeMillis()); String dateStr = dateFormat.format(date); headers.put(RestUtils.Headers.IF_MODIFIED_SINCE, dateStr); RestRequest restRequest = createRestRequest(RestMethod.GET, blobId, headers, null); MockRestResponseChannel restResponseChannel = new MockRestResponseChannel(); doOperation(restRequest, restResponseChannel); assertEquals("Unexpected response status", ResponseStatus.NotModified, restResponseChannel.getStatus()); assertTrue("No Date header", restResponseChannel.getHeader(RestUtils.Headers.DATE) != null); assertNull("No Last-Modified header expected", restResponseChannel.getHeader("Last-Modified")); assertNull(RestUtils.Headers.BLOB_SIZE + " should have been null ", restResponseChannel.getHeader(RestUtils.Headers.BLOB_SIZE)); assertNull("Content-Type should have been null", restResponseChannel.getHeader(RestUtils.Headers.CONTENT_TYPE)); assertEquals("No content expected as blob is not modified", 0, restResponseChannel.getResponseBody().length); assertNull("Accept-Ranges should not be set", restResponseChannel.getHeader(RestUtils.Headers.ACCEPT_RANGES)); assertNull("Content-Range header should not be set", restResponseChannel.getHeader(RestUtils.Headers.CONTENT_RANGE)); }
Source:
public ParametersBuilder addPersistedWithoutHibernate(int yearWhenPersistedWithoutHibernate, int monthWhenPersistedWithoutHibernate, int dayWhenPersistedWithoutHibernate, int hour, int minute, int second, int nanosecond, String offset, ZoneId defaultTimeZone) { if ( isNanosecondPrecisionSupported() ) { nanosecond = 0; } return add( defaultTimeZone, hour, minute, second, nanosecond, offset, yearWhenPersistedWithoutHibernate, monthWhenPersistedWithoutHibernate, dayWhenPersistedWithoutHibernate ); }

Target:
public ParametersBuilder addPersistedWithoutHibernate(int yearWhenPersistedWithoutHibernate, int monthWhenPersistedWithoutHibernate, int dayWhenPersistedWithoutHibernate, int hour, int minute, int second, int nanosecond, String offset, ZoneId defaultTimeZone) { if ( !isNanosecondPrecisionSupported() ) { nanosecond = 0; } return add( defaultTimeZone, hour, minute, second, nanosecond, offset, yearWhenPersistedWithoutHibernate, monthWhenPersistedWithoutHibernate, dayWhenPersistedWithoutHibernate ); }
Source:
public IFilterHolder getFilterHolder(MessageContext ctx, int filterId, int param1) { if (ctx.side == Side.SERVER) { if (ctx.getServerHandler().player.openContainer instanceof ContainerFilter) { final TileEntity tileEntity = ((ContainerFilter) ctx.getServerHandler().player.openContainer).getTileEntity(); if (tileEntity == null || !tileEntity.getPos().equals(getPos())) { Log.warn("Player " + ctx.getServerHandler().player.getName() + " tried to manipulate a filter while another gui was open!"); return null; } } } World world = getWorld(ctx); TileEntity tileEntity = getTileEntity(world); if (tileEntity instanceof IFilterHolder) { return (IFilterHolder) tileEntity; } return null; }

Target:
public IFilterHolder getFilterHolder(MessageContext ctx, int filterId, int param1) { if (ctx.side == Side.SERVER) { if (ctx.getServerHandler().player.openContainer instanceof ContainerFilter) { final TileEntity tileEntity = ((ContainerFilter) ctx.getServerHandler().player.openContainer).getTileEntity(); if (tileEntity == null || !tileEntity.getPos().equals(getPos())) { Log.warn("Player " + ctx.getServerHandler().player.getName() + " tried to manipulate a filter while another gui was open!"); return null; } else { if (tileEntity instanceof IFilterHolder) { return (IFilterHolder) tileEntity; } } } } return null; }
Source:
public TextDocumentInput(String id, String text) { this.id = id; this.text = text; this.language = "en"; }

Target:
public TextDocumentInput(String id, String text) { this.id = id; this.text = text; }
Source:
private void processUpdateMessages(List<EventsBranch> updateEvents) { for (EventsBranch event : updateEvents) { UpdateMessageWrapper updateEvent = (UpdateMessageWrapper) event; Message message = updateEvent.getMessage(); if (message != null) { message.setFormattedContent(updateEvent.getFormattedContent()); Dao<Message, Integer> messageDao = app.getDao(Message.class); try { messageDao.update(message); } catch (SQLException e) { ZLog.logException(e); } } } mActivity.runOnUiThread(new Runnable() { @Override public void run() { mActivity.getCurrentMessageList().getAdapter().notifyDataSetChanged(); } }); }

Target:
private void processUpdateMessages(List<EventsBranch> updateEvents) { final List<Integer> messageIds = new ArrayList<>(); for (EventsBranch event : updateEvents) { UpdateMessageWrapper updateEvent = (UpdateMessageWrapper) event; Message message = updateEvent.getMessage(); if (message != null) { message.setFormattedContent(updateEvent.getFormattedContent()); message.setHasBeenEdited(true); Dao<Message, Integer> messageDao = app.getDao(Message.class); try { messageDao.update(message); messageIds.add(message.getId()); } catch (SQLException e) { ZLog.logException(e); } } } mActivity.runOnUiThread(new Runnable() { @Override public void run() { RecyclerMessageAdapter adapter = mActivity.getCurrentMessageList().getAdapter(); for (int id : messageIds) { adapter.notifyItemChanged(adapter.getItemIndex(id)); } } }); }
Source:
private static ModuleDescription getResourceForModule(String moduleName, String categoryPath) { String pathToModule = String.join("/", moduleName.split("\\.")); String fullPathToModule = categoryPath + pathToModule + ".pyi"; InputStream resource = TypeShed.class.getResourceAsStream(fullPathToModule); if (resource == null) { fullPathToModule = categoryPath + moduleName + "/__init__.pyi"; resource = TypeShed.class.getResourceAsStream(fullPathToModule); if (resource == null) { return null; } } String fileName = Paths.get(fullPathToModule).getFileName().toString(); fileName = fileName.substring(0, fileName.length() - 4); return new ModuleDescription(resource, fileName, moduleName); }

Target:
private static ModuleDescription getResourceForModule(String moduleName, String categoryPath) { String[] moduleNameHierarchy = moduleName.split("\\."); String pathToModule = String.join("/", moduleNameHierarchy); String moduleFileName = moduleNameHierarchy[moduleNameHierarchy.length - 1]; String packageName = String.join(".", Arrays.copyOfRange(moduleNameHierarchy, 0, moduleNameHierarchy.length - 1)); InputStream resource = TypeShed.class.getResourceAsStream(categoryPath + pathToModule + ".pyi"); if (resource == null) { resource = TypeShed.class.getResourceAsStream(categoryPath + moduleName + "/__init__.pyi"); if (resource == null) { return null; } moduleFileName = "__init__"; packageName = moduleName; } return new ModuleDescription(resource, moduleFileName, packageName); }
Source:
public CloseableIterator<SAMRecord> queryAlignmentStart(String sequence, int start) { throw new RuntimeException("queryAlignmentStart is not implemented."); }

Target:
public CloseableIterator<SAMRecord> queryAlignmentStart(String sequence, int start) { int sequenceIndex = virtualHeader.getSequenceIndex(sequence); if (sequenceIndex == -1) { throw new IllegalArgumentException("Unknown sequence '" + sequence + "' was passed to SRAFileReader"); } return getIterator(getSpanContained(sequenceIndex, start, -1)); }
Source:
protected TupleBatch fetchNextReady() throws Exception { TupleBatch nexttb = ans.popAnyUsingTimeout(); if (nexttb != null) { return nexttb; } if (!loadInitially()) { return null; } while (nexttb == null && !deferredEOS) { final int compared = leftBatches.getLast().tupleCompare(leftCompareIndx, leftRowIndex, rightBatches.getLast(), rightCompareIndx, rightRowIndex, ascending); if (compared == 0) { leftAndRightEqual(); } else if (compared > 0) { rightIsLess(); } else { leftIsLess(); } nexttb = ans.popFilled(); if (nexttb != null) { return nexttb; } } if (deferredEOS) { nexttb = ans.popAny(); if (nexttb == null) { setEOS(); } else { return nexttb; } } return nexttb; }

Target:
protected TupleBatch fetchNextReady() throws Exception { TupleBatch nexttb = ans.popAnyUsingTimeout(); if (nexttb != null) { return nexttb; } loadInitially(); if (leftBatches.size() == 0 || rightBatches.size() == 0) { return null; } needData = false; while (nexttb == null && !deferredEOS && !needData) { final int compared = leftBatches.getLast().tupleCompare(leftCompareIndx, leftRowIndex, rightBatches.getLast(), rightCompareIndx, rightRowIndex, ascending); if (compared == 0) { Preconditions.checkState(leftBatches.getLast().tupleCompare(leftCompareIndx, leftRowIndex, rightBatches.getLast(), rightCompareIndx, rightRowIndex, ascending) == 0); Preconditions.checkState(leftBatches.getFirst().tupleCompare(leftCompareIndx, leftBeginIndex, rightBatches.getFirst(), rightCompareIndx, rightBeginIndex, ascending) == 0); leftAndRightEqual(); } else if (compared > 0) { rightIsLess(); } else { leftIsLess(); } nexttb = ans.popFilled(); if (nexttb != null) { return nexttb; } } if (deferredEOS) { nexttb = ans.popAny(); if (nexttb == null) { setEOS(); } } return nexttb; }
Source:
public static void main(String[] args) { OAuthService service = new ServiceBuilder() .provider(LinkedInApi.class) .apiKey("mkz553lz3k26") .apiSecret("BtL5Oz3S6Tpn0as8") .build(); Scanner in = new Scanner(System.in); System.out.println("=== LinkedIn's OAuth Workflow ==="); System.out.println(); System.out.println("Fetching the Request Token..."); Token requestToken = service.getRequestToken(); System.out.println("Got the Request Token!"); System.out.println(); System.out.println("Now go and authorize Scribe here:"); System.out.println(service.getAuthorizationUrl(requestToken)); System.out.println("And paste the verifier here"); System.out.print(">>"); Verifier verifier = new Verifier(in.nextLine()); System.out.println(); System.out.println("Trading the Request Token for an Access Token..."); Token accessToken = service.getAccessToken(requestToken, verifier); System.out.println("Got the Access Token!"); System.out.println("(if your curious it looks like this: " + accessToken + " )"); System.out.println(); System.out.println("Now we're going to access a protected resource..."); OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL); service.signRequest(accessToken, request); Response response = request.send(); System.out.println("Got it! Lets see what we found..."); System.out.println(); System.out.println(response.getBody()); System.out.println(); System.out.println("Thats it man! Go and build something awesome with Scribe! :)"); }

Target:
public static void main(String[] args) { OAuthService service = new ServiceBuilder() .provider(LinkedInApi.class) .apiKey("CiEgwWDkA5BFpNrc0RfGyVuSlOh4tig5kOTZ9q97qcXNrFl7zqk-Ts7DqRGaKDCV") .apiSecret("dhho4dfoCmiQXrkw4yslork5XWLFnPSuMR-8gscPVjY4jqFFHPYWJKgpFl4uLTM6") .build(); Scanner in = new Scanner(System.in); System.out.println("=== LinkedIn's OAuth Workflow ==="); System.out.println(); System.out.println("Fetching the Request Token..."); Token requestToken = service.getRequestToken(); System.out.println("Got the Request Token!"); System.out.println(); System.out.println("Now go and authorize Scribe here:"); System.out.println(service.getAuthorizationUrl(requestToken)); System.out.println("And paste the verifier here"); System.out.print(">>"); Verifier verifier = new Verifier(in.nextLine()); System.out.println(); System.out.println("Trading the Request Token for an Access Token..."); Token accessToken = service.getAccessToken(requestToken, verifier); System.out.println("Got the Access Token!"); System.out.println("(if your curious it looks like this: " + accessToken + " )"); System.out.println(); System.out.println("Now we're going to access a protected resource..."); OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL); service.signRequest(accessToken, request); Response response = request.send(); System.out.println("Got it! Lets see what we found..."); System.out.println(); System.out.println(response.getBody()); System.out.println(); System.out.println("Thats it man! Go and build something awesome with Scribe! :)"); }
Source:
private Runnable getNodesHouseKeepingHandler() { return () -> { List<String> unavailableNodesUrls = this.rmCoreStub.getToBeRemovedUnavailableNodesUrls(); if (!unavailableNodesUrls.isEmpty()) { logger.info("Remove " + unavailableNodesUrls.size() + " unavailable nodes"); if (logger.isDebugEnabled() && unavailableNodesUrls.size() < 100) { logger.debug("Nodes URL: " + Arrays.toString(unavailableNodesUrls.toArray())); } unavailableNodesUrls.forEach(nodeUrl -> this.rmCoreStub.removeNode(nodeUrl, true)); } }; }

Target:
private Runnable getNodesHouseKeepingHandler() { return () -> { List<String> unavailableNodesUrls = this.rmCoreStub.getToBeRemovedUnavailableNodesUrls(); if (!unavailableNodesUrls.isEmpty()) { logger.info("Remove " + unavailableNodesUrls.size() + " unavailable nodes: " + Arrays.toString(unavailableNodesUrls.toArray())); unavailableNodesUrls.forEach(nodeUrl -> this.rmCoreStub.removeNode(nodeUrl, true)); } }; }
Source:
private Thread initAndStartHeartbeat(final StormAMRMClient client, final BlockingQueue<Container> launcherQueue, final int heartBeatIntervalMs) { Thread thread = new Thread() { @Override public void run() { try { while (client.getServiceState() == Service.STATE.STARTED && !Thread.currentThread().isInterrupted()) { Thread.sleep(heartBeatIntervalMs); AllocateResponse allocResponse = client.allocate(0.5f); if (allocResponse.getAMResponse().getReboot()) { LOG.info("Got Reboot from the RM"); _handler.stop(); System.exit(0); } List<Container> allocatedContainers = allocResponse.getAMResponse().getAllocatedContainers(); if (allocatedContainers.size() > 0) { LOG.info("HB: Received allocated containers (" + allocatedContainers.size() + ")"); client.addAllocatedContainers(allocatedContainers); if (client.supervisorsAreToRun()) { LOG.info("HB: Supervisors are to run, so queueing (" + allocatedContainers.size() + ") containers..."); launcherQueue.addAll(allocatedContainers); } else { LOG.info("HB: Supervisors are to stop, so releasing all containers..."); client.stopAllSupervisors(); } } List<ContainerStatus> completedContainers = allocResponse.getAMResponse().getCompletedContainersStatuses(); if (completedContainers.size() > 0 && client.supervisorsAreToRun()) { LOG.info("HB: Containers completed (" + completedContainers.size() + "), so releasing them."); client.stopAllSupervisors(); } } } catch (Throwable t) { LOG.error("Unhandled error in AM: ", t); _handler.stop(); System.exit(1); } } }; thread.start(); return thread; }

Target:
private Thread initAndStartHeartbeat(final StormAMRMClient client, final BlockingQueue<Container> launcherQueue, final int heartBeatIntervalMs) { Thread thread = new Thread() { @Override public void run() { try { while (client.getServiceState() == Service.STATE.STARTED && !Thread.currentThread().isInterrupted()) { Thread.sleep(heartBeatIntervalMs); AllocateResponse allocResponse = client.allocate(0.5f); if (allocResponse.getAMResponse().getReboot()) { LOG.info("Got Reboot from the RM"); _handler.stop(); System.exit(0); } List<Container> allocatedContainers = allocResponse.getAMResponse().getAllocatedContainers(); if (allocatedContainers.size() > 0) { LOG.info("HB: Received allocated containers (" + allocatedContainers.size() + ")"); client.addAllocatedContainers(allocatedContainers); if (client.supervisorsAreToRun()) { LOG.info("HB: Supervisors are to run, so queueing (" + allocatedContainers.size() + ") containers..."); launcherQueue.addAll(allocatedContainers); } else { LOG.info("HB: Supervisors are to stop, so releasing all containers..."); client.stopAllSupervisors(); } } List<ContainerStatus> completedContainers = allocResponse.getAMResponse().getCompletedContainersStatuses(); if (completedContainers.size() > 0 && client.supervisorsAreToRun()) { LOG.info("HB: Containers completed (" + completedContainers.size() + "), so releasing them."); client.startAllSupervisors(); } } } catch (Throwable t) { LOG.error("Unhandled error in AM: ", t); _handler.stop(); System.exit(1); } } }; thread.start(); return thread; }
Source:
public Connection(CustomUIPane pane) { this.pane = pane; this.isError = new SimpleBooleanProperty(false); this.isErrorProperty().addListener((ObservableValue<? extends Boolean> value, Boolean oldValue, Boolean newValue) -> setError(newValue)); }

Target:
public Connection(CustomUIPane pane) { this.pane = pane; this.isError = new SimpleBooleanProperty(false); this.isErrorProperty().addListener(this::checkError); }
Source:
private static void loadXmlFile() { XmlUtils.addXmlFile(TmfXmlTestFiles.CONDITION_FILE.getFile()); XmlUtils.addXmlFile(TmfXmlTestFiles.VALID_TIMEGRAPH_VIEW_ELEMENT_FILE.getFile()); File xmlFile = XmlUtils.getXmlFilesPath().addTrailingSeparator().append(TmfXmlTestFiles.VALID_TIMEGRAPH_VIEW_ELEMENT_FILE.getFile().getName()).toFile(); XmlUtils.preloadXmlAnalysesOutput(xmlFile); XmlAnalysisModuleSource.notifyModuleChange(); }

Target:
private static void loadXmlFile() { XmlUtils.addXmlFile(TmfXmlTestFiles.CONDITION_FILE.getFile()); XmlUtils.addXmlFile(TmfXmlTestFiles.VALID_TIMEGRAPH_VIEW_ELEMENT_FILE.getFile()); XmlAnalysisModuleSource.notifyModuleChange(); }
Source:
private void publishMood(MoodElement moodElement) throws SmackException.NotLoggedInException, InterruptedException, PubSubException.NotALeafNodeException, XMPPException.XMPPErrorException, SmackException.NotConnectedException, SmackException.NoResponseException { if (!connection().isAuthenticated()) { throw new SmackException.NotLoggedInException(); } PubSubManager pubSubManager = PubSubManager.getInstance(connection(), connection().getUser().asBareJid()); LeafNode node = pubSubManager.getOrCreateLeafNode(MOOD_NODE); node.publish(new PayloadItem<>(moodElement)); }

Target:
private void publishMood(MoodElement moodElement) throws SmackException.NotLoggedInException, InterruptedException, PubSubException.NotALeafNodeException, XMPPException.XMPPErrorException, SmackException.NotConnectedException, SmackException.NoResponseException { if (pubSubManager == null) { pubSubManager = PubSubManager.getInstance(getAuthenticatedConnectionOrThrow(), connection().getUser().asBareJid()); } LeafNode node = pubSubManager.getOrCreateLeafNode(MOOD_NODE); node.publish(new PayloadItem<>(moodElement)); }
Source:
public static CoordinateReferenceSystem get( String href ) { if ( CoordinateReferenceSystem.WGS84.href.equals( href ) ) { return CoordinateReferenceSystem.WGS84; } else if ( CoordinateReferenceSystem.Cartesian.href.equals( href ) ) { return CoordinateReferenceSystem.Cartesian; } else { throw new UnsupportedOperationException( "Unknown CRS: " + href ); } }

Target:
public static CoordinateReferenceSystem get( String href ) { if ( CoordinateReferenceSystem.WGS84.href.equals( href ) ) { return CoordinateReferenceSystem.WGS84; } else if ( CoordinateReferenceSystem.Cartesian.href.equals( href ) ) { return CoordinateReferenceSystem.Cartesian; } else { throw new IllegalArgumentException( "Unknown CRS: " + href ); } }
Source:
public List<String> bulkIndex(final List<Map.Entry<IndexSet, Message>> messageList, boolean isSystemTraffic) { if (messageList.isEmpty()) { return Collections.emptyList(); } final List<IndexingRequest> indexingRequestList = messageList.stream() .map(entry -> IndexingRequest.create(entry.getKey(), entry.getValue())) .collect(Collectors.toList()); final List<IndexFailure> indexFailures = messagesAdapter.bulkIndex(indexingRequestList); final Set<String> failedIds = indexFailures.stream().map(IndexFailure::letterId).collect(Collectors.toSet()); final List<IndexingRequest> successfullRequests = indexingRequestList.stream() .filter(indexingRequest -> !failedIds.contains(indexingRequest.message().getId())) .collect(Collectors.toList()); recordTimestamp(successfullRequests); accountTotalMessageSizes(indexingRequestList, isSystemTraffic); return propagateFailure(indexFailures); }

Target:
public List<String> bulkIndex(final List<Map.Entry<IndexSet, Message>> messageList, boolean isSystemTraffic) { if (messageList.isEmpty()) { return Collections.emptyList(); } final List<IndexingRequest> indexingRequestList = messageList.stream() .map(entry -> IndexingRequest.create(entry.getKey(), entry.getValue())) .collect(Collectors.toList()); final List<IndexFailure> indexFailures = messagesAdapter.bulkIndex(indexingRequestList); final Set<String> failedIds = indexFailures.stream().map(IndexFailure::letterId).collect(Collectors.toSet()); final List<IndexingRequest> successfulRequests = indexingRequestList.stream() .filter(indexingRequest -> !failedIds.contains(indexingRequest.message().getId())) .collect(Collectors.toList()); recordTimestamp(successfulRequests); accountTotalMessageSizes(indexingRequestList, isSystemTraffic); return propagateFailure(indexFailures); }
Source:
protected boolean executeAnalysis(@NonNull IProgressMonitor monitor) throws TmfAnalysisException { ITmfTrace trace = getTrace(); if (trace == null) { initialize(false); return false; } IStatus status1 = fSegmentStoreModule.schedule(); IStatus status2 = fStateSystemModule.schedule(); if (!(status1.isOK() && status2.isOK())) { cancelSubAnalyses(); initialize(false); return false; } if (!fStateSystemModule.waitForInitialization()) { initialize(false); return false; } ITmfStateSystem stateSystem = fStateSystemModule.getStateSystem(); if (stateSystem == null) { initialize(false); return false; } initialize(true); if (!(fStateSystemModule.waitForCompletion(monitor) && fSegmentStoreModule.waitForCompletion(monitor))) { return false; } return true; }

Target:
protected boolean executeAnalysis(@NonNull IProgressMonitor monitor) throws TmfAnalysisException { ITmfTrace trace = getTrace(); if (trace == null) { initialize(false); return false; } IStatus segmentStoreStatus = fSegmentStoreModule.schedule(); IStatus stateSystemStatus = fStateSystemModule.schedule(); if (!(segmentStoreStatus.isOK() && stateSystemStatus.isOK())) { cancelSubAnalyses(); initialize(false); return false; } if (!fStateSystemModule.waitForInitialization()) { initialize(false); return false; } ITmfStateSystem stateSystem = fStateSystemModule.getStateSystem(); if (stateSystem == null) { initialize(false); return false; } initialize(true); return fStateSystemModule.waitForCompletion(monitor) && fSegmentStoreModule.waitForCompletion(monitor); }
Source:
private static SessionFactory getSessionFactory() { if (sessionFactory == null) { try { registry = new StandardServiceRegistryBuilder().configure().build(); MetadataSources sources = new MetadataSources(registry); Metadata metadata = sources.getMetadataBuilder().build(); sessionFactory = metadata.getSessionFactoryBuilder().build(); } catch (RuntimeException e) { logger.error( "Probably you have forgotten to adjust your Hibernate configuration! Error: " + e.getMessage(), e); shutdown(); } } return sessionFactory; }

Target:
private static SessionFactory getSessionFactory() { if (Objects.isNull(sessionFactory)) { try { registry = new StandardServiceRegistryBuilder().configure().build(); MetadataSources sources = new MetadataSources(registry); Metadata metadata = sources.getMetadataBuilder().build(); sessionFactory = metadata.getSessionFactoryBuilder().build(); } catch (RuntimeException e) { shutdown(); throw new RuntimeException(e.getMessage(), e); } } return sessionFactory; }
Source:
private static void updateDescription(@NonNull final I_I_BankStatement importRecord) { final String lineDescription = Joiner.on(" / ") .skipNulls() .join(importRecord.getLineDescription(), importRecord.getLineDescriptionExtra_1(), importRecord.getLineDescriptionExtra_2(), importRecord.getLineDescriptionExtra_3(), importRecord.getLineDescriptionExtra_4()); importRecord.setLineDescription(lineDescription); }

Target:
private static void updateDescription(@NonNull final I_I_BankStatement importRecord) { final String lineDescription = Joiner.on(" / ") .skipNulls() .join(StringUtils.trimBlankToNull(importRecord.getLineDescription()), StringUtils.trimBlankToNull(importRecord.getLineDescriptionExtra_1()), StringUtils.trimBlankToNull(importRecord.getLineDescriptionExtra_2()), StringUtils.trimBlankToNull(importRecord.getLineDescriptionExtra_3()), StringUtils.trimBlankToNull(importRecord.getLineDescriptionExtra_4())); importRecord.setLineDescription(lineDescription); }
Source:
public static void setDefaultLookupAttributes(EntityType entityType, int lookupAttributeIndex) { Attribute ownIdAttr = entityType.getOwnIdAttribute(); if (ownIdAttr != null && ownIdAttr.isVisible()) { ownIdAttr.setLookupAttributeIndex(lookupAttributeIndex); lookupAttributeIndex++; } Attribute ownLabelAttr = entityType.getOwnLabelAttribute(); if (ownLabelAttr != null && ownIdAttr != null && !ownIdAttr.getName().equals(ownLabelAttr.getName())) { ownLabelAttr.setLookupAttributeIndex(lookupAttributeIndex); lookupAttributeIndex++; } }

Target:
public static void setDefaultLookupAttributes(EntityType entityType, int lookupAttributeIndex) { Attribute ownIdAttr = entityType.getOwnIdAttribute(); if (ownIdAttr != null && ownIdAttr.isVisible()) { ownIdAttr.setLookupAttributeIndex(lookupAttributeIndex); lookupAttributeIndex++; } Attribute ownLabelAttr = entityType.getOwnLabelAttribute(); if (ownLabelAttr != null && ownIdAttr != null && !ownIdAttr.getName().equals(ownLabelAttr.getName())) { ownLabelAttr.setLookupAttributeIndex(lookupAttributeIndex); } }
Source:
public List<String> getPanelNames() { List<String> openPanelNames = new ArrayList<>(); for (int i = 0; i < openPanels.size(); i++) { openPanelNames.add(openPanels.get(i).getPanelName()); } return openPanelNames; }

Target:
public List<String> getPanelNames() { return lastSessionPanels.stream().map(PanelInfo::getPanelName).collect(Collectors.toList()); }
Source:
private static LinearRing toJtsLinearRing(List<GeoPoint> geoPoints, boolean counterClockwise, boolean lenient) { if (geoPoints.size() < 4) { throw new VertexiumException("A polygon must specify at least 4 points for each boundary and hole."); } Coordinate[] shellCoordinates = geoPoints.stream() .map(geoPoint -> new Coordinate(geoPoint.getLongitude(), geoPoint.getLatitude())) .toArray(Coordinate[]::new); if (!shellCoordinates[0].equals(shellCoordinates[shellCoordinates.length - 1])) { if (lenient) { LOGGER.info("Closing an unclosed GeoShape by appending the beginning coordinate"); shellCoordinates = org.apache.commons.lang3.ArrayUtils.add(shellCoordinates, shellCoordinates[0].copy()); } else { throw new VertexiumException("All polygon boundaries and holes must begin and end at the same point."); } } if (Orientation.isCCW(shellCoordinates) != counterClockwise) { if (lenient) { LOGGER.info("Reversing the coordinates of a ring that has a backwards orientation"); ArrayUtils.reverse(shellCoordinates); } else { throw new VertexiumException("The outer shell of a polygon must be specified in counter-clockwise " + "orientation and all holes must be specified in the clockwise direction."); } } return GEOMETRY_FACTORY.createLinearRing(shellCoordinates); }

Target:
private static LinearRing toJtsLinearRing(List<GeoPoint> geoPoints, boolean counterClockwise, boolean lenient) { if (geoPoints.size() < 4) { throw new VertexiumInvalidShapeException("A polygon must specify at least 4 points for each boundary and hole."); } Coordinate[] shellCoordinates = geoPoints.stream() .map(geoPoint -> new Coordinate(geoPoint.getLongitude(), geoPoint.getLatitude())) .toArray(Coordinate[]::new); if (!shellCoordinates[0].equals(shellCoordinates[shellCoordinates.length - 1])) { if (lenient) { LOGGER.info("Closing an unclosed GeoShape by appending the beginning coordinate"); shellCoordinates = org.apache.commons.lang3.ArrayUtils.add(shellCoordinates, shellCoordinates[0].copy()); } else { throw new VertexiumInvalidShapeException("All polygon boundaries and holes must begin and end at the same point."); } } if (Orientation.isCCW(shellCoordinates) != counterClockwise) { if (lenient) { LOGGER.info("Reversing the coordinates of a ring that has a backwards orientation"); ArrayUtils.reverse(shellCoordinates); } else { throw new VertexiumInvalidShapeException("The outer shell of a polygon must be specified in counter-clockwise " + "orientation and all holes must be specified in the clockwise direction."); } } return GEOMETRY_FACTORY.createLinearRing(shellCoordinates); }