Example usage for com.google.common.collect Iterables all

List of usage examples for com.google.common.collect Iterables all

Introduction

In this page you can find the example usage for com.google.common.collect Iterables all.

Prototype

public static <T> boolean all(Iterable<T> iterable, Predicate<? super T> predicate) 

Source Link

Document

Returns true if every element in iterable satisfies the predicate.

Usage

From source file:com.analog.lyric.dimple.model.factors.Factor.java

public boolean isDiscrete() {
    return Iterables.all(getSiblings(), VariablePredicates.isDiscrete());
}

From source file:com.palantir.atlasdb.keyvalue.cassandra.CassandraKeyValueService.java

@Override
public Map<Cell, Value> get(String tableName, Map<Cell, Long> timestampByCell) {
    if (timestampByCell.isEmpty()) {
        log.info("Attempted get on '{}' table with empty cells", tableName);
        return ImmutableMap.of();
    }/*  w  w w.  j a va 2s  .co  m*/

    try {
        Long firstTs = timestampByCell.values().iterator().next();
        if (Iterables.all(timestampByCell.values(), Predicates.equalTo(firstTs))) {
            StartTsResultsCollector collector = new StartTsResultsCollector(firstTs);
            loadWithTs(tableName, timestampByCell.keySet(), firstTs, false, collector, readConsistency);
            return collector.collectedResults;
        }

        SetMultimap<Long, Cell> cellsByTs = Multimaps.invertFrom(Multimaps.forMap(timestampByCell),
                HashMultimap.<Long, Cell>create());
        Builder<Cell, Value> builder = ImmutableMap.builder();
        for (long ts : cellsByTs.keySet()) {
            StartTsResultsCollector collector = new StartTsResultsCollector(ts);
            loadWithTs(tableName, cellsByTs.get(ts), ts, false, collector, readConsistency);
            builder.putAll(collector.collectedResults);
        }
        return builder.build();
    } catch (Exception e) {
        throw Throwables.throwUncheckedException(e);
    }
}

From source file:org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessSshDriver.java

/**
 * Sets up a {@link ScriptHelper} to generate a script that controls the given phase
 * (<em>check-running</em>, <em>launching</em> etc.) including default header and
 * footer commands.//from ww w  .ja  va2 s. co m
 * <p>
 * Supported flags:
 * <ul>
 * <li><strong>usePidFile</strong> - <em>true</em> or <em>filename</em> to save and retrieve the PID
 * <li><strong>processOwner</strong> - <em>username</em> that owns the running process
 * <li><strong>nonStandardLayout</strong> - <em>true</em> to omit all default commands
 * <li><strong>installIncomplete</strong> - <em>true</em> to prevent marking complete
 * <li><strong>debug</strong> - <em>true</em> to enable shell debug output
 * </li>
 *
 * @param flags a {@link Map} of flags to control script generation
 * @param phase the phase to create the ScriptHelper for
 *
 * @see #newScript(String)
 * @see #USE_PID_FILE
 * @see #PROCESS_OWNER
 * @see #NON_STANDARD_LAYOUT
 * @see #INSTALL_INCOMPLETE
 * @see #DEBUG
 */
