auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static List<String> getCommandsFromScript(final File script, final DatabaseType databaseType) throws IOException { String delimiter = getDelimiterByFileAndDatabase(script, databaseType); String escapedDelimiter = DELIMITER_STANDARD.equals(delimiter) ? "\\" + DELIMITER_STANDARD : delimiter; final List<String> scriptLines = FileUtils.readLines(script, StandardCharsets.UTF_8); final List<String> foundCommands = new ArrayList<String>(); final StringBuilder command = new StringBuilder(); int pgBlockCounter = 0; for (String line : scriptLines) { final String trimmedLine = line.trim(); if ("".equals(trimmedLine) || trimmedLine.startsWith("--") || trimmedLine.startsWith("#") || (trimmedLine.startsWith("/*"))) { continue; } if (databaseType == POSTGRESQL && trimmedLine.matches(DOLLAR_QUOTED_BLOCK)) { pgBlockCounter++; } if (trimmedLine.equals(delimiter)) { if (!"".equals(command.toString())) { foundCommands.add(command.toString()); command.setLength(0); command.trimToSize(); } } if (databaseType == SYBASE && !trimmedLine.startsWith(delimiter) && trimmedLine.contains(delimiter)){ command.append(trimmedLine).append(" "); } else if ((trimmedLine.contains(delimiter) && databaseType != POSTGRESQL) || trimmedLine.contains(delimiter) && databaseType == POSTGRESQL && isEven(pgBlockCounter)) { extractCommandsFromLine(trimmedLine, escapedDelimiter, command, foundCommands); } else { command.append(trimmedLine).append(" "); } } if (!"".equals(command.toString())) { foundCommands.add(command.toString()); } return foundCommands; }

Target:
public static List<String> getCommandsFromScript(final File script, final DatabaseType databaseType) throws IOException { String delimiterRegex = getDelimiterByFileAndDatabase(script, databaseType); String delimiter = delimiterRegex.indexOf(REGEX_OR)!=-1 ? delimiterRegex.substring(0, delimiterRegex.indexOf(REGEX_OR)) : delimiterRegex; String escapedDelimiter = DELIMITER_STANDARD.equals(delimiter) ? "\\" + DELIMITER_STANDARD : delimiter; final List<String> scriptLines = FileUtils.readLines(script, StandardCharsets.UTF_8); final List<String> foundCommands = new ArrayList<String>(); final StringBuilder command = new StringBuilder(); int pgBlockCounter = 0; for (String line : scriptLines) { final String trimmedLine = line.trim(); if (shouldSkip(trimmedLine)) { continue; } if (databaseType == POSTGRESQL && trimmedLine.matches(DOLLAR_QUOTED_BLOCK)) { pgBlockCounter++; } if (trimmedLine.toUpperCase().matches(delimiterRegex)) { if (!"".equals(command.toString())) { foundCommands.add(command.toString()); command.setLength(0); command.trimToSize(); continue; } } if ((trimmedLine.contains(delimiter) && databaseType != POSTGRESQL && databaseType != SYBASE) || trimmedLine.contains(delimiter) && databaseType == POSTGRESQL && isEven(pgBlockCounter)) { extractCommandsFromLine(trimmedLine, escapedDelimiter, command, foundCommands); } else { command.append(trimmedLine).append(" "); } } if (!"".equals(command.toString())) { foundCommands.add(command.toString()); } return foundCommands; }
Source:
public GenericRecord parse(ByteBuffer bytes) { int schemaId = bytes.getInt(); Schema schemaObj = schemaObjs.get(schemaId); if (schemaObj == null) { throw new IAE("Failed to find schema for id [%s]", schemaId); } DatumReader<GenericRecord> reader = new GenericDatumReader<GenericRecord>(schemaObj); ByteBufferInputStream inputStream = new ByteBufferInputStream(Collections.singletonList(bytes)); try { return reader.read(null, DecoderFactory.get().binaryDecoder(inputStream, null)); } catch (Exception e) { throw new ParseException(e, "Fail to decode avro message with schemaId [%s].", schemaId); } }

Target:
public GenericRecord parse(ByteBuffer bytes) { if (bytes.remaining() < 5) { throw new ParseException("record must have at least 5 bytes carrying version and schemaId"); } byte version = bytes.get(); if (version != V1) { throw new ParseException("found record of arbitrary version [%s]", version); } int schemaId = bytes.getInt(); Schema schemaObj = schemaObjs.get(schemaId); if (schemaObj == null) { throw new ParseException("Failed to find schema for id [%s]", schemaId); } try { DatumReader<GenericRecord> reader = new GenericDatumReader<GenericRecord>(schemaObj); ByteBufferInputStream inputStream = new ByteBufferInputStream(Collections.singletonList(bytes)); return reader.read(null, DecoderFactory.get().binaryDecoder(inputStream, null)); } catch (Exception e) { throw new ParseException(e, "Fail to decode avro message with schemaId [%s].", schemaId); } }
Source:
public void createPartControl(@Nullable Composite parent) { runAnalysis(); final LatencyDataStore data = getData(); SashForm sf = new SashForm(parent, SWT.NONE); TableViewer tableViewer = new TableViewer(sf, SWT.FULL_SELECTION | SWT.VIRTUAL); fTableViewer = new LatencyTableViewer(tableViewer, data); }

Target:
public void createPartControl(@Nullable Composite parent) { SashForm sf = new SashForm(parent, SWT.NONE); TableViewer tableViewer = new TableViewer(sf, SWT.FULL_SELECTION | SWT.VIRTUAL); fTableViewer = new LatencyTableViewer(tableViewer); setInitialData(); }
Source:
private void doGitActions() { DISPLAY.asyncExec(() -> { if (!scriptGeneratorViewModel.remoteAvailable()) { MessageDialog.openInformation(DISPLAY.getActiveShell(), "Git error", "Could not connect to remote git repository"); } if (scriptGeneratorViewModel.updatesAvailable()) { int performMerge = MessageDialog.open(MessageDialog.CONFIRM, DISPLAY.getActiveShell(), "Error pulling repository", scriptGeneratorViewModel.getPromptMessage(), 0, "Keep local changes", "Discard local changes and update"); if (performMerge == 1) { scriptGeneratorViewModel.mergeOrigin(); } } Optional<String> gitErrors = scriptGeneratorViewModel.getGitLoadErrors(); if (gitErrors.isPresent()) { MessageDialog.openInformation(DISPLAY.getActiveShell(), "Git errors occurred", gitErrors.get()); } }); scriptGeneratorViewModel.reloadScriptDefinitions(); scriptGeneratorViewModel.setRepoPath(); }

