auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void runTask() { UpdateProgress progress = UpdateProgress.START; Set<String> receivedItemUris = new HashSet<String>(); int offset = 1; while (true) { reportStatus(progress.toString()); String response = null; try { response = gettyClient.getVideoResponse(MAGIC_ALL_ITEMS_SEARCH_KEYWORD, offset); } catch (IOException e) { Throwables.propagate(e); } List<VideoResponse> videos = adapter.parse(response); if (videos.isEmpty()) { break; } for (VideoResponse video : videos) { try { Identified written = dataHandler.handle(video); receivedItemUris.add(written.getCanonicalUri()); progress = progress.reduce(UpdateProgress.SUCCESS); } catch (Exception e) { log.warn(String.format("Failed to interpret a video response"), e); progress = progress.reduce(UpdateProgress.FAILURE); } } offset += itemsPerPage; } Iterator<Content> allContent = contentLister.listContent(ContentListingCriteria.defaultCriteria().forPublisher(Publisher.GETTY).build()); while (allContent.hasNext()) { Content item = allContent.next(); if (! receivedItemUris.contains(item.getCanonicalUri())) { item.setActivelyPublished(false); dataHandler.write(item); } } }

Target:
protected void runTask() { UpdateProgress progress = UpdateProgress.START; Set<String> receivedItemUris = new HashSet<String>(); int offset = 1; while (true) { try { reportStatus(progress.toString()); String response = null; try { log.debug("Requesting Getty items from {}", offset); response = gettyClient.getVideoResponse(MAGIC_ALL_ITEMS_SEARCH_KEYWORD, offset); } catch (IOException e) { Throwables.propagate(e); } log.debug("Parsing response"); List<VideoResponse> videos = adapter.parse(response); if (videos.isEmpty()) { break; } for (VideoResponse video : videos) { try { log.debug("Writing item ({})", video.getAssetId(), video.getTitle()); Identified written = dataHandler.handle(video); receivedItemUris.add(written.getCanonicalUri()); progress = progress.reduce(UpdateProgress.SUCCESS); } catch (Exception e) { log.warn(String.format("Failed to interpret a video response"), e); progress = progress.reduce(UpdateProgress.FAILURE); } } } catch (Exception e) { log.error("Whole batch failed for some reason", e); } offset += itemsPerPage; } Iterator<Content> allContent = contentLister.listContent(ContentListingCriteria.defaultCriteria().forPublisher(Publisher.GETTY).build()); while (allContent.hasNext()) { Content item = allContent.next(); if (! receivedItemUris.contains(item.getCanonicalUri())) { item.setActivelyPublished(false); dataHandler.write(item); } } }
Source:
private static long doConvert(int delta, long amount) { if (delta == 0 || amount == 0) { return amount; } else if (delta < 0) { return amount >> -delta; } else if (delta >= Long.numberOfLeadingZeros(amount < 0 ? ~amount : amount)) { return delta < 0 ? Long.MIN_VALUE : Long.MAX_VALUE; } else { return amount << delta; } }

Target:
private static long doConvert(int delta, long amount) throws ArithmeticException { if (delta == 0 || amount == 0) { return amount; } else if (delta < 0) { long t = amount >> (-delta - 1); t >>>= 64 + delta; t += amount; return t >> -delta; } else if (delta >= Long.numberOfLeadingZeros(amount < 0 ? ~amount : amount)) { throw new ArithmeticException("Conversion overflows"); } else { return amount << delta; } }
Source:
public void createSrcFolderContentNonExistingDestinationFolder() throws IOException { String sourceFolderName = packagingType.getSourceFolderName(); String fakeFileName = "fakeFile.xml"; Path sourceFolderPath = projectBaseFolder.getRoot().toPath().resolve(PackagerTestUtils.SRC).resolve( PackagerTestUtils.MAIN) .resolve(sourceFolderName); PackagerTestUtils.createFolder(sourceFolderPath, fakeFileName, true); contentGenerator.createSrcFolderContent(); }

Target:
public void createSrcFolderContentNonExistingDestinationFolder() throws IOException { String sourceFolderName = packagingType.getSourceFolderName(); Path sourceFolderPath = projectBaseFolder.getRoot().toPath().resolve(PackagerTestUtils.SRC).resolve( PackagerTestUtils.MAIN) .resolve(sourceFolderName); PackagerTestUtils.createFolder(sourceFolderPath, FAKE_FILE_NAME, true); contentGenerator.createSrcFolderContent(); }
Source:
public CompletableFuture<Void> unrankeMapVersion(MapBean map) { String id = map.getId(); MapVersion mapVersion = new MapVersion(); mapVersion.setRanked(false); mapVersion.setId(map.getId()); fafApiAccessor.updateMapVersion(id, mapVersion); return null; }

Target:
public CompletableFuture<Void> unrankeMapVersion(MapBean map) { String id = map.getId(); MapVersion mapVersion = new MapVersion(); mapVersion.setRanked(false); mapVersion.setId(map.getId()); fafApiAccessor.updateMapVersion(id, mapVersion); return CompletableFuture.completedFuture(null); }
Source:
public void testDefaults() { assertRecordedDefaults(recordDefaults(DruidConfig.class) .setDruidBrokerUrl(null) .setDruidCoordinatorUrl(null) .setDruidSchema("druid") .setComputePushdownEnabled(false) .setHadoopResourceConfigFiles((String) null)); }

Target:
public void testDefaults() { assertRecordedDefaults(recordDefaults(DruidConfig.class) .setDruidBrokerUrl(null) .setDruidCoordinatorUrl(null) .setDruidSchema("druid") .setComputePushdownEnabled(false) .setHadoopConfiguration("")); }
Source:
public void clickOnAddWorkspaceBtn() { new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) .until(visibilityOfElementLocated(By.xpath(Locators.ADD_WORKSPACE_BTN))) .click(); }

Target:
public void clickOnAddWorkspaceBtn() { seleniumWebDriverHelper.waitAndClick(By.xpath(Locators.ADD_WORKSPACE_BTN_XPATH)); }
Source:
public PageableResult search(RequestContext context) throws ResponseException { String includeDeadstr = context.getParameter("includeDead"); Boolean includeDead = StringUtils.isNotBlank(includeDeadstr) ? Boolean.parseBoolean(includeDeadstr) : false; List<Patient> allPatients = Context.getPatientService().getAllPatients(); if (allPatients != null && allPatients.size() > 0) { if (includeDead) { return new NeedsPaging<Patient>(allPatients, context); } else { List<Patient> livingPatients = new ArrayList<Patient>(); for (Patient patient : allPatients) { if (!patient.isDead()) { livingPatients.add(patient); } } return new NeedsPaging<Patient>(livingPatients, context); } } return new EmptySearchResult(); }