protected ScriptHelper newScript(Map<String, ?> flags, String phase) {
    if (!Entities.isManaged(getEntity()))
        throw new IllegalStateException(
                getEntity() + " is no longer managed; cannot create script to run here (" + phase + ")");

    if (!Iterables.all(flags.keySet(), StringPredicates.equalToAny(VALID_FLAGS))) {
        throw new IllegalArgumentException("Invalid flags passed: " + flags);
    }

    ScriptHelper s = new ScriptHelper(this, phase + " " + elvis(entity, this));
    if (!groovyTruth(flags.get(NON_STANDARD_LAYOUT))) {
        if (groovyTruth(flags.get(DEBUG))) {
            s.header.prepend("set -x");
        }
        if (INSTALLING.equals(phase)) {
            // mutexId should be global because otherwise package managers will contend with each other
            s.useMutex(getLocation(), "installation lock at host", "installing " + elvis(entity, this));
            s.header.append("export INSTALL_DIR=\"" + getInstallDir() + "\"", "mkdir -p $INSTALL_DIR",
                    "cd $INSTALL_DIR", "test -f BROOKLYN && exit 0");

            if (!groovyTruth(flags.get(INSTALL_INCOMPLETE))) {
                s.footer.append("date > $INSTALL_DIR/BROOKLYN");
            }
            // don't set vars during install phase, prevent dependency resolution
            s.environmentVariablesReset();
        }
        if (ImmutableSet.of(CUSTOMIZING, LAUNCHING, CHECK_RUNNING, STOPPING, KILLING, RESTARTING)
                .contains(phase)) {
            s.header.append("export RUN_DIR=\"" + getRunDir() + "\"", "mkdir -p $RUN_DIR", "cd $RUN_DIR");
        }
    }

    if (ImmutableSet.of(LAUNCHING, RESTARTING).contains(phase)) {
        s.failIfBodyEmpty();
    }
    if (ImmutableSet.of(STOPPING, KILLING).contains(phase)) {
        // stopping and killing allowed to have empty body if pid file set
        if (!groovyTruth(flags.get(USE_PID_FILE)))
            s.failIfBodyEmpty();
    }
    if (ImmutableSet.of(INSTALLING, LAUNCHING).contains(phase)) {
        s.updateTaskAndFailOnNonZeroResultCode();
    }
    if (phase.equalsIgnoreCase(CHECK_RUNNING)) {
        s.setInessential();
        s.setTransient();
        s.setFlag(SshTool.PROP_CONNECT_TIMEOUT, Duration.TEN_SECONDS.toMilliseconds());
        s.setFlag(SshTool.PROP_SESSION_TIMEOUT, Duration.THIRTY_SECONDS.toMilliseconds());
        s.setFlag(SshTool.PROP_SSH_TRIES, 1);
    }

    if (groovyTruth(flags.get(USE_PID_FILE))) {
        Object usePidFile = flags.get(USE_PID_FILE);
        String pidFile = (usePidFile instanceof CharSequence ? usePidFile
                : Os.mergePathsUnix(getRunDir(), PID_FILENAME)).toString();
        String processOwner = (String) flags.get(PROCESS_OWNER);
        if (LAUNCHING.equals(phase)) {
            entity.sensors().set(SoftwareProcess.PID_FILE, pidFile);
            s.footer.prepend("echo $! > " + pidFile);
        } else if (CHECK_RUNNING.equals(phase)) {
            // old method, for supplied service, or entity.id
            // "ps aux | grep ${service} | grep \$(cat ${pidFile}) > /dev/null"
            // new way, preferred?
            if (processOwner != null) {
                s.body.append(BashCommands.sudoAsUser(processOwner, "test -f " + pidFile) + " || exit 1",
                        "ps -p $(" + BashCommands.sudoAsUser(processOwner, "cat " + pidFile) + ")");
            } else {
                s.body.append("test -f " + pidFile + " || exit 1", "ps -p `cat " + pidFile + "`");
            }
            // no pid, not running; 1 is not running
            s.requireResultCode(Predicates.or(Predicates.equalTo(0), Predicates.equalTo(1)));
        } else if (STOPPING.equals(phase)) {
            if (processOwner != null) {
                s.body.append("export PID=$(" + BashCommands.sudoAsUser(processOwner, "cat " + pidFile) + ")",
                        "test -n \"$PID\" || exit 0", BashCommands.sudoAsUser(processOwner, "kill $PID"),
                        BashCommands.sudoAsUser(processOwner, "kill -9 $PID"),
                        BashCommands.sudoAsUser(processOwner, "rm -f " + pidFile));
            } else {
                s.body.append("export PID=$(cat " + pidFile + ")", "test -n \"$PID\" || exit 0", "kill $PID",
                        "kill -9 $PID", "rm -f " + pidFile);
            }
        } else if (KILLING.equals(phase)) {
            if (processOwner != null) {
                s.body.append("export PID=$(" + BashCommands.sudoAsUser(processOwner, "cat " + pidFile) + ")",
                        "test -n \"$PID\" || exit 0", BashCommands.sudoAsUser(processOwner, "kill -9 $PID"),
                        BashCommands.sudoAsUser(processOwner, "rm -f " + pidFile));
            } else {
                s.body.append("export PID=$(cat " + pidFile + ")", "test -n \"$PID\" || exit 0", "kill -9 $PID",
                        "rm -f " + pidFile);
            }
        } else if (RESTARTING.equals(phase)) {
            if (processOwner != null) {
                s.footer.prepend(BashCommands.sudoAsUser(processOwner, "test -f " + pidFile) + " || exit 1",
                        "ps -p $(" + BashCommands.sudoAsUser(processOwner, "cat " + pidFile) + ") || exit 1");
            } else {
                s.footer.prepend("test -f " + pidFile + " || exit 1", "ps -p $(cat " + pidFile + ") || exit 1");
            }
            // no pid, not running; no process; can't restart, 1 is not running
        } else {
            log.warn(USE_PID_FILE + ": script option not valid for " + s.summary);
        }
    }

    return s;
}

