Java Code Examples for org.apache.brooklyn.util.exceptions.Exceptions#propagateIfFatal()

The following examples show how to use org.apache.brooklyn.util.exceptions.Exceptions#propagateIfFatal() . 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: TemplateProcessor.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public TemplateModel get(String key) throws TemplateModelException {
    try {
        Object result = null;
        
        result = location.getConfig(ConfigKeys.builder(Object.class).name(key).build());
        
        if (result==null && mgmt!=null)
            result = mgmt.getConfig().getConfig(ConfigKeys.builder(Object.class).name(key).build());
        
        if (result!=null)
            return wrapAsTemplateModel( result );
        
    } catch (Exception e) {
        Exceptions.propagateIfFatal(e);
        throw new IllegalStateException("Error accessing config '"+key+"'"
            + (location!=null ? " on "+location : "")+": "+e, e);
    }
    
    return null;
}
 
Example 2
Source File: PersistenceExceptionHandlerImpl.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
protected void onErrorImpl(String errmsg, Exception e, boolean isNew) {
    // TODO the default behaviour is simply to warn; we should have a "fail_at_end" behaviour,
    // and a way for other subsystems to tune in to such failures
    Exceptions.propagateIfFatal(e);
    if (isActive()) {
        if (!isNew) {
            if (LOG.isDebugEnabled()) LOG.debug("Repeating problem: "+errmsg, e);
        } else {
            LOG.warn("Problem persisting (ignoring): "+errmsg, e);
        }
    } else {
        if (!isNew) {
            if (LOG.isTraceEnabled()) LOG.trace("Repeating problem: "+errmsg+"; but no longer active (ignoring)", e);
        } else {
            if (LOG.isDebugEnabled()) LOG.debug("Problem: "+errmsg+"; but no longer active (ignoring)", e);
        }
    }
}
 
Example 3
Source File: CatalogTransformer.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
public static CatalogEnricherSummary catalogEnricherSummary(BrooklynRestResourceUtils b, RegisteredType item, UriBuilder ub) {
    final Set<EnricherConfigSummary> config = Sets.newLinkedHashSet();
    EnricherSpec<?> spec = null;
    try{
        spec = b.getTypeRegistry().createSpec(item, null, EnricherSpec.class);
        AtomicInteger priority = new AtomicInteger();
        for (SpecParameter<?> input: spec.getParameters()) {
            config.add(ConfigTransformer.of(input).uiIncrementAndSetPriorityIfPinned(priority).transformLegacyEnricherConfig());
        }
    }catch (Exception e) {
        Exceptions.propagateIfFatal(e);
        log.trace("Unable to create policy spec for "+item+": "+e, e);
    }
    return new CatalogEnricherSummary(item.getSymbolicName(), item.getVersion(), item.getContainingBundle(), item.getDisplayName(),
            spec!=null ? spec.getType().getName() : item.getSuperTypes().toString(), 
            CatalogItemType.ENRICHER.toString(),
            RegisteredTypes.getImplementationDataStringForSpec(item),
            item.getDescription(), tidyIconLink(b, item, item.getIconUrl(), ub), config,
            item.getTags(), item.isDeprecated(), makeLinks(item, ub));
}
 
Example 4
Source File: CatalogTransformer.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/** @deprecated since 0.12.0 use {@link RegisteredType} methods instead */  @Deprecated
public static CatalogEnricherSummary catalogEnricherSummary(BrooklynRestResourceUtils b, CatalogItem<? extends Enricher,EnricherSpec<?>> item, UriBuilder ub) {
    final Set<EnricherConfigSummary> config = Sets.newLinkedHashSet();
    try{
        final EnricherSpec<?> spec = (EnricherSpec<?>) b.getCatalog().peekSpec(item);
        AtomicInteger priority = new AtomicInteger();
        for (SpecParameter<?> input: spec.getParameters()) {
            config.add(ConfigTransformer.of(input).uiIncrementAndSetPriorityIfPinned(priority).transformLegacyEnricherConfig());
        }
    }catch (Exception e) {
        Exceptions.propagateIfFatal(e);
        log.trace("Unable to create policy spec for "+item+": "+e, e);
    }
    return new CatalogEnricherSummary(item.getSymbolicName(), item.getVersion(), item.getContainingBundle(), item.getDisplayName(),
            item.getJavaType(), item.getCatalogItemType().toString(), item.getPlanYaml(),
            item.getDescription(), tidyIconLink(b, item, item.getIconUrl(), ub), config,
            item.tags().getTags(), item.isDeprecated(), makeLinks(item, ub));
}
 
