auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void apply( IndexUpdates updates, IndexUpdateMode updateMode ) throws IOException, IndexEntryConflictException { try ( IndexUpdaterMap updaterMap = indexMapRef.createIndexUpdaterMap( updateMode ) ) { for ( NodeUpdates update : updates ) { for ( IndexEntryUpdate indexUpdate : update.forIndexes( updaterMap.descriptors(), ( nodeId, propertyId ) -> { try { return storeView.getProperty( nodeId, propertyId ).value(); } catch ( EntityNotFoundException e ) { return null; } catch ( PropertyNotFoundException e ) { return null; } } ) ) { updaterMap.getUpdater( indexUpdate.descriptor() ).process( indexUpdate ); } } } }

Target:
private void apply( IndexUpdates updates, IndexUpdateMode updateMode ) throws IOException, IndexEntryConflictException { try ( IndexUpdaterMap updaterMap = indexMapRef.createIndexUpdaterMap( updateMode ) ) { for ( NodeUpdates update : updates ) { for ( IndexEntryUpdate<IndexUpdaterMap.IndexUpdaterWithSchema> indexUpdate : update.forIndexKeys( updaterMap.updaters(), storeView ) ) { indexUpdate.indexKey().process( indexUpdate ); } } } }
Source:
public List<ExecutionIdentifier> getAllExecutions(TenantIdentifier tenant, JobIdentifier job) throws IllegalStateException { final TenantContext tenantContext = _tenantContextFactory.getContext(tenant); final RepositoryFolder resultFolder = tenantContext.getResultFolder(); final List<RepositoryFile> files = resultFolder.getFiles(job.getName(), FileFilters.ANALYSIS_EXECUTION_LOG_XML .getExtension()); final List<ExecutionIdentifier> executionIdentifiers = CollectionUtils.map(files, new Func<RepositoryFile, ExecutionIdentifier>() { @Override public ExecutionIdentifier eval(final RepositoryFile file) { try { ExecutionIdentifier result = file.readFile(new Func<InputStream, ExecutionIdentifier>() { @Override public ExecutionIdentifier eval(InputStream in) { return SaxExecutionIdentifierReader.read(in, file.getQualifiedPath()); } }); return result; } catch (Exception e) { logger.warn("The file " + file.getQualifiedPath() + " could not be read or parsed correctly" + e); return new ExecutionIdentifier("Execution failed for " + FilenameUtils.getBaseName(file .getQualifiedPath())); } } }); Collections.sort(executionIdentifiers); return executionIdentifiers; }

Target:
public List<ExecutionIdentifier> getAllExecutions(TenantIdentifier tenant, JobIdentifier job) throws IllegalStateException { final TenantContext tenantContext = _tenantContextFactory.getContext(tenant); final RepositoryFolder resultFolder = tenantContext.getResultFolder(); final List<RepositoryFile> files = resultFolder.getFiles(job.getName(), FileFilters.ANALYSIS_EXECUTION_LOG_XML .getExtension()); final List<ExecutionIdentifier> executionIdentifiers = CollectionUtils.map(files, new Func<RepositoryFile, ExecutionIdentifier>() { @Override public ExecutionIdentifier eval(final RepositoryFile file) { try { final ExecutionIdentifier result = file.readFile( new Func<InputStream, ExecutionIdentifier>() { @Override public ExecutionIdentifier eval(InputStream in) { return SaxExecutionIdentifierReader.read(in, file.getQualifiedPath()); } }); return result; } catch (Exception e) { logger.warn("The file " + file.getQualifiedPath() + " could not be read or parsed correctly " + e); return new ExecutionIdentifier("Execution failed for " + FilenameUtils.getBaseName(file .getQualifiedPath())); } } }); Collections.sort(executionIdentifiers); return executionIdentifiers; }
Source:
public void testFindFunctionExtensionTestCase1() throws InterruptedException { log.info("FindFunctionExtension TestCase with invalid number of arguments"); SiddhiManager siddhiManager = new SiddhiManager(); String inStreamDefinition = "define stream inputStream (symbol string, price long, regex string);"; String query = ("@info(name = 'query1') " + "from inputStream " + "select symbol , regex:find(regex) as aboutWSO2 " + "insert into outputStream;"); ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime (inStreamDefinition + query); executionPlanRuntime.start(); executionPlanRuntime.shutdown(); }

Target:
public void testFindFunctionExtensionTestCase1() throws InterruptedException { log.info("FindFunctionExtension TestCase with invalid number of arguments"); SiddhiManager siddhiManager = new SiddhiManager(); String inStreamDefinition = "define stream inputStream (symbol string, price long, regex string);"; String query = ("@info(name = 'query1') " + "from inputStream " + "select symbol , regex:find(regex) as aboutWSO2 " + "insert into outputStream;"); siddhiManager.createExecutionPlanRuntime(inStreamDefinition + query); }
Source:
protected void executeVmCommand() { final VmNetworkInterface anInterface = getInterface(); final VmStatic vmStatic = getVmStaticDAO().get(getParameters().getVmId()); addCustomValue("InterfaceType", (VmInterfaceType.forValue(anInterface.getType()).getDescription()).toString()); this.setVmName(vmStatic.getName()); boolean succeeded = false; boolean macAddedToPool = false; final String macAddress = getMacAddress(); final MacPoolManagerStrategy pool = getMacPoolManager(); try { if (StringUtils.isEmpty(macAddress)) { anInterface.setMacAddress(pool.allocateNewMac()); macAddedToPool = true; } else { macAddedToPool = addMacToPool(macAddress, getMacPoolManager()); } anInterface.setSpeed(VmInterfaceType.forValue(anInterface.getType()).getSpeed()); anInterface.setId(Guid.newGuid()); anInterface.setVmId(getParameters().getVmId()); TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { addInterfaceToDb(anInterface); addInterfaceDeviceToDb(); getCompensationContext().stateChanged(); return null; } }); if (anInterface.isPlugged()) { succeeded = activateOrDeactivateNewNic(anInterface, PlugAction.PLUG); } else { succeeded = true; } } finally { setSucceeded(succeeded); if (macAddedToPool && !succeeded) { pool.freeMac(macAddress); } } }

