Java Code Examples for org.apache.brooklyn.util.text.Strings#toString()

The following examples show how to use org.apache.brooklyn.util.text.Strings#toString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SummaryComparators.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Nonnull
static String getDisplayNameOrName(HasName o1) {
    String n1 = null;
    if (o1 instanceof BrooklynObject)
        n1 = ((BrooklynObject)o1).getDisplayName();
    if (Strings.isEmpty(n1) && o1 instanceof HasConfig && ((HasConfig)o1).getConfig()!=null)
        n1 = Strings.toString(((HasConfig)o1).getConfig().get("displayName"));
    // prefer display name if set
    if (Strings.isEmpty(n1))
        n1 = o1.getName();
    if (n1==null) {
        // put last
        return "~~~";
    }
    return n1;
}
 
Example 2
Source File: LocationConfigUtils.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
public static Map<ConfigKey<String>,String> finalAndOriginalSpecs(String finalSpec, Object ...sourcesForOriginalSpec) {
    // yuck!: TODO should clean up how these things get passed around
    Map<ConfigKey<String>,String> result = MutableMap.of();
    if (finalSpec!=null) 
        result.put(LocationInternal.FINAL_SPEC, finalSpec);
    
    String originalSpec = null;
    for (Object source: sourcesForOriginalSpec) {
        if (source instanceof CharSequence) originalSpec = source.toString();
        else if (source instanceof Map) {
            if (originalSpec==null) originalSpec = Strings.toString( ((Map<?,?>)source).get(LocationInternal.ORIGINAL_SPEC) );
            if (originalSpec==null) originalSpec = Strings.toString( ((Map<?,?>)source).get(LocationInternal.ORIGINAL_SPEC.getName()) );
        }
        if (originalSpec!=null) break; 
    }
    if (originalSpec==null) originalSpec = finalSpec;
    if (originalSpec!=null)
        result.put(LocationInternal.ORIGINAL_SPEC, originalSpec);
    
    return result;
}
 
Example 3
Source File: TemplateProcessor.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public TemplateModel get(String key) {
    if (map==null) return null;
    try {
        if (map.containsKey(key)) 
            return wrapAsTemplateModel( map.get(key) );
        
        Map<String,Object> result = MutableMap.of();
        for (Map.Entry<?,?> entry: map.entrySet()) {
            String k = Strings.toString(entry.getKey());
            if (k.startsWith(key+".")) {
                String k2 = Strings.removeFromStart(k, key+".");
                result.put(k2, entry.getValue());
            }
        }
        if (!result.isEmpty()) 
                return wrapAsTemplateModel( result );
        
    } catch (Exception e) {
        Exceptions.propagateIfFatal(e);
        throw new IllegalStateException("Error accessing config '"+key+"'"+": "+e, e);
    }
    
    return null;
}
 
Example 4
Source File: SensorResource.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void setFromMap(String application, String entityToken, Map newValues) {
    final Entity entity = brooklyn().getEntity(application, entityToken);
    if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.MODIFY_ENTITY, entity)) {
        throw WebResourceUtils.forbidden("User '%s' is not authorized to modify entity '%s'",
            Entitlements.getEntitlementContext().user(), entity);
    }

    if (log.isDebugEnabled())
        log.debug("REST user "+Entitlements.getEntitlementContext()+" setting sensors "+newValues);
    for (Object entry: newValues.entrySet()) {
        String sensorName = Strings.toString(((Map.Entry)entry).getKey());
        Object newValue = ((Map.Entry)entry).getValue();
        
        AttributeSensor sensor = findSensor(entity, sensorName);
        entity.sensors().set(sensor, newValue);
    }
}
 