Target:
private void doGitActions() { DISPLAY.asyncExec(() -> { if (!scriptGeneratorViewModel.remoteAvailable()) { MessageDialog.openInformation(DISPLAY.getActiveShell(), "Git error", "Could not update script definitions, because the remote git repository could not be reached. " + "You can still continue to use the existing script definitions, but they may be out of date."); } if (scriptGeneratorViewModel.updatesAvailable()) { int performMerge = MessageDialog.open(MessageDialog.CONFIRM, DISPLAY.getActiveShell(), "Error pulling repository", scriptGeneratorViewModel.getPromptMessage(), 0, "Keep local changes", "Discard local changes and update"); if (performMerge == 1) { scriptGeneratorViewModel.mergeOrigin(); } } Optional<String> gitErrors = scriptGeneratorViewModel.getGitLoadErrors(); if (gitErrors.isPresent()) { MessageDialog.openInformation(DISPLAY.getActiveShell(), "Git errors occurred", gitErrors.get()); } }); scriptGeneratorViewModel.reloadScriptDefinitions(); scriptGeneratorViewModel.setRepoPath(); }
Source:
public static File getUniqueFile(String fileName) { File tempFile = null; int i = 0; try { do { tempFile = new File(TMP_DIR + DIR_SEPARATOR + fileName + "-" + i + "." + KEY_FILENAME_EXT); i++; } while (tempFile.exists()); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); } return tempFile; }

Target:
public static File getUniqueFile(String fileName) { File tempFile = null; int i = 0; do { tempFile = new File(TMP_DIR + DIR_SEPARATOR + fileName + "-" + i + "." + KEY_FILENAME_EXT); i++; } while (tempFile.exists()); return tempFile; }
Source:
protected static Long getLastOffset(String workId) { String stringOffset = getKeyValueStore().getString(getOffsetKey(workId)); return stringOffset == null ? Long.valueOf(-1) : Long.parseLong(stringOffset); }

Target:
protected static long getLastOffset(String workId) { String stringOffset = getKeyValueStore().getString(getOffsetKey(workId)); return stringOffset == null ? -1 : Long.parseLong(stringOffset); }
Source:
public JSONObject listSequencePartitionContainersDataTable(HttpSession session, JSONObject json) { try { JSONObject j = new JSONObject(); JSONArray jsonArray = new JSONArray(); for (SequencerPartitionContainer<SequencerPoolPartition> spc : requestManager.listAllSequencerPartitionContainers()) { String run = ""; String sequencer = ""; if (spc.getRun() != null) { run = TableHelper.hyperLinkify("/miso/run/" + spc.getRun().getId(), spc.getRun().getAlias()); if (spc.getRun().getSequencerReference() != null) { sequencer = TableHelper.hyperLinkify("/miso/sequencer/" + spc.getRun().getSequencerReference().getId(), spc.getRun().getSequencerReference().getPlatform().getNameAndModel()); } } JSONArray inner = new JSONArray(); inner.add(isStringEmptyOrNull(spc.getIdentificationBarcode()) ? TableHelper.hyperLinkify("/miso/container/" + spc.getId(), spc.getIdentificationBarcode()) : ""); inner.add(spc.getPlatform() != null && spc.getPlatform().getPlatformType() != null ? spc.getPlatform().getPlatformType().getKey() : ""); inner.add(run); inner.add(sequencer); jsonArray.add(inner); } j.put("array", jsonArray); return j; } catch (IOException e) { log.error("Failed", e); return JSONUtils.SimpleJSONError("Failed: " + e.getMessage()); } }

Target:
public JSONObject listSequencePartitionContainersDataTable(HttpSession session, JSONObject json) { try { JSONObject j = new JSONObject(); JSONArray jsonArray = new JSONArray(); for (SequencerPartitionContainer<SequencerPoolPartition> spc : requestManager.listAllSequencerPartitionContainers()) { String run = ""; String sequencer = ""; if (spc.getRun() != null) { run = TableHelper.hyperLinkify("/miso/run/" + spc.getRun().getId(), spc.getRun().getAlias()); if (spc.getRun().getSequencerReference() != null) { sequencer = TableHelper.hyperLinkify("/miso/sequencer/" + spc.getRun().getSequencerReference().getId(), spc.getRun().getSequencerReference().getPlatform().getNameAndModel()); } } String identificationBarcode = (isStringEmptyOrNull(spc.getIdentificationBarcode()) ? "Unknown Barcode" : spc.getIdentificationBarcode()); JSONArray inner = new JSONArray(); inner.add(TableHelper.hyperLinkify("/miso/container/" + spc.getId(),identificationBarcode)); inner.add(spc.getPlatform() != null && spc.getPlatform().getPlatformType() != null ? spc.getPlatform().getPlatformType().getKey() : ""); inner.add(run); inner.add(sequencer); jsonArray.add(inner); } j.put("array", jsonArray); return j; } catch (IOException e) { log.error("Failed", e); return JSONUtils.SimpleJSONError("Failed: " + e.getMessage()); } }
Source:
public QueryResponse process(QueryResponse queryResponse) throws PluginExecutionException { if (queryResponse == null) { throw new PluginExecutionException("Cannot process null queryResponse"); } if (!queryResponse.getResults().isEmpty()) { String queryId = (String) queryResponse.getRequest().getProperties().get("id"); if (queryId != null) { Metacard metacard = getWorkspaceMetacard(queryId); WorkspaceMetacardImpl workspaceMetacard = WorkspaceMetacardImpl.from(metacard); if (WorkspaceMetacardImpl.isWorkspaceMetacard(workspaceMetacard)) { String queryIssuerEmail = subjectIdentity.getUniqueIdentifier(SecurityUtils.getSubject()); String workspaceOwnerEmail = AccessControlUtil.getOwner(workspaceMetacard); if (workspaceOwnerEmail.equals(queryIssuerEmail)) { emailNotifierService.sendEmailsForWorkspace(workspaceMetacard, 1L); } } } } return queryResponse; }

