auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected boolean canDoAction() { VmValidator vmValidator = createVmValidator(); SnapshotsValidator snapshotValidator = createSnapshotValidator(); StoragePoolValidator spValidator = createStoragePoolValidator(); boolean result = validateVM(vmValidator); result = validate(spValidator.isUp()) && validate(snapshotValidator.vmNotDuringSnapshot(getVmId())) && validate(snapshotValidator.vmNotInPreview(getVmId())) && validate(vmValidator.vmNotDuringMigration()) && validate(vmValidator.vmNotRunningStateless()) && validate(vmValidator.vmNotIlegal()) && validate(vmValidator.vmNotLocked()); List<DiskImage> disksList = getDisksList(); if (result && disksList.size() > 0) { MultipleStorageDomainsValidator sdValidator = createMultipleStorageDomainsValidator(disksList); DiskImagesValidator diskImagesValidator = createDiskImageValidator(disksList); result = validate(diskImagesValidator.diskImagesNotLocked()) && validate(diskImagesValidator.diskImagesNotIllegal()) && validate(sdValidator.allDomainsExistAndActive()) && validate(sdValidator.allDomainsWithinThresholds()); } return result; }

Target:
protected boolean canDoAction() { VmValidator vmValidator = createVmValidator(); SnapshotsValidator snapshotValidator = createSnapshotValidator(); StoragePoolValidator spValidator = createStoragePoolValidator(); if (!(validateVM(vmValidator) && validate(spValidator.isUp()) && validate(vmValidator.vmNotIlegal()) && validate(vmValidator.vmNotLocked()) && validate(snapshotValidator.vmNotDuringSnapshot(getVmId())) && validate(snapshotValidator.vmNotInPreview(getVmId())) && validate(vmValidator.vmNotDuringMigration()) && validate(vmValidator.vmNotRunningStateless()))) { return false; } List<DiskImage> disksList = getDisksList(); if (disksList.size() > 0) { MultipleStorageDomainsValidator sdValidator = createMultipleStorageDomainsValidator(disksList); DiskImagesValidator diskImagesValidator = createDiskImageValidator(disksList); if (!(validate(diskImagesValidator.diskImagesNotLocked()) && validate(diskImagesValidator.diskImagesNotIllegal()) && validate(sdValidator.allDomainsExistAndActive()) && validate(sdValidator.allDomainsWithinThresholds()))) { return false; } } return true; }
Source:
public void updateState() { if (AccountUtil.isLoggedIn()) { accountNameView.setText(AccountUtil.getUserName()); accountNameView.setVisibility(VISIBLE); loginLogoutButton.setText(getContext().getString(R.string.preference_title_logout)); loginLogoutButton.setTextColor(ResourceUtil.getThemedColor(getContext(), R.attr.colorError)); accountAvatar.setVisibility(View.VISIBLE); accountWikiGlobe.setVisibility(View.GONE); notificationsContainer.setVisibility(View.VISIBLE); } else { accountNameView.setVisibility(GONE); loginLogoutButton.setText(getContext().getString(R.string.main_drawer_login)); loginLogoutButton.setTextColor(ResourceUtil.getThemedColor(getContext(), R.attr.colorAccent)); accountAvatar.setVisibility(View.GONE); accountWikiGlobe.setVisibility(View.VISIBLE); notificationsContainer.setVisibility(View.GONE); } }

Target:
public void updateState() { if (AccountUtil.isLoggedIn()) { accountNameView.setText(AccountUtil.getUserName()); accountNameView.setVisibility(VISIBLE); loginLogoutButton.setText(getContext().getString(R.string.preference_title_logout)); loginLogoutButton.setTextColor(ResourceUtil.getThemedColor(getContext(), R.attr.colorError)); accountAvatar.setVisibility(View.VISIBLE); accountWikiGlobe.setVisibility(View.GONE); notificationsContainer.setVisibility(View.VISIBLE); if (ReleaseUtil.isPreBetaRelease()) { editTasksContainer.setVisibility(VISIBLE); } } else { accountNameView.setVisibility(GONE); loginLogoutButton.setText(getContext().getString(R.string.main_drawer_login)); loginLogoutButton.setTextColor(ResourceUtil.getThemedColor(getContext(), R.attr.colorAccent)); accountAvatar.setVisibility(View.GONE); accountWikiGlobe.setVisibility(View.VISIBLE); notificationsContainer.setVisibility(View.GONE); editTasksContainer.setVisibility(GONE); } }
Source:
public void claimTask(KieApiClaimTask claimTask) throws ApiException { final String configId = claimTask.getConfigId(); if (null != configId) { try { final BpmWidgetInfo bpmWidgetInfo = bpmWidgetInfoManager.getBpmWidgetInfo(Integer.parseInt(configId)); final String information = bpmWidgetInfo.getInformationDraft(); if (StringUtils.isNotEmpty(information)) { final ApsProperties config = new ApsProperties(); config.loadFromXml(information); String knowledgetSource = (String) config.get(KieBpmSystemConstants.WIDGET_INFO_PROP_KIE_SOURCE_ID); KieBpmConfig bpmConfig = this.getKieFormManager().getKieServerConfigurations().get(knowledgetSource); String containerId = config.getProperty("containerId"); String taskId = claimTask.getTaskId(); String username = bpmConfig.getUsername(); this.getKieFormManager().claimTask(bpmConfig, containerId, taskId, username); } } catch (Throwable ex) { logger.error("Error {}", ex); throw new ApiException(IApiErrorCodes.API_VALIDATION_ERROR, "Error executing claim", Response.Status.BAD_REQUEST); } } }