Example 5
Source File: BrooklynNodeUpgradeEffectorBody.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Beta
static boolean isPersistenceModeEnabled(Entity entity) {
    // TODO when there are PERSIST* options in BrooklynNode, look at them here!
    // or, even better, make a REST call to check persistence
    String params = null;
    if (entity instanceof BrooklynCluster) {
        EntitySpec<?> spec = entity.getConfig(BrooklynCluster.MEMBER_SPEC);
        params = Strings.toString( spec.getConfig().get(BrooklynNode.EXTRA_LAUNCH_PARAMETERS) );
    }
    if (params==null) params = entity.getConfig(BrooklynNode.EXTRA_LAUNCH_PARAMETERS);
    if (params==null) return false;
    if (params.indexOf("persist")==0) return false;
    return true;
}
 
Example 6
Source File: ConfigKeys.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public static ConfigKey<?> newInstance(ConfigBag keyDefs) {
    String typeName = Strings.toString(keyDefs.getStringKey("type"));
    if (Strings.isNonBlank(typeName)) {
        // TODO dynamic typing - see TYPE key commented out above; also see AddSensor.getType for type lookup
        log.warn("Setting 'type' is not currently supported for dynamic config keys; ignoring in definition of "+keyDefs);
    }
    
    Class<Object> type = Object.class;
    String name = keyDefs.get(NAME);
    String description = keyDefs.get(DESCRIPTION);
    Object defaultValue = keyDefs.get(DEFAULT_VALUE);
    return newConfigKey(type, name, description, defaultValue);
}
 
Example 7
Source File: BrooklynWebServer.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private void initSecurity(WebAppContext context) {
    if (skipSecurity) {
        // Could add <security-constraint> in an override web.xml here
        // instead of relying on the war having it (useful for downstream).
        // context.addOverrideDescriptor("override-web.xml");
        // But then should do the same in OSGi. For now require the web.xml
        // to have security pre-configured and ignore it if noConsoleSecurity used.
        //
        // Ignore security config in web.xml.
        context.setSecurityHandler(new NopSecurityHandler());
        
        // Above probably not used any more. Handled by the BrooklynSecurityProviderFilter* classes
        String provider = Strings.toString( ((ManagementContextInternal)managementContext).getBrooklynProperties().getConfigRaw(BrooklynWebConfig.SECURITY_PROVIDER_CLASSNAME).orNull() );
        if (provider==null) {
            ((ManagementContextInternal)managementContext).getBrooklynProperties().put(BrooklynWebConfig.SECURITY_PROVIDER_CLASSNAME, 
                AnyoneSecurityProvider.class.getName());
        } else if (AnyoneSecurityProvider.class.getName().equals(provider)) {
            // already set
        } else {
            // mismatch - warn, but continue
            log.warn("Server told to skip security with unexpected security provider: "+provider);
        }
    } else {
        // Cover for downstream projects which don't have the changes.
        context.addOverrideDescriptor(getClass().getResource("/web-security.xml").toExternalForm());
    }
}
 
Example 8
Source File: EntitlementContextFilter.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    String userName = null;

    // first see if there is a principal
    SecurityContext securityContext = requestContext.getSecurityContext();
    Principal user = securityContext.getUserPrincipal();
    if (user!=null) {
        userName = user.getName();
    } else {

        // now look in session attribute - because principals hard to set from javax filter
        if (request!=null) {
            MultiSessionAttributeAdapter s = MultiSessionAttributeAdapter.of(request, false);
            if (s!=null) {
                userName = Strings.toString(s.getAttribute(
                        BrooklynSecurityProviderFilterHelper.AUTHENTICATED_USER_SESSION_ATTRIBUTE));
            }
        }
    }

    if (userName != null) {
        EntitlementContext oldEntitlement = Entitlements.getEntitlementContext();
        if (oldEntitlement!=null && !userName.equals(oldEntitlement.user())) {
            throw new IllegalStateException("Illegal entitement context switch, from user "+oldEntitlement.user()+" to "+userName);
        }

        String uri = request.getRequestURI();
        String remoteAddr = request.getRemoteAddr();

        String uid = RequestTaggingRsFilter.getTag();
        WebEntitlementContext entitlementContext = new WebEntitlementContext(userName, remoteAddr, uri, uid);
        Entitlements.setEntitlementContext(entitlementContext);
    }
}
 