Target:
public PageableResult search(RequestContext context) throws ResponseException { String includeDeadStr = context.getParameter("includeDead"); String searchPhrase = context.getParameter("q"); Boolean includeDead = StringUtils.isNotBlank(includeDeadStr) ? Boolean.parseBoolean(includeDeadStr) : false; if (StringUtils.isNotBlank(searchPhrase)) { List<Patient> allPatients = Context.getPatientService().getPatients(searchPhrase); Boolean resultsExist = allPatients != null && allPatients.size() > 0; if (!resultsExist) { return new EmptySearchResult(); } if (includeDead) { return new NeedsPaging<Patient>(allPatients, context); } else { List<Patient> livingPatients = new ArrayList<Patient>(); for (Patient patient : allPatients) { if (!patient.isDead()) { livingPatients.add(patient); } } return new NeedsPaging<Patient>(livingPatients, context); } } return new EmptySearchResult(); }
Source:
public void decoderCanThrowUnwrappedExceptionInDecode404Mode() throws Exception { server.enqueue(new MockResponse().setBody("success!")); thrown.expect(RuntimeException.class); TestInterface api = new TestInterfaceBuilder() .decode404() .decoder(new Decoder() { @Override public Object decode(Response response, Type type) throws IOException { throw new RuntimeException(); } }).target("http://localhost:" + server.getPort()); api.post(); }

Target:
public void decoderCanThrowUnwrappedExceptionInDecode404Mode() throws Exception { server.enqueue(new MockResponse().setResponseCode(404)); thrown.expect(NoSuchElementException.class); TestInterface api = new TestInterfaceBuilder() .decode404() .decoder(new Decoder() { @Override public Object decode(Response response, Type type) throws IOException { assertEquals(404, response.status()); throw new NoSuchElementException(); } }).target("http://localhost:" + server.getPort()); api.post(); }
Source:
private void emitResourceInjection(StringBuilder builder, ResourceInjection injection) { Collection<ResourceBinding> bindings = injection.getResourceBindings(); for (ResourceBinding binding : bindings) { builder.append(" target.").append(binding.getName()).append(" = "); emitCastIfNeeded(builder, "java.lang.Object", binding.getType()); if (!binding.isRequired()) { builder.append("finder.findOptionalResource(source, ") .append(injection.getId()).append(", ") .append("\"" + binding.getType()).append("\");\n"); } else { builder.append("finder.findRequiredResource(source, ") .append(injection.getId()).append(", ") .append("\"" + binding.getType() + "\", ") .append("\"" + binding.getDescription() + "\");\n"); } } }

Target:
private void emitResourceInjection(StringBuilder builder, ResourceInjection injection) { Collection<ResourceBinding> bindings = injection.getResourceBindings(); for (ResourceBinding binding : bindings) { builder.append(" target.").append(binding.getName()).append(" = "); builder.append("finder.getResources(source).") .append(binding.getGetter()) .append("(" + injection.getId() + ");\n"); } }
Source:
public void testSanitizeForSaving() { AccountAttributes actualAccount = createAccountAttributesToSanitize(); AccountAttributes expectedAccount = createAccountAttributesToSanitize(); actualAccount.sanitizeForSaving(); assertEquals(expectedAccount.googleId, actualAccount.googleId); assertEquals(expectedAccount.name, actualAccount.name); assertEquals(expectedAccount.institute, actualAccount.institute); }

Target:
public void testSanitizeForSaving() { AccountAttributes actualAccount = createAccountAttributesToSanitize(); AccountAttributes expectedAccount = createAccountAttributesToSanitize(); actualAccount.sanitizeForSaving(); assertEquals(SanitizationHelper.sanitizeGoogleId(expectedAccount.googleId), actualAccount.googleId); assertEquals(SanitizationHelper.sanitizeName(expectedAccount.name), actualAccount.name); assertEquals(SanitizationHelper.sanitizeEmail(expectedAccount.email), actualAccount.email); assertEquals(SanitizationHelper.sanitizeTitle(expectedAccount.institute), actualAccount.institute); }
Source:
protected List<String> getSchemaNamesInternal() { Connection connection = getConnection(); try { DatabaseMetaData metaData = connection.getMetaData(); List<String> result = new ArrayList<>(); if (DATABASE_PRODUCT_SQLSERVER.equals(_databaseProductName)) { result = new ArrayList<>(getSchemaSQLServerNames(metaData)); } else if (_usesCatalogsAsSchemas) { String[] catalogNames = getCatalogNames(); for (String name : catalogNames) { logger.debug("Found catalogName: {}", name); result.add(name); } } else { ResultSet rs = metaData.getSchemas(); while (rs.next()) { String schemaName = rs.getString(1); logger.debug("Found schemaName: {}", schemaName); result.add(schemaName); } FileHelper.safeClose(rs); } if (DATABASE_PRODUCT_MYSQL.equals(_databaseProductName)) { result.remove("information_schema"); } if (result.isEmpty()) { logger.info("No schemas or catalogs found. Creating unnamed schema."); result.add(null); } return result; } catch (SQLException e) { throw JdbcUtils.wrapException(e, "get schema names", JdbcActionType.METADATA); } finally { closeIfNecessary(connection); } }

Target:
protected List<String> getSchemaNamesInternal() { Connection connection = getConnection(); try { DatabaseMetaData metaData = connection.getMetaData(); List<String> result = new ArrayList<>(); if (DATABASE_PRODUCT_SQLSERVER.equals(_databaseProductName)) { result = new ArrayList<>(getSchemaSQLServerNames(metaData)); } else if (_usesCatalogsAsSchemas) { String[] catalogNames = getCatalogNames(); for (String name : catalogNames) { logger.debug("Found catalogName: {}", name); result.add(name); } } else { ResultSet rs = null; try { rs = metaData.getSchemas(); while (rs.next()) { String schemaName = rs.getString(1); logger.debug("Found schemaName: {}", schemaName); result.add(schemaName); } }finally { FileHelper.safeClose(rs); } } if (DATABASE_PRODUCT_MYSQL.equals(_databaseProductName)) { result.remove("information_schema"); } if (result.isEmpty()) { logger.info("No schemas or catalogs found. Creating unnamed schema."); result.add(null); } return result; } catch (SQLException e) { throw JdbcUtils.wrapException(e, "get schema names", JdbcActionType.METADATA); } finally { closeIfNecessary(connection); } }
Source:
static public int getVersion(String barrierPath) { return Integer.valueOf(barrierPath.substring(barrierPath.lastIndexOf('_') + 1)); }

