auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected float getLayerHardness(BlockPos targetPos, BlockRailBase.EnumRailDirection dir) { float hardness = layerAction(targetPos, dir, 0F, this::getBlockHardness, (s, r) -> s + r); hardness *= HARDNESS_MULTIPLIER; ItemStack boreSlot = getStackInSlot(0); if (boreSlot != null && boreSlot.getItem() instanceof IBoreHead) { IBoreHead head = (IBoreHead) boreSlot.getItem(); float dig = 2f - head.getDigModifier(); hardness *= dig; hardness /= (1 + EnchantmentHelper.getEnchantmentLevel(Enchantments.EFFICIENCY, boreSlot)); } hardness /= RailcraftConfig.boreMiningSpeedMultiplier(); return hardness; }

Target:
protected float getLayerHardness(BlockPos targetPos, BlockRailBase.EnumRailDirection dir) { float hardness = layerAction(targetPos, dir, 0F, this::getBlockHardness, (s, r) -> s + r); hardness *= HARDNESS_MULTIPLIER; ItemStack boreSlot = getStackInSlot(0); if (!InvTools.isEmpty(boreSlot) && boreSlot.getItem() instanceof IBoreHead) { IBoreHead head = (IBoreHead) boreSlot.getItem(); float dig = 2f - head.getDigModifier(); hardness *= dig; int e = EnchantmentHelper.getEnchantmentLevel(Enchantments.EFFICIENCY, boreSlot); hardness /= e * e * 0.2 + 1; } hardness /= RailcraftConfig.boreMiningSpeedMultiplier(); return hardness; }
Source:
public void unregisterAll() { List<AppRegistration> appRegistrations = appRegistryService.findAll(); for (AppRegistration appRegistration : appRegistrations) { String applicationName = appRegistration.getName(); String applicationVersion = appRegistration.getVersion(); ApplicationType applicationType = appRegistration.getType(); if (applicationType != ApplicationType.task) { String streamWithApp = findStreamContainingAppOf(applicationType, applicationName, applicationVersion); if (streamWithApp != null) { throw new UnregisterAppException(String.format("The app [%s:%s:%s] you're trying to unregister is " + "currently used in stream '%s'.", applicationName, applicationType, applicationVersion, streamWithApp)); } } } appRegistryService.deleteAll(); }

Target:
public void unregisterAll() { List<AppRegistration> appRegistrations = appRegistryService.findAll(); List<AppRegistration> appRegistrationsToUnregister = new ArrayList<>(); for (AppRegistration appRegistration : appRegistrations) { String applicationName = appRegistration.getName(); String applicationVersion = appRegistration.getVersion(); ApplicationType applicationType = appRegistration.getType(); if (applicationType != ApplicationType.task) { String streamWithApp = findStreamContainingAppOf(applicationType, applicationName, applicationVersion); if (streamWithApp == null) { appRegistrationsToUnregister.add(appRegistration); } } else { appRegistrationsToUnregister.add(appRegistration); } } if (!appRegistrationsToUnregister.isEmpty()) { appRegistryService.deleteAll(appRegistrationsToUnregister); } }
Source:
public void setContext(String context){ typingRule.setContext(BloodTestContext.valueOf(context.replaceAll("\\s","").toUpperCase(Locale.FRENCH))); }

Target:
public void setContext(String context){ typingRule.setContext(BloodTestContext.valueOf(context.replaceAll("\\s","").toUpperCase())); }
Source:
private void testCreatePartitionedBucketedTableAsFewRows(Session session, HiveStorageFormat storageFormat) { String tableName = "test_create_partitioned_bucketed_table_as_few_rows"; @Language("SQL") String createTable = "" + "CREATE TABLE " + tableName + " " + "WITH (" + "format = '" + storageFormat + "', " + "partitioned_by = ARRAY[ 'partition_key' ], " + "bucketed_by = ARRAY[ 'bucket_key' ], " + "bucket_count = 11 " + ") " + "AS " + "SELECT * " + "FROM (" + "VALUES " + " (VARCHAR 'a', VARCHAR 'b', VARCHAR 'c'), " + " ('aa', 'bb', 'cc'), " + " ('aaa', 'bbb', 'ccc')" + ") t(bucket_key, col, partition_key)"; assertUpdate( getParallelWriteSession(), createTable, 3); verifyPartitionedBucketedTableAsFewRows(storageFormat, tableName); try { assertUpdate(session, "INSERT INTO " + tableName + " VALUES ('a0', 'b0', 'c')", 1); fail("expected failure"); } catch (Exception e) { assertEquals( e.getMessage(), getExpectedErrorMessageForInsertExistingBucketedTable( HiveSessionProperties.getInsertExistingPartitionsBehavior(session.toConnectorSession(new ConnectorId(session.getCatalog().get()))), "partition_key=c")); } assertUpdate(session, "DROP TABLE " + tableName); assertFalse(getQueryRunner().tableExists(session, tableName)); }

Target:
private void testCreatePartitionedBucketedTableAsFewRows(Session session, HiveStorageFormat storageFormat) { String tableName = "test_create_partitioned_bucketed_table_as_few_rows"; @Language("SQL") String createTable = "" + "CREATE TABLE " + tableName + " " + "WITH (" + "format = '" + storageFormat + "', " + "partitioned_by = ARRAY[ 'partition_key' ], " + "bucketed_by = ARRAY[ 'bucket_key' ], " + "bucket_count = 11 " + ") " + "AS " + "SELECT * " + "FROM (" + "VALUES " + " (VARCHAR 'a', VARCHAR 'b', VARCHAR 'c'), " + " ('aa', 'bb', 'cc'), " + " ('aaa', 'bbb', 'ccc')" + ") t(bucket_key, col, partition_key)"; assertUpdate( getParallelWriteSession(), createTable, 3); verifyPartitionedBucketedTableAsFewRows(storageFormat, tableName); assertThatThrownBy(() -> assertUpdate(session, "INSERT INTO " + tableName + " VALUES ('a0', 'b0', 'c')", 1)) .hasMessage(getExpectedErrorMessageForInsertExistingBucketedTable( getInsertExistingPartitionsBehavior(getConnectorSession(session)), "partition_key=c")); assertUpdate(session, "DROP TABLE " + tableName); assertFalse(getQueryRunner().tableExists(session, tableName)); }
Source:
protected void setBooleanValue(final EObjectObservableValue element, final Object value) { if (value instanceof Collection<?>) { element.setValue(value); } else { if (null == value) { return; } else if (value.equals(0)) { if (element.getValue().toString().equals(booleanProposals[0])) { return; } element.setValue(Boolean.valueOf(booleanProposals[0])); } else if (value.equals(1)) { if (element.getValue().toString().equals(booleanProposals[1])) { return; } element.setValue(Boolean.valueOf(booleanProposals[1])); } else { Activator.log.error("Impossible to set boolean value " + value, null); } } }