Target:
public void claimTask(KieApiClaimTask claimTask) throws ApiException { final String configId = claimTask.getConfigId(); if (null != configId) { try { final BpmWidgetInfo bpmWidgetInfo = bpmWidgetInfoManager.getBpmWidgetInfo(Integer.parseInt(configId)); final String information = bpmWidgetInfo.getInformationDraft(); if (StringUtils.isNotEmpty(information)) { final ApsProperties config = new ApsProperties(); config.loadFromXml(information); String knowledgetSource = (String) config.get(KieBpmSystemConstants.WIDGET_INFO_PROP_KIE_SOURCE_ID); KieBpmConfig bpmConfig = this.getKieFormManager().getKieServerConfigurations().get(knowledgetSource); String containerId = config.getProperty("containerId"); String taskId = claimTask.getTaskId(); String username = bpmConfig.getUsername(); this.getKieFormManager().claimTask(bpmConfig, containerId, taskId, username); } } catch (ApsSystemException e) { logger.error("Error {}", e.getMessage()); } catch (IOException e) { logger.error("Error load configuration ", e.getMessage()); } catch (Throwable ex) { logger.error("Error {}", ex); throw new ApiException(IApiErrorCodes.API_VALIDATION_ERROR, "Error executing claim", Response.Status.BAD_REQUEST); } } }
Source:
public void onBlockPlaceExisting(BlockPlaceEvent e) { Block block = e.getBlock(); if (BlockStorage.hasBlockInfo(block)) { if (e.getBlockReplacedState().getType().isAir()) { Iterator<ItemStack> item = BlockStorage.check(block).getDrops().iterator(); World world = block.getWorld(); Location loc = block.getLocation(); while (item.hasNext()) { world.dropItem(loc, item.next()); } BlockStorage.clearBlockInfo(block); return; } e.setCancelled(true); } }

Target:
public void onBlockPlaceExisting(BlockPlaceEvent e) { Block block = e.getBlock(); if (e.getBlockReplacedState().getType().isAir()) { SlimefunItem sfItem = BlockStorage.check(block); if (sfItem != null) { for (ItemStack item : sfItem.getDrops()) { if (item != null && !item.getType().isAir()) { block.getWorld().dropItemNaturally(block.getLocation(), item); } } BlockStorage.clearBlockInfo(block); } } else if (BlockStorage.hasBlockInfo(e.getBlock())) { e.setCancelled(true); } }
Source:
public final int asInt() { assert NullHandling.replaceWithDefault() || !isNull(); return value.intValue(); }

Target:
public final int asInt() { return value.intValue(); }
Source:
public void theEntityDeviceModelDoesNotExists(final Map<String, String> entity) throws Throwable { final Manufacturer manufacturer = new Manufacturer(); final String manufacturerId = getString(entity, Keys.MANUFACTURER_ID, Defaults.DEFAULT_MANUFACTURER_ID); final String modelCode = getString(entity, Keys.KEY_DEVICE_MODEL_MODELCODE, Defaults.DEFAULT_DEVICE_MODEL_MODEL_CODE); manufacturer.setManufacturerId(manufacturerId); final List<DeviceModel> entityList = this.repo.findByManufacturerId(manufacturer); for (final DeviceModel deviceModel : entityList) { Assert.assertNotEquals(deviceModel.getModelCode(), modelCode); } }

Target:
public void theEntityDeviceModelDoesNotExists(final Map<String, String> entity) throws Throwable { final String modelCode = getString(entity, Keys.KEY_DEVICE_MODEL_MODELCODE, Defaults.DEFAULT_DEVICE_MODEL_MODEL_CODE); final Manufacturer manufacturer = new Manufacturer(); manufacturer.setManufacturerId(getString(entity, Keys.MANUFACTURER_ID, Defaults.DEFAULT_MANUFACTURER_ID)); final List<DeviceModel> entityList = this.repo.findByManufacturerId(manufacturer); for (final DeviceModel deviceModel : entityList) { Assert.assertNotEquals(deviceModel.getModelCode(), modelCode); } }
Source:
public void testFastForwardOnly() throws Exception { insertAndAdd(points1); geogig.command(CommitOp.class).call(); geogig.command(BranchCreateOp.class).setName("TestBranch").call(); Feature points1Modified = feature(pointsType, idP1, "StringProp1_2", new Integer(1000), "POINT(1 1)"); insertAndAdd(points1Modified); geogig.command(CommitOp.class).call(); geogig.command(CheckoutOp.class).setSource("TestBranch").call(); Feature points1ModifiedB = feature(pointsType, idP1, "StringProp1_3", new Integer(2000), "POINT(1 1)"); insertAndAdd(points1ModifiedB); geogig.command(CommitOp.class).call(); geogig.command(CheckoutOp.class).setSource("master").call(); Ref branch = geogig.command(RefParse.class).setName("TestBranch").call().get(); MergeOp mergeOp = geogig.command(MergeOp.class).addCommit(Suppliers.ofInstance(branch.getObjectId())); mergeOp.setFastForwardOnly(true); try { mergeOp.call(); fail(); }catch(IllegalStateException e) { } }

Target:
public void testFastForwardOnly() throws Exception { insertAndAdd(points1); geogig.command(CommitOp.class).call(); geogig.command(BranchCreateOp.class).setName("TestBranch").call(); Feature points1Modified = feature(pointsType, idP1, "StringProp1_2", new Integer(1000), "POINT(1 1)"); insertAndAdd(points1Modified); geogig.command(CommitOp.class).call(); geogig.command(CheckoutOp.class).setSource("TestBranch").call(); Feature points1ModifiedB = feature(pointsType, idP1, "StringProp1_3", new Integer(2000), "POINT(1 1)"); insertAndAdd(points1ModifiedB); geogig.command(CommitOp.class).call(); geogig.command(CheckoutOp.class).setSource("master").call(); Ref branch = geogig.command(RefParse.class).setName("TestBranch").call().get(); MergeOp mergeOp = geogig.command(MergeOp.class).addCommit(Suppliers.ofInstance(branch.getObjectId())); mergeOp.setFastForwardOnly(true); exception.expect(IllegalStateException.class); mergeOp.call(); }
Source:
private void initializeConfig() { config.getHiveConfSystemOverride().put("hive.in.test", "true"); }

Target:
private void initializeConfig() { config.getHiveConfSystemOverride().put(HIVE_IN_TEST.name(), "true"); }
Source:
public static Bitmap create(final String name, final BitmapFactory.Options options, final Point widthAndHeight) { Bitmap bitmap = Shadow.newInstanceOf(Bitmap.class); ShadowBitmap shadowBitmap = Shadow.extract(bitmap); shadowBitmap.appendDescription(name == null ? "Bitmap" : "Bitmap for " + name); Bitmap.Config config; if (options != null && options.inPreferredConfig != null) { config = options.inPreferredConfig; } else { config = Bitmap.Config.ARGB_8888; } shadowBitmap.setConfig(config); String optionsString = stringify(options); if (!optionsString.isEmpty()) { shadowBitmap.appendDescription(" with options "); shadowBitmap.appendDescription(optionsString); } Point p = new Point(selectWidthAndHeight(name, widthAndHeight)); if (options != null && options.inSampleSize > 1) { p.x = p.x / options.inSampleSize; p.y = p.y / options.inSampleSize; p.x = p.x == 0 ? 1 : p.x; p.y = p.y == 0 ? 1 : p.y; } shadowBitmap.setWidth(p.x); shadowBitmap.setHeight(p.y); shadowBitmap.setPixels(new int[p.x * p.y], 0, 0, 0, 0, p.x, p.y); if (options != null) { options.outWidth = p.x; options.outHeight = p.y; } if (shadowBitmap.getDensity() <= Bitmap.DENSITY_NONE) { ReflectionHelpers.setField(bitmap, "mDensity", DisplayMetrics.DENSITY_DEVICE); shadowBitmap.setDensity(DisplayMetrics.DENSITY_DEVICE); } return bitmap; }

