Example usage for java.util.logging Level FINER

List of usage examples for java.util.logging Level FINER

Introduction

In this page you can find the example usage for java.util.logging Level FINER.

Prototype

Level FINER

To view the source code for java.util.logging Level FINER.

Click Source Link

Document

FINER indicates a fairly detailed tracing message.

Usage

From source file:org.b3log.latke.repository.jdbc.JdbcRepository.java

@Override
public Transaction beginTransaction() {
    final JdbcTransaction ret = TX.get();

    if (null != ret) {
        LOGGER.log(Level.FINER, "There is a transaction[isActive={0}] in current thread", ret.isActive());
        if (ret.isActive()) {
            return TX.get(); // Using 'the current transaction'
        }//from ww  w.j a va  2  s .  c  om
    }

    JdbcTransaction jdbcTransaction = null;

    try {
        jdbcTransaction = new JdbcTransaction();
    } catch (final SQLException e) {
        LOGGER.log(Level.SEVERE, "Failed to initialize JDBC transaction", e);

        throw new IllegalStateException("Failed to initialize JDBC transaction");
    }

    TX.set(jdbcTransaction);

    return jdbcTransaction;
}

From source file:org.b3log.latke.repository.gae.GAERepository.java

@Override
public long count() {
    final String cacheKey = CACHE_KEY_PREFIX + getName() + REPOSITORY_CACHE_COUNT;

    if (cacheEnabled) {
        final Object o = CACHE.get(cacheKey);

        if (null != o) {
            LOGGER.log(Level.FINER, "Got an object[cacheKey={0}] from repository cache[name={1}]",
                    new Object[] { cacheKey, getName() });
            try {
                return (Long) o;
            } catch (final Exception e) {
                LOGGER.log(Level.SEVERE, e.getMessage(), e);

                return -1;
            }/* w  w  w. j  a v a  2  s.  c o  m*/
        }
    }

    final Query query = new Query(getName());
    final PreparedQuery preparedQuery = datastoreService.prepare(query);

    final long ret = preparedQuery.countEntities(FetchOptions.Builder.withDefaults());

    if (cacheEnabled) {
        CACHE.putAsync(cacheKey, ret);
        LOGGER.log(Level.FINER, "Added an object[cacheKey={0}] in repository cache[{1}]",
                new Object[] { cacheKey, getName() });
    }

    return ret;
}

From source file:com.ibm.jaggr.core.impl.transport.AbstractHttpTransport.java

/**
 * Validate the {@link com.ibm.jaggr.core.transport.IHttpTransport.LayerContributionType} and argument type specified
 * in a call to//from  ww  w. jav  a 2 s  . c o m
 * {@link #getLayerContribution(HttpServletRequest, com.ibm.jaggr.core.transport.IHttpTransport.LayerContributionType, Object)}
 *
 * @param request
 *            The http request object
 * @param type
 *            The layer contribution (see
 *            {@link com.ibm.jaggr.core.transport.IHttpTransport.LayerContributionType})
 * @param arg
 *            The argument value
 */
protected void validateLayerContributionState(HttpServletRequest request, LayerContributionType type,
        Object arg) {

    final String sourceMethod = "validateLayerContributionState"; //$NON-NLS-1$
    boolean isTraceLogging = log.isLoggable(Level.FINER);
    if (isTraceLogging) {
        log.entering(AbstractHttpTransport.class.getName(), sourceMethod, new Object[] { request, type, arg });
    }
    LayerContributionType previousType = (LayerContributionType) request
            .getAttribute(LAYERCONTRIBUTIONSTATE_REQATTRNAME);
    if (isTraceLogging) {
        log.finer("previousType = " + previousType); //$NON-NLS-1$
    }
    switch (type) {
    case BEGIN_RESPONSE:
        if (previousType != null) {
            throw new IllegalStateException();
        }
        break;
    case BEGIN_MODULES:
        if (previousType != LayerContributionType.BEGIN_RESPONSE) {
            throw new IllegalStateException();
        }
        break;
    case BEFORE_FIRST_MODULE:
        if (previousType != LayerContributionType.BEGIN_MODULES || !(arg instanceof String)) {
            throw new IllegalStateException();
        }
        break;
    case BEFORE_SUBSEQUENT_MODULE:
        if (previousType != LayerContributionType.AFTER_MODULE || !(arg instanceof String)) {
            throw new IllegalStateException();
        }
        break;
    case AFTER_MODULE:
        if (previousType != LayerContributionType.BEFORE_FIRST_MODULE
                && previousType != LayerContributionType.BEFORE_SUBSEQUENT_MODULE || !(arg instanceof String)) {
            throw new IllegalStateException();
        }
        break;
    case END_MODULES:
        if (previousType != LayerContributionType.AFTER_MODULE) {
            throw new IllegalStateException();
        }
        break;
    case BEGIN_LAYER_MODULES:
        if (previousType != LayerContributionType.BEGIN_RESPONSE
                && previousType != LayerContributionType.END_MODULES || !(arg instanceof Set)) {
            throw new IllegalStateException();
        }
        break;
    case BEFORE_FIRST_LAYER_MODULE:
        if (previousType != LayerContributionType.BEGIN_LAYER_MODULES || !(arg instanceof String)) {
            throw new IllegalStateException();
        }
        break;
    case BEFORE_SUBSEQUENT_LAYER_MODULE:
        if (previousType != LayerContributionType.AFTER_LAYER_MODULE || !(arg instanceof String)) {
            throw new IllegalStateException();
        }
        break;
    case AFTER_LAYER_MODULE:
        if (previousType != LayerContributionType.BEFORE_FIRST_LAYER_MODULE
                && previousType != LayerContributionType.BEFORE_SUBSEQUENT_LAYER_MODULE
                || !(arg instanceof String)) {
            throw new IllegalStateException();
        }
        break;
    case END_LAYER_MODULES:
        if (previousType != LayerContributionType.AFTER_LAYER_MODULE || !(arg instanceof Set)) {
            throw new IllegalStateException();
        }
        break;
    case END_RESPONSE:
        if (previousType != LayerContributionType.END_MODULES
                && previousType != LayerContributionType.END_LAYER_MODULES) {
            throw new IllegalStateException();
        }
        break;
    }
    request.setAttribute(LAYERCONTRIBUTIONSTATE_REQATTRNAME, type);
    if (isTraceLogging) {
        log.exiting(AbstractHttpTransport.class.getName(), sourceMethod);
    }
}