Target:
public static int getVersion(String barrierPath) { return Integer.valueOf(barrierPath.substring(barrierPath.lastIndexOf('_') + 1)); }
Source:
public boolean checkFilters(List<Filter> filters, LogicalOperator logicalOperator, TaskContext taskContext) throws TaskHandlerException { LOGGER.debug("Checking if the task with name: matches the filters", taskContext.getTask().getName()); Map<String, Object> parameters = taskContext.getTriggerParameters(); if (isEmpty(filters) || parameters == null) { return true; } boolean filterCheck = false; for (Filter filter : filters) { KeyInformation key = parse(filter.getKey()); Object value; try { KeyEvaluator keyEvaluator = new KeyEvaluator(taskContext); value = keyEvaluator.getManipulatedValue(key); } catch (TaskHandlerException e) { if (TaskFailureCause.DATA_SOURCE.equals(e.getFailureCause())) { throw e; } value = null; } catch (Exception e) { value = null; } filterCheck = value != null && checkValue(filter, value); if (!filter.isNegationOperator()) { filterCheck = !filterCheck; } if (isFilterConditionFulfilled(filterCheck, logicalOperator)) { break; } } return filterCheck; }

Target:
public boolean checkFilters(List<Filter> filters, LogicalOperator logicalOperator, TaskContext taskContext) throws TaskHandlerException { LOGGER.debug("Checking if task: matches the filters", taskContext.getTask().getName()); Map<String, Object> parameters = taskContext.getTriggerParameters(); if (isEmpty(filters) || parameters == null) { return true; } boolean filterCheck = false; for (Filter filter : filters) { KeyInformation key = parse(filter.getKey()); Object value; try { KeyEvaluator keyEvaluator = new KeyEvaluator(taskContext); value = keyEvaluator.getManipulatedValue(key); } catch (TaskHandlerException e) { if (TaskFailureCause.DATA_SOURCE.equals(e.getFailureCause())) { throw e; } LOGGER.debug("During retrieving manipulated value for: {}, the following error occurred: {}", key.getKey(), e); value = null; } catch (Exception e) { LOGGER.debug("During retrieving manipulated value for: {}, the following error occurred: {}", key.getKey(), e); value = null; } filterCheck = value != null && checkValue(filter, value); if (!filter.isNegationOperator()) { filterCheck = !filterCheck; } LOGGER.debug("Result of checking filter: for task: is: {}", filter.getDisplayName(), taskContext.getTask().getName(), filterCheck); if (isFilterConditionFulfilled(filterCheck, logicalOperator)) { LOGGER.debug("Filters condition is fulfilled, because logicalOperator is: and filters checking has already: value", logicalOperator, filterCheck); break; } } LOGGER.info("Result of checking filters for task: is: {}", taskContext.getTask().getName(), filterCheck); return filterCheck; }
Source:
public ForceObject(T element, double x, double y) { this(element, Point.of(x, y), 1000); }

Target:
public ForceObject(T element, double x, double y) { this(element, Point.of(x, y), 1); }
Source:
protected void initializeModel(EObject owner) { super.initializeModel(owner); org.eclipse.uml2.uml.Package packageOwner = (org.eclipse.uml2.uml.Package) owner; packageOwner.setName(getModelName()); Profile sysml = (Profile) PackageUtil.loadPackage(URI.createURI(SysMLResource.PROFILE_PATH), owner.eResource().getResourceSet()); if (sysml != null) { PackageUtil.applyProfile(packageOwner, sysml, true); } Profile standardUMLProfile = (Profile) PackageUtil.loadPackage(URI.createURI(UMLResource.STANDARD_PROFILE_URI), owner.eResource().getResourceSet()); if (standardUMLProfile != null) { PackageUtil.applyProfile(packageOwner, standardUMLProfile, true); } Package umlPrimitiveTypes = (Package) PackageUtil.loadPackage(URI.createURI(UMLResource.UML_PRIMITIVE_TYPES_LIBRARY_URI), owner.eResource().getResourceSet()); if (umlPrimitiveTypes != null){ PackageImport pi = UMLFactory.eINSTANCE.createPackageImport(); pi.setImportedPackage(umlPrimitiveTypes); packageOwner.getPackageImports().add(pi); } }

Target:
protected void initializeModel(EObject owner) { super.initializeModel(owner); Package packageOwner = (Package) owner; Profile sysml = (Profile) PackageUtil.loadPackage(URI.createURI(SysMLResource.PROFILE_PATH), owner.eResource().getResourceSet()); if (sysml != null) { PackageUtil.applyProfile(packageOwner, sysml, true); } Profile standardUMLProfile = (Profile) PackageUtil.loadPackage(URI.createURI(UMLResource.STANDARD_PROFILE_URI), owner.eResource().getResourceSet()); if (standardUMLProfile != null) { PackageUtil.applyProfile(packageOwner, standardUMLProfile, true); } Package umlPrimitiveTypes = (Package) PackageUtil.loadPackage(URI.createURI(UMLResource.UML_PRIMITIVE_TYPES_LIBRARY_URI), owner.eResource().getResourceSet()); if (umlPrimitiveTypes != null){ PackageImport pi = UMLFactory.eINSTANCE.createPackageImport(); pi.setImportedPackage(umlPrimitiveTypes); packageOwner.getPackageImports().add(pi); } }
Source:
protected Path createVolumeDirectory(boolean temporary) { Path directory = new File(".tmp-volume-" + System.currentTimeMillis()).toPath(); PathUtils.mkdirp(directory); recursiveDeleteDir(Paths.get("/tmp/maven-hack")); if (temporary) Runtime.getRuntime().addShutdownHook(new Thread(DockerClientFactory.TESTCONTAINERS_THREAD_GROUP, () -> { recursiveDeleteDir(directory); })); return directory; }