Target:
protected void executeVmCommand() { final VmStatic VM = getVmStaticDAO().get(getParameters().getVmId()); addCustomValue("InterfaceType", (VmInterfaceType.forValue(getInterface().getType()).getDescription()).toString()); this.setVmName(VM.getName()); boolean succeeded = false; boolean macAddedToPool = false; try { if (StringUtils.isEmpty(getMacAddress())) { getInterface().setMacAddress(getMacPool().allocateNewMac()); macAddedToPool = true; } else { macAddedToPool = addMacToPool(getMacAddress()); } getInterface().setSpeed(VmInterfaceType.forValue(getInterface().getType()).getSpeed()); getInterface().setId(Guid.newGuid()); getInterface().setVmId(getParameters().getVmId()); TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { addInterfaceToDb(getInterface()); addInterfaceDeviceToDb(); getCompensationContext().stateChanged(); return null; } }); if (getInterface().isPlugged()) { succeeded = activateOrDeactivateNewNic(getInterface(), PlugAction.PLUG); } else { succeeded = true; } } finally { setSucceeded(succeeded); if (macAddedToPool && !succeeded) { getMacPool().freeMac(getMacAddress()); } } }
Source:
private Future<AggregateResults> createBattleCalcWorker( final GamePlayer attacker, final GamePlayer defender, final Territory location, final Collection<Unit> attacking, final Collection<Unit> defending, final Collection<Unit> bombarding, final Collection<TerritoryEffect> territoryEffects, final int runs) { BattleCalculator calculator = new BattleCalculator(); calculator.setKeepOneAttackingLandUnit(keepOneAttackingLandUnit); calculator.setAmphibious(amphibious); calculator.setRetreatAfterRound(retreatAfterRound); calculator.setRetreatAfterXUnitsLeft(retreatAfterXUnitsLeft); calculator.setRetreatWhenOnlyAirLeft(retreatWhenOnlyAirLeft); calculator.setAttackerOrderOfLosses(attackerOrderOfLosses); calculator.setDefenderOrderOfLosses(defenderOrderOfLosses); calculators.add(calculator); return executor.submit( () -> { try { calculator.setGameData(IoUtils.readFromMemory(bytes, GameDataManager::loadGame)); return calculator.calculate( attacker, defender, location, attacking, defending, bombarding, territoryEffects, runs); } catch (final IOException e) { throw new RuntimeException("Failed to deserialize", e); } finally { calculators.remove(calculator); } }); }

Target:
private Future<AggregateResults> createBattleCalcWorker( final GamePlayer attacker, final GamePlayer defender, final Territory location, final Collection<Unit> attacking, final Collection<Unit> defending, final Collection<Unit> bombarding, final Collection<TerritoryEffect> territoryEffects, final int runs) { final BattleCalculator calculator = new BattleCalculator(); calculator.setKeepOneAttackingLandUnit(keepOneAttackingLandUnit); calculator.setAmphibious(amphibious); calculator.setRetreatAfterRound(retreatAfterRound); calculator.setRetreatAfterXUnitsLeft(retreatAfterXUnitsLeft); calculator.setRetreatWhenOnlyAirLeft(retreatWhenOnlyAirLeft); calculator.setAttackerOrderOfLosses(attackerOrderOfLosses); calculator.setDefenderOrderOfLosses(defenderOrderOfLosses); calculators.add(calculator); return executor.submit( () -> { try { calculator.setGameData(IoUtils.readFromMemory(bytes, GameDataManager::loadGame)); return calculator.calculate( attacker, defender, location, attacking, defending, bombarding, territoryEffects, runs); } catch (final IOException e) { throw new RuntimeException("Failed to deserialize", e); } finally { calculators.remove(calculator); } }); }
Source:
private boolean updateHost() { if (getVm().getStatus() == VMStatus.Up) { setVdsId(getVm().getRunOnVds().getValue()); } if (getRequiredAction() != null){ switch (getRequiredAction()) { case PLUG: { return activateOrDeactivateNic(getInterface().getId(), PlugAction.PLUG); } case UNPLUG: { return activateOrDeactivateNic(getInterface().getId(), PlugAction.UNPLUG); } case UPDATE_VM_DEVICE: { runVdsCommand(VDSCommandType.UpdateVmInterface, new VmNicDeviceVDSParameters(getVdsId(), getVm(), getVmNetworkInterfaceDao().get(getInterface().getId()), oldVmDevice)); } } } return true; }

Target:
private boolean updateHost() { if (getVm().getStatus() == VMStatus.Up) { setVdsId(getVm().getRunOnVds().getValue()); } if (getRequiredAction() != null){ switch (getRequiredAction()) { case PLUG: { return activateOrDeactivateNic(getInterface().getId(), PlugAction.PLUG); } case UNPLUG: { return activateOrDeactivateNic(getInterface().getId(), PlugAction.UNPLUG); } case UPDATE_VM_DEVICE: { runVdsCommand(VDSCommandType.UpdateVmInterface, new VmNicDeviceVDSParameters(getVdsId(), getVm(), getVmNetworkInterfaceDao().get(getInterface().getId()), oldVmDevice)); break; } } } return true; }
Source:
Map<String, Long> getExternalResourcesUnSafe(Object resource) { if (!isYarnResourceTypesAvailable) { return Collections.emptyMap(); } final Map<String, Long> externalResources = new HashMap<>(); final Object[] externalResourcesInfo; try { externalResourcesInfo = (Object[]) resourceGetResourcesMethod.invoke(resource); for (int i = 2; i < externalResourcesInfo.length; i++) { final String name = (String) resourceInformationGetNameMethod.invoke(externalResourcesInfo[i]); final long value = (long) resourceInformationGetValueMethod.invoke(externalResourcesInfo[i]); externalResources.put(name, value); } } catch (Exception e) { LOG.error("Error in getting the external resource.", e); return Collections.emptyMap(); } return externalResources; }

Target:
Map<String, Long> getExternalResourcesUnSafe(Object resource) { if (!isYarnResourceTypesAvailable) { return Collections.emptyMap(); } final Map<String, Long> externalResources = new HashMap<>(); final Object[] externalResourcesInfo; try { externalResourcesInfo = (Object[]) resourceGetResourcesMethod.invoke(resource); for (int i = 2; i < externalResourcesInfo.length; i++) { final String name = (String) resourceInformationGetNameMethod.invoke(externalResourcesInfo[i]); final long value = (long) resourceInformationGetValueMethod.invoke(externalResourcesInfo[i]); externalResources.put(name, value); } } catch (Exception e) { LOG.warn("Could not obtain the external resources supported by the given Resource.", e); return Collections.emptyMap(); } return externalResources; }
Source:
public void launch() throws IOException, InterruptedException { this.action("start-server"); }