Target:
public static Bitmap create(final String name, final BitmapFactory.Options options, final Point widthAndHeight) { return create(name, null, options, widthAndHeight); }
Source:
protected DocumentModelList applyQueryLimits(DocumentModelList results, int limit, int offset) { int safeOffset = Math.max(0, offset); int toIndex = limit >= 1 ? Math.min(results.size(), safeOffset + limit) : results.size(); return new DocumentModelListImpl(results.subList(safeOffset, toIndex)); }

Target:
protected DocumentModelList applyQueryLimits(DocumentModelList results, int limit, int offset) { offset = Math.max(0, offset); int toIndex = limit >= 1 ? Math.min(results.size(), offset + limit) : results.size(); return new DocumentModelListImpl(results.subList(offset, toIndex)); }
Source:
public void testBandwidthForLargeBlocks() throws InterruptedException { String data = "Tuple: test data to be emitted."; long startTime = System.currentTimeMillis(); testMeta.underTest.consumeBandwidth(data.length()); while (!testMeta.underTest.canConsumeBandwidth()) { Thread.sleep(1000); testMeta.mockschedular.execute(null); } long endTime = System.currentTimeMillis(); Assert.assertTrue((endTime - startTime) > ((data.length() / testMeta.bandwidthLimit) * 1000)); }

Target:
public void testBandwidthForLargeBlocks() throws InterruptedException { String data = "Tuple: test data to be emitted."; long timeCounter = 0; testMeta.underTest.consumeBandwidth(data.length()); while (!testMeta.underTest.canConsumeBandwidth()) { timeCounter += TestMeta.ONE_SECOND; testMeta.mockschedular.execute(null); } Assert.assertTrue(timeCounter > ((data.length() / testMeta.bandwidthLimit) * 1000)); }
Source:
public static boolean isIdentical(String expected, String actual) throws IOException, SAXException { XMLUnit.setIgnoreWhitespace(true); XMLUnit.setIgnoreAttributeOrder(true); Diff diff = XMLUnit.compareXML(expected, actual); System.out.println(diff); return diff.identical(); }

Target:
public static boolean isIdentical(String expected, String actual) throws IOException, SAXException { XMLUnit.setIgnoreWhitespace(true); XMLUnit.setIgnoreAttributeOrder(true); Diff diff = XMLUnit.compareXML(expected, actual); logger.info(diff); return diff.identical(); }
Source:
private PageSinkCommitStrategy getPageSinkCommitStrategy() { if (pageSinkCommitRequired) { return TASK_COMMIT; } if (stageExecutionDescriptor.isRecoverableGroupedExecution()) { return LIFESPAN_COMMIT; } return NO_COMMIT; }

Target:
private PageSinkCommitStrategy getPageSinkCommitStrategy() { if (stageExecutionDescriptor.isRecoverableGroupedExecution()) { return LIFESPAN_COMMIT; } if (pageSinkCommitRequired) { return TASK_COMMIT; } return NO_COMMIT; }
Source:
public void notifyItemChanged(@NonNull Card card) { notifyItemChanged(feedAdapter.getItemPosition(card)); }

Target:
public void notifyItemChanged(@NonNull Card card) { if (feedAdapter != null && feedAdapter.getItemPosition(card) > -1) { notifyItemChanged(feedAdapter.getItemPosition(card)); } }
Source:
private void waitForRefill(ValueQueue<?> valueQueue, String queueName, int queueSize) throws TimeoutException, InterruptedException { GenericTestUtils.waitFor(new Supplier<Boolean>() { @Override public Boolean get() { int size = valueQueue.getSize("k1"); if (size != queueSize) { LOG.info("Current ValueQueue size is " + size); return false; } return true; } }, 100, 3000); }

Target:
private void waitForRefill(ValueQueue<?> valueQueue, String queueName, int queueSize) throws TimeoutException, InterruptedException { GenericTestUtils.waitFor(() -> { int size = valueQueue.getSize(queueName); if (size != queueSize) { LOG.info("Current ValueQueue size is " + size); return false; } return true; }, 100, 3000); }
Source:
public CassandraStore createStore(final Config config, final MetricRegistry metrics) { final Cluster cluster = createCluster(config); final String keyspace = config.getString("freki.storage.cassandra.keyspace"); final Session session = connectTo(cluster, keyspace); registerMetrics(cluster, metrics); final IndexStrategy onlineIndexStrategy = indexStrategyFor(session, config.getBoolean("freki.storage.cassandra.online_index")); return new CassandraStore(cluster, session, Clock.systemDefaultZone(), onlineIndexStrategy); }

Target:
public CassandraStore createStore(final Config config, final MetricRegistry metrics) { final Cluster cluster = createCluster(config); final String keyspace = config.getString("freki.storage.cassandra.keyspace"); final Session session = connectTo(cluster, keyspace); registerMetrics(cluster, metrics); final IndexStrategy addPointIndexStrategy = indexStrategyFor(session, config.getBoolean("freki.storage.cassandra.index_on_add_point")); return new CassandraStore(cluster, session, Clock.systemDefaultZone(), addPointIndexStrategy); }
Source:
public void handleGet(ActionParameters params) throws ActionException { JSONObject response = new JSONObject(); JSONArray channelsJSONArray = new JSONArray(); try { for(WFSSearchChannelsConfiguration channel : channelService.findChannels()) { JSONObject channelJSON = channel.getAsJSONObject(); List<Integer> layerIds = new ArrayList<>(); layerIds.add(channel.getWFSLayerId()); JSONObject userLayers = OskariLayerWorker.getListOfMapLayersByIdList(layerIds, params.getUser(), params.getLocale().getLanguage(), params.getHttpParam(PARAM_SRS)); JSONArray layers = userLayers.getJSONArray(OskariLayerWorker.KEY_LAYERS); if(layers.length() > 0){ channelsJSONArray.put(channelJSON); } } } catch (Exception ex){ log.error(org.apache.commons.lang.exception.ExceptionUtils.getStackTrace(ex)); throw new ActionParamsException("Couldn't get WFS search channels"); } JSONHelper.putValue(response, "channels", channelsJSONArray); JSONArray handlers = new JSONArray(); Map<String, WFSChannelHandler> handlerMap = OskariComponentManager.getComponentsOfType(WFSChannelHandler.class); for(String id: handlerMap.keySet()) { handlers.put(id); } JSONHelper.putValue(response, "handlers", handlers); ResponseHelper.writeResponse(params, response); }

