auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Result<Void> createStorage(final JSONObject json) { final String type; final String id; final JSONObject configuration; try { id = json.getString("id"); type = json.getString("storage_type"); switch(type) { case "kafka": configuration = json.getJSONObject("kafka_configuration"); break; default: return Result.problem(Problem.valueOf(UNPROCESSABLE_ENTITY, "Type '" + type + "' is not a valid storage type")); } } catch (JSONException e) { return Result.problem(Problem.valueOf(UNPROCESSABLE_ENTITY, e.getMessage())); } try { if (storageDbRepository.getStorage(id).isPresent()) { return Result.conflict("Storage with ID " + id + " already exists."); } } catch (InternalNakadiException e) { return Result.problem(Problem.valueOf(INTERNAL_SERVER_ERROR, e.getMessage())); } final Storage storage = new Storage(); storage.setId(id); storage.setType(Storage.Type.valueOf(type.toUpperCase())); try { storage.parseConfiguration(objectMapper, configuration.toString()); } catch (final IOException e) { return Result.problem(Problem.valueOf(UNPROCESSABLE_ENTITY, e.getMessage())); } try { storageDbRepository.createStorage(storage); } catch (InternalNakadiException e) { return Result.problem(Problem.valueOf(INTERNAL_SERVER_ERROR, e.getMessage())); } return Result.ok(); }

Target:
public Result<Void> createStorage(final JSONObject json) { final String type; final String id; final JSONObject configuration; try { id = json.getString("id"); type = json.getString("storage_type"); switch(type) { case "kafka": configuration = json.getJSONObject("kafka_configuration"); break; default: return Result.problem(Problem.valueOf(UNPROCESSABLE_ENTITY, "Type '" + type + "' is not a valid storage type")); } } catch (JSONException e) { return Result.problem(Problem.valueOf(UNPROCESSABLE_ENTITY, e.getMessage())); } final Storage storage = new Storage(); storage.setId(id); storage.setType(Storage.Type.valueOf(type.toUpperCase())); try { storage.parseConfiguration(objectMapper, configuration.toString()); } catch (final IOException e) { return Result.problem(Problem.valueOf(UNPROCESSABLE_ENTITY, e.getMessage())); } try { storageDbRepository.createStorage(storage); } catch (DuplicatedStorageIdException | InternalNakadiException e) { return Result.problem(e.asProblem()); } return Result.ok(); }
Source:
public void shouldReturnDefinedMetricsAndTotalMutationCount() { collectedUpdateMetrics.merge(INSERT_NEW_DATA, createSampleUpdateMetrics()); collectedUpdateMetrics.merge(ADD_TIMESTAMPS, createSampleUpdateMetrics()); collectedUpdateMetrics.setMutationCount(10); assertThat(collectedUpdateMetrics.definedMetrics()).isEqualTo(Sets.newHashSet(INSERT_NEW_DATA, ADD_TIMESTAMPS)); assertThat(collectedUpdateMetrics.getMutationCount()).isEqualTo(10); }

Target:
public void shouldReturnDefinedMetricsAndTotalMutationCount() { collectedUpdateMetrics.merge(INSERT_NEW_DATA, createSampleUpdateMetrics()); collectedUpdateMetrics.merge(ADD_TIMESTAMPS, createSampleUpdateMetrics()); collectedUpdateMetrics.setMutationCount(10); assertThat(collectedUpdateMetrics.definedMetrics()).containsExactly(INSERT_NEW_DATA, ADD_TIMESTAMPS); assertThat(collectedUpdateMetrics.getMutationCount()).isEqualTo(10); }
Source:
PooledFileRandomAccessBuffer(File file, boolean readOnly, long forceLength, Random seedRandom, long persistentTempID, boolean deleteOnFree, FDTracker fds) throws IOException { this.file = file; this.readOnly = readOnly; this.persistentTempID = persistentTempID; this.deleteOnFree = deleteOnFree; this.fds = fds; lockLevel = 0; RAFLock lock = lockOpen(); try { long currentLength = raf.length(); if(forceLength >= 0 && forceLength != currentLength) { if(readOnly) throw new IOException("Read only but wrong length"); if (Fallocate.isSupported()) { Fallocate.forDescriptor(raf.getFD(), forceLength).execute(); } else { Logger.normal(this, "fallocate() not supported; using legacy method"); raf.seek(0); MersenneTwister mt = null; if(seedRandom != null) mt = new MersenneTwister(seedRandom.nextLong()); byte[] buf = new byte[4096]; for(long l = 0; l < forceLength; l+=4096) { if(mt != null) mt.nextBytes(buf); int maxWrite = (int)Math.min(4096, forceLength - l); raf.write(buf, 0, maxWrite); } assert(raf.getFilePointer() == forceLength); assert(raf.length() == forceLength); } raf.setLength(forceLength); currentLength = forceLength; } this.length = currentLength; lock.unlock(); } catch (IOException e) { synchronized(this) { raf.close(); raf = null; } throw e; } }

Target:
PooledFileRandomAccessBuffer(File file, boolean readOnly, long forceLength, Random seedRandom, long persistentTempID, boolean deleteOnFree, FDTracker fds) throws IOException { this.file = file; this.readOnly = readOnly; this.persistentTempID = persistentTempID; this.deleteOnFree = deleteOnFree; this.fds = fds; lockLevel = 0; RAFLock lock = lockOpen(); try { long currentLength = raf.length(); if(forceLength >= 0 && forceLength != currentLength) { if(readOnly) throw new IOException("Read only but wrong length"); if (Fallocate.isSupported()) { Fallocate.forDescriptor(raf.getFD(), forceLength).execute(); } else { Logger.normal(this, "fallocate() not supported; using legacy method"); Fallocate.legacyFill(raf.getChannel(), forceLength, 0, false); } raf.setLength(forceLength); currentLength = forceLength; } this.length = currentLength; lock.unlock(); } catch (IOException e) { synchronized(this) { raf.close(); raf = null; } throw e; } }
Source:
public synchronized PublisherSession newSession() { Window it = pushStream.newWindow(sessionRollbackCount); PublisherSession session = new PublisherSession(it, generator .generate()); sessions.put(session.getKey(), session); return session; }

Target:
public synchronized PublisherSession newSession() { Window window = pushStream.newWindow(sessionRollbackCount); PublisherSession session = new PublisherSession( window, generator .generate()); sessions.put(session.getKey(), session); return session; }
Source:
public void onTakeDeleted() { ProjectProgress pp = new ProjectProgress(mProject, db, chunkPlugin.getChapters()); pp.updateProjectProgress(); }