From source file:org.geoserver.jdbcconfig.internal.ConfigDatabase.java

private void updateQueryableProperties(final Info info, final Integer objectId,
        Iterable<Property> changedProperties) {

    Map<String, ?> params;

    final Integer oid = objectId;
    Integer propertyType;/*from   ww  w  .j av a2 s. co m*/
    Integer relatedOid;
    Integer relatedPropertyType;
    Integer colIndex;
    String storedValue;

    for (Property changedProp : changedProperties) {
        LOGGER.finer("Updating property " + changedProp);

        final boolean isRelationship = changedProp.isRelationship();
        propertyType = changedProp.getPropertyType().getOid();

        final List<?> values = valueList(changedProp);

        for (int i = 0; i < values.size(); i++) {
            final Object rawValue = values.get(i);
            storedValue = marshalValue(rawValue);
            checkArgument(changedProp.isCollectionProperty() || values.size() == 1,
                    "Got a multivalued value for a non collection property " + changedProp.getPropertyName()
                            + "=" + values);

            colIndex = changedProp.isCollectionProperty() ? (i + 1) : 0;

            if (isRelationship) {
                final Info relatedObject = lookUpRelatedObject(info, changedProp, colIndex);
                relatedOid = relatedObject == null ? null : findObjectId(relatedObject);
                relatedPropertyType = changedProp.getPropertyType().getTargetPropertyOid();
            } else {
                // it's a self property, lets update the value on the property table
                relatedOid = null;
                relatedPropertyType = null;
            }
            String sql = "update object_property set " //
                    + "related_oid = :related_oid, "//
                    + "related_property_type = :related_property_type, "//
                    + "value = :value "//
                    + "where oid = :oid and property_type = :property_type and colindex = :colindex";
            params = params("related_oid", relatedOid, "related_property_type", relatedPropertyType, "value",
                    storedValue, "oid", oid, "property_type", propertyType, "colindex", colIndex);

            logStatement(sql, params);
            final int updateCnt = template.update(sql, params);

            if (updateCnt == 0) {
                addAttribute(info, oid, changedProp, colIndex, storedValue);
            } else {
                // prop existed already, lets update any related property that points to its old
                // value
                String updateRelated = "update object_property set value = :value "
                        + "where related_oid = :oid and related_property_type = :property_type and colindex = :colindex";
                params = params("oid", oid, "property_type", propertyType, "colindex", colIndex, "value",
                        storedValue);
                logStatement(updateRelated, params);
                int relatedUpdateCnt = template.update(updateRelated, params);
                if (LOGGER.isLoggable(Level.FINER)) {
                    LOGGER.finer("Updated " + relatedUpdateCnt + " back pointer properties to "
                            + changedProp.getPropertyName() + " of " + info.getClass().getSimpleName() + "["
                            + info.getId() + "]");
                }
            }
        }
        if (changedProp.isCollectionProperty()) {
            // delete any remaining collection value that's no longer in the value list
            String sql = "delete from object_property where oid=:oid and property_type=:property_type "
                    + "and colindex > :maxIndex";
            Integer maxIndex = Integer.valueOf(values.size());
            template.update(sql, params("oid", oid, "property_type", propertyType, "maxIndex", maxIndex));
        }
    }
}

From source file:edu.harvard.iq.safe.lockss.impl.LOCKSSDaemonStatusTableTO.java