Target:
public void handleGet(ActionParameters params) throws ActionException { JSONObject response = new JSONObject(); JSONArray channelsJSONArray = new JSONArray(); try { for(WFSSearchChannelsConfiguration channel : channelService.findChannels()) { JSONObject channelJSON = channel.getAsJSONObject(); List<Integer> layerIds = Collections.singletonList(channel.getWFSLayerId()); JSONObject userLayers = OskariLayerWorker.getListOfMapLayersByIdList(layerIds, params.getUser(), params.getLocale().getLanguage(), params.getHttpParam(PARAM_SRS)); JSONArray layers = userLayers.getJSONArray(OskariLayerWorker.KEY_LAYERS); if(layers.length() > 0){ channelsJSONArray.put(channelJSON); } } } catch (Exception ex){ log.error(org.apache.commons.lang.exception.ExceptionUtils.getStackTrace(ex)); throw new ActionParamsException("Couldn't get WFS search channels"); } JSONHelper.putValue(response, "channels", channelsJSONArray); JSONArray handlers = new JSONArray(); Map<String, WFSChannelHandler> handlerMap = OskariComponentManager.getComponentsOfType(WFSChannelHandler.class); for(String id: handlerMap.keySet()) { handlers.put(id); } JSONHelper.putValue(response, "handlers", handlers); ResponseHelper.writeResponse(params, response); }
Source:
private void recursiveCheckConstraints( final Schema schema, final Stack<String> jsonPath, final List<SchemaIncompatibility> schemaIncompatibilities) { for (final SchemaConstraint constraint : CONSTRAINTS) { final Optional<SchemaIncompatibility> incompatibility = constraint.validate(jsonPath, schema); if (incompatibility.isPresent()) { schemaIncompatibilities.add(incompatibility.get()); } } if (schema instanceof ObjectSchema) { recursiveCheckConstraints((ObjectSchema) schema, jsonPath, schemaIncompatibilities); } else if (schema instanceof ArraySchema) { recursiveCheckConstraints((ArraySchema) schema, jsonPath, schemaIncompatibilities); } else if (schema instanceof ReferenceSchema) { recursiveCheckConstraints((ReferenceSchema) schema, jsonPath, schemaIncompatibilities); } else if (schema instanceof CombinedSchema) { recursiveCheckConstraints((CombinedSchema) schema, jsonPath, schemaIncompatibilities); } }

Target:
private void recursiveCheckConstraints( final Schema schema, final Stack<String> jsonPath, final List<SchemaIncompatibility> schemaIncompatibilities) { for (final SchemaConstraint constraint : constraints) { final Optional<SchemaIncompatibility> incompatibility = constraint.validate(jsonPath, schema); if (incompatibility.isPresent()) { schemaIncompatibilities.add(incompatibility.get()); } } if (schema instanceof ObjectSchema) { recursiveCheckConstraints((ObjectSchema) schema, jsonPath, schemaIncompatibilities); } else if (schema instanceof ArraySchema) { recursiveCheckConstraints((ArraySchema) schema, jsonPath, schemaIncompatibilities); } else if (schema instanceof ReferenceSchema) { recursiveCheckConstraints((ReferenceSchema) schema, jsonPath, schemaIncompatibilities); } else if (schema instanceof CombinedSchema) { recursiveCheckConstraints((CombinedSchema) schema, jsonPath, schemaIncompatibilities); } }
Source:
public ListOptions includeMeta() { headers.replaceValues("x-emc-include-meta", ImmutableList.of(Integer.toString(1))); return this; }

Target:
public ListOptions includeMeta() { headers.replaceValues("x-emc-include-meta", INCLUDE_META); return this; }
Source:
@Override public final String toString() { return sampleRepo.getAbsolutePath(); }

Target:
public final String toString() { return sampleRepo.getAbsolutePath(); }
Source:
public UserReport getUserReportByUuid(String uuid) { Criteria criteria = sessionFactory.getCurrentSession().createCriteria(UserReport.class).add(Expression.eq("uuid", uuid)); @SuppressWarnings("unchecked") List<UserReport> userReport = criteria.list(); if (null == userReport || userReport.isEmpty()) { return null; } return userReport.get(0); }

Target:
public UserReport getUserReportByUuid(String uuid) { return (UserReport) sessionFactory.getCurrentSession(). createCriteria(UserReport.class) .add(Expression.eq("uuid", uuid)) .uniqueResult(); }
Source:
public void testThatCorrectTimeZoneWillBeUsedInTarget() { Source source = new Source(); source.setValue( ZonedDateTime.parse( "2018-06-15T00:00:00+12:34" ) ); Target target = Issue1523Mapper.INSTANCE.map( source ); assertThat( target ).isNotNull(); assertThat( target.getValue() ).isNotNull(); assertThat( target.getValue().getTimezone() ).isEqualTo( 12 * 60 + 34 ); }

Target:
public void testThatCorrectTimeZoneWillBeUsedInTarget() { Source source = new Source(); source.setValue( ZonedDateTime.parse( "2018-06-15T00:00:00+01:00" ) ); Calendar cal = Calendar.getInstance( TimeZone.getTimeZone( "GMT+01:00" ) ); cal.set( 2018, 02, 15, 00, 00, 00 ); source.setValue2( cal ); Target target = Issue1523Mapper.INSTANCE.map( source ); assertThat( target ).isNotNull(); assertThat( target.getValue() ).isNotNull(); assertThat( target.getValue2() ).isNotNull(); assertThat( target.getValue().getTimezone() ).isEqualTo( 60 ); assertThat( target.getValue2().getTimezone() ).isEqualTo( 60 ); }
Source:
public void storeExtensionJob(String jobName, String extensionName, List<String> feeds, List<String> processes, byte[] config) { ExtensionJobsBean extensionJobsBean = new ExtensionJobsBean(); Date currentTime = new Date(System.currentTimeMillis()); extensionJobsBean.setJobName(jobName); extensionJobsBean.setExtensionName(extensionName); extensionJobsBean.setCreationTime(currentTime); extensionJobsBean.setFeeds(feeds); extensionJobsBean.setProcesses(processes); extensionJobsBean.setConfig(config); extensionJobsBean.setLastUpdatedTime(currentTime); EntityManager entityManager = getEntityManager(); try { beginTransaction(entityManager); entityManager.merge(extensionJobsBean); } finally { commitAndCloseTransaction(entityManager); } }