Target:
public void onTakeDeleted() { if(projectProgress != null) { projectProgress.updateProjectProgress(); } }
Source:
public RequestTemplate resolve(Map<String, ?> unencoded, Map<String, Boolean> alreadyEncoded) { replaceQueryValues(unencoded, alreadyEncoded); Map<String, String> encoded = new LinkedHashMap<String, String>(); for (Entry<String, ?> entry : unencoded.entrySet()) { final String key = entry.getKey(); final Object objectValue = entry.getValue(); String encodedValue = encodeValueIfNotEncoded(key, objectValue, alreadyEncoded); encoded.put(key, encodedValue); } String resolvedUrl = expand(url.toString(), encoded).replace("+", "%20"); if (decodeSlash) { resolvedUrl = resolvedUrl.replace("%2F", "/"); } url = new StringBuilder(resolvedUrl); Map<String, Collection<String>> resolvedHeaders = new LinkedHashMap<String, Collection<String>>(); for (String field : headers.keySet()) { Collection<String> resolvedValues = new ArrayList<String>(); for (String value : valuesOrEmpty(headers, field)) { String resolved = expand(value, unencoded); resolvedValues.add(resolved); } resolvedHeaders.put(field, resolvedValues); } headers.clear(); headers.putAll(resolvedHeaders); if (bodyTemplate != null) { body(urlDecode(expand(bodyTemplate, encoded))); } return this; }

Target:
RequestTemplate resolve(Map<String, ?> unencoded, Map<String, Boolean> alreadyEncoded) { replaceQueryValues(unencoded, alreadyEncoded); Map<String, String> encoded = new LinkedHashMap<String, String>(); for (Entry<String, ?> entry : unencoded.entrySet()) { final String key = entry.getKey(); final Object objectValue = entry.getValue(); String encodedValue = encodeValueIfNotEncoded(key, objectValue, alreadyEncoded); encoded.put(key, encodedValue); } String resolvedUrl = expand(url.toString(), encoded).replace("+", "%20"); if (decodeSlash) { resolvedUrl = resolvedUrl.replace("%2F", "/"); } url = new StringBuilder(resolvedUrl); Map<String, Collection<String>> resolvedHeaders = new LinkedHashMap<String, Collection<String>>(); for (String field : headers.keySet()) { Collection<String> resolvedValues = new ArrayList<String>(); for (String value : valuesOrEmpty(headers, field)) { String resolved = expand(value, unencoded); resolvedValues.add(resolved); } resolvedHeaders.put(field, resolvedValues); } headers.clear(); headers.putAll(resolvedHeaders); if (bodyTemplate != null) { body(urlDecode(expand(bodyTemplate, encoded))); } return this; }
Source:
public PinotResultSet(org.apache.pinot.client.ResultSet resultSet) { _resultSet = resultSet; _totalRows = _resultSet.getRowCount(); _currentRow = -1; for (int i = 0; i < _resultSet.getColumnCount(); i++) { _columns.put(_resultSet.getColumnName(i), i); } }

Target:
public PinotResultSet(org.apache.pinot.client.ResultSet resultSet) { _resultSet = resultSet; _totalRows = _resultSet.getRowCount(); _totalColumns = _resultSet.getColumnCount(); _currentRow = -1; _closed = false; for (int i = 0; i < _totalColumns; i++) { _columns.put(_resultSet.getColumnName(i), i + 1); } }
Source:
public PlanResultImpl() { this.summary = null; }

Target:
public PlanResultImpl() { this.summary = "The plan result is not specified"; this.numExecutedOps = -1; }
Source:
public void accumulateRowSizes(int[] rowSizes) { int averageElementSize = Long.BYTES + Byte.BYTES; for (int i = 0; i < positionCount; i++) { rowSizes[i] += averageElementSize; } }

Target:
public void accumulateRowSizes(int[] rowSizes) { throw new UnsupportedOperationException("accumulateRowSizes is not supported for fixed width types"); }
Source:
protected void executeVdsBrokerCommand() { GlusterVolumeSnapshotConfig cfgParam = getParameters() .getConfgParam(); String paramValue = cfgParam.getParamValue().endsWith("%") ? cfgParam.getParamValue().substring(0, cfgParam.getParamValue().length() - 1) : cfgParam.getParamValue(); if (cfgParam.getVolumeId() != null) { GlusterVolumeEntity volume = DbFacade.getInstance().getGlusterVolumeDao().getById(cfgParam.getVolumeId()); status = getBroker().glusterVolumeSnapshotConfigSet(volume.getName(), cfgParam.getParamName(), paramValue); } else { status = getBroker().glusterSnapshotConfigSet(cfgParam.getParamName(), paramValue); } proceedProxyReturnValue(); }

Target:
protected void executeVdsBrokerCommand() { GlusterVolumeSnapshotConfig cfgParam = getParameters() .getConfgParam(); String paramValue = cfgParam.getParamValue().endsWith("%") ? StringUtils.removeEnd(cfgParam.getParamValue(), "%") : cfgParam.getParamValue(); if (cfgParam.getVolumeId() != null) { GlusterVolumeEntity volume = DbFacade.getInstance().getGlusterVolumeDao().getById(cfgParam.getVolumeId()); status = getBroker().glusterVolumeSnapshotConfigSet(volume.getName(), cfgParam.getParamName(), paramValue); } else { status = getBroker().glusterSnapshotConfigSet(cfgParam.getParamName(), paramValue); } proceedProxyReturnValue(); }
Source:
public void resetError(int rowIndex, int columnIndex) { Scenario scenarioByIndex = simulation.getScenarioByIndex(rowIndex); FactMapping factMapping = simulation.getSimulationDescriptor().getFactMappingByIndex(columnIndex); Optional<FactMappingValue> factMappingValue = scenarioByIndex.getFactMappingValue(factMapping); if (factMappingValue.isPresent()) { factMappingValue.get().resetStatus(); } refreshErrors(); }

Target:
public void resetError(int rowIndex, int columnIndex) { Scenario scenarioByIndex = simulation.getScenarioByIndex(rowIndex); FactMapping factMapping = simulation.getSimulationDescriptor().getFactMappingByIndex(columnIndex); Optional<FactMappingValue> factMappingValue = scenarioByIndex.getFactMappingValue(factMapping); factMappingValue.ifPresent(fmv -> fmv.resetStatus()); refreshErrors(); }
Source:
public void dropView(StatePrimaryView view) { if (subscription!=null && !subscription.isUnsubscribed()) { subscription.unsubscribe(); } super.dropView(view); ButterKnife.unbind(this); }

