Example usage for com.google.common.base Predicates instanceOf

List of usage examples for com.google.common.base Predicates instanceOf

Introduction

In this page you can find the example usage for com.google.common.base Predicates instanceOf.

Prototype

@GwtIncompatible("Class.isInstance")
public static Predicate<Object> instanceOf(Class<?> clazz) 

Source Link

Document

Returns a predicate that evaluates to true if the object being tested is an instance of the given class.

Usage

From source file:org.dasein.cloud.jclouds.vcloud.director.compute.VmSupport.java

public static <S extends SectionType> S getSection(AbstractVAppType vapp, Class<S> sectionClass) {
    S section = (S) Iterables.find(vapp.getSections(), Predicates.instanceOf(sectionClass));
    return section;
}

From source file:org.apache.impala.analysis.StmtRewriter.java

/**
 * Update the subquery within an inline view by expanding its select list with exprs
 * from a correlated predicate 'expr' that will be 'moved' to an ON clause in the
 * subquery's parent query block. We need to make sure that every expr extracted from
 * the subquery references an item in the subquery's select list. If 'updateGroupBy'
 * is true, the exprs extracted from 'expr' are also added in stmt's GROUP BY clause.
 * Throws an AnalysisException if we need to update the GROUP BY clause but
 * both the lhs and rhs of 'expr' reference a tuple of the subquery stmt.
 *///from   w w  w .  j  a  v  a  2s  .  c om
private static void updateInlineView(InlineViewRef inlineView, Expr expr, List<TupleId> parentQueryTids,
        List<Expr> lhsExprs, List<Expr> rhsExprs, boolean updateGroupBy) throws AnalysisException {
    SelectStmt stmt = (SelectStmt) inlineView.getViewStmt();
    List<TupleId> subqueryTblIds = stmt.getTableRefIds();
    ArrayList<Expr> groupByExprs = null;
    if (updateGroupBy)
        groupByExprs = Lists.newArrayList();

    List<SelectListItem> items = stmt.selectList_.getItems();
    // Collect all the SlotRefs from 'expr' and identify those that are bound by
    // subquery tuple ids.
    ArrayList<Expr> slotRefs = Lists.newArrayList();
    expr.collectAll(Predicates.instanceOf(SlotRef.class), slotRefs);
    List<Expr> exprsBoundBySubqueryTids = Lists.newArrayList();
    for (Expr slotRef : slotRefs) {
        if (slotRef.isBoundByTupleIds(subqueryTblIds)) {
            exprsBoundBySubqueryTids.add(slotRef);
        }
    }
    // The correlated predicate only references slots from a parent block,
    // no need to update the subquery's select or group by list.
    if (exprsBoundBySubqueryTids.isEmpty())
        return;
    if (updateGroupBy) {
        Preconditions.checkState(expr instanceof BinaryPredicate);
        Expr exprBoundBySubqueryTids = null;
        if (exprsBoundBySubqueryTids.size() > 1) {
            // If the predicate contains multiple SlotRefs bound by subquery tuple
            // ids, they must all be on the same side of that predicate.
            if (expr.getChild(0).isBoundByTupleIds(subqueryTblIds)
                    && expr.getChild(1).isBoundByTupleIds(parentQueryTids)) {
                exprBoundBySubqueryTids = expr.getChild(0);
            } else if (expr.getChild(0).isBoundByTupleIds(parentQueryTids)
                    && expr.getChild(1).isBoundByTupleIds(subqueryTblIds)) {
                exprBoundBySubqueryTids = expr.getChild(1);
            } else {
                throw new AnalysisException(
                        "All subquery columns " + "that participate in a predicate must be on the same side of "
                                + "that predicate: " + expr.toSql());
            }
        } else {
            Preconditions.checkState(exprsBoundBySubqueryTids.size() == 1);
            exprBoundBySubqueryTids = exprsBoundBySubqueryTids.get(0);
        }
        exprsBoundBySubqueryTids.clear();
        exprsBoundBySubqueryTids.add(exprBoundBySubqueryTids);
    }

    // Add the exprs bound by subquery tuple ids to the select list and
    // register it for substitution. We use a temporary substitution map
    // because we cannot at this point analyze the new select list expr. Once
    // the new inline view is analyzed, the entries from this map will be
    // added to an ExprSubstitutionMap.
    for (Expr boundExpr : exprsBoundBySubqueryTids) {
        String colAlias = stmt.getColumnAliasGenerator().getNextAlias();
        items.add(new SelectListItem(boundExpr, null));
        inlineView.getExplicitColLabels().add(colAlias);
        lhsExprs.add(boundExpr);
        rhsExprs.add(new SlotRef(Lists.newArrayList(inlineView.getUniqueAlias(), colAlias)));
        if (groupByExprs != null)
            groupByExprs.add(boundExpr);
    }

    // Update the subquery's select list.
    boolean isDistinct = stmt.selectList_.isDistinct();
    stmt.selectList_ = new SelectList(items, isDistinct, stmt.selectList_.getPlanHints());
    // Update subquery's GROUP BY clause
    if (groupByExprs != null && !groupByExprs.isEmpty()) {
        if (stmt.hasGroupByClause()) {
            stmt.groupingExprs_.addAll(groupByExprs);
        } else {
            stmt.groupingExprs_ = groupByExprs;
        }
    }
}