Target:
protected Path createVolumeDirectory(boolean temporary) { Path directory = new File(".tmp-volume-" + System.currentTimeMillis()).toPath(); PathUtils.mkdirp(directory); if (temporary) Runtime.getRuntime().addShutdownHook(new Thread(DockerClientFactory.TESTCONTAINERS_THREAD_GROUP, () -> { PathUtils.recursiveDeleteDir(directory, new DeleteFileVisitor()); })); return directory; }
Source:
private String getPermissionsMap(User currentUser) { List<UserAuthorization> authorizationList = userAuthorizationDAO.listByUser(currentUser .getKey().getId()); Map<Long, UserRole> roleMap = new HashMap<Long, UserRole>(); for (UserRole role : userRoleDAO.list(Constants.ALL_RESULTS)) { roleMap.put(role.getKey().getId(), role); } StringBuilder permissions = new StringBuilder(); permissions.append("{"); for (UserAuthorization auth : authorizationList) { UserRole role = roleMap.get(auth.getRoleId()); if (role != null) { permissions.append("\"" + auth.getObjectPath() + "\":["); for (Permission perm : role.getPermissions()) { permissions.append("\"" + perm.name() + "\","); } permissions.append("]"); permissions.append(","); } } if (permissions.lastIndexOf(",") == permissions.length() - 1) { permissions.deleteCharAt(permissions.lastIndexOf(",")); } permissions.append("}"); return permissions.toString(); }

Target:
private String getPermissionsMap(User currentUser) { List<UserAuthorization> authorizationList = userAuthorizationDAO.listByUser(currentUser .getKey().getId()); Map<Long, UserRole> roleMap = new HashMap<Long, UserRole>(); for (UserRole role : userRoleDAO.list(Constants.ALL_RESULTS)) { roleMap.put(role.getKey().getId(), role); } Map<String, Set<Permission>> permissions = new HashMap<String, Set<Permission>>(); for (UserAuthorization auth : authorizationList) { UserRole role = roleMap.get(auth.getRoleId()); if (role != null) { permissions.put(auth.getObjectPath(), role.getPermissions()); } } ObjectMapper jsonObjectMapper = new ObjectMapper(); StringWriter writer = new StringWriter(); try { jsonObjectMapper.writeValue(writer, permissions); } catch (JsonGenerationException e) { } catch (JsonMappingException e) { } catch (IOException e) { } return writer.toString(); }
Source:
public void testTreeViewer_ReplacingSelectedItemSelectsNewItem() { TreeViewer treeViewer = new TreeViewer(getShell()); Object input = new Object(); ITreeContentProvider contentProvider = new ObservableListTreeContentProvider( new IObservableFactory<Object, IObservableList<String>>() { @Override public IObservableList<String> createObservable(Object target) { if (target == input) { return elementsList; } return null; } }, null); treeViewer.setComparator(new ViewerComparator()); treeViewer.setContentProvider(contentProvider); treeViewer.setInput(input); treeViewer.getTree().selectAll(); elementsList.set(0, "foo"); IStructuredSelection selection = (IStructuredSelection) treeViewer.getSelection(); Assert.assertEquals(elements.length, selection.size()); Assert.assertTrue(selection.toList().contains("foo")); }

Target:
public void testTreeViewer_ReplacingSelectedItemSelectsNewItem() { TreeViewer treeViewer = new TreeViewer(getShell()); Object input = new Object(); ITreeContentProvider contentProvider = new ObservableListTreeContentProvider( target -> target == input ? elementsList : null, null); treeViewer.setComparator(new ViewerComparator()); treeViewer.setContentProvider(contentProvider); treeViewer.setInput(input); treeViewer.getTree().selectAll(); elementsList.set(0, "foo"); IStructuredSelection selection = treeViewer.getStructuredSelection(); Assert.assertEquals(elements.length, selection.size()); Assert.assertTrue(selection.toList().contains("foo")); }
Source:
private static <T> T unwrap(ListenableFuture<T> future) { try { return future.get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } catch (ExecutionException e) { Throwables.throwIfUnchecked(e.getCause()); throw new RuntimeException(e); } }

Target:
private static <T> T unwrap(ListenableFuture<T> future) { return AtlasFutures.getUnchecked(future); }
Source:
private void fileChangedWatchService(File file) { while (file.isFile()) { file = file.getParentFile(); } try { if (watcher != null) { watcher.close(); } watcher = FileSystems.getDefault().newWatchService(); final Path path = FileSystems.getDefault().getPath(file.getAbsolutePath()); path.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY); new Thread(() -> { try { WatchKey key = watcher.take(); while (key != null) { for (WatchEvent<?> event : key.pollEvents()) { final Path changedPath = (Path) event.context(); if (changedPath.toString().endsWith(".html")) { Display.getDefault().asyncExec(() -> browser.refresh()); } } key.reset(); key = watcher.take(); } } catch (InterruptedException e) { e.printStackTrace(); } catch (ClosedWatchServiceException e) { } }).start(); } catch (IOException e) { e.printStackTrace(); } }

Target:
private void fileChangedWatchService(File file) { while (file.isFile()) { file = file.getParentFile(); } try { if (watcher != null) { watcher.close(); } watcher = FileSystems.getDefault().newWatchService(); final Path path = FileSystems.getDefault().getPath(file.getAbsolutePath()); path.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY); new Thread(() -> { try { WatchKey key = watcher.take(); while (key != null) { for (WatchEvent<?> event : key.pollEvents()) { final Path changedPath = (Path) event.context(); Display.getDefault().asyncExec(() -> { if (browser.getUrl().endsWith(changedPath.toString())) { browser.refresh(); } }); } key.reset(); key = watcher.take(); } } catch (InterruptedException e) { e.printStackTrace(); } catch (ClosedWatchServiceException e) { } }).start(); } catch (IOException e) { e.printStackTrace(); } }
Source:
public ESClient create(ElasticSearchEmbeddedNode node, ElasticSearchClientConfig config) { String clientType = System.getProperty(CLIENT_PROPERTY); switch (clientType != null ? clientType : DEFAULT_CLIENT) { case TRANSPORT_CLIENT: return createTransportClient(node); case REST_CLIENT: return createRestClient(node); case RANDOM_CLIENT: getRandomClient(); default: throw new IllegalArgumentException(""); } }

Target:
public ESClient create(ElasticSearchEmbeddedNode node, ElasticSearchClientConfig config) { String clientType = System.getProperty(CLIENT_PROPERTY); switch (clientType != null ? clientType : DEFAULT_CLIENT) { case TRANSPORT_CLIENT: return createTransportClient(node); case REST_CLIENT: return createRestClient(node); default: throw new IllegalArgumentException("Unknown Elasticsearch client type: " + clientType); } }
Source:
public void testPy4jInstalled() throws IOException, InterruptedException { when(mockPythonProcess.sendAndGetResult(eq("\n\nimport py4j\n"))).thenReturn(">>>"); pythonInterpreter.open(); Integer py4jPort = pythonInterpreter.getPy4jPort(); assertNotNull(py4jPort); assertTrue(cmdHistory.contains("def help()")); assertTrue(cmdHistory.contains("class PyZeppelinContext(object):")); assertTrue(cmdHistory.contains("z = Py4jZeppelinContext")); assertTrue(cmdHistory.contains("def show")); assertTrue(cmdHistory.contains("GatewayClient(port=" + py4jPort + ")")); assertTrue(cmdHistory.contains("org.apache.zeppelin.display.Input")); assertTrue(serverIsListeningOn(py4jPort)); pythonInterpreter.close(); TimeUnit.SECONDS.sleep(1); assertFalse(serverIsListeningOn(py4jPort)); }