Target:
public void dropView(StatePrimaryView view) { super.dropView(view); ButterKnife.unbind(this); }
Source:
private void loadDir() { if (getDialogSettings() != null) { String cachedDir = getDialogSettings().get("currentDir"); if (cachedDir != null) { setDirectory(cachedDir); } } }

Target:
private void loadDir() { if (getDialogSettings() != null) { String cachedDir = getDialogSettings().get(CURRENT_DIR_SETTING_ID); if (cachedDir != null) { setDirectory(cachedDir); } } }
Source:
private void readInput() { BufferedReader br = new BufferedReader(new InputStreamReader(is)); while (true) { String s; String[] getCommands; try { s = br.readLine(); if (s == null || s.trim().length() == 0) { break; } if (s.contains("GET") && s.contains("?")) { logger.debug(this.s.getInetAddress().getHostAddress() + " " + s); String[] CommandParse = s.split("[/ ]"); String command = CommandParse[2]; getCommands = command.split("[?&>=]"); if (s.contains("m=1")) { MegaDeviceBinding.updateValues(this.s.getInetAddress().getHostAddress(), getCommands, OnOffType.OFF); } else if (s.contains("m=2")) { logger.debug("m=2"); } else { MegaDeviceBinding.updateValues(this.s.getInetAddress().getHostAddress(), getCommands, OnOffType.ON); for (int i = 0; getCommands.length > i; i++) { logger.debug(i + " value " + getCommands[i]); } } break; } else { break; } } catch (IOException e) { logger.debug("ERROR: " + e.getMessage()); } } }

Target:
private void readInput() { BufferedReader br = new BufferedReader(new InputStreamReader(is)); while (true) { String s; String[] getCommands; try { s = br.readLine(); if (s == null || s.trim().length() == 0) { break; } if (s.contains("GET") && s.contains("?")) { logger.debug("{} ", this.s.getInetAddress().getHostAddress(), s); String[] CommandParse = s.split("[/ ]"); String command = CommandParse[2]; getCommands = command.split("[?&>=]"); if (s.contains("m=1")) { MegaDeviceBinding.updateValues(this.s.getInetAddress().getHostAddress(), getCommands, OnOffType.OFF); } else if (s.contains("m=2")) { } else { MegaDeviceBinding.updateValues(this.s.getInetAddress().getHostAddress(), getCommands, OnOffType.ON); } break; } else break; } catch (IOException e) { logger.error("ERROR: MegaDevice input server error. Restart http socket"); logger.error(e.getLocalizedMessage()); MegadeviceHttpServer.setRunningState(false); } } }
Source:
public PreDestroyMonitor(Map<Class<? extends Annotation>, Scope> scopeBindings) { this.scopeBindings = new HashMap<>(scopeBindings); reqQueueExecutor.submit(new Runnable() { public void run() { while (true) { try { Reference<? extends ScopeCleanupMarker> ref = markerReferenceQueue.remove(500); if (ref != null && ref instanceof ScopeCleanupAction) { Integer markerKey = ((ScopeCleanupAction)ref).getId(); ScopeCleanupAction cleanupAction; synchronized(scopedCleanupActions) { cleanupAction = scopedCleanupActions.remove(markerKey); } if (cleanupAction != null) { cleanupAction.call(); } } } catch (InterruptedException e) { } } } }); }

Target:
public PreDestroyMonitor(Map<Class<? extends Annotation>, Scope> scopeBindings) { this.scopeBindings = new HashMap<>(scopeBindings); this.reqQueueExecutor.submit(new ScopedCleanupWorker()); }
Source:
public void submitStackTraces(String server) { try { File dir = FileUtil.getFilesDir(FileType.STACKTRACE); String[] list = getTraceFiles(dir); if (list != null && list.length > 0) { for (int i = 0; i < list.length; i++) { File f = new File(dir, list[i]); String trace = FileUtil.readFileAsString(f); Map<String, String> params = new HashMap<String, String>(); params.put(ACTION_PARAM, ACTION_VALUE); params.put(PHONE_PARAM, phoneNumber); params.put(IMEI_PARAM, imei); params.put(VER_PARAM, version); params.put(DATE_PARAM, DATE_FMT.get().format(new Date(f.lastModified()))); params.put(DEV_ID_PARAM, deviceId); params.put(TRACE_PARAM, trace); String response = HttpUtil.httpPost(server + EXCEPTION_SERVICE_PATH, params); if (response == null || response.trim().length() == 0 || "ok".equalsIgnoreCase(response)) { f.delete(); } } } } catch (Exception e) { Log.e(TAG, "Could not send exception", e); } }

Target:
public void submitStackTraces(String server) { try { File dir = FileUtil.getFilesDir(FileType.STACKTRACE); String[] list = getTraceFiles(dir); if (list != null && list.length > 0) { for (int i = 0; i < list.length; i++) { File f = new File(dir, list[i]); String trace = FileUtil.readFileAsString(f); Map<String, String> params = new HashMap<String, String>(); params.put(ACTION_PARAM, ACTION_VALUE); params.put(PHONE_PARAM, phoneNumber); params.put(IMEI_PARAM, imei); params.put(VER_PARAM, version); params.put(DATE_PARAM, DATE_FMT.get().format(new Date(f.lastModified()))); params.put(DEV_ID_PARAM, deviceId); params.put(TRACE_PARAM, trace); params.put(ANDROID_ID_PARAM, PlatformUtil.getAndroidID(this)); String response = HttpUtil.httpPost(server + EXCEPTION_SERVICE_PATH, params); if (response == null || response.trim().length() == 0 || "ok".equalsIgnoreCase(response)) { f.delete(); } } } } catch (Exception e) { Log.e(TAG, "Could not send exception", e); } }
Source:
public JupiterActivity generateJupiterActivity(Operation op, User source, SPath editor) { JupiterActivity jupiterActivity = new JupiterActivity(this.vectorTime, op, source, editor); if (!(op instanceof TimestampOperation)) { this.ackJupiterActivityList.add( new OperationWrapper(op, this.vectorTime.getLocalOperationCount())); } this.vectorTime = this.vectorTime.incrementLocalOperationCount(); return jupiterActivity; }

Target:
public JupiterActivity generateJupiterActivity(Operation op, User source, SPath editor) { JupiterActivity jupiterActivity = new JupiterActivity(this.vectorTime, op, source, editor); this.ackJupiterActivityList.add( new OperationWrapper(op, this.vectorTime.getLocalOperationCount())); this.vectorTime = this.vectorTime.incrementLocalOperationCount(); return jupiterActivity; }
Source:
public long calculateAverageDynamicConfigRefreshInterval() { long total = 0; for (GerritServer server : PluginImpl.getServers_()) { total += server.getConfig().getDynamicConfigRefreshInterval(); } long average = total / Math.max(1, PluginImpl.getServers_().size()); return Math.max(GerritDefaultValues.MINIMUM_DYNAMIC_CONFIG_REFRESH_INTERVAL, average); }