From source file:com.eucalyptus.vm.VmControl.java

public RebootInstancesResponseType rebootInstances(final RebootInstancesType request)
        throws EucalyptusCloudException {
    final RebootInstancesResponseType reply = (RebootInstancesResponseType) request.getReply();
    try {/*ww  w  . j  a  v  a2s.c om*/
        List<String> instanceSet = normalizeIdentifiers(request.getInstancesSet());
        ArrayList<String> noAccess = new ArrayList<String>();
        ArrayList<String> migrating = new ArrayList<String>();
        ArrayList<String> noSuchElement = new ArrayList<String>();
        for (int i = 0; i < instanceSet.size(); i++) {
            String currentInstance = instanceSet.get(i);
            try {
                final VmInstance v = VmInstances.lookup(currentInstance);
                if (!RestrictedTypes.filterPrivileged().apply(v)) {
                    noAccess.add(currentInstance);
                }
                if (MigrationState.isMigrating(v)) {
                    migrating.add(currentInstance);
                }
            } catch (NoSuchElementException nse) {
                if (!(nse instanceof TerminatedInstanceException)) {
                    noSuchElement.add(currentInstance);
                } else {
                    instanceSet.remove(i--);
                }
            }
            if ((i == instanceSet.size() - 1) && (!noSuchElement.isEmpty())) {
                String outList = noSuchElement.toString();
                throw new EucalyptusCloudException(
                        "No such instance(s): " + outList.substring(1, outList.length() - 1));
            } else if ((i == instanceSet.size() - 1) && (!noAccess.isEmpty())) {
                String outList = noAccess.toString();
                throw new EucalyptusCloudException(
                        "Permission denied for vm(s): " + outList.substring(1, outList.length() - 1));
            } else if ((i == instanceSet.size() - 1) && (!migrating.isEmpty())) {
                String outList = noAccess.toString();
                throw new EucalyptusCloudException("Cannot reboot an instances which is currently migrating: "
                        + outList.substring(1, outList.length() - 1));
            }
        }
        final boolean result = Iterables.all(instanceSet, new Predicate<String>() {
            @Override
            public boolean apply(final String instanceId) {
                try {
                    final VmInstance v = VmInstances.lookup(instanceId);
                    final Request<RebootInstancesType, RebootInstancesResponseType> req = AsyncRequests
                            .newRequest(new RebootCallback(v.getInstanceId()));
                    req.getRequest().regarding(request);
                    ServiceConfiguration ccConfig = Topology.lookup(ClusterController.class,
                            v.lookupPartition());
                    req.dispatch(ccConfig);
                    return true;
                } catch (final NoSuchElementException e) {
                    return false;
                }
            }
        });
        reply.set_return(result);
        return reply;
    } catch (final Exception e) {
        LOG.error(e);
        LOG.debug(e, e);
        throw new EucalyptusCloudException(e.getMessage());
    }
}

From source file:com.facebook.presto.sql.analyzer.TupleAnalyzer.java