Target:
public QueryResponse process(QueryResponse queryResponse) throws PluginExecutionException { if (queryResponse == null) { throw new PluginExecutionException("Cannot process null queryResponse"); } if (queryResponse.getResults().isEmpty()) { return queryResponse; } String queryId = (String) queryResponse.getRequest().getProperties().get("id"); if (!StringUtils.isEmpty(queryId)) { Metacard metacard = getWorkspaceMetacard(queryId); if (metacard == null) { LOGGER.debug("Could not retrieve workspace metacard."); return queryResponse; } WorkspaceMetacardImpl workspaceMetacard = WorkspaceMetacardImpl.from(metacard); String queryIssuerEmail = subjectIdentity.getUniqueIdentifier(SecurityUtils.getSubject()); String workspaceOwnerEmail = AccessControlUtil.getOwner(workspaceMetacard); if (!queryIssuerEmail.equals(workspaceOwnerEmail)) { LOGGER.debug("Query was not issued by the owner of the workspace."); return queryResponse; } emailNotifierService.sendEmailsForWorkspace(workspaceMetacard, queryResponse.getHits()); } return queryResponse; }
Source:
private void initialize() { if (properties == null) { logger.debug("Retrieve properties from the license properties file"); properties = LicenseConfiguration.getConfiguration().getProperties(); logger.debug("Initializing LicenseSynchronization"); licenseSynchronization = new LicenseSynchronization(); Enumeration propertyNames = properties.propertyNames(); while (propertyNames.hasMoreElements()) { String software = (String) propertyNames.nextElement(); int nbTokens = Integer.parseInt(properties.getProperty(software)); if (nbTokens > 0) { licenseSynchronization.addSoftware(software, nbTokens); } else { licenseSynchronization.addSoftware(software, -1); } } licenseSynchronization.persist(); } }

Target:
private void initialize() { if (properties == null) { logger.debug("Retrieve properties from the license properties file"); properties = LicenseConfiguration.getConfiguration().getProperties(); logger.debug("Initializing LicenseSynchronization"); licenseSynchronization = new LicenseSynchronization(); Enumeration propertyNames = properties.propertyNames(); while (propertyNames.hasMoreElements()) { String software = (String) propertyNames.nextElement(); int nbTokens; try { nbTokens = Integer.parseInt(properties.getProperty(software)); } catch (NumberFormatException e) { logger.debug("Fatal error, cannot parse token number from the license properties file"); throw e; } if (nbTokens > 0) { licenseSynchronization.addSoftware(software, nbTokens); } else { licenseSynchronization.addSoftware(software, -1); } } licenseSynchronization.persist(); } }
Source:
public int countItems(Context context, EPerson submitter, boolean includeArchived, boolean includeWithdrawn) throws SQLException { Query query = createQuery(context, "SELECT count(*) FROM Item i join i.submitter submitter WHERE i" + ".inArchive=:in_archive AND i.withdrawn=:withdrawn AND submitter = :submitter"); query.setParameter("submitter", submitter); query.setParameter("in_archive", includeArchived); query.setParameter("withdrawn", includeWithdrawn); return count(query); }

Target:
public int countItems(Context context, EPerson submitter, boolean includeArchived, boolean includeWithdrawn) throws SQLException { Query query = createQuery(context, "SELECT count(*) FROM Item i join i.submitter submitter " + "WHERE i.inArchive=:in_archive AND i.withdrawn=:withdrawn AND submitter = :submitter"); query.setParameter("submitter", submitter); query.setParameter("in_archive", includeArchived); query.setParameter("withdrawn", includeWithdrawn); return count(query); }
Source:
public void shouldDebugCliPhpScriptFromFirstLine() { menu.runCommand( TestMenuCommandsConstants.Run.RUN_MENU, TestMenuCommandsConstants.Run.EDIT_DEBUG_CONFIGURATION); debugConfig.createConfig(PROJECT); menu.runCommandByXpath( TestMenuCommandsConstants.Run.RUN_MENU, TestMenuCommandsConstants.Run.DEBUG, getXpathForDebugConfigurationMenuItem()); notificationPopup.waitExpectedMessageOnProgressPanelAndClosed("Remote debugger connected"); projectExplorer.openItemByPath(PATH_TO_LIB_PHP); editor.setBreakpoint(14); editor.closeAllTabs(); projectExplorer.openItemByPath(PATH_TO_INDEX_PHP); projectExplorer.invokeCommandWithContextMenu( ProjectExplorer.CommandsGoal.COMMON, PROJECT, DEBUG_PHP_SCRIPT_COMMAND_NAME); debugPanel.openDebugPanel(); debugPanel.waitDebugHighlightedText("<?php include 'lib.php';?>"); debugPanel.waitTextInVariablesPanel("$_GET=array [0]"); debugPanel.clickOnButton(DebugPanel.DebuggerButtonsPanel.RESUME_BTN_ID); editor.waitTabFileWithSavedStatus("lib.php"); debugPanel.waitDebugHighlightedText("return \"Hello, $name\""); debugPanel.waitTextInVariablesPanel("$name=\"man\""); debugPanel.clickOnButton(DebugPanel.DebuggerButtonsPanel.STEP_OUT); editor.waitTabFileWithSavedStatus("index.php"); debugPanel.waitDebugHighlightedText("echo sayHello(\"man\");"); debugPanel.waitTextInVariablesPanel("$_GET=array [0]"); }

Target:
public void shouldDebugCliPhpScriptFromFirstLine() { menu.runCommand( TestMenuCommandsConstants.Run.RUN_MENU, TestMenuCommandsConstants.Run.EDIT_DEBUG_CONFIGURATION); debugConfig.createConfig(PROJECT); menu.runCommandByXpath( TestMenuCommandsConstants.Run.RUN_MENU, TestMenuCommandsConstants.Run.DEBUG, getXpathForDebugConfigurationMenuItem()); notificationPopup.waitExpectedMessageOnProgressPanelAndClosed("Remote debugger connected"); projectExplorer.openItemByPath(PATH_TO_LIB_PHP); editor.setBreakpoint(14); editor.closeAllTabs(); projectExplorer.openItemByPath(PATH_TO_INDEX_PHP); projectExplorer.invokeCommandWithContextMenu( ProjectExplorer.CommandsGoal.COMMON, PROJECT, DEBUG_PHP_SCRIPT_COMMAND_NAME); debugPanel.openDebugPanel(); debugPanel.waitDebugHighlightedText("<?php include 'lib.php';?>"); debugPanel.waitTextInVariablesPanel("$_GET=array [0]"); debugPanel.clickOnButton(DebugPanel.DebuggerButtonsPanel.RESUME_BTN_ID); editor.waitTabFileWithSavedStatus("lib.php"); editor.waitAcitveBreakpoint(14); debugPanel.waitDebugHighlightedText("return \"Hello, $name\""); debugPanel.waitTextInVariablesPanel("$name=\"man\""); debugPanel.clickOnButton(DebugPanel.DebuggerButtonsPanel.STEP_OUT); editor.waitTabFileWithSavedStatus("index.php"); debugPanel.waitDebugHighlightedText("echo sayHello(\"man\");"); debugPanel.waitTextInVariablesPanel("$_GET=array [0]"); }
Source:
public MongoSendTask(Context pContext) { context = pContext; PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "WifiReader"); wakeLock.acquire(); lockCounter++; Log.e(TAG,"MongosendTask - wakelock acquired " + lockCounter); }