Example 5
Source File: BundleMaker.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
private boolean addUrlItemRecursively(ZipOutputStream zout, String root, String item, Predicate<? super String> filter) throws IOException {
    InputStream itemFound = null;
    try {
        itemFound = resources.getResourceFromUrl(item);
    } catch (Exception e) {
        Exceptions.propagateIfFatal(e);
        return false;
    }
    try {
        // can't reliably tell if item a file or a folder (listing files), esp w classpath where folder is treated as a list of files, 
        // so if we can't tell try it as a list of files; not guaranteed, and empty dir and a file of size 0 will appear identical, but better than was
        // (mainly used for tests)
        if (isKnownNotToBeADirectoryListing(item) || !addUrlDirToZipRecursively(zout, root, item, itemFound, filter)) {
            addUrlFileToZip(zout, root, item, filter);
        }
        return true;
    } finally {
        Streams.closeQuietly(itemFound);
    }
}
 
Example 6
Source File: SecurityGroupEditor.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/**
 * Add a permission to the security group. This operation is idempotent (will return the group unmodified if the
 * permission already exists on it).
 * @param group The group to update
 * @param permission The new permission
 * @return The updated group with the added permissions.
 */
public SecurityGroup addPermission(final SecurityGroup group, final IpPermission permission) {
    LOG.debug("Adding permission to security group {}: {}", group.getName(), permission);
    Callable<SecurityGroup> callable = new Callable<SecurityGroup>() {
        @Override
        public SecurityGroup call() throws Exception {
            try {
                return securityApi.addIpPermission(permission, group);
            } catch (Exception e) {
                Exceptions.propagateIfFatal(e);

                if (isDuplicate(e)) {
                    return group;
                }

                throw Exceptions.propagate(e);
            }
        }

        @Override
        public String toString() {
            return "Add permission " + permission + " to security group " + group;
        }
    };
    return runOperationWithRetry(callable);
}
 
Example 7
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 8
Source File: JcloudsSshMachineLocation.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
protected Optional<Image> getOptionalImage() {
  if (_image == null) {
      if (imageId == null) {
          _image = Optional.absent(); // can happen with JcloudsLocation.resumeMachine() usage
      } else {
          try {
              ComputeService computeService = getComputeServiceOrNull();
              if (computeService == null) {
                  if (LOG.isDebugEnabled()) LOG.debug("Cannot get image (with id {}) for {}, because cannot get compute-service from parent {}", new Object[] {imageId, this, getParent()});
                  _image = Optional.absent();
              } else {
                  _image = Optional.fromNullable(computeService.getImage(imageId));
              }
          } catch (Exception e) {
              Exceptions.propagateIfFatal(e);
              if (LOG.isDebugEnabled()) LOG.debug("Problem getting image for " + this + ", image id " + imageId + " (continuing)", e);
              _image = Optional.absent();
          }
      }
  }
  return _image;
}
 
Example 9
Source File: XmlMementoSerializer.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
protected String getContextDescription(Object contextHinter) {
    List<String> entries = MutableList.of();
    
    entries.add("in");
    entries.add(lookupContext.getContextDescription());
    
    if (contextHinter instanceof ReferencingMarshallingContext)
        entries.add("at "+((ReferencingMarshallingContext)contextHinter).currentPath());
    else if (contextHinter instanceof ReferenceByXPathUnmarshaller) {
        try {
            Method m = ReferenceByXPathUnmarshaller.class.getDeclaredMethod("getCurrentReferenceKey");
            m.setAccessible(true);
            entries.add("at "+m.invoke(contextHinter));
        } catch (Exception e) {
            Exceptions.propagateIfFatal(e);
            // ignore otherwise - we just won't have the position in the file
        }
    }
    
    return Strings.join(entries, " ");
}
 