@Override
protected TupleDescriptor visitJoin(Join node, AnalysisContext context) {
    JoinCriteria criteria = node.getCriteria().orElse(null);
    if (criteria instanceof NaturalJoin) {
        throw new SemanticException(NOT_SUPPORTED, node, "Natural join not supported");
    }/*w  w w .ja va 2 s  . c o  m*/

    AnalysisContext leftContext = new AnalysisContext(context);
    TupleDescriptor left = process(node.getLeft(), context);
    leftContext.setLateralTupleDescriptor(left);
    TupleDescriptor right = process(node.getRight(), leftContext);

    // todo this check should be inside of TupleDescriptor.join and then remove the public getRelationAlias method, but the exception needs the node object
    Sets.SetView<QualifiedName> duplicateAliases = Sets.intersection(left.getRelationAliases(),
            right.getRelationAliases());
    if (!duplicateAliases.isEmpty()) {
        throw new SemanticException(DUPLICATE_RELATION, node, "Relations appear more than once: %s",
                duplicateAliases);
    }

    TupleDescriptor output = left.joinWith(right);

    if (node.getType() == Join.Type.CROSS || node.getType() == Join.Type.IMPLICIT) {
        analysis.setOutputDescriptor(node, output);
        return output;
    }

    if (criteria instanceof JoinUsing) {
        // TODO: implement proper "using" semantics with respect to output columns
        List<String> columns = ((JoinUsing) criteria).getColumns();

        List<Expression> expressions = new ArrayList<>();
        for (String column : columns) {
            Expression leftExpression = new QualifiedNameReference(QualifiedName.of(column));
            Expression rightExpression = new QualifiedNameReference(QualifiedName.of(column));

            ExpressionAnalysis leftExpressionAnalysis = analyzeExpression(leftExpression, left, context);
            ExpressionAnalysis rightExpressionAnalysis = analyzeExpression(rightExpression, right, context);
            checkState(leftExpressionAnalysis.getSubqueryInPredicates().isEmpty(), "INVARIANT");
            checkState(rightExpressionAnalysis.getSubqueryInPredicates().isEmpty(), "INVARIANT");

            addCoercionForJoinCriteria(node, leftExpression, rightExpression);
            expressions.add(new ComparisonExpression(EQUAL, leftExpression, rightExpression));
        }

        analysis.setJoinCriteria(node, ExpressionUtils.and(expressions));
    } else if (criteria instanceof JoinOn) {
        Expression expression = ((JoinOn) criteria).getExpression();

        // ensure all names can be resolved, types match, etc (we don't need to record resolved names, subexpression types, etc. because
        // we do it further down when after we determine which subexpressions apply to left vs right tuple)
        ExpressionAnalyzer analyzer = ExpressionAnalyzer.create(analysis, session, metadata, sqlParser,
                experimentalSyntaxEnabled);
        analyzer.analyze(expression, output, context);

        Analyzer.verifyNoAggregatesOrWindowFunctions(metadata, expression, "JOIN");

        // expressionInterpreter/optimizer only understands a subset of expression types
        // TODO: remove this when the new expression tree is implemented
        Expression canonicalized = CanonicalizeExpressions.canonicalizeExpression(expression);

        Object optimizedExpression = expressionOptimizer(canonicalized, metadata, session,
                analyzer.getExpressionTypes()).optimize(NoOpSymbolResolver.INSTANCE);

        if (!(optimizedExpression instanceof Expression) && optimizedExpression instanceof Boolean) {
            // If the JoinOn clause evaluates to a boolean expression, simulate a cross join by adding the relevant redundant expression
            if (optimizedExpression.equals(Boolean.TRUE)) {
                optimizedExpression = new ComparisonExpression(EQUAL, new LongLiteral("0"),
                        new LongLiteral("0"));
            } else {
                optimizedExpression = new ComparisonExpression(EQUAL, new LongLiteral("0"),
                        new LongLiteral("1"));
            }
        }

        if (!(optimizedExpression instanceof Expression)) {
            throw new SemanticException(TYPE_MISMATCH, node, "Join clause must be a boolean expression");
        }
        // The optimization above may have rewritten the expression tree which breaks all the identity maps, so redo the analysis
        // to re-analyze coercions that might be necessary
        analyzer = ExpressionAnalyzer.create(analysis, session, metadata, sqlParser, experimentalSyntaxEnabled);
        analyzer.analyze((Expression) optimizedExpression, output, context);
        analysis.addCoercions(analyzer.getExpressionCoercions());

        for (Expression conjunct : ExpressionUtils.extractConjuncts((Expression) optimizedExpression)) {
            if (!(conjunct instanceof ComparisonExpression)) {
                throw new SemanticException(NOT_SUPPORTED, node, "Non-equi joins not supported: %s", conjunct);
            }

            ComparisonExpression comparison = (ComparisonExpression) conjunct;
            Set<QualifiedName> firstDependencies = DependencyExtractor.extract(comparison.getLeft());
            Set<QualifiedName> secondDependencies = DependencyExtractor.extract(comparison.getRight());

            Expression leftExpression;
            Expression rightExpression;
            if (Iterables.all(firstDependencies, left.canResolvePredicate())
                    && Iterables.all(secondDependencies, right.canResolvePredicate())) {
                leftExpression = comparison.getLeft();
                rightExpression = comparison.getRight();
            } else if (Iterables.all(firstDependencies, right.canResolvePredicate())
                    && Iterables.all(secondDependencies, left.canResolvePredicate())) {
                leftExpression = comparison.getRight();
                rightExpression = comparison.getLeft();
            } else {
                // must have a complex expression that involves both tuples on one side of the comparison expression (e.g., coalesce(left.x, right.x) = 1)
                throw new SemanticException(NOT_SUPPORTED, node, "Non-equi joins not supported: %s", conjunct);
            }

            // analyze the clauses to record the types of all subexpressions and resolve names against the left/right underlying tuples
            ExpressionAnalysis leftExpressionAnalysis = analyzeExpression(leftExpression, left, context);
            ExpressionAnalysis rightExpressionAnalysis = analyzeExpression(rightExpression, right, context);
            addCoercionForJoinCriteria(node, leftExpression, rightExpression);
            analysis.addJoinInPredicates(node,
                    new Analysis.JoinInPredicates(leftExpressionAnalysis.getSubqueryInPredicates(),
                            rightExpressionAnalysis.getSubqueryInPredicates()));
        }

        analysis.setJoinCriteria(node, (Expression) optimizedExpression);
    } else {
        throw new UnsupportedOperationException("unsupported join criteria: " + criteria.getClass().getName());
    }

    analysis.setOutputDescriptor(node, output);
    return output;
}

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