Target:
public MongoSendTask(Context pContext) { context = pContext; PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MongoSendTask"); wakeLock.acquire(); lockCounter++; Log.e(TAG,"MongosendTask - wakelock acquired " + lockCounter); }
Source:
private synchronized void removeSubscription() { logger.debug("Removing WeMo GENA subscription for '{}'", this); if (service.isRegistered(this)) { ThingTypeUID thingTypeUID = thing.getThingTypeUID(); String subscription = null; if (thingTypeUID.equals(THING_TYPE_INSIGHT)) { subscription = "insight1"; } else { subscription = "basicevent1"; service.addSubscription(this, "basicevent1", SUBSCRIPTION_DURATION); } if ((subscriptionState.get(subscription) != null) && subscriptionState.get(subscription).booleanValue()) { logger.debug("WeMo {}: Unsubscribing from service {}...", getUDN(), subscription); service.removeSubscription(this, subscription); } subscriptionState = new HashMap<String, Boolean>(); service.unregisterParticipant(this); } }

Target:
private synchronized void removeSubscription() { logger.debug("Removing WeMo GENA subscription for '{}'", this); if (service.isRegistered(this)) { ThingTypeUID thingTypeUID = thing.getThingTypeUID(); String subscription = null; if (thingTypeUID.equals(THING_TYPE_INSIGHT)) { subscription = "insight1"; } else { subscription = "basicevent1"; } if ((subscriptionState.get(subscription) != null) && subscriptionState.get(subscription).booleanValue()) { logger.debug("WeMo {}: Unsubscribing from service {}...", getUDN(), subscription); service.removeSubscription(this, subscription); } subscriptionState = new HashMap<String, Boolean>(); service.unregisterParticipant(this); } }
Source:
public RawPacket reverseTransform( RawPacket packet) { if (absoluteSendTimeEngine .hasAbsoluteSendTimeExtension(packet) == null) { logger.warn( "RemoteBitrateEstimatorAbsSendTimeImpl: Incoming" + " packet is missing absolute send time extension!"); return null; } logger.info("Using RemoteBitrateEstimatorAbsSendTime: Instantiating."); incomingPacketInfo(System.currentTimeMillis(), absoluteSendTimeEngine .getAbsSendTime(packet), packet.getPayloadLength(), packet.getSSRC()); return packet; }

Target:
public RawPacket reverseTransform( RawPacket packet) { logger.info("Using RemoteBitrateEstimatorAbsSendTime: Instantiating."); incomingPacketInfo(System.currentTimeMillis(), absoluteSendTimeEngine .getAbsSendTime(packet), packet.getPayloadLength(), packet.getSSRCAsLong()); return packet; }
Source:
public void enumToStrings() throws Exception { final String expected = "CRITICAL, URGENT, HIGH, NORMAL, LOW, BACKGROUND"; String actual = Utils.printEnumOptions(com.spectralogic.ds3client.models.Priority.values()); assertEquals(actual, expected); }

Target:
public void enumToStrings() throws Exception { final String expected = "CRITICAL, URGENT, HIGH, NORMAL, LOW, BACKGROUND"; final String actual = Utils.printEnumOptions(com.spectralogic.ds3client.models.Priority.values()); assertEquals(actual, expected); }
Source:
public EhcacheEntityResponse invoke(ClientDescriptor clientDescriptor, EhcacheEntityMessage message) { try { if (this.offHeapResourceIdentifiers.isEmpty()) { throw new ServerMisconfigurationException("Server started without any offheap resources defined." + " Check your server configuration and define at least one offheap resource."); } if (this.ehcacheStateService == null) { throw new ServerMisconfigurationException("Server failed to retrieve EhcacheStateService ."); } switch (message.getType()) { case LIFECYCLE_OP: return invokeLifeCycleOperation(clientDescriptor, (LifecycleMessage) message); case SERVER_STORE_OP: return invokeServerStoreOperation(clientDescriptor, (ServerStoreOpMessage) message); default: throw new IllegalMessageException("Unknown message : " + message); } } catch (ClusterException e) { return responseFactory.failure(e); } catch (Exception e) { LOGGER.error("Unexpected exception raised during operation: " + message, e); return responseFactory.failure(new InvalidOperationException(e)); } }

Target:
public EhcacheEntityResponse invoke(ClientDescriptor clientDescriptor, EhcacheEntityMessage message) { try { if (this.offHeapResourceIdentifiers.isEmpty()) { throw new ServerMisconfigurationException("Server started without any offheap resources defined." + " Check your server configuration and define at least one offheap resource."); } switch (message.getType()) { case LIFECYCLE_OP: return invokeLifeCycleOperation(clientDescriptor, (LifecycleMessage) message); case SERVER_STORE_OP: return invokeServerStoreOperation(clientDescriptor, (ServerStoreOpMessage) message); default: throw new IllegalMessageException("Unknown message : " + message); } } catch (ClusterException e) { return responseFactory.failure(e); } catch (Exception e) { LOGGER.error("Unexpected exception raised during operation: " + message, e); return responseFactory.failure(new InvalidOperationException(e)); } }
Source:
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.debug("Entered SSORestApiLogoutServlet"); String token = request.getParameter("token"); String scope = request.getParameter("scope"); Map<String, Object> revokeResponse = SSOOAuthServiceUtils.revoke(token, scope); String error = (String) revokeResponse.get("error"); if (StringUtils.isNotEmpty(error)) { log.error("Unable to logout user: {}", error); } try (OutputStream os = response.getOutputStream()) { ObjectMapper mapper = new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false) .enableDefaultTyping(ObjectMapper.DefaultTyping.OBJECT_AND_NON_CONCRETE); String jsonPayload = mapper.writeValueAsString(revokeResponse); response.setContentType("application/json"); byte[] jsonPayloadBytes = jsonPayload.getBytes(StandardCharsets.UTF_8.name()); response.setContentLength(jsonPayloadBytes.length); os.write(jsonPayloadBytes); log.trace("Sending json data {}", jsonPayload); } log.debug("Exiting SSORestApiLogoutServlet"); }