Target:
public void testPy4jInstalled() throws IOException, InterruptedException { when(mockPythonProcess.sendAndGetResult(eq("\n\nimport py4j\n"))).thenReturn(">>>"); pythonInterpreter.open(); Integer py4jPort = pythonInterpreter.getPy4jPort(); assertNotNull(py4jPort); assertTrue(cmdHistory.contains("def help()")); assertTrue(cmdHistory.contains("class PyZeppelinContext(object):")); assertTrue(cmdHistory.contains("z = Py4jZeppelinContext")); assertTrue(cmdHistory.contains("def show")); assertTrue(cmdHistory.contains("GatewayClient(port=" + py4jPort + ")")); assertTrue(cmdHistory.contains("org.apache.zeppelin.display.Input")); assertTrue(serverIsListeningOn(py4jPort)); pythonInterpreter.close(); TimeUnit.MILLISECONDS.sleep(100); assertFalse(serverIsListeningOn(py4jPort)); }
Source:
public Dialog onCreateDialog(Bundle bundle) { View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_about, null); Dialog aboutDialog = new AlertDialog.Builder(getActivity()) .setView(view) .setTitle(R.string.app_name) .setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }).create(); aboutDialog.setCanceledOnTouchOutside(true); return aboutDialog; }

Target:
public Dialog onCreateDialog(Bundle bundle) { View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_about, null); Dialog aboutDialog = new AlertDialog.Builder(getActivity()) .setView(view) .setTitle(R.string.about_Dialog) .setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }).create(); aboutDialog.setCanceledOnTouchOutside(true); return aboutDialog; }
Source:
private void compilejob(Item item) { ProcessItem processItem = (ProcessItem) item; Map<ExportChoice, Object> exportChoiceMap = JobScriptsManagerFactory.getDefaultExportChoiceMap(); exportChoiceMap.put(ExportChoice.doNotCompileCode, true); exportChoiceMap.put(ExportChoice.needDependencies, true); exportChoiceMap.put(ExportChoice.addStatistics, false); exportChoiceMap.put(ExportChoice.addTracs, false); exportChoiceMap.put(ExportChoice.needAntScript, false); exportChoiceMap.put(ExportChoice.needMavenScript, false); exportChoiceMap.put(ExportChoice.applyToChildren, false); exportChoiceMap.put(ExportChoice.needContext, true); exportChoiceMap.put(ExportChoice.binaries, true); exportChoiceMap.put(ExportChoice.needSourceCode, false); exportChoiceMap.put(ExportChoice.executeTests, false); exportChoiceMap.put(ExportChoice.includeTestSource, true); exportChoiceMap.put(ExportChoice.includeLibs, true); exportChoiceMap.put(ExportChoice.needLog4jLevel, false); exportChoiceMap.put(ExportChoice.jobType, ERepositoryObjectType.PROCESS); exportChoiceMap.put(ExportChoice.contextName, processItem.getProcess().getDefaultContext()); try { IBuildJobHandler handler = BuildJobFactory.createBuildJobHandler(processItem, processItem.getProcess().getDefaultContext(), processItem.getProperty().getVersion(), exportChoiceMap); Map<String, Object> prepareParams = new HashMap<String, Object>(); prepareParams.put(IBuildResourceParametes.OPTION_ITEMS, true); prepareParams.put(IBuildResourceParametes.OPTION_ITEMS_DEPENDENCIES, true); handler.prepare(null, prepareParams); } catch (ProcessorException e) { ExceptionHandler.process(e); } catch (Exception e) { ExceptionHandler.process(e); } }

Target:
private void compilejob(Item item) { ProcessItem processItem = (ProcessItem) item; Map<ExportChoice, Object> exportChoiceMap = JobScriptsManagerFactory.getDefaultExportChoiceMap(); exportChoiceMap.put(ExportChoice.needDependencies, true); exportChoiceMap.put(ExportChoice.addStatistics, false); exportChoiceMap.put(ExportChoice.addTracs, false); exportChoiceMap.put(ExportChoice.needAntScript, false); exportChoiceMap.put(ExportChoice.needMavenScript, false); exportChoiceMap.put(ExportChoice.applyToChildren, false); exportChoiceMap.put(ExportChoice.needContext, true); exportChoiceMap.put(ExportChoice.binaries, true); exportChoiceMap.put(ExportChoice.needSourceCode, false); exportChoiceMap.put(ExportChoice.includeLibs, true); exportChoiceMap.put(ExportChoice.needLog4jLevel, false); exportChoiceMap.put(ExportChoice.jobType, ERepositoryObjectType.PROCESS); exportChoiceMap.put(ExportChoice.contextName, processItem.getProcess().getDefaultContext()); try { IBuildJobHandler handler = BuildJobFactory.createBuildJobHandler(processItem, processItem.getProcess().getDefaultContext(), processItem.getProperty().getVersion(), exportChoiceMap); Map<String, Object> prepareParams = new HashMap<String, Object>(); prepareParams.put(IBuildResourceParametes.OPTION_ITEMS, true); prepareParams.put(IBuildResourceParametes.OPTION_ITEMS_DEPENDENCIES, true); handler.prepare(null, prepareParams); } catch (Exception e) { log.error(e.getMessage(),e); } }
Source:
private <C extends WriteCommand> Object writeManyRemoteCallback(WriteManyCommandHelper<C , ?, ?> helper,InvocationContext ctx, C command, Object rv) { LocalizedCacheTopology topology = checkTopologyId(command); ConsistentHash ch = topology.getWriteConsistentHash(); Map<Address, IntSet> backups = backupOwnersOfSegments(ch, IntSets.from(ch.getPrimarySegmentsForOwner(rpcManager.getAddress()))); if (backups.isEmpty()) { return rv; } boolean isSync = isSynchronous(command); CompletableFuture[] futures = isSync ? new CompletableFuture[backups.size()] : null; int future = 0; for (Entry<Address, IntSet> backup : backups.entrySet()) { C copy = helper.copyForBackup(command, topology, backup.getValue()); copy.setTopologyId(command.getTopologyId()); Address backupOwner = backup.getKey(); if (isSync) { futures[future++] = rpcManager .invokeCommand(backupOwner, copy, SingleResponseCollector.validOnly(), rpcManager.getSyncRpcOptions()) .toCompletableFuture(); } else { rpcManager.sendTo(backupOwner, copy, DeliverOrder.PER_SENDER); } } return isSync ? asyncValue(CompletableFuture.allOf(futures).thenApply(nil -> rv)) : rv; }