/**
 * Create a map from COUNT([ALL]) -> zeroifnull(COUNT([ALL])) if
 * i) There is no GROUP-BY, and/*from  www .  j a  v  a  2 s .co  m*/
 * ii) There are other distinct aggregates to be evaluated.
 * This transformation is necessary for COUNT to correctly return 0 for empty
 * input relations.
 */
private ExprSubstitutionMap createCountAllMap(List<FunctionCallExpr> aggExprs, Analyzer analyzer)
        throws AnalysisException {
    ExprSubstitutionMap scalarCountAllMap = new ExprSubstitutionMap();

    if (groupingExprs_ != null && !groupingExprs_.isEmpty()) {
        // There are grouping expressions, so no substitution needs to be done.
        return scalarCountAllMap;
    }

    com.google.common.base.Predicate<FunctionCallExpr> isNotDistinctPred = new com.google.common.base.Predicate<FunctionCallExpr>() {
        public boolean apply(FunctionCallExpr expr) {
            return !expr.isDistinct();
        }
    };
    if (Iterables.all(aggExprs, isNotDistinctPred)) {
        // Only [ALL] aggs, so no substitution needs to be done.
        return scalarCountAllMap;
    }

    com.google.common.base.Predicate<FunctionCallExpr> isCountPred = new com.google.common.base.Predicate<FunctionCallExpr>() {
        public boolean apply(FunctionCallExpr expr) {
            return expr.getFnName().getFunction().equals("count");
        }
    };

    Iterable<FunctionCallExpr> countAllAggs = Iterables.filter(aggExprs,
            Predicates.and(isCountPred, isNotDistinctPred));
    for (FunctionCallExpr countAllAgg : countAllAggs) {
        // Replace COUNT(ALL) with zeroifnull(COUNT(ALL))
        ArrayList<Expr> zeroIfNullParam = Lists.newArrayList(countAllAgg.clone());
        FunctionCallExpr zeroIfNull = new FunctionCallExpr("zeroifnull", zeroIfNullParam);
        zeroIfNull.analyze(analyzer);
        scalarCountAllMap.put(countAllAgg, zeroIfNull);
    }

    return scalarCountAllMap;
}

From source file:org.killbill.billing.jaxrs.resources.InvoiceResource.java

@TimedResource
@POST/*from ww  w  .  j  av  a2  s.co  m*/
@Produces(APPLICATION_JSON)
@Consumes(APPLICATION_JSON)
@Path("/" + CHARGES + "/{accountId:" + UUID_PATTERN + "}")
@ApiOperation(value = "Create external charge(s)", response = InvoiceItemJson.class, responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid account id supplied"),
        @ApiResponse(code = 404, message = "Account not found") })