Target:
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.debug("Entered SSORestApiLogoutServlet"); String token = request.getParameter("token"); String scope = request.getParameter("scope"); Map<String, Object> revokeResponse = SSOOAuthServiceUtils.revoke(token, scope); String error = (String) revokeResponse.get("error"); if (StringUtils.isNotEmpty(error)) { log.error("Unable to logout user: {}", error); } try (OutputStream os = response.getOutputStream()) { String jsonPayload = new JsonObjectSerializer().serialize(revokeResponse); response.setContentType("application/json"); byte[] jsonPayloadBytes = jsonPayload.getBytes(StandardCharsets.UTF_8.name()); response.setContentLength(jsonPayloadBytes.length); os.write(jsonPayloadBytes); log.trace("Sending json data {}", jsonPayload); } log.debug("Exiting SSORestApiLogoutServlet"); }
Source:
public void waitForInitialData_resilientInCaseOfRetries() throws InterruptedException { SyncCredentials credentials = SyncCredentials.usernamePassword(UUID.randomUUID().toString(), "password", true); SyncUser user = SyncUser.login(credentials, Constants.AUTH_URL); final SyncConfiguration config = new SyncConfiguration.Builder(user, Constants.USER_REALM) .waitForInitialRemoteData() .build(); Random randomizer = new Random(); for (int i = 0; i < 10; i++) { Thread t = new Thread(new Runnable() { @Override public void run() { Realm realm = null; try { realm = Realm.getInstance(config); } catch (DownloadingRealmInterruptedException ignored) { assertFalse(new File(config.getPath()).exists()); } finally { if (realm != null) { realm.close(); Realm.deleteRealm(config); } } } }); t.start(); SystemClock.sleep(randomizer.nextInt(5)); t.interrupt(); t.join(); } }

Target:
public void waitForInitialData_resilientInCaseOfRetries() throws InterruptedException { SyncCredentials credentials = SyncCredentials.usernamePassword(UUID.randomUUID().toString(), "password", true); SyncUser user = SyncUser.login(credentials, Constants.AUTH_URL); final SyncConfiguration config = new SyncConfiguration.Builder(user, Constants.USER_REALM) .waitForInitialRemoteData() .build(); for (int i = 0; i < 10; i++) { Thread t = new Thread(new Runnable() { @Override public void run() { Realm realm = null; try { Thread.currentThread().interrupt(); realm = Realm.getInstance(config); } catch (DownloadingRealmInterruptedException ignored) { assertFalse(new File(config.getPath()).exists()); } finally { if (realm != null) { realm.close(); Realm.deleteRealm(config); } } } }); t.start(); t.join(); } }
Source:
private boolean hasNewIncomingFile(final Contentlet contentletIn) throws DotContentletStateException{ try { final String identifierStr = contentletIn.getIdentifier(); if(!UtilMethods.isSet(identifierStr)){ return true; } final Identifier identifier = APILocator.getIdentifierAPI().find(identifierStr); final File incomingFile = contentletIn.getBinary(FileAssetAPI.BINARY_FIELD); String incomingFileName = null != incomingFile ? incomingFile.getName() : StringPool.BLANK; if(UtilMethods.isSet(contentletIn.getStringProperty(FileAssetAPI.FILE_NAME_FIELD))){ incomingFileName = contentletIn.getStringProperty(FileAssetAPI.FILE_NAME_FIELD); } return !incomingFileName.equals(identifier.getAssetName()); } catch (Exception e) { throw new DotContentletStateException("Exception trying to determine if there's a new incoming file.",e); } }

Target:
private boolean hasNewIncomingFile(final Contentlet contentletIn) throws DotContentletStateException{ if(!contentletIn.isFileAsset()){ throw new IllegalArgumentException("Contentlet isn't a subtype of FileAsset"); } try { final String identifierStr = contentletIn.getIdentifier(); if(!UtilMethods.isSet(identifierStr)){ return true; } final Identifier identifier = APILocator.getIdentifierAPI().find(identifierStr); final File incomingFile = contentletIn.getBinary(FileAssetAPI.BINARY_FIELD); String incomingFileName = null != incomingFile ? incomingFile.getName() : StringPool.BLANK; if(UtilMethods.isSet(contentletIn.getStringProperty(FileAssetAPI.FILE_NAME_FIELD))){ incomingFileName = contentletIn.getStringProperty(FileAssetAPI.FILE_NAME_FIELD); } return !incomingFileName.equals(identifier.getAssetName()); } catch (Exception e) { throw new DotContentletStateException("Exception trying to determine if there's a new incoming file.",e); } }
Source:
public NettyServer(Responder responder, InetSocketAddress addr, final Consumer<SocketChannel> initializer) throws InterruptedException { this.responder = responder; ServerBootstrap bootstrap = new ServerBootstrap().group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { if (initializer != null) { initializer.accept(ch); } ch.pipeline().addLast("frameDecoder", new NettyFrameDecoder()) .addLast("frameEncoder", new NettyFrameEncoder()).addLast("handler", new NettyServerAvroHandler()); } }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true); serverChannel = bootstrap.bind(addr).sync().channel(); }

Target:
public NettyServer(Responder responder, InetSocketAddress addr, final Consumer<SocketChannel> initializer) throws InterruptedException { this(responder, addr, initializer, null, null, null, null); }
Source:
public void onMatch(RelOptRuleCall call) { final HiveFilter topFilter = call.rel(0); final HiveFilter bottomFilter = call.rel(1); RexBuilder rexBuilder = topFilter.getCluster().getRexBuilder(); RexProgram bottomProgram = createProgram(bottomFilter); RexProgram topProgram = createProgram(topFilter); RexProgram mergedProgram = RexProgramBuilder.mergePrograms( topProgram, bottomProgram, rexBuilder); RexNode newCondition = expandLocalRef(rexBuilder, mergedProgram.getCondition(), mergedProgram.getExprList()); final RelBuilder relBuilder = call.builder(); relBuilder.push(bottomFilter.getInput()) .filter(newCondition); call.transformTo(relBuilder.build()); }