From source file:io.usethesource.criterion.CalculateFootprintsHeterogeneous.java

private static String measureAndReport(final Object objectToMeasure, final String className, DataType dataType,
        Archetype archetype, boolean supportsStagedMutability, int size, int run,
        MemoryFootprintPreset preset) {//from  w  ww.  j  ava 2s  .c o  m
    final Predicate<Object> predicate;

    switch (preset) {
    case DATA_STRUCTURE_OVERHEAD:
        // TODO: create JmhLeaf
        // predicate = Predicates
        // .not(Predicates.or(Predicates.instanceOf(Integer.class),
        // Predicates.instanceOf(BigInteger.class),
        // Predicates.instanceOf(JmhValue.class), Predicates.instanceOf(PureInteger.class)));
        predicate = Predicates.not(Predicates.or(Predicates.instanceOf(PureInteger.class),
                Predicates.instanceOf(PureIntegerWithCustomHashCode.class)));
        break;
    case RETAINED_SIZE:
        predicate = Predicates.alwaysTrue();
        break;
    case RETAINED_SIZE_WITH_BOXED_INTEGER_FILTER:
        predicate = Predicates.not(Predicates.instanceOf(Integer.class));
        break;
    default:
        throw new IllegalStateException();
    }

    return measureAndReport(objectToMeasure, className, dataType, archetype, supportsStagedMutability, size,
            run, predicate);
}

From source file:com.cloudera.impala.analysis.Expr.java

/**
 * @return true if this expr can be evaluated with Expr::GetValue(NULL),
 * ie, if it doesn't contain any references to runtime variables (which
 * at the moment are only slotrefs and subqueries).
 *///from   w w  w.  j a v a 2 s.c o  m
public boolean isConstant() {
    return !contains(Predicates.instanceOf(SlotRef.class)) && !contains(Predicates.instanceOf(Subquery.class));
}

From source file:com.cloudera.impala.service.Frontend.java

/**
 * Create a populated TExecRequest corresponding to the supplied TQueryCtx.
 *//*  w ww .  j a v  a2 s.  c  om*/