Target:
protected void setBooleanValue(final EObjectObservableValue element, final Object value) { if (value instanceof Collection<?>) { element.setValue(value); } else { if (null == value) { } else if (value.equals(0)) { if (!element.getValue().toString().equals(this.booleanProposals[0])) { element.setValue(Boolean.valueOf(this.booleanProposals[0])); } } else if (value.equals(1)) { if (!element.getValue().toString().equals(this.booleanProposals[1])) { element.setValue(Boolean.valueOf(this.booleanProposals[1])); } } else { Activator.log.error("Impossible to set boolean value " + value, null); } } }
Source:
protected Image(String id, Date creationTimestamp, URI selfLink, String name, String description, String sourceType, URI preferredKernel, RawDisk rawDisk, Deprecated deprecated) { super(Kind.IMAGE, id, creationTimestamp, selfLink, name, description); this.sourceType = checkNotNull(sourceType, "sourceType of %s", name); this.preferredKernel = fromNullable(preferredKernel); this.rawDisk = checkNotNull(rawDisk, "rawDisk of %s", name); this.deprecated = fromNullable(deprecated); ; }

Target:
protected Image(String id, Date creationTimestamp, URI selfLink, String name, String description, String sourceType, URI preferredKernel, RawDisk rawDisk, Deprecated deprecated) { super(Kind.IMAGE, id, creationTimestamp, selfLink, name, description); this.sourceType = checkNotNull(sourceType, "sourceType of %s", name); this.preferredKernel = fromNullable(preferredKernel); this.rawDisk = checkNotNull(rawDisk, "rawDisk of %s", name); this.deprecated = fromNullable(deprecated); }
Source:
public String requestToken() { RequestBuilder builder = RequestBuilder.post(RequestBuilder.constructHttpUrl(url, new String[0])); builder.header(HttpHeaders.CONTENT_TYPE, HttpMediaType.APPLICATION_FORM_URLENCODED); builder.header(HttpHeaders.AUTHORIZATION, DEFAULT_AUTHORIZATION); FormBody formBody = new FormBody.Builder() .add("grant_type", "urn:ibm:params:oauth:grant-type:apikey") .add("apikey", apiKey) .add("response_type", "cloud_iam") .build(); builder.body(formBody); tokenData = callIamApi(builder.build()); return tokenData.getAccessToken(); }

Target:
private String requestToken() { RequestBuilder builder = RequestBuilder.post(RequestBuilder.constructHttpUrl(url, new String[0])); builder.header(HttpHeaders.CONTENT_TYPE, HttpMediaType.APPLICATION_FORM_URLENCODED); builder.header(HttpHeaders.AUTHORIZATION, DEFAULT_AUTHORIZATION); FormBody formBody = new FormBody.Builder() .add(GRANT_TYPE, REQUEST_GRANT_TYPE) .add(API_KEY, apiKey) .add(RESPONSE_TYPE, CLOUD_IAM) .build(); builder.body(formBody); tokenData = callIamApi(builder.build()); return tokenData.getAccessToken(); }
Source:
private boolean isPartOfGroup(Object object, final Iterable<? extends Diff> differences) { final Predicate<? super EObject> isPartOfTree = new Predicate<EObject>() { public boolean apply(EObject input) { return Iterables.contains(filter(differences, not(or(fViewerFilter.getPredicates()))), input); } }; boolean ret = false; if (object instanceof Match) { ret = Iterables.any(((Match)object).getAllDifferences(), isPartOfTree); } else if (object instanceof Diff) { if (!isPartOfTree.apply((Diff)object)) { if (object instanceof ReferenceChange && ((ReferenceChange)object).getReference().isContainment()) { ret = Iterables.any(((Diff)object).getMatch().getComparison().getMatch( ((ReferenceChange)object).getValue()).getAllDifferences(), isPartOfTree); } } else { ret = true; } } return ret; }

Target:
private boolean isPartOfGroup(Object object, final Iterable<? extends Diff> differences) { final Predicate<? super EObject> isPartOfTree = new Predicate<EObject>() { public boolean apply(EObject input) { return Iterables.contains(differences, input); } }; boolean ret = false; if (object instanceof Match) { ret = Iterables.any(((Match)object).getAllDifferences(), isPartOfTree); } else if (object instanceof Diff) { if (!isPartOfTree.apply((Diff)object)) { if (object instanceof ReferenceChange && ((ReferenceChange)object).getReference().isContainment()) { ret = Iterables.any(((Diff)object).getMatch().getComparison().getMatch( ((ReferenceChange)object).getValue()).getAllDifferences(), isPartOfTree); } } else { ret = true; } } return ret; }
Source:
public boolean applyCSSProperty(Object element, String property, CSSValue value, String pseudo, CSSEngine engine) throws Exception { boolean applied = true; if ("background".equals(property)) { applyCSSPropertyBackground(element, value, pseudo, engine); } else if ("background-attachment".equals(property)) { applyCSSPropertyBackgroundAttachment(element, value, pseudo, engine); }else if ("background-color".equals(property)) { applyCSSPropertyBackgroundColor(element, value, pseudo, engine); }else if ("background-image".equals(property)) { applyCSSPropertyBackgroundImage(element, value, pseudo, engine); }else if ("background-position".equals(property)) { applyCSSPropertyBackgroundPosition(element, value, pseudo, engine); }else if ("background-repeat".equals(property)) { applyCSSPropertyBackgroundRepeat(element, value, pseudo, engine); } else { applied = false; } return applied; }