Target:
private <C extends WriteCommand> Object writeManyRemoteCallback(WriteManyCommandHelper<C , ?, ?> helper,InvocationContext ctx, C command, Object rv) { LocalizedCacheTopology topology = checkTopologyId(command); ConsistentHash ch = topology.getWriteConsistentHash(); Map<Address, IntSet> backups = backupOwnersOfSegments(ch, topology.getLocalReadSegments()); if (backups.isEmpty()) { return rv; } boolean isSync = isSynchronous(command); CompletableFuture[] futures = isSync ? new CompletableFuture[backups.size()] : null; int future = 0; for (Entry<Address, IntSet> backup : backups.entrySet()) { C copy = helper.copyForBackup(command, topology, backup.getValue()); copy.setTopologyId(command.getTopologyId()); Address backupOwner = backup.getKey(); if (isSync) { futures[future++] = rpcManager .invokeCommand(backupOwner, copy, SingleResponseCollector.validOnly(), rpcManager.getSyncRpcOptions()) .toCompletableFuture(); } else { rpcManager.sendTo(backupOwner, copy, DeliverOrder.PER_SENDER); } } return isSync ? asyncValue(CompletableFuture.allOf(futures).thenApply(nil -> rv)) : rv; }
Source:
public void testAddFailure() throws Exception{ String message = "can not perform mutation"; when(callable.futureCall(rowMutation)).thenReturn(future); future.setException(new RuntimeException(message)); ApiFuture<Void> result = bulkMutationClient.add(rowMutation); Assert.assertTrue(result.isDone()); result.get(); expect.expectMessage(message); verify(callable).futureCall(rowMutation); }

Target:
public void testAddFailure() throws Exception { when(callable.futureCall(rowMutation)).thenReturn(future); future.setException(new RuntimeException("can not perform mutation")); ApiFuture<Void> result = bulkMutationClient.add(rowMutation); assertTrue(result.isDone()); verify(callable).futureCall(rowMutation); result.get(); }
Source:
public DataContainer toContainer() { return super.toContainer() .set(Keys.HIDE_ENCHANTMENTS, enchantments) .set(Keys.HIDE_ATTRIBUTES, attributes) .set(Keys.HIDE_UNBREAKABLE, unbreakable) .set(Keys.HIDE_CAN_DESTROY, canDestroy) .set(Keys.HIDE_CAN_PLACE, canPlace) .set(Keys.HIDE_MISCELLANEOUS, miscellaneous); }

Target:
public DataContainer toContainer() { return super.toContainer() .set(Keys.HIDE_ENCHANTMENTS, this.enchantments) .set(Keys.HIDE_ATTRIBUTES, this.attributes) .set(Keys.HIDE_UNBREAKABLE, this.unbreakable) .set(Keys.HIDE_CAN_DESTROY, this.canDestroy) .set(Keys.HIDE_CAN_PLACE, this.canPlace) .set(Keys.HIDE_MISCELLANEOUS, this.miscellaneous); }
Source:
public byte getByteUnchecked(int internalPosition) { return value.getByteUnchecked(internalPosition); }

Target:
public byte getByteUnchecked(int internalPosition) { assert internalPositionInRange(internalPosition, getOffsetBase(), getPositionCount()); return value.getByte(0); }
Source:
public boolean getHasUserEmail() { return !activityLog.getEmail().contains(Const.ActivityLog.UNKNOWN); }

Target:
public boolean getHasUserEmail() { return !Const.ActivityLog.UNKNOWN.contentEquals(activityLog.getEmail()); }
Source:
private void doTestRangeScan(int fullBlocks, int partialBlocks, boolean invertLoopIndexes) { int value; int value2; int count = 0; for (int i = 0; i <= 100; i++) { for (int j = 0; j <= 100; j++) { if (invertLoopIndexes) { value = j; value2 = i; } else { value = i; value2 = j; } String[] split = callCalculateSuffix(value, value2, fullBlocks, partialBlocks); for (String suffix : split) { String[] values = suffix.split("\\+"); if (values.length > 1) { value = Integer.parseInt(values[0]); value2 = Integer.parseInt(values[1]); if (value > 5 || value2 > 5) { count++; StringBuilder msg = new StringBuilder(); msg.append("Found incorrect value "); msg.append(suffix); msg.append(". value = "); msg.append(invertLoopIndexes ? j : i); msg.append(" value2 = "); msg.append(invertLoopIndexes ? i : j); msg.append(" fullBlocks = "); msg.append(fullBlocks); msg.append(" partialBlocks = "); msg.append(partialBlocks); } } } } } if (count > 0) { Assert.fail("Incorrect values were founded " + count + " times"); } }

Target:
private void doTestRangeScan(int fullBlocks, int partialBlocks, boolean invertLoopIndexes) { int value; int value2; int count = 0; for (int i = 0; i <= 100; i++) { for (int j = 0; j <= 100; j++) { if (invertLoopIndexes) { value = j; value2 = i; } else { value = i; value2 = j; } String[] split = callCalculateSuffix(value, value2, fullBlocks, partialBlocks); for (String suffix : split) { String[] values = suffix.split("\\+"); if (values.length > 1) { value = Integer.valueOf(values[0]); value2 = Integer.valueOf(values[1]); if (value > 5 || value2 > 5) { count++; StringBuffer msg = new StringBuffer(); msg.append("Found incorrect value "); msg.append(suffix); msg.append(". value = "); msg.append(invertLoopIndexes ? j : i); msg.append(" value2 = "); msg.append(invertLoopIndexes ? i : j); msg.append(" fullBlocks = "); msg.append(fullBlocks); msg.append(" partialBlocks = "); msg.append(partialBlocks); } } } } } if (count > 0) { fail("Incorrect values were founded " + count + " times"); } }
Source:
public Neo4jGraph(String path) { service = new GraphDatabaseFactory().newEmbeddedDatabase(path); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { service.shutdown(); } }); nodeLabel = DynamicLabel.label(NODELABEL); try (Transaction tx = service.beginTx()) { service.schema().getConstraints().forEach(e -> e.drop()); service.schema().getIndexes().forEach(e -> e.drop()); service.schema().constraintFor(nodeLabel) .assertPropertyIsUnique(PropertyTypes.ID.name()) .create(); service.schema().indexFor(nodeLabel) .on(RANK.name()) .create(); tx.success(); } }