Example 10
Source File: LocalLocationManager.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
private synchronized void unmanageNonRecursiveClearItsFields(Location loc, ManagementTransitionMode mode) {
    if (mode.isDestroying()) {
        ((AbstractLocation)loc).setParent(null, true);
        
        Location parent = ((AbstractLocation)loc).getParent();
        if (parent instanceof ProvisioningLocation<?>) {
            try {
                ((ProvisioningLocation)parent).release(loc);
            } catch (Exception e) {
                Exceptions.propagateIfFatal(e);
                log.debug("Error releasing "+loc+" in its parent "+parent+": "+e);
            }
        }
    } else {
        // if not destroying, don't change the parent's children list
        ((AbstractLocation)loc).setParent(null, false);
    }
    // clear config to help with GC; everyone says you're not supposed to, but this really seems to help, 
    // else config bag is littered with refs to entities etc and some JVMs seem to keep them around much longer
    ((AbstractLocation)loc).config().removeAllLocalConfig();
}
 
Example 11
Source File: BrooklynServerPaths.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public static File getBrooklynWebTmpDir(ManagementContext mgmt) {
    String brooklynMgmtBaseDir = getMgmtBaseDir(mgmt);
    File webappTempDir = new File(Os.mergePaths(brooklynMgmtBaseDir, "planes", mgmt.getManagementNodeId(), "jetty"));
    try {
        FileUtils.forceMkdir(webappTempDir);
        Os.deleteOnExitRecursivelyAndEmptyParentsUpTo(webappTempDir, new File(brooklynMgmtBaseDir)); 
        return webappTempDir;
    } catch (Exception e) {
        Exceptions.propagateIfFatal(e);
        IllegalStateException e2 = new IllegalStateException("Cannot create working directory "+webappTempDir+" for embedded jetty server: "+e, e);
        log.warn(e2.getMessage()+" (rethrowing)");
        throw e2;
    }
}
 
Example 12
Source File: RebindExceptionHandlerImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void onLoadMementoFailed(BrooklynObjectType type, String msg, Exception e) {
    Exceptions.propagateIfFatal(e);
    String errmsg = "problem loading memento: "+msg;
    
    switch (type) {
        case FEED:
        case POLICY:
        case ENRICHER:
            switch (loadPolicyFailureMode) {
                case FAIL_FAST:
                    throw new IllegalStateException("Rebind: aborting due to "+errmsg, e);
                case FAIL_AT_END:
                    loadPolicyFailures.add(new IllegalStateException(errmsg, e));
                    break;
                case CONTINUE:
                    warn(errmsg+"; continuing: "+e, e);
                    break;
                default:
                    throw new IllegalStateException("Unexpected state '"+loadPolicyFailureMode+"' for loadPolicyFailureMode");
            }
            break;
        default:
            exceptions.add(new IllegalStateException(errmsg, e));
            onErrorImpl(errmsg, e);
    }
}
 
Example 13
Source File: BrooklynDslInterpreter.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void applyYamlPrimitive(PlanInterpretationNode node) {
    String expression = node.getNewValue().toString();

    try {
        currentNode.set(node);
        Object parsedNode = new DslParser(expression).parse();
        if ((parsedNode instanceof FunctionWithArgs) && ((FunctionWithArgs)parsedNode).getArgs()==null) {
            if (node.getRoleInParent() == Role.MAP_KEY) {
                node.setNewValue(parsedNode);
                // will be handled later
            } else {
                throw new IllegalStateException("Invalid function-only expression '"+((FunctionWithArgs)parsedNode).getFunction()+"'");
            }
        } else {
            node.setNewValue( evaluate(parsedNode, true) );
        }
    } catch (Exception e) {
        // we could try parsing it as yaml and if it comes back as a map or a list, reapply the interpreter;
        // useful in some contexts where strings are required by the source (eg CFN, TOSCA)
        log.warn("Error evaluating node (rethrowing) '"+expression+"': "+e);
        Exceptions.propagateIfFatal(e);
        throw new IllegalArgumentException("Error evaluating node '"+expression+"'", e);
    } finally {
        currentNodeClear();
    }
}
 