Target:
public boolean applyCSSProperty(Object element, String property, CSSValue value, String pseudo, CSSEngine engine) throws Exception { if (property == null) { return false; } switch (property) { case "background": applyCSSPropertyBackground(element, value, pseudo, engine); break; case "background-attachment": applyCSSPropertyBackgroundAttachment(element, value, pseudo, engine); break; case "background-color": applyCSSPropertyBackgroundColor(element, value, pseudo, engine); break; case "background-image": applyCSSPropertyBackgroundImage(element, value, pseudo, engine); break; case "background-position": applyCSSPropertyBackgroundPosition(element, value, pseudo, engine); break; case "background-repeat": applyCSSPropertyBackgroundRepeat(element, value, pseudo, engine); break; default: return false; } return true; }
Source:
public void testLoadYamlFileFromDirectory() { final DirectoryYamlFlowLoader loader = new DirectoryYamlFlowLoader(new Props()); loader.loadProjectFlow(this.project, ExecutionsTestUtil.getFlowDir(YAML_FILE_NAME)); Assert.assertEquals(0, loader.getErrors().size()); Assert.assertEquals(1, this.project.getFlowMap().size()); Assert.assertTrue(this.project.getFlowMap().containsKey(FLOW_NAME)); final Flow flow = this.project.getFlowMap().get(FLOW_NAME); final AzkabanFlow azkabanFlow = flow.getAzkabanFlow(); Assert.assertEquals(FLOW_NAME, azkabanFlow.getName()); }

Target:
public void testLoadYamlFileFromDirectory() { final DirectoryYamlFlowLoader loader = new DirectoryYamlFlowLoader(new Props()); loader.loadProjectFlow(this.project, ExecutionsTestUtil.getFlowDir(BASIC_FLOW_YAML_DIR)); Assert.assertEquals(0, loader.getErrors().size()); Assert.assertEquals(1, loader.getFlowMap().size()); Assert.assertTrue(loader.getFlowMap().containsKey(FLOW_NAME_1)); final Flow flow = loader.getFlowMap().get(FLOW_NAME_1); final AzkabanFlow azkabanFlow = flow.getAzkabanFlow(); Assert.assertEquals(FLOW_NAME_1, azkabanFlow.getName()); Assert.assertEquals(4, azkabanFlow.getNodes().size()); }
Source:
public ArrayList<Lecture> getLecture(final List<String> lectureId, final String userId) throws AuthenticationException, DatabaseAccessException { final long currentTime = System.currentTimeMillis(); final ArrayList<Lecture> allLectures = new ArrayList<Lecture>(); for (int lectures = lectureId.size() - 1; lectures >= 0; lectures--) { try { allLectures.add(LectureManager.mongoGetLecture(getInstance().auth, getInstance().database, lectureId.get(lectures), userId, currentTime)); } catch (DatabaseAccessException e) { LOG.info(LoggingConstants.EXCEPTION_MESSAGE, e); if (!e.isRecoverable()) { throw e; } } catch (AuthenticationException e) { LOG.error("Error: {}", e); if (e.getType() != AuthenticationException.INVALID_DATE) { throw e; } } } return allLectures; }

Target:
public ArrayList<Lecture> getLecture(final List<String> lectureId, final String userId) throws AuthenticationException, DatabaseAccessException { final long currentTime = System.currentTimeMillis(); final ArrayList<Lecture> allLectures = new ArrayList<Lecture>(); for (int lectures = lectureId.size() - 1; lectures >= 0; lectures--) { try { allLectures.add(LectureManager.mongoGetLecture(getInstance().auth, getInstance().database, lectureId.get(lectures), userId, currentTime)); } catch (DatabaseAccessException e) { LOG.error(LoggingConstants.EXCEPTION_MESSAGE, e); if (!e.isRecoverable()) { throw e; } } catch (AuthenticationException e) { LOG.error(LoggingConstants.EXCEPTION_MESSAGE, e); if (e.getType() != AuthenticationException.INVALID_DATE) { throw e; } } } return allLectures; }
Source:
private static void logArguments(CmdLineParser parser) { Options defaultOptions = new Options(); CmdLineParser defaultParser = new CmdLineParser(defaultOptions); StringBuilder sb = new StringBuilder("Swarm Client is running with the following configuration: "); for (OptionHandler argument : parser.getArguments()) { logValue(sb, argument, null); } for (OptionHandler option : parser.getOptions()) { logValue(sb, option, defaultParser); } logger.info(sb.toString()); }

Target:
private static void logArguments(CmdLineParser parser) { Options defaultOptions = new Options(); CmdLineParser defaultParser = new CmdLineParser(defaultOptions); StringBuilder sb = new StringBuilder("Client invoked with: "); for (OptionHandler argument : parser.getArguments()) { logValue(sb, argument, null); } for (OptionHandler option : parser.getOptions()) { logValue(sb, option, defaultParser); } logger.info(sb.toString()); }
Source:
public void publish() { this.shareToLAN(mc.playerController.getCurrentGameType(), false); }

Target:
public void publish() { this.shareToLAN(this.mc.playerController.getCurrentGameType(), false); }
Source:
public boolean isAssignableSeveralTimes() { if (Objects.nonNull(selectedLogicalNode) && selectedLogicalNode.getData() instanceof StructureTreeNode) { StructureTreeNode structureTreeNode = (StructureTreeNode) selectedLogicalNode.getData(); if (Objects.nonNull(structureTreeNode.getDataObject()) && structureTreeNode.getDataObject() instanceof View) { List<TreeNode> logicalNodeSiblings = selectedLogicalNode.getParent().getParent().getChildren(); int logicalNodeIndex = logicalNodeSiblings.indexOf(selectedLogicalNode.getParent()); List<TreeNode> viewSiblbings = selectedLogicalNode.getParent().getChildren(); if (viewSiblbings.indexOf(selectedLogicalNode) == viewSiblbings.size() - 1 && logicalNodeSiblings.size() > logicalNodeIndex + 1) { TreeNode nextSibling = logicalNodeSiblings.get(logicalNodeIndex + 1); if (nextSibling.getData() instanceof StructureTreeNode) { StructureTreeNode structureTreeNodeSibling = (StructureTreeNode) nextSibling.getData(); return structureTreeNodeSibling.getDataObject() instanceof IncludedStructuralElement; } } } } return false; }