public Response createExternalCharges(final Iterable<InvoiceItemJson> externalChargesJson,
        @PathParam("accountId") final String accountId,
        @QueryParam(QUERY_REQUESTED_DT) final String requestedDateTimeString,
        @QueryParam(QUERY_PAY_INVOICE) @DefaultValue("false") final Boolean payInvoice,
        @QueryParam(QUERY_PLUGIN_PROPERTY) final List<String> pluginPropertiesString,
        @QueryParam(QUERY_AUTO_COMMIT) @DefaultValue("false") final Boolean autoCommit,
        @QueryParam(QUERY_PAYMENT_EXTERNAL_KEY) final String paymentExternalKey,
        @QueryParam(QUERY_TRANSACTION_EXTERNAL_KEY) final String transactionExternalKey,
        @HeaderParam(HDR_CREATED_BY) final String createdBy, @HeaderParam(HDR_REASON) final String reason,
        @HeaderParam(HDR_COMMENT) final String comment, @javax.ws.rs.core.Context final UriInfo uriInfo,
        @javax.ws.rs.core.Context final HttpServletRequest request)
        throws AccountApiException, InvoiceApiException, PaymentApiException {
    final Iterable<PluginProperty> pluginProperties = extractPluginProperties(pluginPropertiesString);
    final CallContext callContext = context.createContext(createdBy, reason, comment, request);

    final Account account = accountUserApi.getAccountById(UUID.fromString(accountId), callContext);
    final Iterable<InvoiceItem> sanitizedExternalChargesJson = validateSanitizeAndTranformInputItems(
            account.getCurrency(), externalChargesJson);

    // Get the effective date of the external charge, in the account timezone
    final LocalDate requestedDate = toLocalDateDefaultToday(account, requestedDateTimeString, callContext);
    final List<InvoiceItem> createdExternalCharges = invoiceApi.insertExternalCharges(account.getId(),
            requestedDate, sanitizedExternalChargesJson, autoCommit, callContext);

    // if all createdExternalCharges point to the same invoiceId, use the provided paymentExternalKey and / or transactionExternalKey
    final boolean haveSameInvoiceId = Iterables.all(createdExternalCharges, new Predicate<InvoiceItem>() {
        @Override
        public boolean apply(final InvoiceItem input) {
            return input.getInvoiceId().equals(createdExternalCharges.get(0).getInvoiceId());
        }
    });

    if (payInvoice) {
        final Collection<UUID> paidInvoices = new HashSet<UUID>();
        for (final InvoiceItem externalCharge : createdExternalCharges) {
            if (!paidInvoices.contains(externalCharge.getInvoiceId())) {
                paidInvoices.add(externalCharge.getInvoiceId());
                final Invoice invoice = invoiceApi.getInvoice(externalCharge.getInvoiceId(), callContext);
                createPurchaseForInvoice(account, invoice.getId(), invoice.getBalance(),
                        account.getPaymentMethodId(), false,
                        (haveSameInvoiceId && paymentExternalKey != null) ? paymentExternalKey : null,
                        (haveSameInvoiceId && transactionExternalKey != null) ? transactionExternalKey : null,
                        pluginProperties, callContext);
            }
        }
    }

    final List<InvoiceItemJson> createdExternalChargesJson = Lists.<InvoiceItem, InvoiceItemJson>transform(
            createdExternalCharges, new Function<InvoiceItem, InvoiceItemJson>() {
                @Override
                public InvoiceItemJson apply(final InvoiceItem input) {
                    return new InvoiceItemJson(input);
                }
            });
    return Response.status(Status.OK).entity(createdExternalChargesJson).build();
}

From source file:com.isotrol.impe3.pms.core.impl.PortalsServiceImpl.java

@Transactional(rollbackFor = Throwable.class)
@Authorized(global = GlobalAuthority.PORTAL_SET, portal = PortalAuthority.SET)
public void importName(String id, String fileId) throws PMSException {
    // Fetch portal
    loadContextGlobal().toPortal(id);/*from   www.  j ava 2 s .c o m*/
    // Load file
    final PortalNamePB msg = fileManager.parseImportFile(fileId, PortalNamePB.newBuilder(), true).build();
    // Import data
    try {
        checkNotNull(MoreLocales.VALID.apply(msg.getDefaultLocale()));
        checkArgument(Iterables.all(MessageMappers.seKeys(msg.getLocalesList()), MoreLocales.VALID));
        final PortalEntity entity = load(id);
        final PortalDfn dfn = portalManager.touchOffline(entity);
        dfn.setName(Mappers.PB2NAME.apply(msg.getName()));
        dfn.setDescription(msg.getDescription());
        dfn.setDefaultLocale(msg.getDefaultLocale());
        final Map<String, String> locales = PortalObject
                .fromNullName(MessageMappers.seMap(msg.getLocalesList()));
        dfn.getLocales().clear();
        dfn.getLocales().addAll(locales.keySet());
        dfn.getL7DNames().clear();
        dfn.getL7DNames().putAll(filterValues(locales, notNull()));
    } finally {
        purge();
    }
}

From source file:brooklyn.entity.basic.AbstractSoftwareProcessSshDriver.java

/**
 * Sets up a {@link ScriptHelper} to generate a script that controls the given phase
 * (<em>check-running</em>, <em>launching</em> etc.) including default header and
 * footer commands./* w ww  .ja  va 2 s. c o  m*/
 * <p>
 * Supported flags:
 * <ul>
 * <li><strong>usePidFile</strong> - <em>true</em> or <em>filename</em> to save and retrieve the PID
 * <li><strong>processOwner</strong> - <em>username</em> that owns the running process
 * <li><strong>nonStandardLayout</strong> - <em>true</em> to omit all default commands
 * <li><strong>installIncomplete</strong> - <em>true</em> to prevent marking complete
 * <li><strong>debug</strong> - <em>true</em> to enable shell debug output
 * </li>
 *
 * @param flags a {@link Map} of flags to control script generation
 * @param phase the phase to create the ScriptHelper for
 *
 * @see #newScript(String)
 * @see #USE_PID_FILE
 * @see #PROCESS_OWNER
 * @see #NON_STANDARD_LAYOUT
 * @see #INSTALL_INCOMPLETE
 * @see #DEBUG
 */