Target:
public void launch() throws IOException, InterruptedException { executeAdb("start-server"); }
Source:
public void onNext(final EvictionItem evictionItem) { eurekaRegistry.unregister(evictionItem.getInstanceInfo(), evictionItem.getSource()) .doOnCompleted(new Action0() { @Override public void call() { logger.info("Successfully evicted registry entry {}/{}", evictionItem.getSource(), evictionItem.getInstanceInfo().getId()); } }) .retry(2) .subscribe(); if (allowedToEvict()) { resume(); } else { selfPreservation.set(true); metrics.setSelfPreservation(true); logger.info("Entering self preserv4ation mode"); } }

Target:
public void onNext(final EvictionItem evictionItem) { eurekaRegistry.unregister(evictionItem.getInstanceInfo(), evictionItem.getSource()) .doOnCompleted(new Action0() { @Override public void call() { logger.info("Successfully evicted registry entry {}/{}", evictionItem.getSource(), evictionItem.getInstanceInfo().getId()); } }) .retry(2) .subscribe(); if (allowedToEvict()) { resume(); } else { selfPreservation.set(true); metrics.setSelfPreservation(true); logger.info("Entering self preservation mode"); } }
Source:
private void setupView(@NonNull AlertDialog dialog) { if (getArguments() != null && getArguments().getString(TITLE) != null) { dialog.setTitle(getArguments().getString(TITLE)); } if (getArguments() != null && getArguments().getString(MESSAGE) != null) { ((TextView) dialogView.findViewById(R.id.message)).setText(getArguments().getString(MESSAGE)); } if (getArguments() != null && Objects.equals(getArguments().getBoolean(CANCELABLE), false)) { dialog.setCancelable(false); } if (getCancelButtonText() != null) { dialog.setButton(BUTTON_NEGATIVE, getCancelButtonText(), (dialog1, which) -> { dismiss(); getCancellable().cancel(); }); } }

Target:
private void setupView(@NonNull AlertDialog dialog) { if (getArguments() != null && getArguments().getString(TITLE) != null) { dialog.setTitle(getArguments().getString(TITLE)); } if (getArguments() != null && getArguments().getString(MESSAGE) != null) { ((TextView) dialogView.findViewById(R.id.message)).setText(getArguments().getString(MESSAGE)); } if (getArguments() != null) { setCancelable(getArguments().getBoolean(CANCELABLE)); } if (getCancelButtonText() != null) { dialog.setButton(BUTTON_NEGATIVE, getCancelButtonText(), (dialog1, which) -> { dismiss(); getCancellable().cancel(); }); } }
Source:
public void testConfigurationWithNoDataSourceAndNoTransactionManager() throws Exception { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(BatchConfigurationWithNoDataSourceAndNoTransactionManager.class); Assert.assertTrue(applicationContext.containsBean("transactionManager")); PlatformTransactionManager platformTransactionManager = applicationContext.getBean(PlatformTransactionManager.class); Object targetObject = AopTestUtils.getTargetObject(platformTransactionManager); Assert.assertTrue(targetObject instanceof ResourcelessTransactionManager); Assert.assertSame(getTransactionManagerSetOnJobRepository(applicationContext.getBean(JobRepository.class)), targetObject); }

Target:
public void testConfigurationWithNoDataSourceAndNoTransactionManager() throws Exception { ApplicationContext applicationContext = new AnnotationConfigApplicationContext(BatchConfigurationWithNoDataSourceAndNoTransactionManager.class); Assert.assertTrue(applicationContext.containsBean("transactionManager")); PlatformTransactionManager platformTransactionManager = applicationContext.getBean(PlatformTransactionManager.class); Object targetObject = AopTestUtils.getTargetObject(platformTransactionManager); Assert.assertTrue(targetObject instanceof ResourcelessTransactionManager); Assert.assertSame(getTransactionManagerSetOnJobRepository(applicationContext.getBean(JobRepository.class)), targetObject); }
Source:
public Object apply(ChangeResource req, Input input) throws Exception { ChangeControl control = req.getControl(); Change change = req.getChange(); if (!control.canAddPatchSet()) { throw new NoSuchChangeException(change.getId()); } else if (change.getStatus() != Status.MERGED) { throw new ResourceConflictException("change is " + status(change)); } final String message = Strings.emptyToNull(input.message); final PatchSet.Id patchSetId = change.currentPatchSetId(); final ReviewDb db = dbProvider.get(); IdentifiedUser currentUser = (IdentifiedUser) control.getCurrentUser(); Change.Id revertedChangeId = ChangeUtil.revert(patchSetId, currentUser, message, db, revertedSenderFactory, hooks, gitManager, patchSetInfoFactory, replication, myIdent); return json.format(revertedChangeId); }

Target:
public Object apply(ChangeResource req, Input input) throws Exception { ChangeControl control = req.getControl(); Change change = req.getChange(); if (!control.canAddPatchSet()) { throw new AuthException("revert not permitted"); } else if (change.getStatus() != Status.MERGED) { throw new ResourceConflictException("change is " + status(change)); } Change.Id revertedChangeId = ChangeUtil.revert( change.currentPatchSetId(), (IdentifiedUser) control.getCurrentUser(), Strings.emptyToNull(input.message), dbProvider.get(), revertedSenderFactory, hooks, gitManager, patchSetInfoFactory, replication, myIdent); return json.format(revertedChangeId); }
Source:
protected Integer parseNodeInteger(XmlNode sourceNode, String string, Integer defaultValue) { XmlNode subNode = selectSingleNode(sourceNode, string, _xmlNS); if (subNode != null && subNode.innerText != null) { Integer ret = Integer.parseInt(subNode.innerText); return ret; } return defaultValue; }