Target:
public boolean isAssignableSeveralTimes() { if (Objects.nonNull(selectedLogicalNode) && selectedLogicalNode.getData() instanceof StructureTreeNode) { StructureTreeNode structureTreeNode = (StructureTreeNode) selectedLogicalNode.getData(); if (structureTreeNode.getDataObject() instanceof View) { List<TreeNode> logicalNodeSiblings = selectedLogicalNode.getParent().getParent().getChildren(); int logicalNodeIndex = logicalNodeSiblings.indexOf(selectedLogicalNode.getParent()); List<TreeNode> viewSiblbings = selectedLogicalNode.getParent().getChildren(); if (viewSiblbings.indexOf(selectedLogicalNode) == viewSiblbings.size() - 1 && logicalNodeSiblings.size() > logicalNodeIndex + 1) { TreeNode nextSibling = logicalNodeSiblings.get(logicalNodeIndex + 1); if (nextSibling.getData() instanceof StructureTreeNode) { StructureTreeNode structureTreeNodeSibling = (StructureTreeNode) nextSibling.getData(); return structureTreeNodeSibling.getDataObject() instanceof IncludedStructuralElement; } } } } return false; }
Source:
public void should_compile_less_into_css() throws Exception { ArgumentCaptor<byte[]> captor = ArgumentCaptor.forClass(byte[].class); final File lessStyle = directory.newFile("style.less"); FileUtils.writeStringToFile(lessStyle, "@myvar:1px;body{width:@myvar}"); given(modifier.resolve("style.less")).willReturn(lessStyle); compilableFile.compile(modifier); verify(modifier).add(eq("style.css"), captor.capture()); assertThat(new String(captor.getValue())).isEqualTo("body {\n width: 1px;\n}\n\n"); }

Target:
public void should_compile_less_into_css() throws Exception { final File lessStyle = directory.newFile("style.less"); FileUtils.writeStringToFile(lessStyle, "@myvar:1px;body{width:@myvar}"); given(modifier.resolve("style.less")).willReturn(lessStyle); final byte[] compilation = new CompilableFile("style.less", "style.css").compile(modifier); assertThat(new String(compilation, "UTF-8").replace("\r", "")).isEqualTo("body {\n width: 1px;\n}\n\n"); }
Source:
private void returnHandle(WrappedConnection handle, boolean error) { synchronized (stateLock) { if (destroyed) return; } synchronized (handles) { handles.remove(handle); if (handles.size() == 0) { if (mcf.getConnectionListenerPlugin() != null) { try { mcf.getConnectionListenerPlugin().passivated(con); } catch (SQLException se) { mcf.log.errorDuringConnectionListenerPassivation(mcf.getJndiName(), se); } } } } if (cels.size() > 0) { ConnectionEvent ce = null; if (!error) { ce = new ConnectionEvent(this, ConnectionEvent.CONNECTION_CLOSED); } else { ce = new ConnectionEvent(this, ConnectionEvent.CONNECTION_ERROR_OCCURRED, new SQLException(bundle.invalidConnection())); } ce.setConnectionHandle(handle); for (ConnectionEventListener cel : cels) { if (!error) { cel.connectionClosed(ce); } else { cel.connectionErrorOccurred(ce); } } } }

Target:
private void returnHandle(WrappedConnection handle, boolean error) { synchronized (stateLock) { if (destroyed) return; } synchronized (handles) { handles.remove(handle); if (handles.size() == 0) { if (mcf.getConnectionListenerPlugin() != null) { try { mcf.getConnectionListenerPlugin().passivated(con); } catch (SQLException se) { mcf.log.errorDuringConnectionListenerPassivation(mcf.getJndiName(), se); } } } } ConnectionEvent ce = null; if (!error) { ce = new ConnectionEvent(this, ConnectionEvent.CONNECTION_CLOSED); } else { ce = new ConnectionEvent(this, ConnectionEvent.CONNECTION_ERROR_OCCURRED, new SQLException(bundle.invalidConnection())); } ce.setConnectionHandle(handle); for (ConnectionEventListener cel : cels) { if (!error) { cel.connectionClosed(ce); } else { cel.connectionErrorOccurred(ce); } } }
Source:
private IFindReplaceTarget getTarget() { return Optional.ofNullable(fFocusPart.getSourceViewer()).map(SourceViewer::getFindReplaceTarget) .orElse(null); }

Target:
private IFindReplaceTarget getTarget() { return Optional.ofNullable(fFocusPart).map(MergeSourceViewer::getSourceViewer) .map(SourceViewer::getFindReplaceTarget) .orElse(null); }
Source:
public void beforeStep(StepExecution stepExecution) { SourceCode sc = EnumUtils.getEnum(SourceCode.class, sourceCode); judgmentRepository.markAsNotIndexedBySourceCode(sc); if (sc == null) { try { solrJudgmentsServer.deleteByQuery("*:*"); } catch (SolrServerException | IOException e) { throw new RuntimeException(e); } } }

Target:
public void beforeStep(StepExecution stepExecution) { SourceCode sc = EnumUtils.getEnum(SourceCode.class, sourceCode); judgmentRepository.markAsNotIndexedBySourceCode(sc); String deletingQuery = (sc == null) ? "*:*" : JudgmentIndexField.SOURCE_CODE.getFieldName() + ":" + sc.name(); try { solrJudgmentsServer.deleteByQuery(deletingQuery); } catch (SolrServerException | IOException e) { throw new RuntimeException(e); } }
Source:
public Object start(IApplicationContext context) throws Exception { String[] arguments = (String[]) context.getArguments().get(IApplicationContext.APPLICATION_ARGS); List<String> args = Arrays.asList(arguments); if (args.isEmpty() || args.contains("-help") || Arrays.asList(arguments).contains("--help")) { System.out.println(Messages.bind(Messages.CommandLineUsage)); return IApplication.EXIT_OK; } try { ResourcesPlugin.getWorkspace(); } catch (NoClassDefFoundError noClassError) { if (noClassError.getCause() instanceof ClassNotFoundException) { ClassNotFoundException classNotFoundException = (ClassNotFoundException) noClassError.getCause(); if (classNotFoundException.getException() instanceof BundleException) { BundleException bundleException = (BundleException) classNotFoundException.getException(); if (bundleException.getCause() instanceof IllegalStateException) { System.err.println(Messages.bind(Messages.WorkspaceRequired)); System.out.println(Messages.bind(Messages.CommandLineUsage)); return 1; } } } throw noClassError; } return new CodeFormatterApplication().start(context); }