protected ScriptHelper newScript(Map<String, ?> flags, String phase) {
    if (!Entities.isManaged(getEntity()))
        throw new IllegalStateException(
                getEntity() + " is no longer managed; cannot create script to run here (" + phase + ")");

    if (!Iterables.all(flags.keySet(), StringPredicates.equalToAny(VALID_FLAGS))) {
        throw new IllegalArgumentException("Invalid flags passed: " + flags);
    }

    ScriptHelper s = new ScriptHelper(this, phase + " " + elvis(entity, this));
    if (!groovyTruth(flags.get(NON_STANDARD_LAYOUT))) {
        if (groovyTruth(flags.get(DEBUG))) {
            s.header.prepend("set -x");
        }
        if (INSTALLING.equals(phase)) {
            // mutexId should be global because otherwise package managers will contend with each other 
            s.useMutex(getLocation(), "installation lock at host", "installing " + elvis(entity, this));
            s.header.append("export INSTALL_DIR=\"" + getInstallDir() + "\"", "mkdir -p $INSTALL_DIR",
                    "cd $INSTALL_DIR", "test -f BROOKLYN && exit 0");

            if (!groovyTruth(flags.get(INSTALL_INCOMPLETE))) {
                s.footer.append("date > $INSTALL_DIR/BROOKLYN");
            }
            // don't set vars during install phase, prevent dependency resolution
            s.environmentVariablesReset();
        }
        if (ImmutableSet.of(CUSTOMIZING, LAUNCHING, CHECK_RUNNING, STOPPING, KILLING, RESTARTING)
                .contains(phase)) {
            s.header.append("export RUN_DIR=\"" + getRunDir() + "\"", "mkdir -p $RUN_DIR", "cd $RUN_DIR");
        }
    }

    if (ImmutableSet.of(LAUNCHING, RESTARTING).contains(phase)) {
        s.failIfBodyEmpty();
    }
    if (ImmutableSet.of(STOPPING, KILLING).contains(phase)) {
        // stopping and killing allowed to have empty body if pid file set
        if (!groovyTruth(flags.get(USE_PID_FILE)))
            s.failIfBodyEmpty();
    }
    if (ImmutableSet.of(INSTALLING, LAUNCHING).contains(phase)) {
        s.updateTaskAndFailOnNonZeroResultCode();
    }
    if (phase.equalsIgnoreCase(CHECK_RUNNING)) {
        s.setInessential();
        s.setTransient();
        s.setFlag(SshTool.PROP_CONNECT_TIMEOUT, Duration.TEN_SECONDS.toMilliseconds());
        s.setFlag(SshTool.PROP_SESSION_TIMEOUT, Duration.THIRTY_SECONDS.toMilliseconds());
        s.setFlag(SshTool.PROP_SSH_TRIES, 1);
    }

    if (groovyTruth(flags.get(USE_PID_FILE))) {
        Object usePidFile = flags.get(USE_PID_FILE);
        String pidFile = (usePidFile instanceof CharSequence ? usePidFile
                : Os.mergePathsUnix(getRunDir(), PID_FILENAME)).toString();
        String processOwner = (String) flags.get(PROCESS_OWNER);
        if (LAUNCHING.equals(phase)) {
            entity.setAttribute(SoftwareProcess.PID_FILE, pidFile);
            s.footer.prepend("echo $! > " + pidFile);
        } else if (CHECK_RUNNING.equals(phase)) {
            // old method, for supplied service, or entity.id
            // "ps aux | grep ${service} | grep \$(cat ${pidFile}) > /dev/null"
            // new way, preferred?
            if (processOwner != null) {
                s.body.append(BashCommands.sudoAsUser(processOwner, "test -f " + pidFile) + " || exit 1",
                        "ps -p $(" + BashCommands.sudoAsUser(processOwner, "cat " + pidFile) + ")");
            } else {
                s.body.append("test -f " + pidFile + " || exit 1", "ps -p `cat " + pidFile + "`");
            }
            // no pid, not running; 1 is not running
            s.requireResultCode(Predicates.or(Predicates.equalTo(0), Predicates.equalTo(1)));
        } else if (STOPPING.equals(phase)) {
            if (processOwner != null) {
                s.body.append("export PID=$(" + BashCommands.sudoAsUser(processOwner, "cat " + pidFile) + ")",
                        "test -n \"$PID\" || exit 0", BashCommands.sudoAsUser(processOwner, "kill $PID"),
                        BashCommands.sudoAsUser(processOwner, "kill -9 $PID"),
                        BashCommands.sudoAsUser(processOwner, "rm -f " + pidFile));
            } else {
                s.body.append("export PID=$(cat " + pidFile + ")", "test -n \"$PID\" || exit 0", "kill $PID",
                        "kill -9 $PID", "rm -f " + pidFile);
            }
        } else if (KILLING.equals(phase)) {
            if (processOwner != null) {
                s.body.append("export PID=$(" + BashCommands.sudoAsUser(processOwner, "cat " + pidFile) + ")",
                        "test -n \"$PID\" || exit 0", BashCommands.sudoAsUser(processOwner, "kill -9 $PID"),
                        BashCommands.sudoAsUser(processOwner, "rm -f " + pidFile));
            } else {
                s.body.append("export PID=$(cat " + pidFile + ")", "test -n \"$PID\" || exit 0", "kill -9 $PID",
                        "rm -f " + pidFile);
            }
        } else if (RESTARTING.equals(phase)) {
            if (processOwner != null) {
                s.footer.prepend(BashCommands.sudoAsUser(processOwner, "test -f " + pidFile) + " || exit 1",
                        "ps -p $(" + BashCommands.sudoAsUser(processOwner, "cat " + pidFile) + ") || exit 1");
            } else {
                s.footer.prepend("test -f " + pidFile + " || exit 1", "ps -p $(cat " + pidFile + ") || exit 1");
            }
            // no pid, not running; no process; can't restart, 1 is not running
        } else {
            log.warn(USE_PID_FILE + ": script option not valid for " + s.summary);
        }
    }

    return s;
}

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