Target:
protected Integer parseNodeInteger(XmlNode sourceNode, String string, Integer defaultValue) { XmlNode subNode = selectSingleNode(sourceNode, string, _xmlNS); if (subNode != null && subNode.innerText != null) { return Integer.parseInt(subNode.innerText); } return defaultValue; }
Source:
private static Map<Integer, ColumnStatistics> getRowGroupStatistics(OrcType rootStructType, Map<StreamId, List<RowGroupIndex>> columnIndexes, int rowGroup) { requireNonNull(rootStructType, "rootStructType is null"); checkArgument(rootStructType.getOrcTypeKind() == OrcTypeKind.STRUCT); requireNonNull(columnIndexes, "columnIndexes is null"); checkArgument(rowGroup >= 0, "rowGroup is negative"); Map<Integer, List<ColumnStatistics>> columnStatisticsByColumn = new HashMap<>(); for (Entry<StreamId, List<RowGroupIndex>> entry : columnIndexes.entrySet()) { columnStatisticsByColumn.computeIfAbsent(entry.getKey().getColumn(), (key) -> new ArrayList<>()) .add(entry.getValue().get(rowGroup).getColumnStatistics()); } ImmutableMap.Builder<Integer, ColumnStatistics> statistics = ImmutableMap.builder(); for (int ordinal = 0; ordinal < rootStructType.getFieldCount(); ordinal++) { List<ColumnStatistics> columnStatistics = columnStatisticsByColumn.get(rootStructType.getFieldTypeIndex(ordinal)); if (columnStatistics != null) { statistics.put(ordinal, ColumnStatistics.mergeColumnStatistics(columnStatistics)); } } return statistics.build(); }

Target:
private static Map<Integer, ColumnStatistics> getRowGroupStatistics(OrcType rootStructType, Map<StreamId, List<RowGroupIndex>> columnIndexes, int rowGroup) { requireNonNull(rootStructType, "rootStructType is null"); checkArgument(rootStructType.getOrcTypeKind() == OrcTypeKind.STRUCT); requireNonNull(columnIndexes, "columnIndexes is null"); checkArgument(rowGroup >= 0, "rowGroup is negative"); Map<Integer, List<ColumnStatistics>> columnStatisticsByColumn = new HashMap<>(); for (Entry<StreamId, List<RowGroupIndex>> entry : columnIndexes.entrySet()) { columnStatisticsByColumn.computeIfAbsent(entry.getKey().getColumn(), key -> new ArrayList<>()) .add(entry.getValue().get(rowGroup).getColumnStatistics()); } ImmutableMap.Builder<Integer, ColumnStatistics> statistics = ImmutableMap.builder(); for (int ordinal = 0; ordinal < rootStructType.getFieldCount(); ordinal++) { List<ColumnStatistics> columnStatistics = columnStatisticsByColumn.get(rootStructType.getFieldTypeIndex(ordinal)); if (columnStatistics != null) { statistics.put(ordinal, ColumnStatistics.mergeColumnStatistics(columnStatistics)); } } return statistics.build(); }
Source:
private void executePostsendScript(ExtendedEmailPublisherContext context, MimeMessage msg, Session session, Transport transport) throws RuntimeException { String script = ContentBuilder.transformText(postsendScript, context, getRuntimeMacros(context)); if (StringUtils.isNotBlank(script)) { debug(context.getListener().getLogger(), "Executing post-send script"); ClassLoader cl = Jenkins.getInstance().getPluginManager().uberClassLoader; ScriptSandbox sandbox = null; CompilerConfiguration cc = new CompilerConfiguration(); cc.setScriptBaseClass(EmailExtScript.class.getCanonicalName()); cc.addCompilationCustomizers(new ImportCustomizer().addStarImports( "jenkins", "jenkins.model", "hudson", "hudson.model")); expandClasspath(context, cc); if (getDescriptor().isSecurityEnabled()) { debug(context.getListener().getLogger(), "Setting up sandbox for post-send script"); cc.addCompilationCustomizers(new SandboxTransformer()); sandbox = new ScriptSandbox(); } Binding binding = new Binding(); binding.setVariable("build", context.getBuild()); binding.setVariable("msg", msg); binding.setVariable("props", session.getProperties()); binding.setVariable("transport", transport); binding.setVariable("listener", context.getListener()); binding.setVariable("logger", context.getListener().getLogger()); binding.setVariable("trigger", context.getTrigger()); binding.setVariable("triggered", ImmutableMultimap.copyOf(context.getTriggered())); GroovyShell shell = new GroovyShell(cl, binding, cc); StringWriter out = new StringWriter(); PrintWriter pw = new PrintWriter(out); if (sandbox != null) { sandbox.register(); } try { shell.evaluate(script); } catch (SecurityException e) { context.getListener().getLogger().println("Post-send script tried to access secured objects: " + e.getMessage()); } catch (Throwable t) { t.printStackTrace(pw); context.getListener().getLogger().println(out.toString()); } debug(context.getListener().getLogger(), out.toString()); } }

Target:
private void executePostsendScript(ExtendedEmailPublisherContext context, MimeMessage msg, Session session, Transport transport) throws RuntimeException { executeScript(postsendScript, "post-send", context, msg, session, transport); }
Source:
private Sample save(Sample sample) throws IOException { if (sample.isDiscarded()) { sample.setVolume(0.0); } try { Long newId = sample.getId(); if (newId == Sample.UNSAVED_ID) { newId = sampleDao.addSample(sample); } else { sampleDao.update(sample); } if (!hasTemporaryAlias(sample)) { validateAlias(sample); } Sample created = sampleDao.getSample(newId); boolean needsUpdate = false; if (hasTemporaryName(sample)) { created.setName(namingScheme.generateNameFor(created)); if (autoGenerateIdBarcodes && isStringEmptyOrNull(created.getIdentificationBarcode())) generateAndSetIdBarcode(created); needsUpdate = true; } if (hasTemporaryAlias(sample)) { String generatedAlias = namingScheme.generateSampleAlias(created); validateAliasUniqueness(generatedAlias); created.setAlias(generatedAlias); needsUpdate = true; } if (isStringBlankOrNull(created.getAlias())) { created.setAlias(created.getName()); needsUpdate = true; } if (needsUpdate) { validateAlias(created); sampleDao.update(created); } return created; } catch (MisoNamingException e) { throw new IllegalArgumentException("Name generator failed to generate a valid name", e); } catch (ConstraintViolationException e) { throw new ConstraintViolationException(e.getMessage() + " " + ExceptionUtils.getRootCauseMessage(e), e.getSQLException(), e.getConstraintName()); } catch (SQLException e) { throw new IOException(e); } }