Target:
public Object start(IApplicationContext context) throws Exception { String[] arguments = (String[]) context.getArguments().get(IApplicationContext.APPLICATION_ARGS); List<String> args = Arrays.asList(arguments); if (args.isEmpty() || args.contains("-help") || args.contains("--help")) { System.out.println(Messages.bind(Messages.CommandLineUsage)); return IApplication.EXIT_OK; } try { ResourcesPlugin.getWorkspace(); } catch (NoClassDefFoundError noClassError) { if (noClassError.getCause() instanceof ClassNotFoundException) { ClassNotFoundException classNotFoundException = (ClassNotFoundException) noClassError.getCause(); if (classNotFoundException.getException() instanceof BundleException) { BundleException bundleException = (BundleException) classNotFoundException.getException(); if (bundleException.getCause() instanceof IllegalStateException) { System.err.println(Messages.bind(Messages.WorkspaceRequired)); System.out.println(Messages.bind(Messages.CommandLineUsage)); return 1; } } } throw noClassError; } return new CodeFormatterApplication().start(context); }
Source:
public void changeConfiguration(WorkloadConfiguration configuration) { log.debug("Configuration change request received"); for (Iterator<WorkloadService> it = threads.iterator(); it.hasNext(); ){ WorkloadService workloadService = it.next(); if (workloadService.state().equals(Service.State.TERMINATED)) { samplesFromTerminatedThreads += workloadService.getSamples(); it.remove(); } } final int threadDiff = configuration.getThreads() - threads.size(); if (threadDiff < 0) { log.debug("Going to decrease thread count by {}", threadDiff); for (int i = threadDiff; i < 0; i++) { removeThread(); } } if (totalSamplesRequested != configuration.getSamples()) { samplesLeft.addAndGet(configuration.getSamples() - totalSamplesRequested); totalSamplesRequested = configuration.getSamples(); } if (threadDiff > 0 && (!predefinedSamplesCount() || samplesLeft.get() > 0)) { log.debug("Going to increase thread count by {}", threadDiff); for (int i = threadDiff; i > 0; i--) { addThread(); } } delay = configuration.getDelay(); log.debug("Delay should be changed to {}", delay); for (WorkloadService thread : threads) { thread.changeDelay(delay); } }

Target:
public void changeConfiguration(WorkloadConfiguration configuration) { log.debug("Configuration change request received"); for (Iterator<WorkloadService> it = threads.iterator(); it.hasNext(); ){ WorkloadService workloadService = it.next(); if (workloadService.state().equals(Service.State.TERMINATED)) { samplesCountDoneFromTerminatedThreads += workloadService.getSamples(); it.remove(); } } final int threadDiff = configuration.getThreads() - threads.size(); if (threadDiff < 0) { log.debug("Going to decrease thread count by {}", threadDiff); for (int i = threadDiff; i < 0; i++) { removeThread(); } } if (totalSamplesCountRequested != configuration.getSamples()) { leftSamplesCount.addAndGet(configuration.getSamples() - totalSamplesCountRequested); totalSamplesCountRequested = configuration.getSamples(); } if (threadDiff > 0 && (!predefinedSamplesCount() || leftSamplesCount.get() > 0)) { log.debug("Going to increase thread count by {}", threadDiff); for (int i = threadDiff; i > 0; i--) { addThread(); } } delay = configuration.getDelay(); log.debug("Delay should be changed to {}", delay); for (WorkloadService thread : threads) { thread.changeDelay(delay); } }
Source:
private Collection<IASTLiteralExpression> findAllLiterals(IProgressMonitor monitor) throws OperationCanceledException, CoreException { SubMonitor progress = SubMonitor.convert(monitor, 2); try { final Collection<IASTLiteralExpression> result = new ArrayList<IASTLiteralExpression>(); IASTTranslationUnit ast = getAST(tu, progress.newChild(1)); ast.accept(new ASTVisitor() { { shouldVisitExpressions = true; } @Override public int visit(IASTExpression expression) { if (expression instanceof IASTLiteralExpression) { if (!(expression.getNodeLocations().length == 1 && expression.getNodeLocations()[0] instanceof IASTMacroExpansionLocation)) { IASTLiteralExpression literal = (IASTLiteralExpression) expression; result.add(literal); } } return super.visit(expression); } }); return result; } finally { if (monitor != null) { monitor.done(); } } }

Target:
private Collection<IASTLiteralExpression> findAllLiterals(IProgressMonitor monitor) throws OperationCanceledException, CoreException { SubMonitor subMonitor = SubMonitor.convert(monitor, 5); final Collection<IASTLiteralExpression> result = new ArrayList<>(); IASTTranslationUnit ast = getAST(tu, subMonitor.split(4)); ast.accept(new ASTVisitor() { { shouldVisitExpressions = true; } @Override public int visit(IASTExpression expression) { if (expression instanceof IASTLiteralExpression) { if (!(expression.getNodeLocations().length == 1 && expression.getNodeLocations()[0] instanceof IASTMacroExpansionLocation)) { IASTLiteralExpression literal = (IASTLiteralExpression) expression; result.add(literal); } } return super.visit(expression); } }); subMonitor.split(1); return result; }
Source:
DbSchema(DbContents contents, String name, boolean isDefault) { this.contents = contents; this.name = name; this.quotedName = contents.quoteIdentifier(name); this.isDefault = isDefault; if (name == null) { isSystem = true; } else if ("INFORMATION_SCHEMA".equals(name)) { isSystem = true; } else if (!contents.isH2() && StringUtils.toUpperEnglish(name).startsWith("INFO")) { isSystem = true; } else if (contents.isPostgreSQL() && StringUtils.toUpperEnglish(name).startsWith("PG_")) { isSystem = true; } else isSystem = contents.isDerby() && name.startsWith("SYS"); }

Target:
DbSchema(DbContents contents, String name, boolean isDefault) { this.contents = contents; this.name = name; this.quotedName = contents.quoteIdentifier(name); this.isDefault = isDefault; if (name == null) { isSystem = true; } else if ("INFORMATION_SCHEMA".equals(name)) { isSystem = true; } else if (!contents.isH2() && StringUtils.toUpperEnglish(name).startsWith("INFO")) { isSystem = true; } else if (contents.isPostgreSQL() && StringUtils.toUpperEnglish(name).startsWith("PG_")) { isSystem = true; } else if (contents.isDerby() && name.startsWith("SYS")) { isSystem = true; } else { isSystem = false; } }
Source:
public StreamInputPacketIndexEntry(long dataOffsetBits, long fileSizeBytes) { fContentSizeBits = (fileSizeBytes * 8); fPacketSizeBits = (fileSizeBytes * 8); fOffsetBytes = dataOffsetBits; fLostEvents = 0; fTarget = ""; fTargetID = 0; fTimestampBegin = Long.MIN_VALUE; fTimestampEnd = Long.MAX_VALUE; }