public TExecRequest createExecRequest(TQueryCtx queryCtx, StringBuilder explainString) throws ImpalaException {
    // Analyze the statement
    AnalysisContext.AnalysisResult analysisResult = analyzeStmt(queryCtx);
    Preconditions.checkNotNull(analysisResult.getStmt());

    TExecRequest result = new TExecRequest();
    result.setQuery_options(queryCtx.request.getQuery_options());
    result.setAccess_events(analysisResult.getAccessEvents());
    result.analysis_warnings = analysisResult.getAnalyzer().getWarnings();

    if (analysisResult.isCatalogOp()) {
        result.stmt_type = TStmtType.DDL;
        createCatalogOpRequest(analysisResult, result);

        // All DDL operations except for CTAS are done with analysis at this point.
        if (!analysisResult.isCreateTableAsSelectStmt())
            return result;
    } else if (analysisResult.isLoadDataStmt()) {
        result.stmt_type = TStmtType.LOAD;
        result.setResult_set_metadata(
                new TResultSetMetadata(Arrays.asList(new TColumn("summary", Type.STRING.toThrift()))));
        result.setLoad_data_request(analysisResult.getLoadDataStmt().toThrift());
        return result;
    } else if (analysisResult.isSetStmt()) {
        result.stmt_type = TStmtType.SET;
        result.setResult_set_metadata(new TResultSetMetadata(Arrays.asList(
                new TColumn("option", Type.STRING.toThrift()), new TColumn("value", Type.STRING.toThrift()))));
        result.setSet_query_option_request(analysisResult.getSetStmt().toThrift());
        return result;
    }

    // create TQueryExecRequest
    Preconditions.checkState(analysisResult.isQueryStmt() || analysisResult.isDmlStmt()
            || analysisResult.isCreateTableAsSelectStmt());

    TQueryExecRequest queryExecRequest = new TQueryExecRequest();
    // create plan
    LOG.debug("create plan");
    Planner planner = new Planner(analysisResult, queryCtx);
    ArrayList<PlanFragment> fragments = planner.createPlan();
    List<ScanNode> scanNodes = Lists.newArrayList();
    // map from fragment to its index in queryExecRequest.fragments; needed for
    // queryExecRequest.dest_fragment_idx
    Map<PlanFragment, Integer> fragmentIdx = Maps.newHashMap();

    for (int fragmentId = 0; fragmentId < fragments.size(); ++fragmentId) {
        PlanFragment fragment = fragments.get(fragmentId);
        Preconditions.checkNotNull(fragment.getPlanRoot());
        fragment.getPlanRoot().collect(Predicates.instanceOf(ScanNode.class), scanNodes);
        fragmentIdx.put(fragment, fragmentId);
    }

    // set fragment destinations
    for (int i = 1; i < fragments.size(); ++i) {
        PlanFragment dest = fragments.get(i).getDestFragment();
        Integer idx = fragmentIdx.get(dest);
        Preconditions.checkState(idx != null);
        queryExecRequest.addToDest_fragment_idx(idx.intValue());
    }

    // Set scan ranges/locations for scan nodes.
    // Also assemble list of tables names missing stats for assembling a warning message.
    LOG.debug("get scan range locations");
    Set<TTableName> tablesMissingStats = Sets.newTreeSet();
    for (ScanNode scanNode : scanNodes) {
        queryExecRequest.putToPer_node_scan_ranges(scanNode.getId().asInt(), scanNode.getScanRangeLocations());
        if (scanNode.isTableMissingStats()) {
            tablesMissingStats.add(scanNode.getTupleDesc().getTableName().toThrift());
        }
    }
    queryExecRequest.setHost_list(analysisResult.getAnalyzer().getHostIndex().getList());
    for (TTableName tableName : tablesMissingStats) {
        queryCtx.addToTables_missing_stats(tableName);
    }

    // Optionally disable spilling in the backend. Allow spilling if there are plan hints
    // or if all tables have stats.
    if (queryCtx.request.query_options.isDisable_unsafe_spills() && !tablesMissingStats.isEmpty()
            && !analysisResult.getAnalyzer().hasPlanHints()) {
        queryCtx.setDisable_spilling(true);
    }

    // Compute resource requirements after scan range locations because the cost
    // estimates of scan nodes rely on them.
    try {
        planner.computeResourceReqs(fragments, true, queryExecRequest);
    } catch (Exception e) {
        // Turn exceptions into a warning to allow the query to execute.
        LOG.error("Failed to compute resource requirements for query\n" + queryCtx.request.getStmt(), e);
    }

    // The fragment at this point has all state set, serialize it to thrift.
    for (PlanFragment fragment : fragments) {
        TPlanFragment thriftFragment = fragment.toThrift();
        queryExecRequest.addToFragments(thriftFragment);
    }

    // Use VERBOSE by default for all non-explain statements.
    TExplainLevel explainLevel = TExplainLevel.VERBOSE;
    // Use the query option for explain stmts and tests (e.g., planner tests).
    if (analysisResult.isExplainStmt() || RuntimeEnv.INSTANCE.isTestEnv()) {
        explainLevel = queryCtx.request.query_options.getExplain_level();
    }

    // Global query parameters to be set in each TPlanExecRequest.
    queryExecRequest.setQuery_ctx(queryCtx);

    explainString.append(planner.getExplainString(fragments, queryExecRequest, explainLevel));
    queryExecRequest.setQuery_plan(explainString.toString());
    queryExecRequest.setDesc_tbl(analysisResult.getAnalyzer().getDescTbl().toThrift());

    if (analysisResult.isExplainStmt()) {
        // Return the EXPLAIN request
        createExplainRequest(explainString.toString(), result);
        return result;
    }

    result.setQuery_exec_request(queryExecRequest);

    if (analysisResult.isQueryStmt()) {
        // fill in the metadata
        LOG.debug("create result set metadata");
        result.stmt_type = TStmtType.QUERY;
        result.query_exec_request.stmt_type = result.stmt_type;
        TResultSetMetadata metadata = new TResultSetMetadata();
        QueryStmt queryStmt = analysisResult.getQueryStmt();
        int colCnt = queryStmt.getColLabels().size();
        for (int i = 0; i < colCnt; ++i) {
            TColumn colDesc = new TColumn();
            colDesc.columnName = queryStmt.getColLabels().get(i);
            colDesc.columnType = queryStmt.getResultExprs().get(i).getType().toThrift();
            metadata.addToColumns(colDesc);
        }
        result.setResult_set_metadata(metadata);
    } else {
        Preconditions.checkState(analysisResult.isInsertStmt() || analysisResult.isCreateTableAsSelectStmt());

        // For CTAS the overall TExecRequest statement type is DDL, but the
        // query_exec_request should be DML
        result.stmt_type = analysisResult.isCreateTableAsSelectStmt() ? TStmtType.DDL : TStmtType.DML;
        result.query_exec_request.stmt_type = TStmtType.DML;

        // create finalization params of insert stmt
        InsertStmt insertStmt = analysisResult.getInsertStmt();
        if (insertStmt.getTargetTable() instanceof HdfsTable) {
            TFinalizeParams finalizeParams = new TFinalizeParams();
            finalizeParams.setIs_overwrite(insertStmt.isOverwrite());
            finalizeParams.setTable_name(insertStmt.getTargetTableName().getTbl());
            finalizeParams.setTable_id(insertStmt.getTargetTable().getId().asInt());
            String db = insertStmt.getTargetTableName().getDb();
            finalizeParams.setTable_db(db == null ? queryCtx.session.database : db);
            HdfsTable hdfsTable = (HdfsTable) insertStmt.getTargetTable();
            finalizeParams.setHdfs_base_dir(hdfsTable.getHdfsBaseDir());
            finalizeParams.setStaging_dir(hdfsTable.getHdfsBaseDir() + "/_impala_insert_staging");
            queryExecRequest.setFinalize_params(finalizeParams);
        }
    }
    return result;
}