Target:
public Neo4jGraph(String path) { service = new GraphDatabaseFactory().newEmbeddedDatabase(path); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { service.shutdown(); } }); nodeLabel = DynamicLabel.label(NODELABEL.name()); execute(new IndexCommand(nodeLabel)); }
Source:
public ImmutableList<SimpleColumn> getList() { if (columns == null) { columns = Builder.getDefaultInstance().listBuilder.build(); } return columns; }

Target:
public List<SimpleColumn> getList() { return columns; }
Source:
public void verifyRelatedVideoAdded(String videoName) { waitForTextToBePresentInElementByBy(rvFirstVideo, videoName); }

Target:
public void verifyRelatedVideoAdded(String videoName) { waitForTextToBePresentInElementByElement(rvFirstVideo, videoName); }
Source:
public ExtentBufferedCompositePattern(Extent extent, Pattern... patterns) { super(extent); checkArgument(patterns.length == 0, "patterns cannot be empty"); this.patterns = patterns; }

Target:
public ExtentBufferedCompositePattern(Extent extent, Pattern... patterns) { super(extent); checkArgument(patterns.length != 0, "patterns cannot be empty"); this.patterns = patterns; }
Source:
public ZeppelinDevServer(int port) throws TException, IOException { super(null, port, ""); }

Target:
public ZeppelinDevServer(int port) throws TException, IOException { super(null, port, ":"); }
Source:
public void should_fail_if_the_map_under_test_is_empty_whatever_the_assertions_requirements_are() { actual.clear(); try { maps.assertAnySatisfy(someInfo(), actual, ($1,$2) -> assertThat(true).isTrue()); } catch (AssertionError e) { verify(failures).failure(info, elementsShouldSatisfyAny(actual)); return; } failBecauseExpectedAssertionErrorWasNotThrown(); }

Target:
public void should_fail_if_the_map_under_test_is_empty_whatever_the_assertions_requirements_are() { actual.clear(); AssertionError error = expectAssertionError(() -> maps.assertAnySatisfy(someInfo(), actual, ($1, $2) -> assertThat(true).isTrue())); assertThat(error).hasMessage(elementsShouldSatisfyAny(actual).create()); }
Source:
public void run() { try { index.addNotification(TEST_DEFAULT_NOTIFICATION); Assert.assertTrue(exists(TEST_DEFAULT_NOTIFICATION)); index.addNotification(TEST_URL_NOTIFICATION); Assert.assertTrue(exists(TEST_URL_NOTIFICATION)); } catch (Exception e) { e.printStackTrace(); } }

Target:
public void run() { try { index.addNotification(TEST_DEFAULT_NOTIFICATION); defaultNotificationExists = exists(TEST_DEFAULT_NOTIFICATION); index.addNotification(TEST_URL_NOTIFICATION); urlNotificationExists = exists(TEST_URL_NOTIFICATION); } catch (Exception e) { this.exception = e; e.printStackTrace(); } }
Source:
public void equalityTestZoned() { ZonedDateTime zoned = ZonedDateTime.now(); DateTimeType dt1 = new DateTimeType(zoned); DateTimeType dt2 = DateTimeType.valueOf(dt1.toString()); assertTrue(dt1.toString().equals(dt2.toString())); assertTrue(dt1.equals(dt2)); assertTrue(dt1.getZonedDateTime().equals(dt2.getZonedDateTime())); assertTrue(dt1.equals(dt2)); }

Target:
public void equalityTestZoned() { ZonedDateTime zoned = ZonedDateTime.now(); DateTimeType dt1 = new DateTimeType(zoned); DateTimeType dt2 = DateTimeType.valueOf(dt1.toFullString()); assertTrue(dt1.toString().equals(dt2.toFullString())); assertTrue(dt1.getZonedDateTime().equals(dt2.getZonedDateTime())); assertTrue(dt1.equals(dt2)); }
Source:
private static void putReportedMetrics(IndexedSet<Metric> metricSet, String instanceId, List<Metric> reportedMetrics) { for (Metric metric : reportedMetrics) { if (metric.getHostname() == null) { continue; } Metric oldMetric = metricSet.getFirstByField(FULL_NAME_INDEX, metric.getFullMetricName()); if (oldMetric == null) { metricSet.add(metric); } else if (metric.getMetricType() == MetricType.COUNTER) { oldMetric.addValue(metric.getValue()); } else { oldMetric.setValue(metric.getValue()); } } }

Target:
private static void putReportedMetrics(IndexedSet<Metric> metricSet, String instanceId, List<Metric> reportedMetrics) { for (Metric metric : reportedMetrics) { if (metric.getHostname() == null) { continue; } if (!metricSet.add(metric)) { Metric oldMetric = metricSet.getFirstByField(FULL_NAME_INDEX, metric.getFullMetricName()); if (metric.getMetricType() == MetricType.COUNTER) { if (metric.getValue() != 0L) { oldMetric.addValue(metric.getValue()); } } else { oldMetric.setValue(metric.getValue()); } } } }
Source:
public void processHeader(final ParserContext context) { Options options = getAsciiDocOptionsAndAttributes(context); final Asciidoctor asciidoctor = getEngine(options); DocumentHeader header = asciidoctor.readDocumentHeader(context.getFile()); Map<String, Object> documentModel = context.getDocumentModel(); if (header.getDocumentTitle() != null) { documentModel.put("title", header.getDocumentTitle().getCombined()); } Map<String, Object> attributes = header.getAttributes(); for (Map.Entry<String, Object> attribute : attributes.entrySet()) { String key = attribute.getKey(); Object value = attribute.getValue(); if (hasJBakePrefix(key)) { String pKey = key.substring(6); if(value instanceof String) { processHeader(pKey, (String) value, documentModel); } else { documentModel.put(pKey, value); } } if (hasRevdate(key) && canCastToString(value)) { String dateFormat = context.getConfig().getDateFormat(); DateFormat df = new SimpleDateFormat(dateFormat); try { Date date = df.parse((String) value); context.setDate(date); } catch (ParseException e) { LOGGER.error("Unable to parse revdate. Expected {}", dateFormat, e); } } if (key.equals("jbake-tags")) { if (canCastToString(value)) { context.setTags(((String) value).split(",")); } else { LOGGER.error("Wrong value of 'jbake-tags'. Expected a String got '{}'", getValueClassName(value)); } } else { documentModel.put(key, attributes.get(key)); } } }