Example 14
Source File: JcloudsStoreObjectAccessor.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public String get() {
    try {
        if (!blobStore.blobExists(containerName, blobName)) return null;
        Blob blob = blobStore.getBlob(containerName, blobName);
        if (blob==null) return null;
        return Strings2.toStringAndClose(blob.getPayload().openStream());
    } catch (IOException e) {
        Exceptions.propagateIfFatal(e);
        throw new IllegalStateException("Error reading blobstore "+containerName+" "+blobName+": "+e, e);
    }
}
 
Example 15
Source File: LocationResource.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public List<LocationSummary> list() {
    if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.SEE_LOCATION, Entitlements.StringAndArgument.of("list locations", "see"))) {
        throw WebResourceUtils.forbidden("User '%s' is not authorized to see locations",
                Entitlements.getEntitlementContext().user());
    }

    Function<LocationDefinition, LocationSummary> transformer = new Function<LocationDefinition, LocationSummary>() {
        @Override
        public LocationSummary apply(LocationDefinition l) {
            try {
                return LocationTransformer.newInstance(mgmt(), l, LocationDetailLevel.LOCAL_EXCLUDING_SECRET, ui.getBaseUriBuilder());
            } catch (Exception e) {
                Exceptions.propagateIfFatal(e);
                String spec = l.getSpec();
                if (spec == null || specsWarnedOnException.add(spec)) {
                    log.warn("Unable to find details of location {} in REST call to list (ignoring location): {}", l, e);
                    if (log.isDebugEnabled()) log.debug("Error details for location " + l, e);
                } else {
                    if (log.isTraceEnabled())
                        log.trace("Unable again to find details of location {} in REST call to list (ignoring location): {}", l, e);
                }
                return null;
            }
        }
    };
    return FluentIterable.from(brooklyn().getLocationRegistry().getDefinedLocations(true).values())
            .transform(transformer)
            .filter(LocationSummary.class)
            .toSortedList(nameOrSpecComparator());
}
 
Example 16
Source File: WebResourceUtils.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public static MediaType getImageMediaTypeFromExtension(String extension) {
    com.google.common.net.MediaType mime = IMAGE_FORMAT_MIME_TYPES.get(extension.toLowerCase());
    if (mime==null) return null;
    try {
        return MediaType.valueOf(mime.toString());
    } catch (Exception e) {
        log.warn("Unparseable MIME type "+mime+"; ignoring ("+e+")");
        Exceptions.propagateIfFatal(e);
        return null;
    }
}
 
Example 17
Source File: Reflections.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public static Maybe<Object> getFieldValueMaybe(Object instance, Field field) {
    try {
        if (instance==null) return null;
        if (field==null) return null;
        field.setAccessible(true);
        return Maybe.of(field.get(instance));
    } catch (Exception e) {
        Exceptions.propagateIfFatal(e);
        return Maybe.absent(e);
    }
}
 
Example 18
Source File: CatalogDo.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private void loadCatalogClasspath() {
    try {
        classpath = new CatalogClasspathDo(this);
        classpath.load();
    } catch (Exception e) {
        Exceptions.propagateIfFatal(e);
        log.error("Unable to load catalog "+this+" (ignoring): "+e);
        log.info("Trace for failure to load "+this+": "+e, e);
    }
}
 