Target:
public void storeExtensionJob(String jobName, String extensionName, List<String> feeds, List<String> processes, byte[] config) { ExtensionJobsBean extensionJobsBean = new ExtensionJobsBean(); Date currentTime = new Date(System.currentTimeMillis()); extensionJobsBean.setJobName(jobName); extensionJobsBean.setExtensionName(extensionName); extensionJobsBean.setCreationTime(currentTime); extensionJobsBean.setFeeds(feeds); extensionJobsBean.setProcesses(processes); extensionJobsBean.setConfig(config); extensionJobsBean.setLastUpdatedTime(currentTime); EntityManager entityManager = getEntityManager(); try { beginTransaction(entityManager); entityManager.persist(extensionJobsBean); } finally { commitAndCloseTransaction(entityManager); } }
Source:
public void setInitialAttributes(Map<String, String> initialAttributes) { this.initialAttributes = initialAttributes; }

Target:
public void setInitialAttributes(Map<String, String> initialAttributes) { checkNotNull(initialAttributes, "initialAttributes can not be null"); this.initialAttributes = ImmutableMap.copyOf(initialAttributes); }
Source:
public boolean provides(IDiagramElementEditPart editPart) { boolean provides = false; if (!(editPart instanceof IDiagramNameEditPart)) { provides = true; } return provides; }

Target:
public boolean provides(IDiagramElementEditPart editPart) { return true; }
Source:
public JID getValidJID(String username) { if (username != null && !username.isEmpty()) { try { if (username.contains("@")) { JID jid = new JID(username); if (userManager.isRegisteredUser(jid, true)) { return jid; } } else if (userManager.isRegisteredUser(username)) { return xmppServer.createJID(username, null); } } catch (IllegalArgumentException e) { Log.debug("Unable to parse value '{}' as a JID.", username); } } return null; }

Target:
public JID getValidJID(String username) { if (username != null && !username.isEmpty()) { try { if (username.contains("@")) { JID jid = new JID(username); if (userManager.isRegisteredUser(jid, true)) { return jid; } } else { final JID jid = xmppServer.createJID(username, null); if (userManager.isRegisteredUser(jid, false)) { return jid; } } } catch (IllegalArgumentException e) { Log.debug("Unable to parse value '{}' as a JID.", username); } } return null; }
Source:
public Builder newInstance(StaplerRequest req, JSONObject formData) throws FormException { if (Boolean.FALSE.equals(formData.remove("stripPathPrefix"))) { formData.remove("pathPrefix"); } return super.newInstance(req, formData); }

Target:
public Publisher newInstance(StaplerRequest req, JSONObject formData) throws FormException { if (Boolean.FALSE.equals(formData.remove("stripPathPrefix"))) { formData.remove("pathPrefix"); } return super.newInstance(req, formData); }
Source:
public AgentInfo invoke(File nodeRoot, VirtualChannel virtualChannel) throws IOException, InterruptedException { OsType os; if (Platform.isDarwin()) { os = OsType.DARWIN; } else if (Platform.current() == Platform.WINDOWS) { os = OsType.WINDOWS; } else if(Platform.current() == Platform.UNIX && System.getProperty("os.name").equals("z/OS")) { os = OsType.ZOS; } else { os = OsType.UNIX; } String arch = System.getProperty("os.arch"); if (arch.contains("86") || arch.contains("amd64")) { x86 = true; } else { x86 = false; } ArchBits archBits; String bits = System.getProperty("sun.arch.data.model"); if (bits.equals("64")) { archBits = ArchBits._64; } else { archBits = ArchBits._32; } String binaryName = BINARY_PREFIX + binaryVersion + "_" + os.getNameForBinary() + archBits; String binaryPath; boolean isCached; boolean cachingAvailable; try { Path cachePath = Paths.get(nodeRoot.toPath().toString(), CACHE_PATH); Files.createDirectories(cachePath); File binaryFile = new File(cachePath.toFile(), binaryName); binaryPath = binaryFile.toPath().toString(); isCached = binaryFile.exists(); cachingAvailable = true; } catch (IOException | SecurityException e) { binaryPath = binaryName; isCached = false; cachingAvailable = false; } AgentInfo agentInfo = new AgentInfo(os, archBits, x86, binaryPath, cachingAvailable); agentInfo.setBinaryAvailability(isCached); return agentInfo; }

Target:
public AgentInfo invoke(File nodeRoot, VirtualChannel virtualChannel) throws IOException, InterruptedException { OsType os; if (Platform.isDarwin()) { os = OsType.DARWIN; } else if (Platform.current() == Platform.WINDOWS) { os = OsType.WINDOWS; } else if(Platform.current() == Platform.UNIX && System.getProperty("os.name").equals("z/OS")) { os = OsType.ZOS; } else if(Platform.current() == Platform.UNIX && System.getProperty("os.name").equals("FreeBSD")) { os = OsType.FREEBSD; } else { os = OsType.UNIX; } String arch = System.getProperty("os.arch"); boolean binaryCompatible; if ((os != OsType.FREEBSD) && (arch.contains("86") || arch.contains("amd64"))) { binaryCompatible = true; } else { binaryCompatible = false; } ArchBits archBits; String bits = System.getProperty("sun.arch.data.model"); if (bits.equals("64")) { archBits = ArchBits._64; } else { archBits = ArchBits._32; } String binaryName = BINARY_PREFIX + binaryVersion + "_" + os.getNameForBinary() + archBits; String binaryPath; boolean isCached; boolean cachingAvailable; try { Path cachePath = Paths.get(nodeRoot.toPath().toString(), CACHE_PATH); Files.createDirectories(cachePath); File binaryFile = new File(cachePath.toFile(), binaryName); binaryPath = binaryFile.toPath().toString(); isCached = binaryFile.exists(); cachingAvailable = true; } catch (Exception e) { binaryPath = binaryName; isCached = false; cachingAvailable = false; } AgentInfo agentInfo = new AgentInfo(os, binaryCompatible, binaryPath, cachingAvailable); agentInfo.setBinaryAvailability(isCached); return agentInfo; }
Source:
public void launch(IBinary bin, String mode) { ProfileLaunchShortcut provider = null; String providerId = null; providerId = SnapshotPreferencesPage.getSelectedProviderId(); if (!providerId.equals("")) { provider = ProfileLaunchShortcut .getLaunchShortcutProviderFromId(providerId); } if (provider == null) { providerId = ProfileLaunchShortcut .getDefaultLaunchShortcutProviderId(SNAPSHOT); provider = ProfileLaunchShortcut .getLaunchShortcutProviderFromId(providerId); } if (provider == null) { providerId = ProfileLaunchConfigurationTabGroup .getHighestProviderId(SNAPSHOT); provider = ProfileLaunchShortcut .getLaunchShortcutProviderFromId(providerId); } if (provider != null){ provider.launch(bin, mode); }else{ handleFail(Messages.SnapshotLaunchShortcut_0 + SNAPSHOT); } }