Target:
private Sample save(Sample sample) throws IOException { if (sample.isDiscarded()) { sample.setVolume(0.0); } try { Long newId = sample.getId(); if (!hasTemporaryAlias(sample)) { validateAlias(sample); } if (newId == Sample.UNSAVED_ID) { newId = sampleDao.addSample(sample); } else { sampleDao.update(sample); } Sample created = sampleDao.getSample(newId); boolean needsUpdate = false; if (hasTemporaryName(sample)) { created.setName(namingScheme.generateNameFor(created)); validateNameOrThrow(created, namingScheme); needsUpdate = true; } if (hasTemporaryAlias(sample)) { String generatedAlias = namingScheme.generateSampleAlias(created); validateAliasUniqueness(generatedAlias); created.setAlias(generatedAlias); validateAlias(created); needsUpdate = true; } if (autoGenerateIdBarcodes && isStringEmptyOrNull(created.getIdentificationBarcode())) { generateAndSetIdBarcode(created); needsUpdate = true; } if (needsUpdate) { sampleDao.update(created); } return created; } catch (MisoNamingException e) { throw new IllegalArgumentException("Name generator failed to generate a valid name", e); } catch (ConstraintViolationException e) { throw new ConstraintViolationException(e.getMessage() + " " + ExceptionUtils.getRootCauseMessage(e), e.getSQLException(), e.getConstraintName()); } catch (SQLException e) { throw new IOException(e); } }
Source:
public void deviceOutputSettingsForLightValues(final Map<String, String> settings) throws Throwable { String deviceIdentification = getString(settings, Keys.KEY_DEVICE_IDENTIFICATION, Defaults.DEFAULT_DEVICE_IDENTIFICATION); Ssld device = this.ssldRepository.findByDeviceIdentification(deviceIdentification); String[] lightValues = getString(settings, Keys.KEY_LIGHTVALUES, Defaults.DEFAULT_DEVICE_IDENTIFICATION).split(Keys.SEPARATOR_SEMICOLON); String[] deviceOutputSettings = getString(settings, Keys.DEVICE_OUTPUT_SETTINGS, "").split(Keys.SEPARATOR_SEMICOLON); List<DeviceOutputSetting> outputSettings = new ArrayList<>(); for (int i = 0; i < lightValues.length;i++) { final String[] lightValueParts = lightValues[i].split(Keys.SEPARATOR); final String[] deviceOutputSettingsPart = deviceOutputSettings[i].split(Keys.SEPARATOR); DeviceOutputSetting deviceOutputSettingsForLightValue = new DeviceOutputSetting( Integer.parseInt(deviceOutputSettingsPart[0]), Integer.parseInt(lightValueParts[0]), Enum.valueOf(RelayType.class, deviceOutputSettingsPart[1]), deviceOutputSettingsPart[2]); outputSettings.add(deviceOutputSettingsForLightValue); } device.updateOutputSettings(outputSettings); this.ssldRepository.save(device); }

Target:
public void deviceOutputSettingsForLightValues(final Map<String, String> settings) throws Throwable { final String deviceIdentification = getString(settings, Keys.KEY_DEVICE_IDENTIFICATION, Defaults.DEFAULT_DEVICE_IDENTIFICATION); final Ssld device = this.ssldRepository.findByDeviceIdentification(deviceIdentification); final String[] lightValues = getString(settings, Keys.KEY_LIGHTVALUES, Defaults.DEFAULT_DEVICE_IDENTIFICATION) .split(Keys.SEPARATOR_SEMICOLON); final String[] deviceOutputSettings = getString(settings, Keys.DEVICE_OUTPUT_SETTINGS, "") .split(Keys.SEPARATOR_SEMICOLON); final List<DeviceOutputSetting> outputSettings = new ArrayList<>(); for (int i = 0; i < lightValues.length; i++) { final String[] lightValueParts = lightValues[i].split(Keys.SEPARATOR_COMMA); final String[] deviceOutputSettingsPart = deviceOutputSettings[i].split(Keys.SEPARATOR_COMMA); final DeviceOutputSetting deviceOutputSettingsForLightValue = new DeviceOutputSetting( Integer.parseInt(deviceOutputSettingsPart[0]), Integer.parseInt(lightValueParts[0]), Enum.valueOf(RelayType.class, deviceOutputSettingsPart[1]), deviceOutputSettingsPart[2]); outputSettings.add(deviceOutputSettingsForLightValue); } device.updateOutputSettings(outputSettings); this.ssldRepository.save(device); }
Source:
public Response stopNoteJobs(@PathParam("noteId") String noteId) throws IOException, IllegalArgumentException { LOG.info("stop notebook jobs ", noteId); Note note = notebook.getNote(noteId); if (note == null) { return new JsonResponse<>(Status.NOT_FOUND, "note not found.").build(); } for (Paragraph p : note.getParagraphs()) { if (!p.isTerminated()) { p.abort(); } } return new JsonResponse<>(Status.OK).build(); }