Example 19
Source File: ReflectiveEntityDriverFactory.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
protected <D extends EntityDriver> ReferenceWithError<Class<? extends D>> loadClass(String className, ClassLoader classLoader) {
    try {
        return (ReferenceWithError) ReferenceWithError.newInstanceWithoutError((Class<? extends EntityDriver>)classLoader.loadClass(className));
    } catch (Exception e) {
        Exceptions.propagateIfFatal(e);
        return ReferenceWithError.newInstanceThrowingError(null, e);
    }
}
 
Example 20
Source File: BasicBrooklynTypeRegistry.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings({ "deprecation", "unchecked", "rawtypes" })
private <SpecT extends AbstractBrooklynObjectSpec<?,?>> SpecT createSpec(
        RegisteredType type,
        TypeImplementationPlan plan,
        @Nullable String symbolicName, @Nullable String version, Set<Object> superTypes,
        @Nullable RegisteredTypeLoadingContext constraint, @Nullable Class<SpecT> specSuperType) {
    // TODO type is only used to call to "transform"; we should perhaps change transform so it doesn't need the type?
    if (constraint!=null) {
        if (constraint.getExpectedKind()!=null && constraint.getExpectedKind()!=RegisteredTypeKind.SPEC) {
            throw new IllegalStateException("Cannot create spec with constraint "+constraint);
        }
        if (symbolicName != null && constraint.getAlreadyEncounteredTypes().contains(symbolicName)) {
            // avoid recursive cycle
            // TODO implement using java if permitted
        }
    }
    constraint = RegisteredTypeLoadingContexts.withSpecSuperType(constraint, specSuperType);

    Maybe<Object> result = TypePlanTransformers.transform(mgmt, type, constraint);
    if (result.isPresent()) return (SpecT) result.get();
    
    // fallback: look up in (legacy) catalog
    // TODO remove once all transformers are available in the new style
    CatalogItem item = symbolicName!=null ? (CatalogItem) mgmt.getCatalog().getCatalogItemLegacy(symbolicName, version) : null;
    if (item==null) {
        // if not in catalog (because loading a new item?) then look up item based on type
        // (only really used in tests; possibly also for any recursive legacy transformers we might have to create a CI; cross that bridge when we come to it)
        CatalogItemType ciType = CatalogItemType.ofTargetClass( (Class)constraint.getExpectedJavaSuperType() );
        if (ciType==null) {
            // throw -- not supported for non-spec types
            result.get();
        }
        item = CatalogItemBuilder.newItem(ciType, 
                symbolicName!=null ? symbolicName : Identifiers.makeRandomId(8), 
                version!=null ? version : BasicBrooklynCatalog.DEFAULT_VERSION)
            .plan((String)plan.getPlanData())
            .build();
    }
    try {
        SpecT resultLegacy = (SpecT) BasicBrooklynCatalog.internalCreateSpecLegacy(mgmt, item, constraint.getAlreadyEncounteredTypes(), false);
        log.warn("Item '"+item+"' was only parseable using legacy transformers; may not be supported in future versions: "+resultLegacy);
        return resultLegacy;
    } catch (Exception exceptionFromLegacy) {
        Exceptions.propagateIfFatal(exceptionFromLegacy);
        // for now, combine this failure with the original
        try {
            result.get();
            // above will throw -- so won't come here
            throw new IllegalStateException("should have failed getting type resolution for "+symbolicName);
        } catch (Exception exceptionFromPrimary) {
            // ignore the legacy error. means much nicer errors in the happy case.
            
            if (log.isTraceEnabled()) {
                log.trace("Unable to instantiate "+(symbolicName==null ? "item" : symbolicName)+", primary error", 
                    exceptionFromPrimary);
                log.trace("Unable to instantiate "+(symbolicName==null ? "item" : symbolicName)+", legacy error", 
                    exceptionFromLegacy);
            }

            Throwable exception = Exceptions.collapse(exceptionFromPrimary);
            throw symbolicName==null ? Exceptions.propagate(exception) : Exceptions.propagateAnnotated("Unable to instantiate "+symbolicName, exception);
        }
    }
}