Target:
public void onMatch(RelOptRuleCall call) { final HiveFilter topFilter = call.rel(0); final HiveFilter bottomFilter = call.rel(1); final RelBuilder relBuilder = call.builder(); relBuilder.push(bottomFilter.getInput()) .filter(bottomFilter.getCondition(), topFilter.getCondition()); call.transformTo(relBuilder.build()); }
Source:
void checkOperationChains(List<OperationChain> opChains) throws Exception { Map<PartitionId, Integer> partitionCount = new HashMap<>(); double blobsPut = 0; for (OperationChain opChain : opChains) { opChain.latch.await(); synchronized (opChain.testFutures) { for (TestFuture testFuture : opChain.testFutures) { testFuture.check(); } } if (opChain.blobId != null) { blobsPut++; PartitionId partitionId = new BlobId(opChain.blobId, clusterMap).getPartition(); int count = partitionCount.containsKey(partitionId) ? partitionCount.get(partitionId) : 0; partitionCount.put(partitionId, count + 1); } } double blobBalanceThreshold = 3.0 * Math.ceil(blobsPut / (double) clusterMap.getWritablePartitionIds().size()); for (Map.Entry<PartitionId, Integer> entry : partitionCount.entrySet()) { Assert.assertTrue("Number of blobs is " + entry.getValue() + " on partition: " + entry.getKey() + ", which is greater than the threshold of " + blobBalanceThreshold, entry.getValue() <= blobBalanceThreshold); } }

Target:
void checkOperationChains(List<OperationChain> opChains) throws Exception { Map<PartitionId, Integer> partitionCount = new HashMap<>(); double blobsPut = 0; for (OperationChain opChain : opChains) { if (!opChain.latch.await(AWAIT_TIMEOUT, TimeUnit.SECONDS)) { Assert.fail("Timeout waiting for operation chain " + opChain.chainId + " to finish."); } synchronized (opChain.testFutures) { for (TestFuture testFuture : opChain.testFutures) { testFuture.check(); } } if (opChain.blobId != null) { blobsPut++; PartitionId partitionId = new BlobId(opChain.blobId, clusterMap).getPartition(); int count = partitionCount.containsKey(partitionId) ? partitionCount.get(partitionId) : 0; partitionCount.put(partitionId, count + 1); } } double numPartitions = clusterMap.getWritablePartitionIds().size(); if (opChains.size() > numPartitions) { double blobBalanceThreshold = BALANCE_FACTOR * Math.ceil(blobsPut / numPartitions); for (Map.Entry<PartitionId, Integer> entry : partitionCount.entrySet()) { Assert.assertTrue("Number of blobs is " + entry.getValue() + " on partition: " + entry.getKey() + ", which is greater than the threshold of " + blobBalanceThreshold, entry.getValue() <= blobBalanceThreshold); } } }
Source:
protected void validateUserPasswordAndUpdateIfNeeded(String newPassword, UserVO user, String currentPassword) { if (newPassword == null) { s_logger.trace("No new password to update for user: " + user.getUuid()); return; } if (StringUtils.isBlank(newPassword)) { throw new InvalidParameterValueException("Password cannot be empty or blank."); } Account callingAccount = getCurrentCallingAccount(); boolean isRootAdminExecutingPasswordUpdate = callingAccount.getId() == Account.ACCOUNT_ID_SYSTEM || isRootAdmin(callingAccount.getId()); boolean isDomainAdmin = isDomainAdmin(callingAccount.getId()); boolean isAdmin = isDomainAdmin || isRootAdminExecutingPasswordUpdate; if (isAdmin) { s_logger.trace(String.format("Admin account [uuid=%s] executing password update for user [%s] ", callingAccount.getUuid(), user.getUuid())); } if (!isAdmin && StringUtils.isBlank(currentPassword)) { throw new InvalidParameterValueException("You must inform the current password when updating a user password."); } if (CollectionUtils.isEmpty(_userPasswordEncoders)) { throw new CloudRuntimeException("No user authenticators configured!"); } if (!isAdmin) { validateCurrentPassword(user, currentPassword); } UserAuthenticator userAuthenticator = _userPasswordEncoders.get(0); String newPasswordEncoded = userAuthenticator.encode(newPassword); user.setPassword(newPasswordEncoded); }

Target:
protected void validateUserPasswordAndUpdateIfNeeded(String newPassword, UserVO user, String currentPassword) { if (newPassword == null) { s_logger.trace("No new password to update for user: " + user.getUuid()); return; } if (StringUtils.isBlank(newPassword)) { throw new InvalidParameterValueException("Password cannot be empty or blank."); } Account callingAccount = getCurrentCallingAccount(); boolean isRootAdminExecutingPasswordUpdate = callingAccount.getId() == Account.ACCOUNT_ID_SYSTEM || isRootAdmin(callingAccount.getId()); boolean isDomainAdmin = isDomainAdmin(callingAccount.getId()); boolean isAdmin = isDomainAdmin || isRootAdminExecutingPasswordUpdate; if (isAdmin) { s_logger.trace(String.format("Admin account [uuid=%s] executing password update for user [%s] ", callingAccount.getUuid(), user.getUuid())); } if (!isAdmin && StringUtils.isBlank(currentPassword)) { throw new InvalidParameterValueException("To set a new password the current password must be provided."); } if (CollectionUtils.isEmpty(_userPasswordEncoders)) { throw new CloudRuntimeException("No user authenticators configured!"); } if (!isAdmin) { validateCurrentPassword(user, currentPassword); } UserAuthenticator userAuthenticator = _userPasswordEncoders.get(0); String newPasswordEncoded = userAuthenticator.encode(newPassword); user.setPassword(newPasswordEncoded); }
Source:
public Integer getTo() { if (to == null) { return null; } else return this.to; }