Example 9
Source File: TemplateProcessor.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public boolean contains(String key) {
    if (map==null) return false;
    if (map.containsKey(key)) return true;
    for (Map.Entry<?,?> entry: map.entrySet()) {
        String k = Strings.toString(entry.getKey());
        if (k.startsWith(key+".")) {
            // contains this prefix
            return true;
        }
    }
    return false;
}
 
Example 10
Source File: BrooklynServerPaths.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
protected String getDefaultPathFromConfig() {
    Maybe<Object> result = brooklynProperties.getConfigLocalRaw(BrooklynServerConfig.PERSISTENCE_BACKUPS_DIR);
    if (result.isPresent()) return Strings.toString(result.get());
    if (isBackupSameLocation()) {
        return backupContainerFor(brooklynProperties.getConfig(BrooklynServerConfig.PERSISTENCE_DIR));
    }
    return null;
}
 
Example 11
Source File: ElectPrimaryPolicy.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public void rescanImpl() throws InterruptedException {
    String contextString;
    synchronized (rescanTriggers) {
        while (rescanInProgress) {
            Tasks.setBlockingDetails("Waiting for ongoing scan to complete");
            rescanTriggers.wait();
            Tasks.resetBlockingDetails();
        }
        if (rescanTriggers.isEmpty()) {
            if (log.isTraceEnabled()) {
                log.trace("Policy "+this+" scheduled rescan unnecessary, trigger already handled");
            }
            return;
        }
        contextString = Strings.join(rescanTriggers, ", ");
        rescanTriggers.clear();
        rescanInProgress = true;
    }
    String code = null;
    try {
        String effName = config().get(EFFECTOR_NAME);
        if (log.isTraceEnabled()) {
            log.trace("Policy "+this+" got event: "+contextString+"; triggering rescan with "+effName);
        }
        Task<?> task = Effectors.invocation(entity, Preconditions.checkNotNull( ((EntityInternal)entity).getEffector(effName) ), config().getBag()).asTask();
        BrooklynTaskTags.addTagDynamically(task, BrooklynTaskTags.NON_TRANSIENT_TASK_TAG);
        
        highlight("lastScan", "Running "+effName+" on "+contextString, task);
        
        Object result = DynamicTasks.get(task);
        if (result instanceof Map) code = Strings.toString( ((Map<?,?>)result).get("code") );
        
        if (ElectPrimaryEffector.ResultCode.NEW_PRIMARY_ELECTED.name().equalsIgnoreCase(code)) {
            highlightAction("New primary elected: "+((Map<?,?>)result).get("primary"), null);
        }
        if (ElectPrimaryEffector.ResultCode.NO_PRIMARY_AVAILABLE.name().equalsIgnoreCase(code)) {
            highlightViolation("No primary available");
        }
    } catch (Throwable e) {
        Exceptions.propagateIfFatal(e);
        if (Entities.isNoLongerManaged(entity)) throw Exceptions.propagate(e);
        
        Throwable root = Throwables.getRootCause(e);
        if (root instanceof UserFacingException) {
            // prefer user-facing root cause to history; mainly for SelectionModeStrictFailed.
            // possibly not right if it's another (eg exposition on why promote failed)
            e = root;
        }
        if (e instanceof UserFacingException) {
            log.warn("Error running policy "+this+" on "+entity+": "+Exceptions.collapseText(e));
        } else {
            log.warn("Error running policy "+this+" on "+entity+": "+Exceptions.collapseText(e), e);
        }
    }
    
    synchronized (rescanTriggers) {
        rescanTriggers.notifyAll();
        rescanInProgress = false;
    }
}
 
Example 12
Source File: EntityConfigResource.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Override
public String getPlain(String application, String entityToken, String configKeyName, Boolean raw) {
    return Strings.toString(get(false, application, entityToken, configKeyName, raw));
}
 
Example 13
Source File: CouchbaseNodeSshDriver.java    From brooklyn-library with Apache License 2.0 4 votes vote down vote up
protected DownloadLinkSegmentComputer newDownloadLinkSegmentComputer() {
    return new DownloadLinkSegmentComputer(getLocation().getOsDetails(), !isPreV3(), Strings.toString(getEntity()));
}
 