@Override
public Peers tabulateAgreedPeers(long pollCutoffTime) {

    String timeZone = this.getTimezoneOffset();
    //String rawlastPollTime = "03:16:33 04/14/12";

    logger.log(Level.FINE, "timeZone={0}", timeZone);

    ///*  w w w  .  ja  v  a 2s  . co m*/
    logger.log(Level.FINE, "Poll cutoff Time={0}", pollCutoffTime);

    // use map
    List<Map<String, String>> tblh = this.getTableData();

    Peers result = new Peers();

    result.setAuId(this.tableKey);
    result.setAuName(this.tableTitle);

    Set<PeerRepairBox> ipSet100pct = new LinkedHashSet<PeerRepairBox>();
    Set<PeerRepairBox> ipSetNon100pct = new LinkedHashSet<PeerRepairBox>();
    long newestPollDate = 0;
    for (int i = 0; i < tblh.size(); i++) {
        // 1st filter: deals with concesus-reached peers only
        if (!tblh.get(i).get("Last").equals("Yes")) {
            continue;
        }

        // 2nd filter: exclude old-poll peer
        String pcnt = null;
        if (StringUtils.isNotBlank(tblh.get(i).get("LastPercentAgreement"))) {
            pcnt = tblh.get(i).get("LastPercentAgreement").replace("%", "");
            logger.log(Level.FINE, "pcnt is not null:{0}", pcnt);
        } else {
            logger.log(Level.FINE, "pcnt is null or empty:{0}", pcnt);
        }

        String ipAddressFromTable = DaemonStatusDataUtil.getPeerIpAddress(tblh.get(i).get("Box"));
        logger.log(Level.FINE, "{0}-th ip={1} pcnt={2}", new Object[] { i, ipAddressFromTable, pcnt });

        long pollEndTime = DaemonStatusDataUtil.getEpocTimeFromString(tblh.get(i).get("LastAgree"), timeZone);
        logger.log(Level.FINE, "H:pollEndTime is    {0}", pollEndTime);

        if (pollEndTime < pollCutoffTime) {
            logger.log(Level.FINE, "H: {0}: pollEndTime is beyond the cutoff point", ipAddressFromTable);
            continue;
        }
        logger.log(Level.FINE, "H: {0}: pollEndTime is within the cutoff range", ipAddressFromTable);

        if (pollEndTime > newestPollDate) {
            newestPollDate = pollEndTime;
        }
        // older daemon 1.53.3 used 100% instead of 100.00
        //            if (pcnt.startsWith("100")) {
        //                // add this peer's Ip address
        //                ipSet100pct.add(new PeerRepairBox(ipAddressFromTable,
        //                    pollEndTime));
        //            } else {
        //                Double parsedPcnt = 0.0d;
        //                if (StringUtils.isNotBlank(pcnt)) {
        //                    try {
        //                        parsedPcnt = Double.parseDouble(pcnt);
        //                    } catch (NumberFormatException e) {
        //                        logger.log(Level.WARNING, "percent value(={1}) cannot be parsed for {0}-th auId", new Object[]{i, pcnt});
        //                    } finally {
        //logger.log(Level.INFO, "double value(={1}) for {0}-th auId", new Object[]{i, parsedPcnt});
        //                    ipSetNon100pct.add(new PeerRepairBox(ipAddressFromTable,
        //                        pollEndTime, parsedPcnt));
        //                    }
        //                } else {
        //
        //                    ipSetNon100pct.add(new PeerRepairBox(ipAddressFromTable,
        //                        pollEndTime, parsedPcnt));
        //                }
        //
        //            }

        Double parsedPcnt = 0.0d;

        if (StringUtils.isNotBlank(pcnt)) {
            try {
                parsedPcnt = Double.parseDouble(pcnt);
            } catch (NumberFormatException e) {
                logger.log(Level.WARNING, "percent value(={1}) cannot be parsed for {0}-th auId",
                        new Object[] { i, pcnt });
            } finally {
                logger.log(Level.FINE, "double value(={1}) for {0}-th auId", new Object[] { i, parsedPcnt });

                if (Double.compare(parsedPcnt, 100d) == 0) {
                    // 100% case
                    ipSet100pct.add(new PeerRepairBox(ipAddressFromTable, pollEndTime));
                    logger.log(Level.FINER, "100%: double value(={1}) for {0}-th auId",
                            new Object[] { i, parsedPcnt });
                } else {
                    // less than 100% cases
                    ipSetNon100pct.add(new PeerRepairBox(ipAddressFromTable, pollEndTime, parsedPcnt));
                    logger.log(Level.FINER, "not 100%: double value(={1}) for {0}-th auId",
                            new Object[] { i, parsedPcnt });
                }

            }
        } else {
            logger.log(Level.FINE, "null %: double value(={1}) for {0}-th auId",
                    new Object[] { i, parsedPcnt });
            ipSetNon100pct.add(new PeerRepairBox(ipAddressFromTable, pollEndTime, parsedPcnt));
        }

    }
    logger.log(Level.FINE, "The latest Poll time of this AU={0}", newestPollDate);
    result.setLastAgree(newestPollDate);
    result.setFullyAgreedPeerSet(ipSet100pct);
    result.setNonfullyAgreedPeerSet(ipSetNon100pct);
    result.setPoller(this.ipAddress);

    logger.log(Level.FINE, "H:number of 100% boxes={0}", ipSet100pct.size());
    logger.log(Level.FINE, "H:number of non-100% boxes={0}", ipSetNon100pct.size());

    return result;
}

From source file:org.b3log.solo.processor.ArticleProcessor.java

/**
 * Shows an article with the specified context.
 * //from   www  .  j a  v  a 2  s.  com
 * @param context the specified context
 * @param request the specified HTTP servlet request
 * @param response the specified HTTP servlet response
 * @throws IOException io exception 
 */