Target:
public StreamInputPacketIndexEntry(long dataOffsetBits, long fileSizeBytes) { fContentSizeBits = (fileSizeBytes * Byte.SIZE); fPacketSizeBits = (fileSizeBytes * Byte.SIZE); fOffsetBytes = (dataOffsetBits / Byte.SIZE); fLostEvents = 0; fTarget = ""; fTargetID = 0; fTimestampBegin = Long.MIN_VALUE; fTimestampEnd = Long.MAX_VALUE; }
Source:
private String[] section(final Profile profile, final String... section) throws IOException { final StringBuilder path = new StringBuilder(Tv.HUNDRED); for (final String element : section) { path.append(String.format("/entry[@key='%s']", element)); } path.append(""); final List<String> result = profile.read().xpath( String.format("/%s/item/text()", path.toString()) ); return result.toArray(new String[result.size()]); }

Target:
private static String[] section(final Profile profile, final String... section) throws IOException { final StringBuilder path = new StringBuilder(Tv.HUNDRED); for (final String element : section) { path.append(String.format("/entry[@key='%s']", element)); } final List<String> result = profile.read().xpath( String.format("/%s/item/text()", path.toString()) ); return result.toArray(new String[result.size()]); }
Source:
public void testEmpty() { List<Object> response = client.execute( prepareGet().setUri(uriFor("/v1/person")).build(), createJsonResponseHandler(listCodec)); assertEquals(response, Collections.emptyList()); }

Target:
public void testEmpty() { List<Object> response = client.execute( prepareGet().setUri(uriFor("/v1/person")).build(), createJsonResponseHandler(listCodec)); assertEquals(response, ImmutableList.of()); }
Source:
public static OffsetDate of(LocalDate localDate, ZoneOffset zoneOffset) { final OffsetDate result = OffsetDate.newBuilder() .setDate(localDate) .setOffset(zoneOffset) .build(); return result; }

Target:
public static OffsetDate of(LocalDate localDate, ZoneOffset zoneOffset) { checkNotNull(localDate); checkNotNull(zoneOffset); final OffsetDate result = OffsetDate.newBuilder() .setDate(localDate) .setOffset(zoneOffset) .build(); return result; }
Source:
public void parseArgs(ScriptEntry scriptEntry) throws InvalidArgumentsException { for (Argument arg : scriptEntry.getProcessedArgs()) { if (!scriptEntry.hasObject("mythicmob") && arg.matchesArgumentType(MythicMobsMobTag.class)) { scriptEntry.addObject("mythicmob", arg.asType(MythicMobsMobTag.class)); } else if (!scriptEntry.hasObject("operation") && arg.matchesEnum(Operation.values())) { scriptEntry.addObject("operation", arg.asElement()); } else if (!scriptEntry.hasObject("threat") && arg.matchesFloat()) { scriptEntry.addObject("threat", arg.asElement()); } else if (!scriptEntry.hasObject("targets") && arg.matchesPrefix("for") && arg.matchesArgumentList(EntityTag.class)) { scriptEntry.addObject("targets", arg.asType(ListTag.class).filter(EntityTag.class, scriptEntry)); } else { arg.reportUnhandled(); } } if (!scriptEntry.hasObject("mythicmob")) { throw new InvalidArgumentsException("Must specify a MythicMob"); } if (!scriptEntry.hasObject("operation")) { throw new InvalidArgumentsException("Must specify an Operation"); } if (!scriptEntry.hasObject("threat")) { throw new InvalidArgumentsException("Must specify a threat value"); } if (!scriptEntry.hasObject("targets")) { scriptEntry.defaultObject("targets", (Utilities.entryHasPlayer(scriptEntry) ? Arrays.asList(Utilities.getEntryPlayer(scriptEntry).getDenizenEntity()) : null)); } }

Target:
public void parseArgs(ScriptEntry scriptEntry) throws InvalidArgumentsException { for (Argument arg : scriptEntry.getProcessedArgs()) { if (!scriptEntry.hasObject("mythicmob") && arg.matchesArgumentType(MythicMobsMobTag.class)) { scriptEntry.addObject("mythicmob", arg.asType(MythicMobsMobTag.class)); } else if (!scriptEntry.hasObject("operation") && arg.matchesEnum(Operation.values())) { scriptEntry.addObject("operation", arg.asElement()); } else if (!scriptEntry.hasObject("threat") && arg.matchesFloat()) { scriptEntry.addObject("threat", arg.asElement()); } else if (!scriptEntry.hasObject("targets") && arg.matchesPrefix("for") && arg.matchesArgumentList(EntityTag.class)) { scriptEntry.addObject("targets", arg.asType(ListTag.class).filter(EntityTag.class, scriptEntry)); } else { arg.reportUnhandled(); } } if (!scriptEntry.hasObject("mythicmob")) { throw new InvalidArgumentsException("Must specify a MythicMob!"); } if (!scriptEntry.hasObject("operation")) { throw new InvalidArgumentsException("Must specify an Operation!"); } if (!scriptEntry.hasObject("threat")) { throw new InvalidArgumentsException("Must specify a threat value!"); } if (!scriptEntry.hasObject("targets")) { scriptEntry.defaultObject("targets", (Utilities.entryHasPlayer(scriptEntry) ? Arrays.asList(Utilities.getEntryPlayer(scriptEntry).getDenizenEntity()) : null)); } }
Source:
default Optional<MessageId> rootMessage() { EventContext.OriginCase origin = getOriginCase(); switch (origin) { case PAST_MESSAGE: return Optional.of(getPastMessage().root()); case IMPORT_CONTEXT: return Optional.empty(); case EVENT_CONTEXT: case COMMAND_CONTEXT: case ORIGIN_NOT_SET: default: @SuppressWarnings("DuplicateStringLiteralInspection") MessageId id = MessageId .newBuilder() .setId(Identifier.pack(getRootCommandId())) .setTypeUrl("Unknown") .vBuild(); return Optional.of(id); } }

Target:
default Optional<MessageId> rootMessage() { EventContext.OriginCase origin = getOriginCase(); switch (origin) { case PAST_MESSAGE: return Optional.of(getPastMessage().root()); case IMPORT_CONTEXT: return Optional.empty(); case EVENT_CONTEXT: case COMMAND_CONTEXT: case ORIGIN_NOT_SET: default: if (hasRootCommandId()) { @SuppressWarnings("DuplicateStringLiteralInspection") MessageId id = MessageId .newBuilder() .setId(Identifier.pack(getRootCommandId())) .setTypeUrl("Unknown") .vBuild(); return Optional.of(id); } else { _warn().log("Cannot determine root message ID."); return Optional.empty(); } } }
Source:
public void edit(@Load Answer original, MarkedText description, String comment, List<Long> attachmentsIds) { AnswerInformation information = new AnswerInformation(description, currentUser, comment); brutalValidator.validate(information); validator.onErrorRedirectTo(this).answerEditForm(original); UpdateStatus status = original.updateWith(information); answers.save(original); List<Attachment> attachmentsLoaded = attachments.load(attachmentsIds); original.removeAttachments(); original.add(attachmentsLoaded); result.include("mamuteMessages", Arrays.asList(messageFactory.build("confirmation", status.getMessage()))); Question originalQuestion = original.getMainThread(); result.redirectTo(QuestionController.class).showQuestion(originalQuestion, originalQuestion.getSluggedTitle()); }