Example 14
Source File: ResourceUtils.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public ResourceUtils(Object contextObject) {
    this(contextObject, Strings.toString(contextObject));
}
 
Example 15
Source File: RedisClusterViaRestIntegrationTest.java    From brooklyn-library with Apache License 2.0 4 votes vote down vote up
/** REST seems to show up a different behaviour in context entity used when adding children entities,
 * causing different config to be set, so we test that, using Redis as a comparatively simple example. */
@Test(groups = "Integration")
public void testDeployRedisCluster() throws InterruptedException, ExecutionException, TimeoutException {
    final URI webConsoleUri = URI.create(getBaseUriRest());

    // Test setup
    final EntitySpec<BrooklynNode> spec = EntitySpec.create(BrooklynNode.class);
    final ManagementContext mgmt = getManagementContextFromJettyServerAttributes(server);
    final BrooklynNode node = mgmt.getEntityManager().createEntity(spec);
    node.sensors().set(BrooklynNode.WEB_CONSOLE_URI, webConsoleUri);

    // Deploy it.
    final String blueprint = "location: localhost\n" +
            "services:\n" +
            "- type: org.apache.brooklyn.entity.nosql.redis.RedisCluster";
    HttpToolResponse response = node.http().post(
            "/applications",
            ImmutableMap.of("Content-Type", "text/yaml"),
            blueprint.getBytes());
    HttpAsserts.assertHealthyStatusCode(response.getResponseCode());

    // Assert application is eventually running and not on fire.
    final Entity entity = mgmt.getApplications().iterator().next().getChildren().iterator().next();
    assertTrue(entity instanceof RedisCluster,
            "expected " + RedisCluster.class.getName() + ", found: " + entity);
    RedisCluster cluster = RedisCluster.class.cast(entity);
    Entities.dumpInfo(cluster);
    assertDownloadUrl(cluster.getMaster());
    for (Entity slave : cluster.getSlaves().getMembers()) {
        assertDownloadUrl(slave);
    }

    @SuppressWarnings("unchecked")
    String taskId = Strings.toString( ((Map<String,Object>) Yamls.parseAll(response.getContentAsString()).iterator().next()).get("id") );
    Task<?> task = mgmt.getExecutionManager().getTask(taskId);
    Assert.assertNotNull(task);
    
    task.get(Duration.minutes(20));
    
    Entities.dumpInfo(cluster);
    
    EntityAsserts.assertAttributeEquals(entity, SoftwareProcess.SERVICE_UP, true);
}
 
Example 16
Source File: ConstraintSerialization.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public static PredicateSerializationRuleAdder<String> stringConstructor(Function<String,Predicate<?>> constructor) {
    return new PredicateSerializationRuleAdder<String>(constructor, 
        o -> Strings.toString(Iterables.getOnlyElement(o)), "");
}
 
Example 17
Source File: CatalogItemDtoAbstract.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public void setContainingBundle(VersionedName versionedName) {
    this.containingBundle = Strings.toString(versionedName);
}
 
Example 18
Source File: AbstractSubscriptionManager.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
protected <T> String getSubscriptionDescription(Map<String, Object> flags, Subscription<T> s) {
    return s.subscriptionDescription!=null ? s.subscriptionDescription : flags.containsKey("subscriptionDescription") ? Strings.toString(flags.remove("subscriptionDescription")) : null;
}
 
Example 19
Source File: RegisteredTypes.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Beta
public static RegisteredType setContainingBundle(RegisteredType type, @Nullable ManagedBundle bundle) {
    ((BasicRegisteredType)type).containingBundle =
        bundle==null ? null : Strings.toString(bundle.getVersionedName());
    return type;
}
 
Example 20
Source File: RebindFeedTest.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Override
public String apply(Object input) {
    System.out.println(Strings.maxlen(Strings.toString(input), 80));
    return Strings.toString(input);
}