From source file:org.eclipse.sirius.diagram.ui.tools.api.figure.locator.DBorderItemLocator.java

/**
 * Get the figures of the brother's border nodes of
 * <code>targetBorderItem</code>.
 * /*ww  w. j a  va2 s. c om*/
 * @param targetBorderItem
 *            Contextual border item.
 * @return The list of figure of the brother border nodes.
 */
protected List<IFigure> getBrotherFigures(final IFigure targetBorderItem) {
    @SuppressWarnings("unchecked")
    Iterable<IFigure> brotherFigures = Iterables.filter(targetBorderItem.getParent().getChildren(), Predicates
            .and(Predicates.instanceOf(IFigure.class), Predicates.not(Predicates.equalTo(targetBorderItem))));
    return Lists.newArrayList(brotherFigures);
}

From source file:org.opendaylight.netconf.sal.restconf.impl.RestconfImpl.java

@Override
public Response deleteConfigurationData(final String identifier) {
    final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
    final DOMMountPoint mountPoint = iiWithData.getMountPoint();
    final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();

    try {/*from ww w . j  a v  a  2 s . co  m*/
        if (mountPoint != null) {
            this.broker.commitConfigurationDataDelete(mountPoint, normalizedII);
        } else {
            this.broker.commitConfigurationDataDelete(normalizedII).get();
        }
    } catch (final Exception e) {
        final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(e),
                Predicates.instanceOf(ModifiedNodeDoesNotExistException.class));
        if (searchedException.isPresent()) {
            throw new RestconfDocumentedException("Data specified for deleting doesn't exist.",
                    ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
        }
        final String errMsg = "Error while deleting data";
        LOG.info(errMsg, e);
        throw new RestconfDocumentedException(errMsg, e);
    }
    return Response.status(Status.OK).build();
}