Target:
public void launch(IBinary bin, String mode) { ProfileLaunchShortcut provider = null; String providerId = null; providerId = SnapshotPreferencesPage.getSelectedProviderId(); if (!providerId.equals("")) { provider = ProfileLaunchShortcut .getLaunchShortcutProviderFromId(providerId); } if (provider == null) { providerId = ProfileLaunchShortcut .getDefaultLaunchShortcutProviderId(SNAPSHOT); provider = ProfileLaunchShortcut .getLaunchShortcutProviderFromId(providerId); if (provider == null) { providerId = ProfileLaunchConfigurationTabGroup .getHighestProviderId(SNAPSHOT); provider = ProfileLaunchShortcut .getLaunchShortcutProviderFromId(providerId); } } if (provider != null){ provider.launch(bin, mode); }else{ handleFail(Messages.SnapshotLaunchShortcut_0 + SNAPSHOT); } }
Source:
protected void createMainControl(Composite parent, IEEFFormContainer formContainer) { EEFWidgetFactory widgetFactory = formContainer.getWidgetFactory(); this.radioGroupViewer = new RadioGroupViewer(parent, widgetFactory, this.description.getNumberOfColumns()); this.radioGroup = radioGroupViewer.getRadioGroup(); this.radioGroupViewer.setContentProvider(ArrayContentProvider.getInstance()); this.radioGroupViewer.setLabelProvider(new EEFRadioLabelProvider()); this.radioGroupViewer.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); widgetFactory.paintBordersFor(parent); FormData radioGroupFormData = new FormData(); radioGroupFormData.left = new FormAttachment(0, LABEL_WIDTH); this.radioGroup.setLayoutData(radioGroupFormData); if (!isEnabled()) { this.radioGroup.setEnabled(false); } this.controller = new EEFControllersFactory().createRadioController(this.description, this.variableManager, this.interpreter, this.editingDomain); }

Target:
protected void createMainControl(Composite parent, IEEFFormContainer formContainer) { EEFWidgetFactory widgetFactory = formContainer.getWidgetFactory(); this.radioGroupViewer = new RadioGroupViewer(parent, widgetFactory, this.description.getNumberOfColumns()); this.radioGroup = radioGroupViewer.getRadioGroup(); this.radioGroupViewer.setContentProvider(ArrayContentProvider.getInstance()); this.radioGroupViewer.setLabelProvider(new EEFRadioLabelProvider()); this.radioGroupViewer.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); widgetFactory.paintBordersFor(parent); FormData radioGroupFormData = new FormData(); radioGroupFormData.left = new FormAttachment(0, LABEL_WIDTH); this.radioGroup.setLayoutData(radioGroupFormData); this.controller = new EEFControllersFactory().createRadioController(this.description, this.variableManager, this.interpreter, this.editingDomain); }
Source:
public Reader getConfigurationFileName() throws UnsupportedEncodingException { Map<String, String> props = new HashMap<>(); props.put("jboss.server.data.dir", System.getProperty("jboss.server.data.dir")); return new TokenReplacingReader(new InputStreamReader(getClass().getClassLoader() .getResourceAsStream("hawkular-inventory.properties"), "UTF-8"), props); }

Target:
public InventoryConfigurationData getConfigurationFileName() throws UnsupportedEncodingException { Map<String, String> props = new HashMap<>(); System.getProperties().stringPropertyNames().forEach((k) -> props.put(k, System.getProperty(k))); return new InventoryConfigurationData(getClass().getClassLoader().getResource("hawkular-inventory.properties"), props); }
Source:
public void init(List<TransformFunction> arguments, Map<String, DataSource> dataSourceMap) { if (arguments.size() != 1) { throw new IllegalArgumentException("Exactly 1 argument is required for ARRAY_AVERAGE transform function"); } TransformFunction firstArgument = arguments.get(0); if (firstArgument instanceof LiteralTransformFunction || firstArgument.getResultMetadata().isSingleValue()) { throw new IllegalArgumentException( "The argument of ARRAY_AVERAGE transform function must be a multi-valued column or a transform function"); } FieldSpec.DataType resultDataType; switch (firstArgument.getResultMetadata().getDataType()) { case INT: case LONG: resultDataType = FieldSpec.DataType.LONG; break; case FLOAT: case DOUBLE: resultDataType = FieldSpec.DataType.DOUBLE; break; default: throw new IllegalArgumentException( "The argument of ARRAY_AVERAGE transform function must be numeric"); } _resultMetadata = new TransformResultMetadata(resultDataType, true, false); _argument = firstArgument; }

Target:
public void init(List<TransformFunction> arguments, Map<String, DataSource> dataSourceMap) { if (arguments.size() != 1) { throw new IllegalArgumentException("Exactly 1 argument is required for ArraySum transform function"); } TransformFunction firstArgument = arguments.get(0); if (firstArgument instanceof LiteralTransformFunction || firstArgument.getResultMetadata().isSingleValue()) { throw new IllegalArgumentException( "The argument of ArraySum transform function must be a multi-valued column or a transform function"); } if (!firstArgument.getResultMetadata().getDataType().isNumeric()) { throw new IllegalArgumentException("The argument of ArraySum transform function must be numeric"); } _argument = firstArgument; }
Source:
protected OperatingMode determineConnectionMode() throws InterfaceNotOpenException, TimeoutException { try { operatingMode = OperatingMode.API; dataReader.setXBeeReaderMode(operatingMode); ATCommandResponse response = sendATCommand(new ATCommand("AP")); if (response.getResponse() != null && response.getResponse().length > 0) { if (response.getResponse()[0] == OperatingMode.API.getID()) { logger.debug("Using API operating mode."); return OperatingMode.API; } else { logger.debug("Using API Escaped operating mode."); return OperatingMode.API_ESCAPE; } } } catch (InvalidOperatingModeException e) { logger.error("Invalid operating mode", e); } catch (IOException e) { logger.error(e.getMessage(), e); } return OperatingMode.UNKNOWN; }