Target:
public void edit(@Load Answer original, MarkedText description, String comment, List<Long> attachmentsIds) { AnswerInformation information = new AnswerInformation(description, currentUser, comment); brutalValidator.validate(information); validator.onErrorRedirectTo(this).answerEditForm(original); UpdateStatus status = original.updateWith(information); answers.save(original); List<Attachment> attachmentsLoaded = attachments.load(attachmentsIds); original.replace(attachmentsLoaded); result.include("mamuteMessages", Arrays.asList(messageFactory.build("confirmation", status.getMessage()))); Question originalQuestion = original.getMainThread(); result.redirectTo(QuestionController.class).showQuestion(originalQuestion, originalQuestion.getSluggedTitle()); }
Source:
private void addValueToLine(String key, List<String> columns, List<String> line, Object value) { if (!columns.contains(key)) { columns.add(key); } int position = columns.indexOf(key); if (line.size() < columns.size()) { for (int i = line.size(); i < columns.size(); i++) { line.add(null); } } if (value != null) { if (value instanceof Value) { Value val = (Value) value; if (val.hasType(InternalTypeSystem.TYPE_SYSTEM.LIST())) { value = val.asList(); } else if (val.hasType(InternalTypeSystem.TYPE_SYSTEM.MAP())) { value = val.asMap(); } } if (value instanceof Collection) { try { value = jsonMapper.writer().writeValueAsString(value); } catch (Exception ignored) { logger.info(ignored.getMessage()); } } } line.set(position, value == null ? null : value.toString()); }

Target:
private void addValueToLine(String key, List<String> columns, List<String> line, Object value) { if (!columns.contains(key)) { columns.add(key); } int position = columns.indexOf(key); if (line.size() < columns.size()) { for (int i = line.size(); i < columns.size(); i++) { line.add(null); } } if (value != null) { if (value instanceof Value) { Value val = (Value) value; if (val.hasType(InternalTypeSystem.TYPE_SYSTEM.LIST())) { value = val.asList(); } else if (val.hasType(InternalTypeSystem.TYPE_SYSTEM.MAP())) { value = val.asMap(); } } if (value instanceof Collection) { try { value = jsonMapper.writer().writeValueAsString(value); } catch (Exception e) { logger.debug("ignored exception: " + e.getMessage()); } } } line.set(position, value == null ? null : value.toString()); }
Source:
public void onVideoCallScreenUiReady() { LogUtil.v("VideoCallPresenter.onVideoCallScreenUiReady", ""); Assert.checkState(!isVideoCallScreenUiReady); if (!CompatUtils.isVideoCompatible()) { return; } isVideoCallScreenUiReady = true; mDeviceOrientation = InCallOrientationEventListener.getCurrentOrientation(); InCallPresenter.getInstance().addListener(this); InCallPresenter.getInstance().addDetailsListener(this); InCallPresenter.getInstance().addIncomingCallListener(this); InCallPresenter.getInstance().addOrientationListener(this); InCallPresenter.getInstance().addInCallEventListener(this); InCallPresenter.getInstance().getLocalVideoSurfaceTexture().setDelegate(new LocalDelegate()); InCallPresenter.getInstance().getRemoteVideoSurfaceTexture().setDelegate(new RemoteDelegate()); InCallVideoCallCallbackNotifier.getInstance().addSurfaceChangeListener(this); mCurrentVideoState = VideoProfile.STATE_AUDIO_ONLY; mCurrentCallState = DialerCall.State.INVALID; InCallPresenter.InCallState inCallState = InCallPresenter.getInstance().getInCallState(); onStateChange(inCallState, inCallState, CallList.getInstance()); }

Target:
public void onVideoCallScreenUiReady() { LogUtil.v("VideoCallPresenter.onVideoCallScreenUiReady", ""); Assert.checkState(!isVideoCallScreenUiReady); if (!CompatUtils.isVideoCompatible()) { return; } mDeviceOrientation = InCallOrientationEventListener.getCurrentOrientation(); InCallPresenter.getInstance().addListener(this); InCallPresenter.getInstance().addDetailsListener(this); InCallPresenter.getInstance().addIncomingCallListener(this); InCallPresenter.getInstance().addOrientationListener(this); InCallPresenter.getInstance().addInCallEventListener(this); InCallPresenter.getInstance().getLocalVideoSurfaceTexture().setDelegate(new LocalDelegate()); InCallPresenter.getInstance().getRemoteVideoSurfaceTexture().setDelegate(new RemoteDelegate()); InCallVideoCallCallbackNotifier.getInstance().addSurfaceChangeListener(this); mCurrentVideoState = VideoProfile.STATE_AUDIO_ONLY; mCurrentCallState = DialerCall.State.INVALID; isVideoCallScreenUiReady = true; InCallPresenter.InCallState inCallState = InCallPresenter.getInstance().getInCallState(); onStateChange(inCallState, inCallState, CallList.getInstance()); }
Source:
public void testTemplateMatch() throws Exception { ImmutableMap<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap. <HttpRequest, HttpResponse>builder() .put(requestForScopes(COMPUTE_READONLY_SCOPE), TOKEN_RESPONSE) .put(GET_PROJECT_REQUEST, GET_PROJECT_RESPONSE) .put(LIST_ZONES_REQ, LIST_ZONES_RESPONSE) .put(LIST_PROJECT_IMAGES_REQUEST, LIST_PROJECT_IMAGES_RESPONSE) .put(LIST_GOOGLE_IMAGES_REQUEST, LIST_GOOGLE_IMAGES_RESPONSE) .put(LIST_MACHINE_TYPES_REQUEST, LIST_MACHINE_TYPES_RESPONSE) .put(LIST_CENTRAL1B_MACHINE_TYPES_REQUEST, LIST_CENTRAL1B_MACHINE_TYPES_RESPONSE) .build(); ComputeService client = requestsSendResponses(requestResponseMap); Template template = client.templateBuilder().build(); Hardware defaultSize = client.templateBuilder().build().getHardware(); Hardware smallest = client.templateBuilder().smallest().build().getHardware(); assertEquals(defaultSize, smallest); Hardware fastest = client.templateBuilder().fastest().build().getHardware(); assertNotNull(fastest); assertEquals(client.listHardwareProfiles().size(), 4); Template toMatch = client.templateBuilder() .imageId(template.getImage().getId()) .build(); assertEquals(toMatch.getImage(), template.getImage()); }