From source file:org.apache.impala.service.Frontend.java

/**
 * Return a TPlanExecInfo corresponding to the plan with root fragment 'planRoot'.
 *///from ww  w. j  a va2  s .c  o m
private TPlanExecInfo createPlanExecInfo(PlanFragment planRoot, Planner planner, TQueryCtx queryCtx,
        TQueryExecRequest queryExecRequest) {
    TPlanExecInfo result = new TPlanExecInfo();
    ArrayList<PlanFragment> fragments = planRoot.getNodesPreOrder();

    // collect ScanNodes
    List<ScanNode> scanNodes = Lists.newArrayList();
    for (PlanFragment fragment : fragments) {
        Preconditions.checkNotNull(fragment.getPlanRoot());
        fragment.getPlanRoot().collect(Predicates.instanceOf(ScanNode.class), scanNodes);
    }

    // Set scan ranges/locations for scan nodes.
    LOG.trace("get scan range locations");
    Set<TTableName> tablesMissingStats = Sets.newTreeSet();
    Set<TTableName> tablesWithCorruptStats = Sets.newTreeSet();
    Set<TTableName> tablesWithMissingDiskIds = Sets.newTreeSet();
    for (ScanNode scanNode : scanNodes) {
        result.putToPer_node_scan_ranges(scanNode.getId().asInt(), scanNode.getScanRangeLocations());

        TTableName tableName = scanNode.getTupleDesc().getTableName().toThrift();
        if (scanNode.isTableMissingStats())
            tablesMissingStats.add(tableName);
        if (scanNode.hasCorruptTableStats())
            tablesWithCorruptStats.add(tableName);
        if (scanNode instanceof HdfsScanNode && ((HdfsScanNode) scanNode).hasMissingDiskIds()) {
            tablesWithMissingDiskIds.add(tableName);
        }
    }

    for (TTableName tableName : tablesMissingStats) {
        queryCtx.addToTables_missing_stats(tableName);
    }
    for (TTableName tableName : tablesWithCorruptStats) {
        queryCtx.addToTables_with_corrupt_stats(tableName);
    }
    for (TTableName tableName : tablesWithMissingDiskIds) {
        queryCtx.addToTables_missing_diskids(tableName);
    }

    // Compute resource requirements after scan range locations because the cost
    // estimates of scan nodes rely on them.
    try {
        planner.computeResourceReqs(fragments, true, queryExecRequest);
    } catch (Exception e) {
        // Turn exceptions into a warning to allow the query to execute.
        LOG.error("Failed to compute resource requirements for query\n" + queryCtx.client_request.getStmt(), e);
    }

    // The fragment at this point has all state set, serialize it to thrift.
    for (PlanFragment fragment : fragments) {
        TPlanFragment thriftFragment = fragment.toThrift();
        result.addToFragments(thriftFragment);
    }

    return result;
}