Target:
protected OperatingMode determineConnectionMode() throws InterfaceNotOpenException, TimeoutException { try { operatingMode = OperatingMode.API; dataReader.setXBeeReaderMode(operatingMode); ATCommandResponse response = sendATCommand(new ATCommand("AP")); if (response.getResponse() != null && response.getResponse().length > 0) { if (response.getResponse()[0] != OperatingMode.API.getID()) operatingMode = OperatingMode.API_ESCAPE; logger.debug(toString() + "Using {}.", operatingMode.getName()); return operatingMode; } } catch (InvalidOperatingModeException e) { logger.error("Invalid operating mode", e); } catch (IOException e) { logger.error(e.getMessage(), e); } return OperatingMode.UNKNOWN; }
Source:
public String toString() { byte[] array = checkNotNull(fPayload.array()); String string = "Payload: " + ConversionHelper.bytesToHex(array, true); final Packet child = fChildPacket; if (child != null) { return string + child.toString(); } return string; }

Target:
public String toString() { byte[] array = Arrays.copyOfRange(fPayload.array(), fPayload.arrayOffset(), fPayload.arrayOffset() + fPayload.limit()); String string = "Payload: " + ConversionHelper.bytesToHex(array, true); final Packet child = fChildPacket; if (child != null) { return string + child.toString(); } return string; }
Source:
public EventsMeta( @JsonProperty("dt") Instant timestamp, @JsonProperty("id") String id, @JsonProperty("domain") String domain, @JsonProperty("chronology_id") String chronologyId ) { this.timestamp = timestamp; this.id = id; this.domain = domain; this.chronologyId = (chronologyId != null && chronologyId.length() > 0) ? chronologyId : null; }

Target:
public EventsMeta( @JsonProperty("dt") Instant timestamp, @JsonProperty("id") String id, @JsonProperty("domain") String domain, @JsonProperty("chronology_id") String chronologyId ) { this.timestamp = timestamp; this.id = id; this.domain = domain; this.chronologyId = Strings.emptyToNull(chronologyId); }
Source:
public static String serialize(Object... objectsToSerialise) { StringBuilder sb = new StringBuilder().append("{"); int i = 1; for (Object o : objectsToSerialise) { if (i != 1) { sb.append(','); } sb.append("\"Payload-").append(i).append("-").append(o.getClass().getSimpleName()).append("\":"); try { if (o.getClass() != Entry.class && o.getClass() != Feed.class) { sb.append(objectMapper.writeValueAsString(o)); } else { sb.append("{"); sb.append(beautifyEntryAsJsonString(o)); sb.append("}"); } } catch (JsonProcessingException e) { sb.append("{\"objectMapper\": \"Couldn't convert the given object to a JSON string. (" ) .append(StringEscapeUtils.escapeJava(e.getMessage())).append( ")\"}" ); } i++; } sb.append("}"); return sb.toString(); }

Target:
public static String serialize(Object... objectsToSerialise) { StringBuilder sb = new StringBuilder().append("{"); int i = 1; for (Object o : objectsToSerialise) { if (o == null) { continue; } if (i != 1) { sb.append(','); } sb.append("\"Payload-").append(i).append("-").append(o.getClass().getSimpleName()).append("\":"); try { if (o.getClass() != Entry.class && o.getClass() != Feed.class) { sb.append(objectMapper.writeValueAsString(o)); } else { sb.append("{"); sb.append(beautifyEntryAsJsonString(o)); sb.append("}"); } } catch (JsonProcessingException e) { sb.append("{\"objectMapper\": \"Couldn't convert the given object to a JSON string. (" ) .append(StringEscapeUtils.escapeJava(e.getMessage())).append( ")\"}" ); } i++; } sb.append("}"); return sb.toString(); }
Source:
public JobInfo waitForEventJobFinished(Scheduler userInterface, JobId id) throws Exception { try { return waitForJobEvent(userInterface, id, 700000, JobStatus.FINISHED, SchedulerEvent.JOB_RUNNING_TO_FINISHED); } catch (ProActiveTimeoutException e) { JobState jobState = null; try { jobState = userInterface.getJobState(id); } catch (UnknownJobException un) { System.err.println(un); } if (jobState != null) { System.err.println("jobState.getId = " + jobState.getId()); System.err.println("jobState.getJobInfo = " + jobState.getJobInfo()); System.err.println("jobState.getStatus = " + jobState.getStatus()); System.err.println("jobState.isFinished " + jobState.isFinished()); for (JobEventMonitor event : getSchedulerMonitorsHandler().getJobEvents(id)) { System.err.println("event.getJobInfo().getJobId = " + event.getJobInfo()); System.err.println("event.getJobInfo = " + event.getJobInfo()); System.err.println("monitorRTF.eventOccured = " + event.eventOccured()); System.err.println("monitorRTF.isTimeouted = " + event.isTimeouted()); System.err.println("monitorRTF.getJobId = " + event.getJobId()); } } return null; } }