Target:
public void processHeader(final ParserContext context) { Options options = getAsciiDocOptionsAndAttributes(context); final Asciidoctor asciidoctor = getEngine(options); DocumentHeader header = asciidoctor.readDocumentHeader(context.getFile()); Map<String, Object> documentModel = context.getDocumentModel(); if (header.getDocumentTitle() != null) { documentModel.put("title", header.getDocumentTitle().getCombined()); } Map<String, Object> attributes = header.getAttributes(); for (Map.Entry<String, Object> attribute : attributes.entrySet()) { String key = attribute.getKey(); Object value = attribute.getValue(); if (hasJBakePrefix(key)) { String pKey = key.substring(6); if(canCastToString(value)) { storeHeaderValue(pKey, (String) value, documentModel); } else { documentModel.put(pKey, value); } } if (hasRevdate(key) && canCastToString(value)) { String dateFormat = context.getConfig().getDateFormat(); DateFormat df = new SimpleDateFormat(dateFormat); try { Date date = df.parse((String) value); context.setDate(date); } catch (ParseException e) { LOGGER.error("Unable to parse revdate. Expected {}", dateFormat, e); } } if (key.equals("jbake-tags")) { if (canCastToString(value)) { context.setTags(((String) value).split(",")); } else { LOGGER.error("Wrong value of 'jbake-tags'. Expected a String got '{}'", getValueClassName(value)); } } else { documentModel.put(key, attributes.get(key)); } } }
Source:
public void testConcurrentClose() { List<Type> types = ImmutableList.of(VARCHAR, BIGINT, BIGINT); OperatorContext operatorContext = driverContext.addOperatorContext(0, new PlanNodeId("test"), "values"); ValuesOperator source = new ValuesOperator(operatorContext, rowPagesBuilder(types) .addSequencePage(10, 20, 30, 40) .build()); Operator sink = createSinkOperator(types); Driver driver = Driver.createDriver(driverContext, source, sink); scheduledExecutor.submit(() -> driver.processFor(new Duration(1, TimeUnit.NANOSECONDS))); scheduledExecutor.submit(() -> driver.close()); while (!driverContext.isDone()) { Uninterruptibles.sleepUninterruptibly(10, TimeUnit.MILLISECONDS); } }

Target:
public void testConcurrentClose() { List<Type> types = ImmutableList.of(VARCHAR, BIGINT, BIGINT); OperatorContext operatorContext = driverContext.addOperatorContext(0, new PlanNodeId("test"), "values"); ValuesOperator source = new ValuesOperator(operatorContext, rowPagesBuilder(types) .addSequencePage(10, 20, 30, 40) .build()); Operator sink = createSinkOperator(types); Driver driver = Driver.createDriver(driverContext, source, sink); scheduledExecutor.submit(() -> driver.processFor(new Duration(1, TimeUnit.NANOSECONDS))); scheduledExecutor.submit(() -> driver.close()); while (!driverContext.isDone()) { Uninterruptibles.sleepUninterruptibly(1, TimeUnit.MILLISECONDS); } }
Source:
private static void refreshBorderFigure(final BorderedStyle borderedStyle, final StyledFigure styledFigure) { LineBorder lineBorder = null; if (styledFigure.getBorder() instanceof LineBorder) { lineBorder = (LineBorder) styledFigure.getBorder(); } else { lineBorder = new LineBorder(); if (styledFigure instanceof Shape) { styledFigure.setBorder(null); } else { styledFigure.setBorder(lineBorder); } } if (borderedStyle.getBorderSize() != null) { lineBorder.setWidth(borderedStyle.getBorderSize().intValue()); } else { lineBorder.setWidth(0); } final RGBValues borderColor = borderedStyle.getBorderColor(); if (borderColor != null) { lineBorder.setColor(VisualBindingManager.getDefault().getColorFromRGBValues(borderColor)); } if (borderedStyle.getBorderSize() == null || borderedStyle.getBorderSize().intValue() == 0) { if (!(styledFigure instanceof NoteFigure)) { styledFigure.setBorder(null); } } }

Target:
private static void refreshBorderFigure(final BorderedStyle borderedStyle, final StyledFigure styledFigure) { LineBorder lineBorder = null; if (styledFigure.getBorder() instanceof LineBorder) { lineBorder = (LineBorder) styledFigure.getBorder(); } else { lineBorder = new LineBorder(); if (styledFigure instanceof Shape) { styledFigure.setBorder(null); } else { styledFigure.setBorder(lineBorder); } } int borderSize = 0; if (borderedStyle.getBorderSize() != null) { borderSize = borderedStyle.getBorderSize().intValue(); } lineBorder.setWidth(borderSize); final RGBValues borderColor = borderedStyle.getBorderColor(); if (borderColor != null) { lineBorder.setColor(VisualBindingManager.getDefault().getColorFromRGBValues(borderColor)); } if (borderedStyle.getBorderSize() == null || borderedStyle.getBorderSize().intValue() == 0) { if (!(styledFigure instanceof NoteFigure)) { styledFigure.setBorder(null); } } }
Source:
public synchronized void run(JobConfig jobConfig, long jobId) throws JobDoesNotExistException, ResourceExhaustedException { Context forkedCtx = Context.current().fork(); Context prevCtx = forkedCtx.attach(); try { LOG.info("jobConfig class {}", jobConfig.getClass().getCanonicalName()); if (jobConfig instanceof PlanConfig) { mPlanTracker.run((PlanConfig) jobConfig, mCommandManager, mJobServerContext, getWorkerInfoList(), jobId); return; } else if (jobConfig instanceof WorkflowConfig) { mWorkflowTracker.run((WorkflowConfig) jobConfig, jobId); return; } throw new JobDoesNotExistException( ExceptionMessage.JOB_DEFINITION_DOES_NOT_EXIST.getMessage(jobConfig.getName())); } finally { forkedCtx.detach(prevCtx); } }

Target:
public synchronized void run(JobConfig jobConfig, long jobId) throws JobDoesNotExistException, ResourceExhaustedException { Context forkedCtx = Context.current().fork(); Context prevCtx = forkedCtx.attach(); try { if (jobConfig instanceof PlanConfig) { mPlanTracker.run((PlanConfig) jobConfig, mCommandManager, mJobServerContext, getWorkerInfoList(), jobId); return; } else if (jobConfig instanceof WorkflowConfig) { mWorkflowTracker.run((WorkflowConfig) jobConfig, jobId); return; } throw new JobDoesNotExistException( ExceptionMessage.JOB_DEFINITION_DOES_NOT_EXIST.getMessage(jobConfig.getName())); } finally { forkedCtx.detach(prevCtx); } }