/**
 * Checks if an expr containing a correlated subquery is eligible for rewrite by
 * tranforming into a join. 'correlatedPredicates' contains the correlated
 * predicates identified in the subquery. Throws an AnalysisException if 'expr'
 * is not eligible for rewrite.//from   www.j  av a  2 s. c  o m
 * TODO: Merge all the rewrite eligibility tests into a single function.
 */
private static void canRewriteCorrelatedSubquery(Expr expr, List<Expr> correlatedPredicates)
        throws AnalysisException {
    Preconditions.checkNotNull(expr);
    Preconditions.checkNotNull(correlatedPredicates);
    Preconditions.checkState(expr.contains(Subquery.class));
    SelectStmt stmt = (SelectStmt) expr.getSubquery().getStatement();
    Preconditions.checkNotNull(stmt);
    // Grouping and/or aggregation is not allowed on correlated scalar and IN subqueries
    if ((expr instanceof BinaryPredicate && (stmt.hasGroupByClause() || stmt.hasAnalyticInfo()))
            || (expr instanceof InPredicate && (stmt.hasAggInfo() || stmt.hasAnalyticInfo()))) {
        throw new AnalysisException(
                "Unsupported correlated subquery with grouping " + "and/or aggregation: " + stmt.toSql());
    }

    final com.google.common.base.Predicate<Expr> isSingleSlotRef = new com.google.common.base.Predicate<Expr>() {
        @Override
        public boolean apply(Expr arg) {
            return arg.unwrapSlotRef(false) != null;
        }
    };

    // A HAVING clause is only allowed on correlated EXISTS subqueries with
    // correlated binary predicates of the form Slot = Slot (see IMPALA-2734)
    // TODO Handle binary predicates with IS NOT DISTINCT op
    if (expr instanceof ExistsPredicate && stmt.hasHavingClause() && !correlatedPredicates.isEmpty()
            && (!stmt.hasAggInfo() || !Iterables.all(correlatedPredicates,
                    Predicates.or(Expr.IS_EQ_BINARY_PREDICATE, isSingleSlotRef)))) {
        throw new AnalysisException(
                "Unsupported correlated EXISTS subquery with a " + "HAVING clause: " + stmt.toSql());
    }

    // The following correlated subqueries with a limit clause are supported:
    // 1. EXISTS subqueries
    // 2. Scalar subqueries with aggregation
    if (stmt.hasLimit()
            && (!(expr instanceof BinaryPredicate) || !stmt.hasAggInfo() || stmt.selectList_.isDistinct())
            && !(expr instanceof ExistsPredicate)) {
        throw new AnalysisException(
                "Unsupported correlated subquery with a " + "LIMIT clause: " + stmt.toSql());
    }
}