From source file:dagger2.internal.codegen.ComponentGenerator.java

private void initializeFrameworkTypes(BindingGraph input, ClassWriter componentWriter,
        ConstructorWriter constructorWriter, Optional<ClassName> builderName,
        Map<TypeElement, MemberSelect> componentContributionFields,
        ImmutableMap<BindingKey, MemberSelect> memberSelectSnippets,
        ImmutableMap<ContributionBinding, Snippet> parentMultibindingContributionSnippets,
        ImmutableMap<ContributionBinding, Snippet> multibindingContributionSnippets) throws AssertionError {
    List<List<BindingKey>> partitions = Lists.partition(input.resolvedBindings().keySet().asList(), 100);
    for (int i = 0; i < partitions.size(); i++) {
        MethodWriter initializeMethod = componentWriter.addMethod(VoidName.VOID,
                "initialize" + ((i == 0) ? "" : i));
        initializeMethod.body();/*from   ww w.  j a  va2 s.  c o m*/
        initializeMethod.addModifiers(PRIVATE);
        if (builderName.isPresent()) {
            initializeMethod.addParameter(builderName.get(), "builder").addModifiers(FINAL);
            constructorWriter.body().addSnippet("%s(builder);", initializeMethod.name());
        } else {
            constructorWriter.body().addSnippet("%s();", initializeMethod.name());
        }

        for (BindingKey bindingKey : partitions.get(i)) {
            Snippet memberSelectSnippet = memberSelectSnippets.get(bindingKey)
                    .getSnippetFor(componentWriter.name());
            ResolvedBindings resolvedBindings = input.resolvedBindings().get(bindingKey);
            switch (bindingKey.kind()) {
            case CONTRIBUTION:
                ImmutableSet<? extends ContributionBinding> bindings = resolvedBindings.contributionBindings();

                switch (ContributionBinding.bindingTypeFor(bindings)) {
                case SET:
                    boolean hasOnlyProvisions = Iterables.all(bindings,
                            Predicates.instanceOf(ProvisionBinding.class));
                    ImmutableList.Builder<Snippet> parameterSnippets = ImmutableList.builder();
                    for (ContributionBinding binding : bindings) {
                        if (multibindingContributionSnippets.containsKey(binding)) {
                            Snippet initializeSnippet = initializeFactoryForContributionBinding(binding, input,
                                    componentWriter.name(), componentContributionFields, memberSelectSnippets);
                            Snippet snippet = multibindingContributionSnippets.get(binding);
                            initializeMethod.body().addSnippet("this.%s = %s;", snippet, initializeSnippet);
                            parameterSnippets.add(snippet);
                        } else if (parentMultibindingContributionSnippets.containsKey(binding)) {
                            parameterSnippets.add(parentMultibindingContributionSnippets.get(binding));
                        } else {
                            throw new IllegalStateException(binding + " was not found in");
                        }
                    }
                    Snippet initializeSetSnippet = Snippet.format("%s.create(%s)",
                            hasOnlyProvisions ? ClassName.fromClass(SetFactory.class)
                                    : ClassName.fromClass(SetProducer.class),
                            Snippet.makeParametersSnippet(parameterSnippets.build()));
                    initializeMethod.body().addSnippet("this.%s = %s;", memberSelectSnippet,
                            initializeSetSnippet);
                    break;
                case MAP:
                    if (Sets.filter(bindings, Predicates.instanceOf(ProductionBinding.class)).isEmpty()) {
                        @SuppressWarnings("unchecked") // checked by the instanceof filter above
                        ImmutableSet<ProvisionBinding> provisionBindings = (ImmutableSet<ProvisionBinding>) bindings;
                        for (ProvisionBinding provisionBinding : provisionBindings) {
                            if (!isNonProviderMap(provisionBinding)
                                    && multibindingContributionSnippets.containsKey(provisionBinding)) {
                                Snippet snippet = multibindingContributionSnippets.get(provisionBinding);
                                initializeMethod.body().addSnippet("this.%s = %s;", snippet,
                                        initializeFactoryForProvisionBinding(provisionBinding,
                                                componentWriter.name(),
                                                input.componentDescriptor().dependencyMethodIndex(),
                                                componentContributionFields, memberSelectSnippets));
                            }
                        }
                        if (!provisionBindings.isEmpty()) {
                            Snippet initializeMapSnippet = initializeMapBinding(componentWriter.name(),
                                    memberSelectSnippets,
                                    new ImmutableMap.Builder<ContributionBinding, Snippet>()
                                            .putAll(parentMultibindingContributionSnippets)
                                            .putAll(multibindingContributionSnippets).build(),
                                    provisionBindings);
                            initializeMethod.body().addSnippet("this.%s = %s;", memberSelectSnippet,
                                    initializeMapSnippet);
                        }
                    } else {
                        // TODO(user): Implement producer map bindings.
                        throw new IllegalStateException("producer map bindings not implemented yet");
                    }
                    break;
                case UNIQUE:
                    if (!resolvedBindings.ownedContributionBindings().isEmpty()) {
                        ContributionBinding binding = Iterables.getOnlyElement(bindings);
                        if (binding instanceof ProvisionBinding) {
                            ProvisionBinding provisionBinding = (ProvisionBinding) binding;
                            if (!provisionBinding.factoryCreationStrategy().equals(ENUM_INSTANCE)
                                    || provisionBinding.scope().isPresent()) {
                                initializeMethod.body().addSnippet("this.%s = %s;", memberSelectSnippet,
                                        initializeFactoryForProvisionBinding(provisionBinding,
                                                componentWriter.name(),
                                                input.componentDescriptor().dependencyMethodIndex(),
                                                componentContributionFields, memberSelectSnippets));
                            }
                        } else if (binding instanceof ProductionBinding) {
                            ProductionBinding productionBinding = (ProductionBinding) binding;
                            initializeMethod.body().addSnippet("this.%s = %s;", memberSelectSnippet,
                                    initializeFactoryForProductionBinding(productionBinding, input,
                                            componentWriter.name(),
                                            input.componentDescriptor().dependencyMethodIndex(),
                                            componentContributionFields, memberSelectSnippets));
                        } else {
                            throw new AssertionError();
                        }
                    }
                    break;
                default:
                    throw new IllegalStateException();
                }
                break;
            case MEMBERS_INJECTION:
                MembersInjectionBinding binding = Iterables
                        .getOnlyElement(resolvedBindings.membersInjectionBindings());
                if (!binding.injectionStrategy().equals(MembersInjectionBinding.Strategy.NO_OP)) {
                    initializeMethod.body().addSnippet("this.%s = %s;", memberSelectSnippet,
                            initializeMembersInjectorForBinding(componentWriter.name(), binding,
                                    memberSelectSnippets));
                }
                break;
            default:
                throw new AssertionError();
            }
        }
    }
}

From source file:org.opendaylight.controller.sal.restconf.impl.RestconfImpl.java

@Override
public Response deleteConfigurationData(final String identifier) {
    final InstanceIdentifierContext<?> iiWithData = controllerContext.toInstanceIdentifier(identifier);
    final DOMMountPoint mountPoint = iiWithData.getMountPoint();
    final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();

    try {//from w w  w. ja  va 2s. c  om
        if (mountPoint != null) {
            broker.commitConfigurationDataDelete(mountPoint, normalizedII);
        } else {
            broker.commitConfigurationDataDelete(normalizedII).get();
        }
    } catch (final Exception e) {
        final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(e),
                Predicates.instanceOf(ModifiedNodeDoesNotExistException.class));
        if (searchedException.isPresent()) {
            throw new RestconfDocumentedException("Data specified for deleting doesn't exist.",
                    ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
        }
        final String errMsg = "Error while deleting data";
        LOG.info(errMsg, e);
        throw new RestconfDocumentedException(errMsg, e);
    }
    return Response.status(Status.OK).build();
}