Target:
long calculateAverageDynamicConfigRefreshInterval() { long total = 0; for (GerritServer server : PluginImpl.getServers_()) { total += server.getConfig().getDynamicConfigRefreshInterval(); } long average = total / Math.max(1, PluginImpl.getServers_().size()); return Math.max(GerritDefaultValues.MINIMUM_DYNAMIC_CONFIG_REFRESH_INTERVAL, average); }
Source:
protected static void nullInstance(Object instance) { if (instance == null) { return; } Field[] fields = instance.getClass().getDeclaredFields(); for (Field field : fields) { int mods = field.getModifiers(); if (field.getType().isPrimitive() || (field.getName().contains("$"))) { continue; } try { field.setAccessible(true); if (Modifier.isStatic(mods) && Modifier.isFinal(mods)) { } else { Object value = field.get(instance); if (null != value) { Class<?> valueClass = value.getClass(); if (!loadedByThisOrChild(valueClass)) { if (log.isDebugEnabled()) { log.debug("Not setting field " + field.getName() + " to null in object of class " + instance.getClass().getName() + " because the referenced object was of type " + valueClass.getName() + " which was not loaded by this WebappClassLoader."); } } else { field.set(instance, null); if (log.isDebugEnabled()) { log.debug("Set field " + field.getName() + " to null in class " + instance.getClass().getName()); } } } } } catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Could not set field " + field.getName() + " to null in object instance of class " + instance.getClass().getName(), e); } } } }

Target:
protected static void nullInstance(Object instance) { if (instance == null) { return; } Field[] fields = instance.getClass().getDeclaredFields(); for (Field field : fields) { int mods = field.getModifiers(); if (field.getType().isPrimitive() || (field.getName().contains("$"))) { continue; } try { field.setAccessible(true); if (!Modifier.isStatic(mods) || !Modifier.isFinal(mods)) { Object value = field.get(instance); if (null != value) { Class<?> valueClass = value.getClass(); if (!loadedByThisOrChild(valueClass)) { if (log.isDebugEnabled()) { log.debug("Not setting field " + field.getName() + " to null in object of class " + instance.getClass().getName() + " because the referenced object was of type " + valueClass.getName() + " which was not loaded by this WebappClassLoader."); } } else { field.set(instance, null); if (log.isDebugEnabled()) { log.debug("Set field " + field.getName() + " to null in class " + instance.getClass().getName()); } } } } } catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Could not set field " + field.getName() + " to null in object instance of class " + instance.getClass().getName(), e); } } } }
Source:
public void dispose() { super.dispose(); getSite().getPage().removePostSelectionListener(this); RegistryFactory.getRegistry().removeListener(this); SaveablesList saveables = (SaveablesList) getSite().getService(ISaveablesLifecycleListener.class); if (saveables != null) { saveables.removeModelLifecycleListener(saveablesTracker); } currentPart = null; currentSelection = null; pinPropertySheetAction = null; }

Target:
public void dispose() { super.dispose(); getSite().getPage().removePostSelectionListener(this); RegistryFactory.getRegistry().removeListener(this); ISaveablesLifecycleListener saveables = getSite().getService(ISaveablesLifecycleListener.class); if (saveables instanceof SaveablesList) { ((SaveablesList) saveables).removeModelLifecycleListener(saveablesTracker); } currentPart = null; currentSelection = null; pinPropertySheetAction = null; }
Source:
AbstractTableManager(ConnectionFactory connectionFactory, TableManipulationConfiguration config, DbMetaData metaData, String cacheName, String identifierQuoteString, Log log) { if (cacheName == null || cacheName.trim().length() == 0) throw new PersistenceException("cacheName needed in order to create table"); this.connectionFactory = connectionFactory; this.config = config; this.metaData = metaData; this.tableName = new TableName(identifierQuoteString, config.tableNamePrefix(), cacheName); this.identifierQuoteString = identifierQuoteString; this.log = log; this.insertRowSql = getInsertRowSql(); this.updateRowSql = getUpdateRowSql(); this.upsertRowSql = getUpsertRowSql(); this.selectRowSql = getSelectRowSql(); this.selectIdRowSql = getSelectIdRowSql(); this.deleteRowSql = getDeleteRowSql(); this.loadAllRowsSql = getLoadAllRowsSql(); this.countRowsSql = getCountNonExpiredRowsSql(); this.loadAllNonExpiredRowsSql = getLoadNonExpiredAllRowsSql(); this.selectExpiredRowsSql = getSelectExpiredBucketsSql(); this.deleteExpiredRowsSql = getSelectOnlyExpiredRowsSql(); }

Target:
AbstractTableManager(ConnectionFactory connectionFactory, TableManipulationConfiguration config, DbMetaData metaData, String cacheName, String identifierQuoteString, Log log) { if (cacheName == null || cacheName.trim().length() == 0) throw new PersistenceException("cacheName needed in order to create table"); this.connectionFactory = connectionFactory; this.config = config; this.metaData = metaData; this.tableName = new TableName(identifierQuoteString, config.tableNamePrefix(), cacheName); this.identifierQuoteString = identifierQuoteString; this.log = log; this.insertRowSql = initInsertRowSql(); this.updateRowSql = initUpdateRowSql(); this.upsertRowSql = initUpsertRowSql(); this.selectRowSql = initSelectRowSql(); this.selectIdRowSql = initSelectIdRowSql(); this.deleteRowSql = initDeleteRowSql(); this.loadAllRowsSql = initLoadAllRowsSql(); this.countRowsSql = initCountNonExpiredRowsSql(); this.loadAllNonExpiredRowsSql = initLoadNonExpiredAllRowsSql(); this.deleteAllRows = initDeleteAllRowsSql(); this.selectExpiredRowsSql = initSelectExpiredBucketsSql(); this.deleteExpiredRowsSql = initSelectOnlyExpiredRowsSql(); }
Source:
OAuth2TokenIntrospectionClient getIntrospectionClient() { if (this.introspectionClient != null) { return this.introspectionClient; } if (this.introspectionUri != null || this.restOperations != null) { return new NimbusOAuth2TokenIntrospectionClient(this.introspectionUri, this.restOperations); } return this.context.getBean(OAuth2TokenIntrospectionClient.class); }

Target:
OAuth2TokenIntrospectionClient getIntrospectionClient() { if (this.introspectionClient != null) { return this.introspectionClient.get(); } return this.context.getBean(OAuth2TokenIntrospectionClient.class); }
Source:
public long estimatedInMemorySize() { return INSTANCE_SIZE + SizeOf.SIZE_OF_INT + SizeOf.SIZE_OF_INT + 2 * SizeOf.SIZE_OF_DOUBLE * Math.min(count, samples.length); }

Target:
public long estimatedInMemorySize() { return INSTANCE_SIZE + SizeOf.sizeOf(samples); }
Source:
public void testGetValueAtDetailNode() { final DetailAST commentContentNode = tree.getFirstChild().getNextSibling().getFirstChild(); Assert.assertNotNull("Comment node cannot be null", commentContentNode); final int nodeType = commentContentNode.getType(); Assert.assertTrue("Comment node should be a comment type", TokenUtils.isCommentType(nodeType)); Assert.assertEquals("This should be a javadoc comment", "/*", commentContentNode.getParent().getText()); final ParseTreeTablePModel parseTree = new ParseTreeTablePModel(null); parseTree.setParseMode(ParseMode.JAVA_WITH_JAVADOC_AND_COMMENTS); final Object child = parseTree.getChild(commentContentNode, 0); Assert.assertFalse(parseTree.isLeaf(child)); Assert.assertTrue(parseTree.isLeaf(tree.getFirstChild())); final Object treeModel = parseTree.getValueAt(child, 0); final String type = (String) parseTree.getValueAt(child, 1); final int line = (int) parseTree.getValueAt(child, 2); final int column = (int) parseTree.getValueAt(child, 3); final String text = (String) parseTree.getValueAt(child, 4); final String expectedText = String.join("", System.lineSeparator(), "* class javadoc", System.lineSeparator(), "<EOF>"); Assert.assertEquals(null, treeModel); Assert.assertEquals("JAVADOC", type); Assert.assertEquals(1, line); Assert.assertEquals(0, column); Assert.assertEquals(expectedText, text); try { parseTree.getValueAt(child, 6); Assert.fail("IllegalStateException expected"); } catch (IllegalStateException ex) { Assert.assertEquals("Unknown column", ex.getMessage()); } }

Target:
public void testGetValueAtDetailNode() { final DetailAST commentContentNode = tree.getFirstChild().getNextSibling().getFirstChild(); Assert.assertNotNull("Comment node cannot be null", commentContentNode); final int nodeType = commentContentNode.getType(); Assert.assertTrue("Comment node should be a comment type", TokenUtils.isCommentType(nodeType)); Assert.assertEquals("This should be a javadoc comment", "/*", commentContentNode.getParent().getText()); final ParseTreeTablePModel parseTree = new ParseTreeTablePModel(null); parseTree.setParseMode(ParseMode.JAVA_WITH_JAVADOC_AND_COMMENTS); final Object child = parseTree.getChild(commentContentNode, 0); Assert.assertFalse(parseTree.isLeaf(child)); Assert.assertTrue(parseTree.isLeaf(tree.getFirstChild())); final Object treeModel = parseTree.getValueAt(child, 0); final String type = (String) parseTree.getValueAt(child, 1); final int line = (int) parseTree.getValueAt(child, 2); final int column = (int) parseTree.getValueAt(child, 3); final String text = (String) parseTree.getValueAt(child, 4); final String expectedText = String.join("", System.lineSeparator(), "* class javadoc", System.lineSeparator(), "<EOF>"); Assert.assertEquals(null, treeModel); Assert.assertEquals("JAVADOC", type); Assert.assertEquals(1, line); Assert.assertEquals(0, column); Assert.assertEquals(expectedText, text); try { parseTree.getValueAt(child, parseTree.getColumnCount()); Assert.fail("IllegalStateException expected"); } catch (IllegalStateException ex) { Assert.assertEquals("Unknown column", ex.getMessage()); } }
Source:
private MethodExpression removePrefix(MethodExpression expression) { return expression.getMethod().getWords().get(0).equals(MANDATORY) || expression.getMethod().getWords().get(0).equals(OPTIONAL) ? (MethodExpression)expression.getParameters().get(0) : expression; }

Target:
private MethodExpression removePrefix(MethodExpression expression) { return expression.getMethod().equals(MANDATORY) || expression.getMethod().equals(OPTIONAL) ? (MethodExpression)expression.getParameters().get(0) : expression; }
Source:
public DefaultDockerClientConfig build() { SSLContext sslContext = null; if (customSslContext == null) { if (dockerTlsVerify) { dockerCertPath = checkDockerCertPath(dockerCertPath); sslContext = new LocalDirectorySSLConfig(dockerCertPath).getSSLContext(); } } else { sslContext = customSslContext; } return new DefaultDockerClientConfig(dockerHost, dockerConfig, apiVersion, registryUrl, registryUsername, registryPassword, registryEmail, sslContext); }

Target:
public DefaultDockerClientConfig build() { SSLConfig sslConfig = null; if (customSslConfig == null) { if (dockerTlsVerify) { dockerCertPath = checkDockerCertPath(dockerCertPath); sslConfig = new LocalDirectorySSLConfig(dockerCertPath); } } else { sslConfig = customSslConfig; } return new DefaultDockerClientConfig(dockerHost, dockerConfig, apiVersion, registryUrl, registryUsername, registryPassword, registryEmail, sslConfig); }
Source:
public OpenTxnMessage getOpenTxnMessage(String messageBody) { try { return mapper.readValue(messageBody, JSONOpenTxnMessage.class); } catch (Exception e) { throw new IllegalArgumentException("Could not construct DropConstraintMessage", e); } }

Target:
public OpenTxnMessage getOpenTxnMessage(String messageBody) { try { return mapper.readValue(messageBody, JSONOpenTxnMessage.class); } catch (Exception e) { throw new IllegalArgumentException("Could not construct OpenTxnMessage", e); } }
Source:
private void putImpl(final String bucket, final String key, final byte[] csum, final TemporaryBuffer buf, ProgressMonitor monitor, String monitorTask) throws IOException { if (monitor == null) monitor = NullProgressMonitor.INSTANCE; if (monitorTask == null) monitorTask = MessageFormat.format(JGitText.get().progressMonUploading, key); final String md5str = Base64.encodeBytes(csum); final long len = buf.length(); for (int curAttempt = 0; curAttempt < maxAttempts; curAttempt++) { final HttpURLConnection c = open("PUT", bucket, key); c.setFixedLengthStreamingMode(len); c.setRequestProperty("Content-MD5", md5str); c.setRequestProperty(X_AMZ_ACL, acl); encryption.request(c, X_AMZ_META); authorize(c); c.setDoOutput(true); c.setFixedLengthStreamingMode((int) len); monitor.beginTask(monitorTask, (int) (len / 1024)); final OutputStream os = c.getOutputStream(); try { buf.writeTo(os, monitor); } finally { monitor.endTask(); os.close(); } switch (HttpSupport.response(c)) { case HttpURLConnection.HTTP_OK: return; case HttpURLConnection.HTTP_INTERNAL_ERROR: continue; default: throw error("Writing", key, c); } } throw maxAttempts("Writing", key); }

Target:
private void putImpl(final String bucket, final String key, final byte[] csum, final TemporaryBuffer buf, ProgressMonitor monitor, String monitorTask) throws IOException { if (monitor == null) monitor = NullProgressMonitor.INSTANCE; if (monitorTask == null) monitorTask = MessageFormat.format(JGitText.get().progressMonUploading, key); final String md5str = Base64.encodeBytes(csum); final long len = buf.length(); for (int curAttempt = 0; curAttempt < maxAttempts; curAttempt++) { final HttpURLConnection c = open("PUT", bucket, key); c.setFixedLengthStreamingMode(len); c.setRequestProperty("Content-MD5", md5str); c.setRequestProperty(X_AMZ_ACL, acl); encryption.request(c, X_AMZ_META); authorize(c); c.setDoOutput(true); monitor.beginTask(monitorTask, (int) (len / 1024)); final OutputStream os = c.getOutputStream(); try { buf.writeTo(os, monitor); } finally { monitor.endTask(); os.close(); } switch (HttpSupport.response(c)) { case HttpURLConnection.HTTP_OK: return; case HttpURLConnection.HTTP_INTERNAL_ERROR: continue; default: throw error("Writing", key, c); } } throw maxAttempts("Writing", key); }
Source:
public synchronized Collection<PendingConfirm> expire(Listener listener, long cutoffTime) { SortedMap<Long, PendingConfirm> pendingConfirmsForListener = this.pendingConfirms.get(listener); if (pendingConfirmsForListener == null) { return Collections.<PendingConfirm>emptyList(); } else { List<PendingConfirm> expired = new ArrayList<PendingConfirm>(); Iterator<Entry<Long, PendingConfirm>> iterator = pendingConfirmsForListener.entrySet().iterator(); while (iterator.hasNext()) { PendingConfirm pendingConfirm = iterator.next().getValue(); if (pendingConfirm.getTimestamp() < cutoffTime) { expired.add(pendingConfirm); iterator.remove(); CorrelationData correlationData = pendingConfirm.getCorrelationData(); if (correlationData != null && StringUtils.hasText(correlationData.getReturnCorrelation())) { this.pendingReturns.remove(correlationData.getReturnCorrelation()); } } else { break; } } return expired; } }

Target:
public synchronized Collection<PendingConfirm> expire(Listener listener, long cutoffTime) { SortedMap<Long, PendingConfirm> pendingConfirmsForListener = this.pendingConfirms.get(listener); if (pendingConfirmsForListener == null) { return Collections.<PendingConfirm>emptyList(); } else { List<PendingConfirm> expired = new ArrayList<PendingConfirm>(); Iterator<Entry<Long, PendingConfirm>> iterator = pendingConfirmsForListener.entrySet().iterator(); while (iterator.hasNext()) { PendingConfirm pendingConfirm = iterator.next().getValue(); if (pendingConfirm.getTimestamp() < cutoffTime) { expired.add(pendingConfirm); iterator.remove(); CorrelationData correlationData = pendingConfirm.getCorrelationData(); if (correlationData != null && StringUtils.hasText(correlationData.getId())) { this.pendingReturns.remove(correlationData.getId()); } } else { break; } } return expired; } }
Source:
private QueryPlan getFetchPlan(boolean isNext, int fetchSize) throws SQLException { if (!isOpen) throw new SQLException("Fetch call on closed cursor '" + this.cursorName + "'!"); ((CursorResultIterator)fetchPlan.iterator()).setFetchSize(fetchSize); if (!queryPlan.getStatement().isAggregate() || !queryPlan.getStatement().isDistinct()) { if (islastCallNext != isNext) { if (islastCallNext && !isReversed){ ScanUtil.setReversed(scan); } else { ScanUtil.unsetReversed(scan); } isReversed = !isReversed; } if (!isReversed) { if (row!=null){ scan.setStartRow(row.get()); } } else { if(previousRow!=null){ scan.setStopRow(previousRow.get()); } } islastCallNext = isNext; } return this.fetchPlan; }

Target:
private QueryPlan getFetchPlan(boolean isNext, int fetchSize) throws SQLException { if (!isOpen) throw new SQLException("Fetch call on closed cursor '" + this.cursorName + "'!"); ((CursorResultIterator)fetchPlan.iterator()).setFetchSize(fetchSize); if (!isAggregate) { if (row!=null){ scan.setStartRow(row.get()); } } return this.fetchPlan; }
Source:
public StructType getExternalFileSchema(String storedAs, String location){ StructType schema = null; if (storedAs!=null) { if (storedAs.toLowerCase().equals("p")) { schema = SpliceSpark.getSession().read().parquet(location).schema(); } if (storedAs.toLowerCase().equals("a")) { schema = SparkSession.builder().master("local").getOrCreate().read().format("com.databricks.spark.avro").load(location).schema(); } if (storedAs.toLowerCase().equals("o")) { schema = SpliceSpark.getSession().read().orc(location).schema(); } if (storedAs.toLowerCase().equals("t")) { schema = SpliceSpark.getSession().read().csv(location).schema(); } } return schema; }

Target:
public StructType getExternalFileSchema(String storedAs, String location){ StructType schema = null; if (storedAs!=null) { if (storedAs.toLowerCase().equals("p")) { schema = SpliceSpark.getSession().read().parquet(location).schema(); } else if (storedAs.toLowerCase().equals("a")) { schema = SpliceSpark.getSession().read().format("com.databricks.spark.avro").load(location).schema(); } else if (storedAs.toLowerCase().equals("o")) { schema = SpliceSpark.getSession().read().orc(location).schema(); } else if (storedAs.toLowerCase().equals("t")) { schema = SpliceSpark.getSession().read().csv(location).schema(); } } return schema; }
Source:
private CachedCuratorFrameworkImpl( final ReferenceCountedCache<K, CuratorFramework> cache, final K key, final CuratorFrameworkImpl delegate ) { super(delegate); mCache = cache; mCacheKey = key; DebugResourceTracker .get() .registerResource(this, ExceptionUtils.getStackTrace(new Exception())); }

Target:
private CachedCuratorFrameworkImpl( final ReferenceCountedCache<K, CuratorFramework> cache, final K key, final CuratorFrameworkImpl delegate ) { super(delegate); mCache = cache; mCacheKey = key; DebugResourceTracker.get().registerResource(this); }
Source:
public Object createVisit(UiUtils ui, Session session, @BindParams("visit") @Validate Visit visit) { if (visit.getLocation() == null) visit.setLocation(Context.getService(KenyaEmrService.class).getDefaultLocation()); visit = Context.getVisitService().endVisit(visit, visit.getStopDatetime()); Visit saved = Context.getVisitService().saveVisit(visit); return simpleVisit(ui, saved); }

Target:
public SimpleObject createVisit(UiUtils ui, Session session, @BindParams("visit") @Validate Visit visit) { if (visit.getLocation() == null) { visit.setLocation(Context.getService(KenyaEmrService.class).getDefaultLocation()); } visit = Context.getVisitService().endVisit(visit, visit.getStopDatetime()); Visit saved = Context.getVisitService().saveVisit(visit); return simpleVisit(ui, saved); }
Source:
public String getQueryId() { return queryId.getId(); }

Target:
public QueryId getQueryId() { return queryId; }
Source:
protected KeyValueService getKeyValueService() { return CassandraKeyValueServiceImpl.createForTesting( container.getConfig(), CassandraContainer.LEADER_CONFIG); }

Target:
protected KeyValueService getKeyValueService() { return CASSANDRA.getDefaultKvs(); }
Source:
protected InputStream readContent(BinaryKey key, Connection connection) throws SQLException { PreparedStatement readContentStatement = readContentSQLStatement(key, true, connection); ResultSet rs = executeQuery(readContentStatement); if (!rs.next()) { tryToClose(readContentStatement); tryToClose(connection); return null; } return new DatabaseBinaryStream(connection, readContentStatement, rs.getBinaryStream(1)); }

Target:
protected InputStream readContent(BinaryKey key, Connection connection) throws SQLException { PreparedStatement readContentStatement = prepareStatement(USED_CONTENT_STMT_KEY, connection); try { readContentStatement.setString(1, key.toString()); ResultSet rs = executeQuery(readContentStatement); if (!rs.next()) { tryToClose(readContentStatement); tryToClose(connection); return null; } else { return new DatabaseBinaryStream(connection, readContentStatement, rs.getBinaryStream(1)); } } catch (SQLException e) { tryToClose(readContentStatement); tryToClose(connection); throw e; } catch (Throwable t) { tryToClose(readContentStatement); tryToClose(connection); throw new RuntimeException(t); } }
Source:
public RenameResourceWizard(IResource resource, String newName) { this(resource); RenameResourceProcessor fRenameResourceProcessor= (RenameResourceProcessor) ((RenameRefactoring) super.getRefactoring()).getProcessor(); fRenameResourceProcessor.setNewResourceName(newName); setDefaultPageTitle(RefactoringUIMessages.RenameResourceWizard_page_title); setWindowTitle(RefactoringUIMessages.RenameResourceWizard_window_title); }

Target:
public RenameResourceWizard(IResource resource, String newName) { this(resource); RenameResourceProcessor fRenameResourceProcessor= (RenameResourceProcessor) ((RenameRefactoring) super.getRefactoring()).getProcessor(); fRenameResourceProcessor.setNewResourceName(newName); }
Source:
public static <R> R runInTransaction(TraversalContext<?, ?> context, boolean readOnly, PotentiallyCommittingPayload<R> payload) { int failures = 0; Exception lastException = null; int maxFailures = context.getTransactionRetriesCount(); int waitTime = 100; while (failures < maxFailures) { try { InventoryBackend.Transaction t = context.backend.startTransaction(!readOnly); try { R ret = payload.run(t); if (readOnly) { context.backend.commit(t); } return ret; } catch (Throwable e) { Log.LOGGER.error("\n\n\nTRANSACTION failed: " + e.getMessage()); context.backend.rollback(t); throw e; } } catch (CommitFailureException e) { failures++; Log.LOGGER.debugf(e, "Commit attempt %d/%d failed. Will wait for %d ms before retrying." + " The failure message was: %s", failures, maxFailures, waitTime, e.getMessage()); lastException = e; if (failures < maxFailures) { try { Thread.sleep(waitTime); } catch (InterruptedException ie) { Log.LOGGER.wInterruptedWhileWaitingForTransactionRetry(); Thread.currentThread().interrupt(); break; } waitTime = waitTime * 2 + rand.nextInt(waitTime / 10); } } } throw new TransactionFailureException(lastException, failures); }

Target:
public static <R> R runInTransaction(TraversalContext<?, ?> context, boolean readOnly, PotentiallyCommittingPayload<R> payload) { int failures = 0; Exception lastException = null; int maxFailures = context.getTransactionRetriesCount(); int waitTime = 100; while (failures < maxFailures) { try { InventoryBackend.Transaction t = context.backend.startTransaction(!readOnly); try { R ret = payload.run(t); if (readOnly) { context.backend.commit(t); } return ret; } catch (Throwable e) { Log.LOGGER.dTransactionFailed(e.getMessage()); context.backend.rollback(t); throw e; } } catch (CommitFailureException e) { failures++; Log.LOGGER.debugf(e, "Commit attempt %d/%d failed. Will wait for %d ms before retrying." + " The failure message was: %s", failures, maxFailures, waitTime, e.getMessage()); lastException = e; if (failures < maxFailures) { try { Thread.sleep(waitTime); } catch (InterruptedException ie) { Log.LOGGER.wInterruptedWhileWaitingForTransactionRetry(); Thread.currentThread().interrupt(); break; } waitTime = waitTime * 2 + rand.nextInt(waitTime / 10); } } } throw new TransactionFailureException(lastException, failures); }
Source:
public Map<String, ValueResolver<? extends Object>> getParameters() { if (builder instanceof ParameterValueResolver) { return ((ParameterValueResolver) builder).getParameters(); } else { return new HashMap<>(); } }

Target:
public Map<String, ValueResolver<? extends Object>> getParameters() throws ValueResolvingException { if (builder instanceof ParameterValueResolver) { return unmodifiableMap(((ParameterValueResolver) builder).getParameters()); } else { return emptyMap(); } }
Source:
protected int hashLine(final byte[] raw, int ptr, final int end) { int hash = 5381; for (; ptr < end; ptr++) { if (!RawCharUtil.isWhitespace(raw[ptr])) { hash = (hash << 5) ^ (raw[ptr] & 0xff); } } return hash; }

Target:
protected int hashLine(final byte[] raw, int ptr, final int end) { int hash = 5381; for (; ptr < end; ptr++) { byte c = raw[ptr]; if (!isWhitespace(c)) hash = (hash << 5) ^ (c & 0xff); } return hash; }
Source:
public static IoOperationType getType(int rwbs) { if (rwbs % 2 == 0) { return READ; } return WRITE; }

Target:
public static IoOperationType getType(int rwbs) { return (rwbs % 2 == 0) ? READ : WRITE; }
Source:
public Void visit(SqlCall call) { if (call.getKind() == SqlKind.OVER) { throw new FoundOne(call); } return super.visit(call); }

Target:
public Void visit(SqlCall call) { if (call.getKind() == SqlKind.OVER) { throw FoundOne.NULL; } return super.visit(call); }
Source:
PageFilePageReader( long readStart, long readLength, FSDataInputStream inputStream, PagesSerde pagesSerde) throws IOException { this.pagesSerde = requireNonNull(pagesSerde, "pagesSerde is null"); this.readLength = readLength; requireNonNull(inputStream, "inputStream is null"); inputStream.seek(readStart); this.input = new InputStreamSliceInput(inputStream); }

Target:
public PageFilePageReader( long readStart, long readLength, FSDataInputStream inputStream, PagesSerde pagesSerde) throws IOException { this.pagesSerde = requireNonNull(pagesSerde, "pagesSerde is null"); this.readLength = readLength; requireNonNull(inputStream, "inputStream is null"); inputStream.seek(readStart); this.input = new InputStreamSliceInput(inputStream); }
Source:
public void constructorTest() { final double memoryLength = 1e6; final double[] minorAlleleFractions = new double[] {0.1, 0.5, 0.23}; final double[] weights = new double[] {0.2, 0.2, 0.6}; final AllelicBiasParameters params = new AllelicBiasParameters(0.1, 0.01, 0.03); AlleleFractionHiddenMarkovModel model = new AlleleFractionHiddenMarkovModel(minorAlleleFractions, weights, memoryLength, AllelicPanelOfNormals.EMPTY_PON, params); Assert.assertEquals(memoryLength, model.getMemoryLength()); for (int n = 0; n < weights.length; n++) { Assert.assertEquals(weights[n], model.getWeight(n)); Assert.assertEquals(minorAlleleFractions[n], model.getMinorAlleleFraction(n)); } Assert.assertEquals(model.getParameters().getMeanBias(), params.getMeanBias()); Assert.assertEquals(model.getParameters().getBiasVariance(), params.getBiasVariance()); Assert.assertEquals(model.getParameters().getOutlierProbability(), params.getOutlierProbability()); }

Target:
public void constructorTest() { final double memoryLength = 1e6; final double[] minorAlleleFractions = new double[] {0.1, 0.5, 0.23}; final double[] weights = new double[] {0.2, 0.2, 0.6}; final AlleleFractionGlobalParameters params = new AlleleFractionGlobalParameters(0.1, 0.01, 0.03); final AlleleFractionHiddenMarkovModel model = new AlleleFractionHiddenMarkovModel(minorAlleleFractions, weights, memoryLength, AllelicPanelOfNormals.EMPTY_PON, params); Assert.assertEquals(memoryLength, model.getMemoryLength()); for (int n = 0; n < weights.length; n++) { Assert.assertEquals(weights[n], model.getWeight(n)); Assert.assertEquals(minorAlleleFractions[n], model.getMinorAlleleFraction(n)); } Assert.assertEquals(model.getParameters().getMeanBias(), params.getMeanBias()); Assert.assertEquals(model.getParameters().getBiasVariance(), params.getBiasVariance()); Assert.assertEquals(model.getParameters().getOutlierProbability(), params.getOutlierProbability()); }
Source:
public void enable() { if ( !enabled ) { this.enabled = true; Collection<SyncBeanDef<MenuDevCommand>> beanDefs = beanManager.lookupBeans( MenuDevCommand.class ); for ( SyncBeanDef<MenuDevCommand> beanDef : beanDefs ) { MenuDevCommand devCommand = beanDef.getInstance(); devCommands.add( devCommand ); } } }

Target:
public void enable() { if ( !enabled ) { this.enabled = true; menuDevCommandManagedInstances.iterator().forEachRemaining( devCommands::add ); } }
Source:
protected List<DatabaseObject> mergeDatabaseObjects(List<DatabaseObject> objects) { int maxIdx = -1; for (DatabaseObject object: objects) { maxIdx = Math.max(maxIdx, object.getOrder()); } final List<DatabaseObject> orderedObjects = createListAndFillNull(maxIdx); final List<DatabaseObject> unorderedObjects = new ArrayList<>(); final List<DatabaseObject> mergedObjects = new ArrayList<>(); for (DatabaseObject object: objects) { if (object.getOrder() > -1) { int objIdx = object.getOrder(); if (objIdx < orderedObjects.size() && orderedObjects.get(objIdx) != null) { throw new TajoInternalError("This catalog configuration contains duplicated order of DatabaseObject"); } orderedObjects.add(objIdx, object); } else { unorderedObjects.add(object); } } orderedObjects.stream().filter(object -> object != null).forEach(mergedObjects::add); unorderedObjects.stream().filter(object -> object != null).forEach(mergedObjects::add); return mergedObjects; }

Target:
protected List<DatabaseObject> mergeDatabaseObjects(List<DatabaseObject> objects) { int maxIdx = -1; for (DatabaseObject object: objects) { maxIdx = Math.max(maxIdx, object.getOrder()); } final List<DatabaseObject> orderedObjects = createListAndFillNull(maxIdx); final List<DatabaseObject> unorderedObjects = new ArrayList<>(); final List<DatabaseObject> mergedObjects = new ArrayList<>(); for (DatabaseObject object: objects) { if (object.getOrder() > -1) { int objIdx = object.getOrder(); if (objIdx < orderedObjects.size() && orderedObjects.get(objIdx) != null) { throw new TajoInternalError("This catalog configuration contains duplicated order of DatabaseObject"); } orderedObjects.add(objIdx, object); } else { unorderedObjects.add(object); } } Stream.concat(orderedObjects.stream(), unorderedObjects.stream()) .filter(object -> object != null).forEach(mergedObjects::add); return mergedObjects; }
Source:
private long createTable(String name) { return dbi.onDemand(MetadataDao.class).insertTable("test", name, false, true, null, 0, false); }

Target:
private long createTable(String name) { return dbi.onDemand(MetadataDao.class).insertTable("test", name, false, false, null, 0, false); }