Target:
public Integer getTo() { return this.to; }
Source:
public void setUp() { assertUpdate("CREATE TABLE nation_partitioned(nationkey BIGINT, name VARCHAR, comment VARCHAR, regionkey BIGINT) WITH (partitioned_by = ARRAY['regionkey'])"); assertUpdate("CREATE TABLE orders(orderkey BIGINT, totalprice BIGINT, categoryid BIGINT) WITH (partitioned_by = ARRAY['categoryid'])"); assertUpdate("INSERT INTO nation_partitioned SELECT nationkey, name, comment, regionkey from tpch.tiny.nation", 25); }

Target:
public void setUp() { assertUpdate("CREATE TABLE nation_partitioned(nationkey BIGINT, name VARCHAR, comment VARCHAR, regionkey BIGINT) WITH (partitioned_by = ARRAY['regionkey'])"); assertUpdate("INSERT INTO nation_partitioned SELECT nationkey, name, comment, regionkey from tpch.tiny.nation", 25); assertUpdate("CREATE TABLE region(regionkey BIGINT, name VARCHAR, comment VARCHAR)"); assertUpdate("CREATE TABLE orders(orderkey BIGINT, custkey BIGINT, totalprice DOUBLE, orderdate DATE, " + "orderpriority VARCHAR, clerk VARCHAR, shippriority VARCHAR, comment VARCHAR, orderstatus VARCHAR)"); }
Source:
public boolean canPerform(ApprovalCategory.Id actionId, short level) { boolean projectLevel = projectControl.canPerform(actionId, level); Collection<RefRight> refRights = getRefRights(); final Set<AccountGroup.Id> groups = getCurrentUser().getEffectiveGroups(); int val = Integer.MIN_VALUE; for (final RefRight right : refRights) { if (right.getApprovalCategoryId().equals(actionId) && groups.contains(right.getAccountGroupId()) && matches(refName, right.getRefPattern())) { if (val < 0 && right.getMaxValue() > 0) { val = right.getMaxValue(); } else { val = Math.max(right.getMaxValue(), val); } } } boolean refLevel = (val >= level); return projectLevel || refLevel; }

Target:
public boolean canPerform(ApprovalCategory.Id actionId, short level) { boolean projectLevel = projectControl.canPerform(actionId, level); Collection<RefRight> refRights = getRefRights(); final Set<AccountGroup.Id> groups = getCurrentUser().getEffectiveGroups(); int val = Integer.MIN_VALUE; for (final RefRight right : refRights) { if (right.getApprovalCategoryId().equals(actionId) && groups.contains(right.getAccountGroupId()) && matches(refName, right.getRefPattern())) { if (val < 0 && right.getMaxValue() > 0) { val = right.getMaxValue(); } else { val = Math.max(right.getMaxValue(), val); } } } if (val == Integer.MIN_VALUE) { return val >= level; } else { return projectLevel; } }
Source:
private Map<String, Object> largeMessageConf() { Map<String, Object> conf = basicConf(); conf.put(Config.STORM_MESSAGING_NETTY_BUFFER_SIZE, 1024000); return conf; }

Target:
private Map<String, Object> largeMessageConf() { Map<String, Object> conf = basicConf(); conf.put(Config.STORM_MESSAGING_NETTY_BUFFER_SIZE, 102_400); return conf; }
Source:
public FeedbackSessionQuestionsBundle getFeedbackSessionQuestionsForInstructor( String feedbackSessionName, String courseId, String feedbackQuestionId, String userEmail) throws EntityDoesNotExistException { FeedbackSessionAttributes fsa = fsDb.getFeedbackSession( courseId, feedbackSessionName); if (fsa == null) { throw new EntityDoesNotExistException( ERROR_GET_NON_EXISTENT_SESSION); } InstructorAttributes instructor = instructorsLogic.getInstructorForEmail(courseId, userEmail); Map<FeedbackQuestionAttributes, List<FeedbackResponseAttributes>> bundle = new HashMap<FeedbackQuestionAttributes, List<FeedbackResponseAttributes>>(); Map<String, Map<String, String>> recipientList = new HashMap<String, Map<String, String>>(); FeedbackQuestionAttributes question = fqLogic.getFeedbackQuestion(feedbackQuestionId); InstructorAttributes instructorGiver = instructor; StudentAttributes studentGiver = null; updateBundleAndRecipientListWithResponsesForInstructor(courseId, userEmail, fsa, instructor, bundle, recipientList, question, instructorGiver, studentGiver); return new FeedbackSessionQuestionsBundle(fsa, bundle, recipientList); }

Target:
public FeedbackSessionQuestionsBundle getFeedbackSessionQuestionsForInstructor( String feedbackSessionName, String courseId, String feedbackQuestionId, String userEmail) throws EntityDoesNotExistException { FeedbackSessionAttributes fsa = fsDb.getFeedbackSession( courseId, feedbackSessionName); if (fsa == null) { throw new EntityDoesNotExistException(ERROR_NON_EXISTENT_FS_GET + courseId + "/" + feedbackSessionName); } InstructorAttributes instructor = instructorsLogic.getInstructorForEmail(courseId, userEmail); Map<FeedbackQuestionAttributes, List<FeedbackResponseAttributes>> bundle = new HashMap<FeedbackQuestionAttributes, List<FeedbackResponseAttributes>>(); Map<String, Map<String, String>> recipientList = new HashMap<String, Map<String, String>>(); FeedbackQuestionAttributes question = fqLogic.getFeedbackQuestion(feedbackQuestionId); InstructorAttributes instructorGiver = instructor; StudentAttributes studentGiver = null; updateBundleAndRecipientListWithResponsesForInstructor(courseId, userEmail, fsa, instructor, bundle, recipientList, question, instructorGiver, studentGiver); return new FeedbackSessionQuestionsBundle(fsa, bundle, recipientList); }
Source:
public GISModel trainModel(ObjectStream<Event> eventStream, int iterations, int cutoff) throws IOException { DataIndexer indexer = new OnePassDataIndexer(); Map<String, String> params = new HashMap<>(); params.put(GIS.ITERATIONS_PARAM, Integer.toString(iterations)); params.put(GIS.CUTOFF_PARAM, Integer.toString(cutoff)); indexer.init(params); indexer.index(eventStream); return trainModel(iterations, indexer, cutoff); }