@RequestProcessing(value = "/article", method = HTTPRequestMethod.GET)
public void showArticle(final HTTPRequestContext context, final HttpServletRequest request,
        final HttpServletResponse response) throws IOException {
    // See PermalinkFiler#dispatchToArticleOrPageProcessor()
    final JSONObject article = (JSONObject) request.getAttribute(Article.ARTICLE);
    if (null == article) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    final String articleId = article.optString(Keys.OBJECT_ID);
    LOGGER.log(Level.FINER, "Article[id={0}]", articleId);
    final AbstractFreeMarkerRenderer renderer = new FrontRenderer();
    context.setRenderer(renderer);
    renderer.setTemplateName("article.ftl");

    try {
        final JSONObject preference = preferenceQueryService.getPreference();

        final boolean allowVisitDraftViaPermalink = preference
                .getBoolean(Preference.ALLOW_VISIT_DRAFT_VIA_PERMALINK);
        if (!article.optBoolean(Article.ARTICLE_IS_PUBLISHED) && !allowVisitDraftViaPermalink) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);

            return;
        }

        LOGGER.log(Level.FINEST, "Article[title={0}]", article.getString(Article.ARTICLE_TITLE));

        articleQueryService.markdown(article);

        final Map<String, String> langs = langPropsService.getAll(Latkes.getLocale());

        request.setAttribute(PageCaches.CACHED_TYPE, langs.get(PageTypes.ARTICLE.getLangeLabel()));
        request.setAttribute(PageCaches.CACHED_OID, articleId);
        request.setAttribute(PageCaches.CACHED_TITLE, article.getString(Article.ARTICLE_TITLE));
        request.setAttribute(PageCaches.CACHED_LINK, article.getString(Article.ARTICLE_PERMALINK));
        request.setAttribute(PageCaches.CACHED_PWD, article.optString(Article.ARTICLE_VIEW_PWD));

        // For <meta name="description" content="${article.articleAbstract}"/>
        final String metaDescription = Jsoup.parse(article.optString(Article.ARTICLE_ABSTRACT)).text();
        article.put(Article.ARTICLE_ABSTRACT, metaDescription);

        if (preference.getBoolean(Preference.ENABLE_ARTICLE_UPDATE_HINT)) {
            article.put(Common.HAS_UPDATED, articleUtils.hasUpdated(article));
        } else {
            article.put(Common.HAS_UPDATED, false);
        }

        final JSONObject author = articleUtils.getAuthor(article);
        final String authorName = author.getString(User.USER_NAME);
        article.put(Common.AUTHOR_NAME, authorName);
        final String authorId = author.getString(Keys.OBJECT_ID);
        article.put(Common.AUTHOR_ID, authorId);
        article.put(Common.AUTHOR_ROLE, author.getString(User.USER_ROLE));

        final Map<String, Object> dataModel = renderer.getDataModel();

        prepareShowArticle(preference, dataModel, article);

        dataModel.put(Keys.PAGE_TYPE, PageTypes.ARTICLE);

        filler.fillBlogHeader(request, dataModel, preference);
        filler.fillBlogFooter(dataModel, preference);
        filler.fillSide(request, dataModel, preference);
        Skins.fillSkinLangs(preference.optString(Preference.LOCALE_STRING),
                (String) request.getAttribute(Keys.TEMAPLTE_DIR_NAME), dataModel);
    } catch (final Exception e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);

        try {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        } catch (final IOException ex) {
            LOGGER.severe(ex.getMessage());
        }
    }
}

From source file:com.ibm.jaggr.core.impl.layer.LayerImpl.java

/**
 * Unfolds a folded module list and returns a list of Source objects
 *
 * @param request The request//ww w  .  j a  v a 2  s. co m
 * @return A list of Source objects
 * @throws IOException
 */