Target:
public void testTemplateMatch() throws Exception { ImmutableMap<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap. <HttpRequest, HttpResponse>builder() .put(requestForScopes(COMPUTE_READONLY_SCOPE), TOKEN_RESPONSE) .put(GET_PROJECT_REQUEST, GET_PROJECT_RESPONSE) .put(LIST_ZONES_REQ, LIST_ZONES_RESPONSE) .put(LIST_PROJECT_IMAGES_REQUEST, LIST_PROJECT_IMAGES_RESPONSE) .put(LIST_GOOGLE_IMAGES_REQUEST, LIST_GOOGLE_IMAGES_RESPONSE) .put(LIST_MACHINE_TYPES_REQUEST, LIST_MACHINE_TYPES_RESPONSE) .put(LIST_CENTRAL1B_MACHINE_TYPES_REQUEST, LIST_CENTRAL1B_MACHINE_TYPES_RESPONSE) .build(); ComputeService client = requestsSendResponses(requestResponseMap); Template template = client.templateBuilder().build(); Hardware defaultSize = client.templateBuilder().build().getHardware(); Hardware smallest = client.templateBuilder().smallest().build().getHardware(); assertEquals(defaultSize, smallest); Hardware fastest = client.templateBuilder().fastest().build().getHardware(); assertNotNull(fastest); assertEquals(client.listHardwareProfiles().size(), 5); Template toMatch = client.templateBuilder() .imageId(template.getImage().getId()) .build(); assertEquals(toMatch.getImage(), template.getImage()); }
Source:
private String correctEmojiFormat(String iconEmoji) { if(StringUtils.isEmpty(iconEmoji)) { return iconEmoji; } else if (!iconEmoji.startsWith(":")) { iconEmoji = ":" + iconEmoji; } if (!iconEmoji.endsWith(":")) { iconEmoji = iconEmoji + ":"; } return iconEmoji; }

Target:
private String correctEmojiFormat(String iconEmoji) { if (StringUtils.isEmpty(iconEmoji)) { return iconEmoji; } iconEmoji = StringUtils.appendIfMissing(iconEmoji, ":"); iconEmoji = StringUtils.prependIfMissing(iconEmoji, ":"); return iconEmoji; }
Source:
private RepositoryArtifactProvider createRemoteArtifactProvider(Set<MavenRepositoryLocation> completeRepositories, List<TargetDefinitionContent> targetDefinitionsContent) { List<URI> allRemoteArtifactRepositories = new ArrayList<URI>(); for (MavenRepositoryLocation location : completeRepositories) { if (!offline || URIUtil.isFileURI(location.getURL())) { allRemoteArtifactRepositories.add(location.getURL()); } } for (TargetDefinitionContent targetDefinitionContent : targetDefinitionsContent) { allRemoteArtifactRepositories.addAll(targetDefinitionContent.getArtifactRepositoryLocations()); } IProgressMonitor monitor = new DuplicateFilteringLoggingProgressMonitor(logger); RepositoryArtifactProvider provider = new RepositoryArtifactProvider(allRemoteArtifactRepositories, ArtifactTransferPolicies.forRemoteArtifacts(), remoteAgent, monitor); return provider; }

Target:
private RepositoryArtifactProvider createRemoteArtifactProvider(Set<MavenRepositoryLocation> completeRepositories, List<TargetDefinitionContent> targetDefinitionsContent) { List<URI> allRemoteArtifactRepositories = new ArrayList<URI>(); for (MavenRepositoryLocation location : completeRepositories) { if (!offline || URIUtil.isFileURI(location.getURL())) { allRemoteArtifactRepositories.add(location.getURL()); } } for (TargetDefinitionContent targetDefinitionContent : targetDefinitionsContent) { allRemoteArtifactRepositories.addAll(targetDefinitionContent.getArtifactRepositoryLocations()); } return new RepositoryArtifactProvider(allRemoteArtifactRepositories, ArtifactTransferPolicies.forRemoteArtifacts(), remoteAgent, monitor); }
Source:
private static SwitchingBackend createForwardingBackend(ComponentRegistry componentRegistry, String indexName, LocalBackendFactory localBackendFactory, CacheManagerService cacheManagerService, DirectoryBasedIndexManager indexManager) { RpcManager rpcManager = componentRegistry.getComponent(RpcManager.class); if (rpcManager==null) { LocalonlyBackend backend = new LocalonlyBackend(localBackendFactory); backend.initialize(); return backend; } else { EmbeddedCacheManager embeddedCacheManager = cacheManagerService.getEmbeddedCacheManager(); TransactionManager transactionManager = componentRegistry.getComponent(TransactionManager.class); IndexLockController lockControl = new IndexManagerBasedLockController(indexManager, transactionManager); ClusteredSwitchingBackend backend = new ClusteredSwitchingBackend(componentRegistry, indexName, localBackendFactory, lockControl); backend.initialize(); embeddedCacheManager.addListener(backend); return backend; } }

Target:
private static SwitchingBackend createForwardingBackend(ComponentRegistry componentRegistry, String indexName, LocalBackendFactory localBackendFactory, CacheManagerService cacheManagerService, DirectoryBasedIndexManager indexManager) { RpcManager rpcManager = componentRegistry.getComponent(RpcManager.class); if (rpcManager == null) { LocalOnlyBackend backend = new LocalOnlyBackend(localBackendFactory); backend.initialize(); return backend; } else { EmbeddedCacheManager embeddedCacheManager = cacheManagerService.getEmbeddedCacheManager(); TransactionManager transactionManager = componentRegistry.getComponent(TransactionManager.class); IndexLockController lockControl = new IndexManagerBasedLockController(indexManager, transactionManager); ClusteredSwitchingBackend backend = new ClusteredSwitchingBackend(componentRegistry, indexName, localBackendFactory, lockControl); backend.initialize(); embeddedCacheManager.addListener(backend); return backend; } }