Target:
public GISModel trainModel(ObjectStream<Event> eventStream, int iterations, int cutoff) throws IOException { DataIndexer indexer = new OnePassDataIndexer(); TrainingParameters indexingParameters = new TrainingParameters(); indexingParameters.put(GIS.CUTOFF_PARAM, Integer.toString(cutoff)); indexingParameters.put(GIS.ITERATIONS_PARAM, Integer.toString(iterations)); reportMap = new HashMap<>(); indexer.init(indexingParameters,reportMap); indexer.index(eventStream); return trainModel(iterations, indexer); }
Source:
public synchronized void stopIt() { stop = true; }

Target:
public void stopIt() { stop = true; }
Source:
public Template resolveTemplate(String templateName) { if (wikiBaseUrl != null) { int indexOf = templateName.indexOf(':'); if (indexOf == 0) { templateName = templateName.substring(1); } else if (indexOf == -1) { templateName = "Template:" + templateName; } URL url = computeRawUrl(templateName); if (url != null) { try { Reader input = createInputReader(url); try { String content = readFully(input); Template template = new Template(); String basicName = templateName.toLowerCase().startsWith("template:") ? templateName.substring(templateName.lastIndexOf(':') + 1) : templateName; template.setName(basicName); template.setTemplateMarkup(content); return template; } finally { input.close(); } } catch (final IOException e) { final String message = MessageFormat.format("Cannot read from {0}: {1}", url, e.getMessage()); Logger.getLogger(WikiTemplateResolver.class.getName()).log(Level.WARNING, message, e); } } } return null; }

Target:
public Template resolveTemplate(String templateName) { if (wikiBaseUrl != null) { int indexOf = templateName.indexOf(':'); if (indexOf == 0) { templateName = templateName.substring(1); } else if (indexOf == -1) { templateName = "Template:" + templateName; } URL url = computeRawUrl(templateName); if (url != null) { try { String content = readContent(url); Template template = new Template(); String basicName = templateName.toLowerCase().startsWith("template:") ? templateName.substring(templateName.lastIndexOf(':') + 1) : templateName; template.setName(basicName); template.setTemplateMarkup(content); return template; } catch (final IOException e) { final String message = MessageFormat.format("Cannot read from {0}: {1}", url, e.getMessage()); Logger.getLogger(WikiTemplateResolver.class.getName()).log(Level.WARNING, message, e); } } } return null; }
Source:
public void init() { Assert.hasText(nextUri, "nextUri cannot be null or empty."); Assert.hasText(logoutUri, "logoutUri cannot be null or empty."); Assert.hasText(resendVerificationUri, "resendVerificationUri cannot be null or empty."); Assert.notNull(client, "client cannot be null."); Assert.notNull(eventPublisher, "eventPublisher cannot be null."); }

Target:
public void init() { Assert.hasText(nextUri, "nextUri cannot be null or empty."); Assert.hasText(logoutUri, "logoutUri cannot be null or empty."); Assert.hasText(sendVerificationEmailUri, "sendVerificationEmailUri cannot be null or empty."); Assert.notNull(client, "client cannot be null."); Assert.notNull(eventPublisher, "eventPublisher cannot be null."); }
Source:
protected void populateElements(Object inputElement) { final Object[] convertedInputElement = ((List<?>) inputElement).toArray(); for (int i = 0; i < convertedInputElement.length; i++) { if (convertedInputElement[i] instanceof Variable) { final Variable variable = (Variable) convertedInputElement[i]; final IPath path = variable.getPath().makeAbsolute(); variable.setPath(path); registerElement(path, convertedInputElement[i]); } } setShowRoot(false); for (final IPath additionalPath : fAdditionalPaths) { registerPath(additionalPath); } }

Target:
protected void populateElements(Object inputElement) { if (inputElement instanceof List<?>) { final Object[] convertedInputElement = ((List<?>) inputElement).toArray(); for (int i = 0; i < convertedInputElement.length; i++) { if (convertedInputElement[i] instanceof Variable) { final Variable variable = (Variable) convertedInputElement[i]; final IPath path = variable.getPath().makeAbsolute(); variable.setPath(path); registerElement(path, convertedInputElement[i]); } } } setShowRoot(false); for (final IPath additionalPath : fAdditionalPaths) { registerPath(additionalPath); } }
Source:
public List<Map<String, String>> taskConfigs(int maxTasks) { String query = config.getString(JdbcSourceConnectorConfig.QUERY_CONFIG); List<Map<String, String>> taskConfigs; if (!query.isEmpty()) { taskConfigs = new ArrayList<>(1); Map<String, String> taskProps = new HashMap<>(configProperties); taskProps.put(JdbcSourceTaskConfig.TABLES_CONFIG, ""); taskConfigs.add(taskProps); } else { List<String> currentTables = tableMonitorThread.tables(); if (currentTables.isEmpty()) { taskConfigs = new ArrayList<>(); log.warn("No tasks are running because no tables were found"); } else { int numGroups = Math.min(currentTables.size(), maxTasks); List<List<String>> tablesGrouped = ConnectorUtils.groupPartitions(currentTables, numGroups); taskConfigs = new ArrayList<>(tablesGrouped.size()); for (List<String> taskTables : tablesGrouped) { Map<String, String> taskProps = new HashMap<>(configProperties); taskProps.put(JdbcSourceTaskConfig.TABLES_CONFIG, StringUtils.join(taskTables, ",")); taskConfigs.add(taskProps); } } } return taskConfigs; }

Target:
public List<Map<String, String>> taskConfigs(int maxTasks) { String query = config.getString(JdbcSourceConnectorConfig.QUERY_CONFIG); List<Map<String, String>> taskConfigs; if (!query.isEmpty()) { Map<String, String> taskProps = new HashMap<>(configProperties); taskProps.put(JdbcSourceTaskConfig.TABLES_CONFIG, ""); taskConfigs = Collections.singletonList(taskProps); } else { List<String> currentTables = tableMonitorThread.tables(); if (currentTables.isEmpty()) { taskConfigs = Collections.emptyList(); log.warn("No tasks will be run because no tables were found"); } else { int numGroups = Math.min(currentTables.size(), maxTasks); List<List<String>> tablesGrouped = ConnectorUtils.groupPartitions(currentTables, numGroups); taskConfigs = new ArrayList<>(tablesGrouped.size()); for (List<String> taskTables : tablesGrouped) { Map<String, String> taskProps = new HashMap<>(configProperties); taskProps.put(JdbcSourceTaskConfig.TABLES_CONFIG, StringUtils.join(taskTables, ",")); taskConfigs.add(taskProps); } } } return taskConfigs; }