@Override protected Class<?> findClass(String name) throws ClassNotFoundException { return currentLoader.get().loadClass(name); }
private Class<? extends MachineLocation> getLocationClass(String osFamily) { try { if (osFamily != null) { String className = OS_TO_MACHINE_LOCATION_TYPE.get(osFamily.toLowerCase(Locale.ENGLISH)); return new ClassLoaderUtils(this, managementContext).loadClass(className).asSubclass(MachineLocation.class); } } catch (ClassNotFoundException ex) {} return null; }
private EntitySpec<?> buildSpec(String specTypName) { // TODO is this hardcoded list deprecated? If so log a warning. try { Class<?> specType = new ClassLoaderUtils(this.getClass()).loadClass(specTypName); return buildSpec(specType); } catch (ClassNotFoundException e) { throw new IllegalStateException("Unable to load hardcoded catalog type " + specTypName, e); } }
@Override public Class apply(final String input) { try { //return Class.forName(input); return new ClassLoaderUtils(this.getClass()).loadClass(input); } catch (ClassNotFoundException e) { throw Exceptions.propagate(e); } } });
@Override public <D extends EntityDriver> String inferDriverClassName(DriverDependentEntity<D> entity, Class<D> driverInterface, Location location) { String driverInterfaceName = driverInterface.getName(); // TODO: use a proper registry later on try { Class<?> winRmLocationClass = new ClassLoaderUtils(this, entity).loadClass("org.apache.brooklyn.software-winrm", BrooklynVersion.get(), "org.apache.brooklyn.location.winrm.WinRmMachineLocation"); if (!winRmLocationClass.isInstance(location)) return null; } catch (ClassNotFoundException ex) { return null; } if (!driverInterfaceName.endsWith("Driver")) { throw new IllegalArgumentException(String.format("Driver name [%s] doesn't end with 'Driver'; cannot auto-detect WinRmDriver class name", driverInterfaceName)); } return Strings.removeFromEnd(driverInterfaceName, "Driver")+"WinRmDriver"; } }
@Override public HttpExecutor getHttpExecutor(Map<?, ?> props) { HttpExecutor httpExecutor; String httpExecutorClass = (String) props.get(HTTP_EXECUTOR_CLASS_CONFIG); if (httpExecutorClass != null) { Map<String,Object> httpExecutorProps = MutableMap.of(); Map<?, ?> executorProps = Maps.filterKeys(props, StringPredicates.isStringStartingWith(HTTP_EXECUTOR_CLASS_CONFIG_PREFIX)); if (executorProps.size() > 0) { for (Entry<?, ?> entry: executorProps.entrySet()) { String keyName = Strings.removeFromStart((String)entry.getKey(), HTTP_EXECUTOR_CLASS_CONFIG_PREFIX); httpExecutorProps.put(keyName, entry.getValue()); } } try { httpExecutor = (HttpExecutor) new ClassLoaderUtils(getClass()).loadClass(httpExecutorClass).getConstructor(Map.class).newInstance(httpExecutorProps); } catch (Exception e) { throw Exceptions.propagate(e); } } else { LOG.info(HTTP_EXECUTOR_CLASS_CONFIG + " parameter not provided. Using the default implementation " + HttpExecutorImpl.class.getName()); httpExecutor = HttpExecutorImpl.newInstance(); } return httpExecutor; } }
@SuppressWarnings({ "unchecked", "rawtypes" }) private void loadExtension() { Map<String, String> extensions = getConfig(LocationConfigKeys.EXTENSIONS); if (extensions != null) { for (Map.Entry<String, String> extension: extensions.entrySet()) { try { Class<?> extensionClassType = new ClassLoaderUtils(this, getManagementContext()).loadClass(extension.getKey()); if (!hasExtension(extensionClassType)) { Object extensionClass = new ClassLoaderUtils(this, getManagementContext()).loadClass(extension.getValue()).newInstance(); addExtension((Class)extensionClassType, extensionClass); } } catch (Exception e) { LOG.error("Location extension can not be loaded (rethrowing): {} {} {}", new Object[] {extension.getKey(), extension.getValue(), e}); throw Exceptions.propagate(e); } } } }
@SuppressWarnings("unchecked") public static Map<String, Sensor<?>> getDefinedSensors(String entityTypeName) { try { return getDefinedSensors((Class<? extends Entity>) new ClassLoaderUtils(BrooklynTypes.class).loadClass(entityTypeName)); } catch (ClassNotFoundException e) { throw Exceptions.propagate(e); } }
@SuppressWarnings("unchecked") protected Class<T> getType(Entity entity, String className) { try { // TODO use OSGi loader (low priority however); also ensure that allows primitives Maybe<Class<?>> primitive = Boxing.getPrimitiveType(className); if (primitive.isPresent()) return (Class<T>) primitive.get(); return (Class<T>) new ClassLoaderUtils(this, entity).loadClass(className); } catch (ClassNotFoundException e) { if (!className.contains(".")) { // could be assuming "java.lang" package; try again with that try { return (Class<T>) Class.forName("java.lang."+className); } catch (ClassNotFoundException e2) { throw new IllegalArgumentException("Invalid target type for sensor "+name+": " + className+" (also tried java.lang."+className+")"); } } else { throw new IllegalArgumentException("Invalid target type for sensor "+name+": " + className); } } }
@SuppressWarnings("unchecked") public static Map<String, ConfigKey<?>> getDefinedConfigKeys(String brooklynTypeName) { try { return getDefinedConfigKeys((Class<? extends BrooklynObject>) new ClassLoaderUtils(BrooklynTypes.class).loadClass(brooklynTypeName)); } catch (ClassNotFoundException e) { throw Exceptions.propagate(e); } }
private static HostGeoLookup findHostGeoLookupImpl() throws InstantiationException, IllegalAccessException, ClassNotFoundException { String type = BrooklynSystemProperties.HOST_GEO_LOOKUP_IMPL.getValue(); if (type==null) { type = BrooklynSystemProperties.HOST_GEO_LOOKUP_IMPL_LEGACY.getValue(); if (type!=null && !warnedLegacy) { warnedLegacy = true; log.warn("Using deprecated host-geo-lookup property "+BrooklynSystemProperties.HOST_GEO_LOOKUP_IMPL_LEGACY+"; " + "set "+BrooklynSystemProperties.HOST_GEO_LOOKUP_IMPL+" instead"); } } /* utrace seems more accurate than geobytes, and it gives a report of how many tokens are left; * but maxmind if it's installed locally is even better (does not require remote lookup), * so use it if available */ if (type==null) { if (MaxMind2HostGeoLookup.getDatabaseReader()!=null) return new MaxMind2HostGeoLookup(); log.debug("Using Utrace remote for geo lookup because MaxMind2 is not available"); return new UtraceHostGeoLookup(); } if (type.isEmpty()) return null; return (HostGeoLookup) new ClassLoaderUtils(HostGeoInfo.class).loadClass(type).newInstance(); }
@Override public UsageListener apply(String input) { Class<?> clazz; try { clazz = new ClassLoaderUtils(this.getClass()).loadClass(input); } catch (ClassNotFoundException e) { throw new IllegalStateException("Failed to load usage listener class: " + input, e); } Maybe<Object> result = Reflections.invokeConstructorFromArgs(clazz); if (result.isPresentAndNonNull() && result.get() instanceof UsageListener) { return (UsageListener) result.get(); } else if (result.isPresent()) { throw new IllegalStateException("Object is not a UsageListener: " + result.get()); } else { throw new IllegalStateException("Failed to create UsageListener from class name '"+input+"' using no-arg constructor"); } } });
@Test public void testDebug() throws ClassNotFoundException { System.out.println(BasicSpecParameter.fromClass(mgmt, new ClassLoaderUtils(this.getClass()).loadClass("org.apache.brooklyn.entity.stock.BasicApplication"))); }
protected Class<?> loadClass(String jType) throws ClassNotFoundException { try { return reflections.loadClass(jType); } catch (Exception e) { Exceptions.propagateIfFatal(e); } return new ClassLoaderUtils(reflections.getClassLoader(), managementContext).loadClass(jType); }
public static EntitlementManager load(@Nullable ManagementContext mgmt, BrooklynProperties brooklynProperties, String type) { if ("root".equalsIgnoreCase(type)) { return root(); } else if ("readonly".equalsIgnoreCase(type) || "read_only".equalsIgnoreCase(type)) { return readOnly(); } else if ("minimal".equalsIgnoreCase(type)) { return minimal(); } else if ("user".equalsIgnoreCase(type)) { return user(); } if (Strings.isNonBlank(type)) { try { Class<?> clazz = new ClassLoaderUtils(Entitlements.class, mgmt).loadClass(DeserializingClassRenamesProvider.INSTANCE.findMappedName(type)); return (EntitlementManager) instantiate(clazz, ImmutableList.of( new Object[] {mgmt, brooklynProperties}, new Object[] {mgmt}, new Object[] {brooklynProperties}, new Object[0])); } catch (Exception e) { throw Exceptions.propagate(e); } } throw new IllegalStateException("Invalid entitlement manager specified: '"+type+"'"); }
@Override @SuppressWarnings({ "rawtypes", "unchecked" }) public Maybe<Class<?>> tryLoadClass(String className) { String mappedClassName = DeserializingClassRenamesProvider.INSTANCE.findMappedName(className); Maybe<Class<?>> cls = tryLoadClass0(mappedClassName); if (cls.isPresent()) { return cls; } try { return (Maybe) Maybe.of(new ClassLoaderUtils(loader, mgmt).loadClass(mappedClassName)); } catch (Exception e) { Exceptions.propagateIfFatal(e); // return original error return cls; } }
private void assertLoadSucceeds(ClassLoaderUtils clu, String bundledClassName, Class<?> expectedClass) throws ClassNotFoundException { BundledName className = new BundledName(bundledClassName); Class<?> cls = clu.loadClass(bundledClassName); assertEquals(cls.getName(), className.name); if (expectedClass != null) { assertEquals(cls, expectedClass); } ClassLoader cl = cls.getClassLoader(); BundledName resource = className.toResource(); String bundledResource = resource.toString(); URL resourceUrl = cl.getResource(resource.name); assertEquals(clu.getResource(bundledResource), resourceUrl); assertEquals(clu.getResources(bundledResource), ImmutableList.of(resourceUrl), "Loading with "+clu); BundledName rootResource = new BundledName(resource.bundle, resource.version, "/" + resource.name); String rootBundledResource = rootResource.toString(); assertEquals(clu.getResource(rootBundledResource), resourceUrl); assertEquals(clu.getResources(rootBundledResource), ImmutableList.of(resourceUrl)); }
private void assertLoadFails(ClassLoaderUtils clu, String bundledClassName) { BundledName className = new BundledName(bundledClassName); try { clu.loadClass(bundledClassName); Asserts.shouldHaveFailedPreviously("Using loader " + clu); } catch (ClassNotFoundException e) { Asserts.expectedFailureContains(e, bundledClassName, "not found on the application class path, nor in the bundle white list"); } BundledName resource = className.toResource(); String bundledResource = resource.toString(); assertNull(clu.getResource(bundledResource), resource + " is supposed to fail resource loading, but it was successful"); assertEquals(clu.getResources(bundledResource), ImmutableList.of(), resource + " is supposed to fail resource loading, but it was successful"); }
@Test public void testLoadBrooklynClass() throws Exception { mgmt = LocalManagementContextForTests.builder(true).enableOsgiReusable().build(); new ClassLoaderUtils(this, mgmt).loadClass( "org.apache.brooklyn.api", BrooklynVersion.get(), Entity.class.getName()); new ClassLoaderUtils(this, mgmt).loadClass( "org.apache.brooklyn.api", BrooklynVersion.getOsgiVersion(), Entity.class.getName()); try { new ClassLoaderUtils(this, mgmt).loadClass( "org.apache.brooklyn.api", "100.100.100-alpha-version_wth.tags", new ClassLoaderUtils(this, mgmt).loadClass( "org.apache.brooklyn.api", "100.100.100-SNAPSHOT",
@SuppressWarnings("unchecked") @Override public PolicySummary addPolicy( String application,String entityToken, String policyTypeName, Map<String, String> config) { Entity entity = brooklyn().getEntity(application, entityToken); Class<? extends Policy> policyType; try { policyType = (Class<? extends Policy>) new ClassLoaderUtils(this, mgmt()).loadClass(policyTypeName); } catch (ClassNotFoundException e) { throw WebResourceUtils.badRequest("No policy with type %s found", policyTypeName); } catch (ClassCastException e) { throw WebResourceUtils.badRequest("No policy with type %s found", policyTypeName); } catch (Exception e) { throw Exceptions.propagate(e); } Policy policy = entity.policies().add(PolicySpec.create(policyType).configure(config)); log.debug("REST API added policy " + policy + " to " + entity); return PolicyTransformer.policySummary(entity, policy, ui.getBaseUriBuilder()); }