protected ModuleList getModules(HttpServletRequest request) throws IOException {
    final String sourceMethod = "getModules"; //$NON-NLS-1$
    final boolean isTraceLogging = log.isLoggable(Level.FINER);
    if (isTraceLogging) {
        log.entering(sourceMethod, sourceMethod, new Object[] { request });
    }
    ModuleList result = (ModuleList) request.getAttribute(MODULE_FILES_PROPNAME);
    if (result == null) {
        IAggregator aggr = (IAggregator) request.getAttribute(IAggregator.AGGREGATOR_REQATTRNAME);
        IRequestedModuleNames requestedModuleNames = (IRequestedModuleNames) request
                .getAttribute(IHttpTransport.REQUESTEDMODULENAMES_REQATTRNAME);

        result = new ModuleList();
        if (requestedModuleNames != null) {
            Features features = (Features) request.getAttribute(IHttpTransport.FEATUREMAP_REQATTRNAME);
            Set<String> dependentFeatures = new HashSet<String>();
            List<String> names = requestedModuleNames.getModules();
            if (!names.isEmpty()) {
                for (String name : names) {
                    if (name != null) {
                        name = aggr.getConfig().resolve(name, features, dependentFeatures, null, false, // Don't resolve aliases when locating modules requested by the loader
                                //  because the loader should have already done alias resolution and
                                //  we can't rename a requested module.
                                false // Loader doesn't request modules with has! plugin
                        );
                        result.add(new ModuleList.ModuleListEntry(newModule(request, name),
                                ModuleSpecifier.MODULES));
                    }
                }
            } else {
                boolean includeRequireDeps = RequestUtil.isIncludeRequireDeps(request);
                names = requestedModuleNames.getScripts();
                for (String name : names) {
                    if (name != null) {
                        name = aggr.getConfig().resolve(name, features, dependentFeatures, null, false, // Don't resolve aliases when locating modules requested by the loader
                                //  because the loader should have already done alias resolution and
                                //  we can't rename a requested module.
                                true // Resolve has! loader plugin
                        );
                        result.add(new ModuleList.ModuleListEntry(newModule(request, name),
                                ModuleSpecifier.SCRIPTS));
                    }
                }
                // See if we need to add required modules.
                DependencyList requiredList = null, preloadList = null, excludeList = null;
                ModuleDeps combined = new ModuleDeps(), explicit = new ModuleDeps();
                if (!requestedModuleNames.getDeps().isEmpty()) {

                    // If there's a required module, then add it and its dependencies
                    // to the module list.
                    requiredList = new DependencyList(DEPSOURCE_REQDEPS, requestedModuleNames.getDeps(), aggr,
                            features, true, // resolveAliases
                            RequestUtil.isRequireExpLogging(request), // include details
                            includeRequireDeps);
                    dependentFeatures.addAll(requiredList.getDependentFeatures());

                    result.setRequiredModules(requiredList.getExplicitDeps().getModuleIds());

                    explicit.addAll(requiredList.getExplicitDeps());
                    combined.addAll(requiredList.getExplicitDeps());
                    combined.addAll(requiredList.getExpandedDeps());
                }
                if (!requestedModuleNames.getPreloads().isEmpty()) {
                    preloadList = new DependencyList(DEPSOURCE_REQPRELOADS, requestedModuleNames.getPreloads(),
                            aggr, features, true, // resolveAliases
                            RequestUtil.isRequireExpLogging(request), // include details
                            includeRequireDeps);
                    dependentFeatures.addAll(preloadList.getDependentFeatures());

                    explicit.addAll(preloadList.getExplicitDeps());
                    combined.addAll(preloadList.getExplicitDeps());
                    combined.addAll(preloadList.getExpandedDeps());
                }
                if (!requestedModuleNames.getExcludes().isEmpty()) {
                    excludeList = new DependencyList(DEPSOURCE_EXCLUDES, requestedModuleNames.getExcludes(),
                            aggr, features, true, // resolveAliases
                            RequestUtil.isRequireExpLogging(request), // include details
                            false);
                    dependentFeatures.addAll(excludeList.getDependentFeatures());
                    combined.subtractAll(excludeList.getExplicitDeps());
                    combined.subtractAll(excludeList.getExpandedDeps());
                }
                boolean isAssertNoNLS = RequestUtil.isAssertNoNLS(request);
                for (Map.Entry<String, ModuleDepInfo> entry : combined.entrySet()) {
                    String name = entry.getKey();
                    if (isAssertNoNLS && nlsPat.matcher(name).find()) {
                        throw new BadRequestException("AssertNoNLS: " + name); //$NON-NLS-1$
                    }
                    ModuleDepInfo info = entry.getValue();
                    if (aggr.getTransport().isServerExpandable(request, name)) {
                        int idx = name.indexOf("!"); //$NON-NLS-1$
                        if (idx != -1) {
                            // convert name to a delegate plugin if necessary
                            String plugin = name.substring(0, idx);
                            if (aggr.getConfig().getTextPluginDelegators().contains(plugin)) {
                                name = aggr.getTransport().getAggregatorTextPluginName() + name.substring(idx);
                            } else if (aggr.getConfig().getJsPluginDelegators().contains(plugin)) {
                                name = name.substring(idx + 1);
                            }
                        }
                        Collection<String> prefixes = info.getHasPluginPrefixes();
                        if (prefixes == null || // condition is TRUE
                                RequestUtil.isIncludeUndefinedFeatureDeps(request) && !prefixes.isEmpty()) {
                            IModule module = newModule(request, name);
                            if (!explicit.containsKey(name) && aggr
                                    .getResourceFactory(new MutableObject<URI>(module.getURI())) == null) {
                                // Module is server-expanded and it's not a server resource type that we
                                // know how handle, so just ignore it.
                                if (isTraceLogging) {
                                    log.logp(Level.FINER, sourceClass, sourceMethod,
                                            "Ignoring module " + name + " due to no resource factory found."); //$NON-NLS-1$ //$NON-NLS-2$
                                }
                                continue;
                            }
                            result.add(new ModuleList.ModuleListEntry(module, ModuleSpecifier.LAYER,
                                    !explicit.containsKey(name)));
                        }
                    }
                }
                if ((requiredList != null || preloadList != null) && RequestUtil.isRequireExpLogging(request)) {
                    ModuleDeps expanded = new ModuleDeps();
                    if (requiredList != null) {
                        expanded.addAll(requiredList.getExpandedDeps());
                    }
                    if (preloadList != null) {
                        expanded.addAll(preloadList.getExpandedDeps());
                    }
                    if (excludeList != null) {
                        explicit.subtractAll(excludeList.getExplicitDeps());
                        explicit.subtractAll(excludeList.getExpandedDeps());
                        expanded.subtractAll(excludeList.getExplicitDeps());
                        expanded.subtractAll(excludeList.getExpandedDeps());
                    }
                    request.setAttribute(BOOTLAYERDEPS_PROPNAME,
                            new DependencyList(explicit, expanded, dependentFeatures));
                }
                result.setDependenentFeatures(dependentFeatures);
            }
        }
        if (result.isEmpty()) {
            throw new BadRequestException(request.getQueryString());
        }
        request.setAttribute(MODULE_FILES_PROPNAME, result);
    }
    if (isTraceLogging) {
        log.exiting(sourceClass, sourceMethod, result);
    }
    return result;
}

From source file:com.newrelic.agent.transport.DataSenderImpl.java

private Object invoke(String method, String encoding, String uri, JSONStreamAware params,
        int timeoutInMillis)/* 590:    */ throws Exception