Target:
public JobInfo waitForEventJobFinished(Scheduler userInterface, JobId id) throws Exception { try { return waitForJobEvent(userInterface, id, (long) (0.8 * CentralPAPropertyRepository.PA_TEST_TIMEOUT.getValue()), JobStatus.FINISHED, SchedulerEvent.JOB_RUNNING_TO_FINISHED); } catch (ProActiveTimeoutException e) { JobState jobState = null; try { jobState = userInterface.getJobState(id); } catch (UnknownJobException un) { System.err.println(un); } if (jobState != null) { System.err.println("jobState.getId = " + jobState.getId()); System.err.println("jobState.getJobInfo = " + jobState.getJobInfo()); System.err.println("jobState.getStatus = " + jobState.getStatus()); System.err.println("jobState.isFinished " + jobState.isFinished()); for (JobEventMonitor event : getSchedulerMonitorsHandler().getJobEvents(id)) { System.err.println("event.getJobInfo().getJobId = " + event.getJobInfo()); System.err.println("event.getJobInfo = " + event.getJobInfo()); System.err.println("monitorRTF.eventOccured = " + event.eventOccured()); System.err.println("monitorRTF.isTimeouted = " + event.isTimeouted()); System.err.println("monitorRTF.getJobId = " + event.getJobId()); } } return null; } }
Source:
private Map<TopicPartition, OffsetAndMetadata> createOffset(Set<SubscriptionPartitionOffset> partitionOffsets) { Set<TopicPartition> assignments = consumer.assignment(); Map<TopicPartition, OffsetAndMetadata> offsetsData = new LinkedHashMap<>(); for (SubscriptionPartitionOffset partitionOffset : partitionOffsets) { TopicPartition topicAndPartition = new TopicPartition( partitionOffset.getKafkaTopicName().asString(), partitionOffset.getPartition()); if (assignments.contains(topicAndPartition)) { if (consumer.position(topicAndPartition) >= partitionOffset.getOffset()) { offsetsData.put(topicAndPartition, new OffsetAndMetadata(partitionOffset.getOffset())); } else { metrics.counter("offset-committer.skipped").inc(); } } else { logger.warn("Consumer is not assigned to partition of topic {}, ignoring offset to commit", topicAndPartition.partition(), topicAndPartition.topic(), partitionOffset.getOffset()); } } return offsetsData; }

Target:
private Map<TopicPartition, OffsetAndMetadata> createOffset(Set<SubscriptionPartitionOffset> partitionOffsets) { Map<TopicPartition, OffsetAndMetadata> offsetsData = new LinkedHashMap<>(); for (SubscriptionPartitionOffset partitionOffset : partitionOffsets) { TopicPartition topicAndPartition = new TopicPartition( partitionOffset.getKafkaTopicName().asString(), partitionOffset.getPartition()); if (partitionAssignmentState.isAssignedPartitionAtCurrentTerm(partitionOffset.getSubscriptionPartition())) { if (consumer.position(topicAndPartition) >= partitionOffset.getOffset()) { offsetsData.put(topicAndPartition, new OffsetAndMetadata(partitionOffset.getOffset())); } else { metrics.counter("offset-committer.skipped").inc(); } } else { logger.warn("Consumer is not assigned to partition of subscription at current term {}, ignoring offset from term to commit", partitionOffset.getPartition(), partitionOffset.getSubscriptionName(), partitionAssignmentState.currentTerm(partitionOffset.getSubscriptionName()), partitionOffset.getOffset(), partitionOffset.getPartitionAssignmentTerm()); } } return offsetsData; }
Source:
public R inPeriods(@NonNull List<Period> periods) { List<DatePeriod> datePeriods = new ArrayList<>(); for (Period period : periods) { datePeriods.add(DatePeriod.builder().startDate(period.startDate()).endDate(period.endDate()).build()); } return newWithWrappedScope(InPeriodQueryHelper.buildInPeriodsQuery(key, datePeriods)); }

Target:
public R inPeriods(@NonNull List<Period> periods) { List<DatePeriod> datePeriods = new ArrayList<>(); for (Period period : periods) { datePeriods.add(DatePeriod.builder().startDate(period.startDate()).endDate(period.endDate()).build()); } return inDatePeriods(datePeriods); }
Source:
public void instrument(final InputStream input, final OutputStream output, final String name) throws IOException { try { output.write(instrument(input, name)); } catch (final RuntimeException e) { throw instrumentError(name, e); } }

Target:
public void instrument(final InputStream input, final OutputStream output, final String name) throws IOException { output.write(instrument(input, name)); }
Source:
public static CompletableFuture<Boolean> register(String username, SigningPrivateKeyAndPublicHash signer, Hasher hasher, NetworkAccess network, Consumer<String> progressCallback) { LocalDate now = LocalDate.now(); LocalDate expiry = now.plusMonths(2); LOG.info("claiming username: " + username + " with expiry " + expiry); return network.dhtClient.id() .thenCompose(id -> { List<UserPublicKeyLink> claimChain = UserPublicKeyLink.createInitial(signer, username, expiry, Arrays.asList(id)); return network.coreNode.getChain(username).thenCompose(existing -> { if (existing.size() > 0) throw new IllegalStateException("User already exists!"); byte[] data = new CborObject.CborList(claimChain).serialize(); return hasher.generateProofOfWork(ProofOfWork.DEFAULT_DIFFICULTY, data) .thenCompose(proof -> network.coreNode.updateChain(username, claimChain, proof)); }); }); }

Target:
public static CompletableFuture<Boolean> register(String username, SigningPrivateKeyAndPublicHash signer, Hasher hasher, NetworkAccess network, Consumer<String> progressCallback) { LocalDate now = LocalDate.now(); LocalDate expiry = now.plusMonths(2); LOG.info("claiming username: " + username + " with expiry " + expiry); return network.dhtClient.id() .thenCompose(id -> { List<UserPublicKeyLink> claimChain = UserPublicKeyLink.createInitial(signer, username, expiry, Arrays.asList(id)); return network.coreNode.getChain(username).thenCompose(existing -> { if (existing.size() > 0) throw new IllegalStateException("User already exists!"); return updateChainWithRetry(username, claimChain, hasher, network, progressCallback); }); }); }
Source:
public void shutdown(boolean join) { if (executor != null) { ThreadPoolExecutor pool = executor; executor = null; pool.shutdown(); try { if (!pool.awaitTermination(WAIT_FOR_JOBS_SHUTDOWN_TIMEOUT, TimeUnit.SECONDS)) { pool.shutdownNow(); if (!pool.awaitTermination(WAIT_FOR_JOBS_SHUTDOWN_TIMEOUT, TimeUnit.SECONDS)) { logger.error("Pool did not terminate"); } } } catch (InterruptedException ie) { pool.shutdownNow(); Thread.currentThread().interrupt(); } } }

Target:
public void shutdown(boolean join) { ThreadPoolExecutor pool = executor; executor = null; pool.shutdown(); if (join) { try { if (!pool.awaitTermination(WAIT_FOR_JOBS_SHUTDOWN_TIMEOUT, TimeUnit.SECONDS)) { pool.shutdownNow(); if (!pool.awaitTermination(WAIT_FOR_JOBS_SHUTDOWN_TIMEOUT, TimeUnit.SECONDS)) { logger.error("Pool did not terminate"); } } } catch (InterruptedException ie) { pool.shutdownNow(); Thread.currentThread().interrupt(); } } }