Target:
public Response stopNoteJobs(@PathParam("noteId") String noteId) throws IOException, IllegalArgumentException { LOG.info("stop note jobs ", noteId); Note note = notebook.getNote(noteId); if (note == null) { return new JsonResponse<>(Status.NOT_FOUND, "note not found.").build(); } for (Paragraph p : note.getParagraphs()) { if (!p.isTerminated()) { p.abort(); } } return new JsonResponse<>(Status.OK).build(); }
Source:
private static void setLookAndFeel(String themeName, Frame window) { Runnable runnable = () -> { try { UIManager.setLookAndFeel(themeName); if (window != null) { SwingUtilities.updateComponentTreeUI(window); } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { e.printStackTrace(); } }; SwingUtilities.invokeLater(runnable); }

Target:
private static void setLookAndFeel(String themeName, Frame window) { final String METHOD_NAME = "setLookAndFeel"; Runnable runnable = () -> { try { UIManager.setLookAndFeel(themeName); if (window != null) { SwingUtilities.updateComponentTreeUI(window); } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { MekHQ.getLogger().error( MekHQ.class, METHOD_NAME, e); } }; SwingUtilities.invokeLater(runnable); }
Source:
public Callable<Exercise> getAdaptiveExercise() throws OAuthSystemException, OAuthProblemException, NotLoggedInException { return wrapWithNotLoggedInException(new Callable<Exercise>() { @Override public Exercise call() throws Exception { try { Callable<String> download = new HttpTasks() .getForText(URI.create(SKILLIFIER_URL)); String json = download.call(); return adaptiveExerciseParser.parseFromJson(json); } catch (Exception ex) { LOG.log(Level.WARNING, "Downloading and parsing adaptive exercise URL failed with exception: {0}", ex.getMessage()); return null; } } }); }

Target:
public Callable<Exercise> getAdaptiveExercise() throws OAuthSystemException, OAuthProblemException, NotLoggedInException { return wrapWithNotLoggedInException(new Callable<Exercise>() { @Override public Exercise call() throws Exception { try { Callable<String> download = new HttpTasks() .getForText(URI.create(SKILLIFIER_URL)); String json = download.call(); return adaptiveExerciseParser.parseFromJson(json); } catch (Exception ex) { LOG.log(Level.WARNING, "Downloading and parsing adaptive exercise URL failed with exception: " + ex.getMessage(), ex); return null; } } }); }
Source:
public String getGenre(@Context HttpServletRequest request, @Context HttpServletResponse response, @QueryParam("path") final String path) throws IOException, ParseException { File file = getFile(path, response); if (file == null) { return null; } Document doc; if ((doc = getDocument(file)) == null) { response.sendError(HttpServletResponse.SC_NOT_FOUND, "Cannot find document for file"); return null; } return AbstractAnalyzer.Genre.get(doc.get(QueryBuilder.T)).toString(); }

Target:
public String getGenre(@Context HttpServletRequest request, @Context HttpServletResponse response, @QueryParam("path") final String path) throws IOException, ParseException { File file = getFile(path, response); if (file == null) { return null; } Document doc; if ((doc = getDocument(file)) == null) { response.sendError(HttpServletResponse.SC_NOT_FOUND, "Cannot get document for file"); return null; } AbstractAnalyzer.Genre genre = AbstractAnalyzer.Genre.get(doc.get(QueryBuilder.T)); if (genre == null) { response.sendError(HttpServletResponse.SC_NOT_FOUND, "Cannot get genre from the document"); return null; } return genre.toString(); }
Source:
public void init() { get( "/REST/v1/Locations", (req, res) -> { String jsonp = req.queryParams("jsonp"); String jsonString = geoCoderService.getLocation(jsonp, req.queryParams("query")); if (jsonString != null) { res.status(HttpStatus.SC_OK); res.body(jsonp + "(" + jsonString + ")"); return res; } else { res.status(HttpStatus.SC_BAD_REQUEST); return res; } }); get( "/REST/v1/Locations/nearby/cities/:wkt", (req, res) -> { String wkt = req.params(":wkt"); try { String jsonString = geoCoderService.getNearbyCities(wkt); if (jsonString != null) { return Response.ok(jsonString).build(); } else { return Response.status(Response.Status.NO_CONTENT).build(); } } catch (GeoEntryQueryException e) { LOGGER.debug("Error querying GeoNames resource with wkt:{}", wkt, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } }); }

Target:
public void init() { get( "/REST/v1/Locations", (req, res) -> { String jsonp = req.queryParams("jsonp"); String jsonString = geoCoderService.getLocation(jsonp, req.queryParams("query")); if (jsonString != null) { res.status(HttpStatus.SC_OK); res.body(jsonp + "(" + jsonString + ")"); return res; } else { res.status(HttpStatus.SC_BAD_REQUEST); return res; } }); get( "/REST/v1/Locations/nearby/cities/:wkt", (req, res) -> { String wkt = req.params(":wkt"); try { String jsonString = geoCoderService.getNearbyCities(wkt); if (jsonString != null) { res.status(HttpStatus.SC_OK); res.body(jsonString); return res; } else { res.status(HttpStatus.SC_NO_CONTENT); return res; } } catch (GeoEntryQueryException e) { LOGGER.debug("Error querying GeoNames resource with wkt:{}", wkt, e); res.status(HttpStatus.SC_BAD_REQUEST); return res; } }); }
Source:
public List<String> getDependencies() { List<String> dependencies = new ArrayList<String>(); dependencies.add(A_R_unixGID_namespace + ":*"); dependencies.add(A_G_unixGID_namespace + ":*"); dependencies.add(A_F_unixGroupName_namespace); return dependencies; }

Target:
public List<String> getDependencies() { List<String> dependencies = new ArrayList<String>(); return dependencies; }
Source:
private void initialize() { BufferedInputStream is = new BufferedInputStream(iis); is.mark(0); Reader in = new InputStreamReader(is); br = new BufferedReader(new InputStreamReader(is)); try { headerRow = br.readLine().split("\",\""); for(int i = 0; i < headerRow.length; i++) { String header = headerRow[i]; if("behavior id".equals(header)) { remoteBehaviorIdIdx = i; } else if("first name".equals(header)) { firstNameIdx = i; } else if("last name".equals(header)) { lastNameIdx = i; } else if("staff last name".equals(header)) { staffLastIdx = i; } else if("staff first name".equals(header)) { staffFirstIdx = i; } else if("\"student id".equals(header)) { remoteStudentIdIdx = i; } else if("external id".equals(header)) { externalIdIdx = i; } else if("date".equals(header)) { behaviorDateIdx = i; } else if("behavior".equals(header)) { behaviorNameIdx = i; } else if("category".equals(header)) { behaviorCategoryIdx = i; } else if("merit points".equals(header)) { meritPointsIdx = i; } else if("staff id".equals(header)) { staffIdx = i; } else if("incident id\"".equals(header)) { incidentIdIdx = i; } } is.reset(); } catch (IOException e) { LOGGER.error("Unable to parse the header row of the behavior CSV file."); } }

Target:
private void initialize() { BufferedInputStream is = new BufferedInputStream(iis); is.mark(0); Reader in = new InputStreamReader(is); br = new BufferedReader(new InputStreamReader(is)); try { headerRow = br.readLine().split(","); for(int i = 0; i < headerRow.length; i++) { String header = headerRow[i]; header = header.replaceAll("^\"|\"$", ""); if("behavior id".equals(header)) { remoteBehaviorIdIdx = i; } else if("first name".equals(header)) { firstNameIdx = i; } else if("last name".equals(header)) { lastNameIdx = i; } else if("staff last name".equals(header)) { staffLastIdx = i; } else if("staff first name".equals(header)) { staffFirstIdx = i; } else if("student id".equals(header)) { remoteStudentIdIdx = i; } else if("external id".equals(header)) { externalIdIdx = i; } else if("date".equals(header)) { behaviorDateIdx = i; } else if("behavior".equals(header)) { behaviorNameIdx = i; } else if("category".equals(header)) { behaviorCategoryIdx = i; } else if("merit points".equals(header)) { meritPointsIdx = i; } else if("staff id".equals(header)) { staffIdx = i; } else if("incident id".equals(header)) { incidentIdIdx = i; } } is.reset(); } catch (IOException e) { LOGGER.error("Unable to parse the header row of the behavior CSV file."); } }
Source:
public void test_cpd() { Offset<Double> offset = Offset.offset(0.01d); assertThat(getFileMeasureAsDouble("file1.py","duplicated_lines")).isEqualTo(27.0d, offset); assertThat(getFileMeasureAsDouble("file1.py","duplicated_blocks")).isEqualTo(1.0d, offset); assertThat(getFileMeasureAsDouble("file1.py","duplicated_files")).isEqualTo(1.0d, offset); assertThat(getFileMeasureAsDouble("file1.py","duplicated_lines_density")).isEqualTo(96.4d, offset); assertThat(getFileMeasureAsDouble("file2.py","duplicated_lines")).isEqualTo(27.0d, offset); assertThat(getFileMeasureAsDouble("file2.py","duplicated_blocks")).isEqualTo(1.0d, offset); assertThat(getFileMeasureAsDouble("file2.py","duplicated_files")).isEqualTo(1.0d, offset); assertThat(getFileMeasureAsDouble("file2.py","duplicated_lines_density")).isEqualTo(96.4d, offset); assertThat(getFileMeasureAsDouble("file3.py","duplicated_lines")).isEqualTo(0.0d, offset); assertThat(getFileMeasureAsDouble("file3.py","duplicated_blocks")).isEqualTo(0.0d, offset); assertThat(getFileMeasureAsDouble("file3.py","duplicated_files")).isEqualTo(0.0d, offset); assertThat(getFileMeasureAsDouble("file3.py","duplicated_lines_density")).isEqualTo(0.0d, offset); assertThat(getMeasureAsDouble(PROJECT_KEY, "duplicated_lines")).isEqualTo(54.0d, offset); assertThat(getMeasureAsDouble(PROJECT_KEY, "duplicated_blocks")).isEqualTo(2.0d, offset); assertThat(getMeasureAsDouble(PROJECT_KEY, "duplicated_files")).isEqualTo(2.0d, offset); assertThat(getMeasureAsDouble(PROJECT_KEY, "duplicated_lines_density")).isEqualTo(63.5d, offset); }

Target:
public void test_cpd() { Offset<Double> offset = Offset.offset(0.01d); assertThat(getMeasureAsDouble(FILE_1_KEY, DUPLICATED_LINES)).isEqualTo(27.0d, offset); assertThat(getMeasureAsDouble(FILE_1_KEY, DUPLICATED_BLOCKS)).isEqualTo(1.0d, offset); assertThat(getMeasureAsDouble(FILE_1_KEY, DUPLICATED_FILES)).isEqualTo(1.0d, offset); assertThat(getMeasureAsDouble(FILE_1_KEY, DUPLICATED_LINES_DENSITY)).isEqualTo(93.1d, offset); assertThat(getMeasureAsDouble(FILE_2_KEY, DUPLICATED_LINES)).isEqualTo(27.0d, offset); assertThat(getMeasureAsDouble(FILE_2_KEY, DUPLICATED_BLOCKS)).isEqualTo(1.0d, offset); assertThat(getMeasureAsDouble(FILE_2_KEY, DUPLICATED_FILES)).isEqualTo(1.0d, offset); assertThat(getMeasureAsDouble(FILE_2_KEY, DUPLICATED_LINES_DENSITY)).isEqualTo(90.0d, offset); assertThat(getMeasureAsDouble(FILE_3_KEY, DUPLICATED_LINES)).isEqualTo(0.0d, offset); assertThat(getMeasureAsDouble(FILE_3_KEY, DUPLICATED_BLOCKS)).isEqualTo(0.0d, offset); assertThat(getMeasureAsDouble(FILE_3_KEY, DUPLICATED_FILES)).isEqualTo(0.0d, offset); assertThat(getMeasureAsDouble(FILE_3_KEY, DUPLICATED_LINES_DENSITY)).isEqualTo(0.0d, offset); assertThat(getMeasureAsDouble(PROJECT_KEY, DUPLICATED_LINES)).isEqualTo(54.0d, offset); assertThat(getMeasureAsDouble(PROJECT_KEY, DUPLICATED_BLOCKS)).isEqualTo(2.0d, offset); assertThat(getMeasureAsDouble(PROJECT_KEY, DUPLICATED_FILES)).isEqualTo(2.0d, offset); assertThat(getMeasureAsDouble(PROJECT_KEY, DUPLICATED_LINES_DENSITY)).isEqualTo(61.4d, offset); }
Source:
public FormValidation doCheckSshKeysCredentialsId(@QueryParameter String value) throws IOException, ServletException { if (value == null || value.isEmpty()){ return FormValidation.error("No ssh credentials selected"); } BasicSSHUserPrivateKey sshCredential = getSshCredential(value); String privateKey = ""; if (sshCredential != null) { privateKey = sshCredential.getPrivateKey(); } else { return FormValidation.error("Failed to find credential \"" + value + "\" in store."); } boolean hasStart = false, hasEnd = false; BufferedReader br = new BufferedReader(new StringReader(privateKey)); String line; while ((line = br.readLine()) != null) { if (line.equals("-----BEGIN RSA PRIVATE KEY-----")) hasStart = true; if (line.equals("-----END RSA PRIVATE KEY-----")) hasEnd = true; } if (!hasStart) return FormValidation.error("This doesn't look like a private key at all"); if (!hasEnd) return FormValidation .error("The private key is missing the trailing 'END RSA PRIVATE KEY' marker. Copy&paste error?"); return FormValidation.ok(); }

Target:
public FormValidation doCheckSshKeysCredentialsId(@QueryParameter String value) throws IOException, ServletException { Jenkins.get().checkPermission(Jenkins.ADMINISTER); if (value == null || value.isEmpty()){ return FormValidation.error("No ssh credentials selected"); } BasicSSHUserPrivateKey sshCredential = getSshCredential(value); String privateKey = ""; if (sshCredential != null) { privateKey = sshCredential.getPrivateKey(); } else { return FormValidation.error("Failed to find credential \"" + value + "\" in store."); } boolean hasStart = false, hasEnd = false; BufferedReader br = new BufferedReader(new StringReader(privateKey)); String line; while ((line = br.readLine()) != null) { if (line.equals("-----BEGIN RSA PRIVATE KEY-----")) hasStart = true; if (line.equals("-----END RSA PRIVATE KEY-----")) hasEnd = true; } if (!hasStart) return FormValidation.error("This doesn't look like a private key at all"); if (!hasEnd) return FormValidation .error("The private key is missing the trailing 'END RSA PRIVATE KEY' marker. Copy&paste error?"); return FormValidation.ok(); }
Source:
private String getMatchingDynamicMdcFieldType(String fieldName) { String fieldType = null; for (final Map.Entry<Pattern, String> entry : dynamicMdcFieldTypes.entrySet()) { if(entry.getKey().matcher(fieldName).matches()) { fieldType = entry.getValue(); break; } } return fieldType; }

Target:
private String getMatchingDynamicMdcFieldType(String fieldName) { String fieldType = null; for (Map.Entry<Pattern, String> entry : dynamicMdcFieldTypes.entrySet()) { if(entry.getKey().matcher(fieldName).matches()) { fieldType = entry.getValue(); break; } } return fieldType; }
Source:
private boolean verifyAggregationOrderBy(OrderingScheme orderingScheme, OrderBy expectedSortOrder) { if (orderingScheme.getOrderBy().size() != expectedSortOrder.getSortItems().size()) { return false; } for (int i = 0; i < expectedSortOrder.getSortItems().size(); i++) { Symbol orderingSymbol = orderingScheme.getOrderBy().get(i); if (expectedSortOrder.getSortItems().get(i).getSortKey().equals(orderingSymbol.toSymbolReference()) && toSortOrder(expectedSortOrder.getSortItems().get(i)).equals(orderingScheme.getOrdering(orderingSymbol))) { continue; } return false; } return true; }

Target:
private static boolean verifyAggregationOrderBy(OrderingScheme orderingScheme, OrderBy expectedSortOrder) { if (orderingScheme.getOrderBy().size() != expectedSortOrder.getSortItems().size()) { return false; } for (int i = 0; i < expectedSortOrder.getSortItems().size(); i++) { Symbol orderingSymbol = orderingScheme.getOrderBy().get(i); if (expectedSortOrder.getSortItems().get(i).getSortKey().equals(orderingSymbol.toSymbolReference()) && toSortOrder(expectedSortOrder.getSortItems().get(i)).equals(orderingScheme.getOrdering(orderingSymbol))) { continue; } return false; } return true; }
Source:
protected Object decode( Channel channel, SocketAddress remoteAddress, Object msg) throws Exception { Parser parser = new Parser(PATTERN, (String) msg); if (!parser.matches()) { return null; } Position position = new Position(); position.setProtocol(getProtocolName()); DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, parser.next()); if (deviceSession == null) { return null; } position.setDeviceId(deviceSession.getDeviceId()); position.set(Position.KEY_INDEX, parser.nextInt()); position.set(Position.KEY_POWER, parser.nextInt() * 0.01); position.set(Position.KEY_BATTERY, parser.nextInt() * 0.01); position.set(Position.KEY_IGNITION, parser.nextInt() == 1); position.set(Position.KEY_INPUT, parser.nextInt()); int satellites = parser.nextInt(); position.set(Position.KEY_SATELLITES, satellites); DateBuilder dateBuilder = new DateBuilder() .setTime(parser.nextInt(), parser.nextInt(), parser.nextInt()); position.setValid(satellites >= 3); position.setLatitude(parser.nextCoordinate()); position.setLongitude(parser.nextCoordinate()); position.setSpeed(parser.nextDouble()); position.setCourse(parser.nextDouble()); dateBuilder.setDateReverse(parser.nextInt(), parser.nextInt(), parser.nextInt()); position.setTime(dateBuilder.getDate()); return position; }

Target:
protected Object decode( Channel channel, SocketAddress remoteAddress, Object msg) throws Exception { Parser parser = new Parser(PATTERN, (String) msg); if (!parser.matches()) { return null; } Position position = new Position(); position.setProtocol(getProtocolName()); DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, parser.next()); if (deviceSession == null) { return null; } position.setDeviceId(deviceSession.getDeviceId()); position.set(Position.KEY_INDEX, parser.nextInt()); position.set(Position.KEY_POWER, parser.nextInt() * 0.01); position.set(Position.KEY_BATTERY, parser.nextInt() * 0.01); position.set(Position.KEY_IGNITION, parser.nextInt() == 1); position.set(Position.KEY_INPUT, parser.nextInt()); position.set(Position.KEY_SATELLITES, parser.nextInt()); DateBuilder dateBuilder = new DateBuilder() .setTime(parser.nextInt(), parser.nextInt(), parser.nextInt()); position.setValid(true); position.setLatitude(parser.nextCoordinate()); position.setLongitude(parser.nextCoordinate()); position.setSpeed(parser.nextDouble()); position.setCourse(parser.nextDouble()); dateBuilder.setDateReverse(parser.nextInt(), parser.nextInt(), parser.nextInt()); position.setTime(dateBuilder.getDate()); return position; }
Source:
public void stop() { _log.info("Stopping coordinator"); _shutdown = true; while (_eventThread.isAlive()) { try { _eventThread.join(EVENT_THREAD_JOIN_TIMEOUT.toMillis()); _eventThread.interrupt(); } catch (InterruptedException e) { _log.warn("Exception caught while stopping coordinator", e); } } for (String connectorType : _connectors.keySet()) { try { _connectors.get(connectorType).getConnector().stop(); } catch (Exception ex) { _log.warn(String.format( "Connector stop threw an exception for connectorType %s, " + "Swallowing it and continuing shutdown.", connectorType), ex); } } for (DatastreamTask task : _assignedDatastreamTasks.values()) { ((EventProducer) task.getEventProducer()).shutdown(); } _adapter.disconnect(); _log.info("Coordinator stopped"); }

Target:
public void stop() { _log.info("Stopping coordinator"); _shutdown = true; _eventQueue.put(CoordinatorEvent.NO_OP_EVENT); try { _eventThread.join(EVENT_THREAD_LONG_JOIN_TIMEOUT); } catch (InterruptedException e) { _log.warn("Exception caught while waiting event thread to stop", e); return; } while (_eventThread.isAlive()) { try { _eventThread.interrupt(); _eventThread.join(EVENT_THREAD_SHORT_JOIN_TIMEOUT); } catch (InterruptedException e) { _log.warn("Exception caught while stopping coordinator", e); return; } } for (String connectorType : _connectors.keySet()) { try { _connectors.get(connectorType).getConnector().stop(); } catch (Exception ex) { _log.warn(String.format( "Connector stop threw an exception for connectorType %s, " + "Swallowing it and continuing shutdown.", connectorType), ex); } } for (DatastreamTask task : _assignedDatastreamTasks.values()) { ((EventProducer) task.getEventProducer()).shutdown(); } _adapter.disconnect(); _log.info("Coordinator stopped"); }