/* 591:    */ {/*from  ww  w  . j av  a  2  s. com*/
    /* 592:554 */ ReadResult readResult = send(method, encoding, uri, params, timeoutInMillis);
    /* 593:555 */ Map<?, ?> responseMap = null;
    /* 594:556 */ String responseBody = readResult.getResponseBody();
    /* 595:558 */ if (responseBody != null)
    /* 596:    */ {
        /* 597:559 */ Exception ex = null;
        /* 598:    */ try
        /* 599:    */ {
            /* 600:561 */ responseMap = getResponseMap(responseBody);
            /* 601:562 */ ex = parseException(responseMap);
            /* 602:    */ }
        /* 603:    */ catch (Exception e)
        /* 604:    */ {
            /* 605:565 */ Agent.LOG.log(Level.WARNING, "Error parsing response JSON({0}) from NewRelic: {1}",
                    new Object[] { method, e.toString() });
            /* 606:    */
            /* 607:567 */ Agent.LOG.log(Level.FINEST, "Invalid response JSON({0}): {1}",
                    new Object[] { method, responseBody });
            /* 608:    */
            /* 609:569 */ throw e;
            /* 610:    */ }
        /* 611:571 */ if (ex != null) {
            /* 612:572 */ throw ex;
            /* 613:    */ }
        /* 614:    */ }
    /* 615:    */ else
    /* 616:    */ {
        /* 617:576 */ Agent.LOG.log(Level.FINER, "Response was null ({0})", new Object[] { method });
        /* 618:    */ }
    /* 619:579 */ if (responseMap != null) {
        /* 620:580 */ return responseMap.get("return_value");
        /* 621:    */ }
    /* 622:582 */ return null;
    /* 623:    */ }

From source file:org.cloudifysource.esc.driver.provisioning.privateEc2.PrivateEC2CloudifyDriver.java

private Instance waitRunningInstance(final Instance ec2instance, final long duration, final TimeUnit unit)
        throws CloudProvisioningException, TimeoutException {

    final long endTime = System.currentTimeMillis() + unit.toMillis(duration);

    while (System.currentTimeMillis() < endTime) {
        // Sleep before requesting the instance description
        // because we can get a AWS Error Code: InvalidInstanceID.NotFound if the request is too early.
        this.sleep();

        final DescribeInstancesRequest describeRequest = new DescribeInstancesRequest();
        describeRequest.setInstanceIds(Arrays.asList(ec2instance.getInstanceId()));
        final DescribeInstancesResult describeInstances = this.ec2.describeInstances(describeRequest);

        for (final Reservation resa : describeInstances.getReservations()) {
            for (final Instance instance : resa.getInstances()) {
                final InstanceStateType state = InstanceStateType.valueOf(instance.getState().getCode());
                if (logger.isLoggable(Level.FINER)) {
                    logger.finer("instance= " + instance.getInstanceId() + " state=" + state);
                }/*from w ww  . j av  a 2  s.  c om*/
                switch (state) {
                case PENDING:
                    break;
                case RUNNING:
                    logger.fine("running okay...");
                    return instance;
                case STOPPING:
                case SHUTTING_DOWN:
                case TERMINATED:
                case STOPPED:
                default:
                    throw new CloudProvisioningException("Failed to allocate server - Cloud reported node in "
                            + state.getName() + " state. Node details: " + ec2instance);

                }
            }
        }
    }

    throw new TimeoutException("Node failed to reach RUNNING mode in time");
}

From source file:org.aselect.server.request.handler.aselect.authentication.ApplicationBrowserHandler.java

/**
 * Handles the <code>request=org_choice</code> request. <br>
 * <br>/*  w w  w  .java  2s.  co  m*/
 * <b>Description:</b> <br>
 * Store the user's organization choice in the TGT and redirect the user
 * to the application he desires.
 * TGT has already been issued, Rid is still present (contains the application url)
 * 
 * @param htServiceRequest
 *            HashMap containing request parameters
 * @param servletResponse
 *            Used to send (HTTP) information back to user
 * @param pwOut
 *            Used to write information back to the user (HTML)
 * @throws ASelectException
 *             the a select exception
 */
private void handleOnBehalfOf(HashMap htServiceRequest, HttpServletResponse servletResponse, PrintWriter pwOut)
        throws ASelectException {
    String sMethod = "handleOnBehalfOf";

    //      String sRid = (String)htServiceRequest.get("rid");   // we are logged in, old rid has gone
    String sOBOId = (String) htServiceRequest.get("obouid");
    String sTgt = (String) htServiceRequest.get("aselect_credentials_tgt");
    String sStep = (String) htServiceRequest.get("step");
    String sOBOyn = (String) htServiceRequest.get("oboyn");
    String sAppUrl = (String) _htTGTContext.get("obo_app_url"); // session already deleted, we need the app_url
    String sAppId = (String) _htTGTContext.get("app_id");

    String sUid = (String) _htTGTContext.get("uid");
    Integer iOboRetries = (Integer) _htTGTContext.get("obo_retries");

    if (sStep == null) {
        _systemLogger.log(Level.WARNING, _sModule, sMethod, "Missing some request parameter");
        throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
    }
    if (!Utils.hasValue(sAppId) || !ApplicationManager.getHandle().getApplication(sAppId).isOBOEnabled()) {
        _systemLogger.log(Level.WARNING, _sModule, sMethod,
                "On Behalf Of not enabled for application: " + sAppId);
        throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
    }

    HashMap oboParms = ApplicationManager.getHandle().getApplication(sAppId).getOBOParameters();
    int obo_maxRetries = OBO_MAXTRIES;
    try {
        obo_maxRetries = Integer.parseInt((String) oboParms.get("maxtries"));
    } catch (NumberFormatException nfe) {
        _systemLogger.log(Level.WARNING, _sModule, sMethod, "Invalid parameter maxtries: "
                + oboParms.get("maxtries") + ", using default:" + obo_maxRetries);
    }

    _systemLogger.log(Level.FINER, _sModule, sMethod,
            "obouid=" + sOBOId + ", step=" + sStep + ", oboyn=" + sOBOyn + ", obo_retries=" + iOboRetries);
    if (iOboRetries == null) {
        iOboRetries = 0;
    }
    int iStep = Integer.parseInt(sStep);

    switch (iStep) {
    case 0:
        if ("y".equalsIgnoreCase(sOBOyn)) {
            try {
                String sSelectForm;
                sSelectForm = org.aselect.server.utils.Utils.presentOnBehalfOf(_servletRequest, _configManager,
                        htServiceRequest, null, (String) _htTGTContext.get("language"),
                        1 /* step 1, present obo request */);

                Tools.pauseSensorData(_configManager, _systemLogger, _htSessionContext);

                pwOut.println(sSelectForm);
            } catch (IOException e) {
                _systemLogger.log(Level.WARNING, _sModule, sMethod, "Cannot present OnBehalfOf form");
                throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
            }
            return;
        } else { // no obo requested
            _systemLogger.log(Level.FINEST, _sModule, sMethod, "No obo requested by user");
        }

        break;
    case 1:
    case 2:
        // test obo_id here 11-proef, also prevents XSS on obo
        // allow for re-entering obo from user
        iOboRetries++;
        if (iOboRetries > obo_maxRetries) {
            _systemLogger.log(Level.WARNING, _sModule, sMethod,
                    "Maximum nuber of retries reached for on behalf of");
            // maybe be more user friendly here, prsent some other form
            throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
        }
        boolean oboK = false;
        String status = null; // Permit  Deny / Inderterminate / Invalid
        if (org.aselect.system.utils.Utils.bsnCheck(sOBOId)) {

            String sIssuer = (String) htServiceRequest.get("a-select-server");
            if (oboParms.get("issuer") != null) {
                sIssuer = (String) oboParms.get("issuer"); // overrule issuer
            }

            String prefix = "";
            if (oboParms.get("prefix") != null) {
                prefix = (String) oboParms.get("prefix");
            }

            if (oboParms.get("identificatieCodeGemachtigde") != null) { // FOR TESTING 
                sUid = (String) oboParms.get("identificatieCodeGemachtigde"); // only for wsserver request, does not update tgt
            }

            String sSubjectPrefix = "";
            if (oboParms.get("subjectprefix") != null) {
                sSubjectPrefix = (String) oboParms.get("subjectprefix");
            }

            String sSubject = sSubjectPrefix + sUid;
            String identificatieCodeVertegenwoordigde = prefix + sOBOId;
            String identificatieSoortVertegenwoordigde = (String) oboParms
                    .get("identificatieSoortVertegenwoordigde");
            String identificatieCodeGemachtigde = prefix + sUid;
            String identificatieSoortGemachtigde = (String) oboParms.get("identificatieSoortGemachtigde");
            String identificatieCodeDienst = (String) oboParms.get("identificatieCodeDienst");
            String identificatieCodeDienstAanbieder = (String) oboParms.get("identificatieCodeDienstAanbieder");

            HashMap<String, String> parms = new HashMap<String, String>();
            // No attributes to add for assertion (yet)

            Assertion assertion = HandlerTools.createAuthnStatementAttributeStatementAssertion(parms, sIssuer,
                    sSubject, true); //

            // Marshall to the Node
            MarshallerFactory factory = org.opensaml.xml.Configuration.getMarshallerFactory();
            Marshaller marshaller = factory.getMarshaller(assertion);

            Node node = null;
            try {
                node = marshaller.marshall(assertion);
            } catch (MarshallingException e) {
                _systemLogger.log(Level.SEVERE, MODULE, sMethod, e.getMessage(), e);
                _systemLogger.log(Level.WARNING, MODULE, sMethod, "Could not marshall assertion", e);
                throw new ASelectException(Errors.ERROR_ASELECT_INIT_ERROR, e);
            }
            _systemLogger.log(Level.INFO, MODULE, sMethod, "Marshalling done");
            String sAssertion = XMLHelper.nodeToString(node);

            _systemLogger.log(Level.INFO, MODULE, sMethod, "sAssertion: " + sAssertion);

            IClientCommunicator _communicator;

            _communicator = new JSONCommunicator(_systemLogger);
            _systemLogger.log(Level.FINEST, MODULE, sMethod, "communicator= 'json' loaded");

            String sURL = (String) oboParms.get("wsserverurl");

            HashMap jsonrequest = new HashMap();
            HashMap htRequestpairs = new HashMap();
            try {
                //               sAssertion = Base64.encodeBytes(sAssertion.getBytes("UTF-8"));   // gives newlines, not accepted by json on receiver
                sAssertion = Base64.encodeBytes(sAssertion.getBytes("UTF-8"), Base64.DONT_BREAK_LINES); // violates strict Base64 specification
                String key_assertion = "assertion";
                htRequestpairs.put(key_assertion, URLEncoder.encode(sAssertion, "UTF-8"));
                String key_identificatiecodevertegenwoordigde = "identificatiecodevertegenwoordigde";
                htRequestpairs.put(key_identificatiecodevertegenwoordigde,
                        URLEncoder.encode(identificatieCodeVertegenwoordigde, "UTF-8"));
                String key_identificatiesoortvertegenwoordigde = "identificatiesoortvertegenwoordigde";
                htRequestpairs.put(key_identificatiesoortvertegenwoordigde,
                        URLEncoder.encode(identificatieSoortVertegenwoordigde, "UTF-8"));
                String key_identificatiecodegemachtigde = "identificatiecodegemachtigde";
                htRequestpairs.put(key_identificatiecodegemachtigde,
                        URLEncoder.encode(identificatieCodeGemachtigde, "UTF-8"));
                String key_identificatiesoortgemachtigde = "identificatiesoortgemachtigde";
                htRequestpairs.put(key_identificatiesoortgemachtigde,
                        URLEncoder.encode(identificatieSoortGemachtigde, "UTF-8"));
                String key_identificatiecodedienst = "identificatiecodedienst";
                htRequestpairs.put(key_identificatiecodedienst,
                        URLEncoder.encode(identificatieCodeDienst, "UTF-8"));
                String key_identificatiecodedienstaanbieder = "identificatiecodedienstaanbieder";
                htRequestpairs.put(key_identificatiecodedienstaanbieder,
                        URLEncoder.encode(identificatieCodeDienstAanbieder, "UTF-8"));

                String key_issuer = "issuer";
                htRequestpairs.put(key_issuer, URLEncoder.encode(sIssuer, "UTF-8"));
                String key_subjectprefix = "subjectprefix";
                htRequestpairs.put(key_subjectprefix, URLEncoder.encode(sSubjectPrefix, "UTF-8"));

            } catch (UnsupportedEncodingException e) {
                _systemLogger.log(Level.SEVERE, _sModule, sMethod,
                        "Could not find or encode parameters for: " + sURL);
                throw new ASelectException(Errors.ERROR_ASELECT_INIT_ERROR, e);
            }

            String jsonkey = "jsoninput";
            jsonrequest.put("request", (String) oboParms.get("wsserverrequest"));
            jsonrequest.put(jsonkey, htRequestpairs);
            //            // set Configuration parameters
            _systemLogger.log(Level.FINEST, MODULE, sMethod, "jsonrequest:" + jsonrequest);

            // send message
            HashMap jsonResponse = new HashMap();

            try {
                jsonResponse = _communicator.sendMessage(jsonrequest, sURL);
                _systemLogger.log(Level.FINEST, MODULE, sMethod, "jsonResponse:" + jsonResponse);
                status = (String) jsonResponse.get((String) oboParms.get("wsserverresponse"));
                // status can be null if request failed with error
            } catch (ASelectCommunicationException cex) {
                status = "Deny";
            }

            _systemLogger.log(Level.FINER, MODULE, sMethod, "MachtigenClient returned status: " + status);

        } else {
            _systemLogger.log(Level.FINER, MODULE, sMethod, "BSN check failed");
            status = "Deny";
        }
        oboK = "Permit".equalsIgnoreCase(status);
        if (oboK) {
            _systemLogger.log(Level.FINEST, _sModule, sMethod, "Valide obo requested by user");
            _htTGTContext.put("obouid", sOBOId);
            _htTGTContext.remove("obo_retries");
            _htTGTContext.remove("obo_app_url");
            _tgtManager.updateTGT(sTgt, _htTGTContext);

            ASelectEntrustmentLogger.getHandle().log((String) _htTGTContext.get("uid"),
                    (String) _htTGTContext.get("client_ip"), (String) _htTGTContext.get("app_id"), sOBOId,
                    status);
        } else { // not a bsn or invalid obo
            _systemLogger.log(Level.INFO, _sModule, sMethod, "Invalid bsn for obo, status: " + status);
            ASelectEntrustmentLogger.getHandle().log((String) _htTGTContext.get("uid"),
                    (String) _htTGTContext.get("client_ip"), (String) _htTGTContext.get("app_id"), sOBOId,
                    status);
            _systemLogger.log(Level.FINEST, _sModule, sMethod, "Retrying, retry number:" + iOboRetries);
            _htTGTContext.put("obo_retries", iOboRetries);
            // store oriuid, OBOServiceId, OBOValidFrom in tgt
            _tgtManager.updateTGT(sTgt, _htTGTContext);

            // allow for re-entering obo from user
            try {
                String sSelectForm;
                sSelectForm = org.aselect.server.utils.Utils.presentOnBehalfOf(_servletRequest, _configManager,
                        htServiceRequest, null, (String) _htTGTContext.get("language"),
                        2 /* step 2, retry obo */);

                Tools.pauseSensorData(_configManager, _systemLogger, _htSessionContext);

                pwOut.println(sSelectForm);
            } catch (IOException e) {
                _systemLogger.log(Level.WARNING, _sModule, sMethod, "Cannot present OnBehalfOf form");
                throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
            }
            return;
        }
        break;
    default:
        _systemLogger.log(Level.WARNING, _sModule, sMethod, "Invalid step parameter received");
        throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
    }

    if (_htTGTContext == null) {
        _systemLogger.log(Level.WARNING, _sModule, sMethod, "Cannot get TGT");
        throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
    }

    // The tgt was just issued and updated, report sensor data
    Tools.calculateAndReportSensorData(_configManager, _systemLogger, "srv_sbh", null, _htSessionContext, sTgt,
            true);
    _systemLogger.log(Level.INFO, _sModule, sMethod, "REDIRECT to " + sAppUrl);

    _sessionManager.setDeleteSession(_htSessionContext, _systemLogger); // 20120401, Bauke: postpone session action

    TGTIssuer oTGTIssuer = new TGTIssuer(_sMyServerId);
    String sLang = (String) _htTGTContext.get("language");
    oTGTIssuer.sendTgtRedirect(sAppUrl, sTgt, null, servletResponse, sLang);
}