Example usage for java.lang Class asSubclass

List of usage examples for java.lang Class asSubclass

Introduction

In this page you can find the example usage for java.lang Class asSubclass.

Prototype

@SuppressWarnings("unchecked")
public <U> Class<? extends U> asSubclass(Class<U> clazz) 

Source Link

Document

Casts this Class object to represent a subclass of the class represented by the specified class object.

Usage

From source file:org.jenkinsci.plugins.workflow.structs.DescribableHelper.java

@SuppressWarnings("unchecked")
private static Object coerce(String context, Type type, @Nonnull Object o) throws Exception {
    if (type instanceof Class) {
        o = ReflectionCache.getCachedClass((Class) type).coerceArgument(o);
    }//from   ww w . jav a 2 s . c o  m
    if (type instanceof Class && Primitives.wrap((Class) type).isInstance(o)) {
        return o;
    } else if (o instanceof Map) {
        Map<String, Object> m = new HashMap<String, Object>();
        for (Map.Entry<?, ?> entry : ((Map<?, ?>) o).entrySet()) {
            m.put((String) entry.getKey(), entry.getValue());
        }

        String clazzS = (String) m.remove(CLAZZ);
        Class<?> clazz;
        if (clazzS == null) {
            if (Modifier.isAbstract(((Class) type).getModifiers())) {
                throw new UnsupportedOperationException(
                        "must specify " + CLAZZ + " with an implementation of " + type);
            }
            clazz = (Class) type;
        } else if (clazzS.contains(".")) {
            Jenkins j = Jenkins.getInstance();
            ClassLoader loader = j != null ? j.getPluginManager().uberClassLoader
                    : DescribableHelper.class.getClassLoader();
            clazz = loader.loadClass(clazzS);
        } else if (type instanceof Class) {
            clazz = null;
            for (Class<?> c : findSubtypes((Class<?>) type)) {
                if (c.getSimpleName().equals(clazzS)) {
                    if (clazz != null) {
                        throw new UnsupportedOperationException(clazzS + " as a " + type + " could mean either "
                                + clazz.getName() + " or " + c.getName());
                    }
                    clazz = c;
                }
            }
            if (clazz == null) {
                throw new UnsupportedOperationException(
                        "no known implementation of " + type + " is named " + clazzS);
            }
        } else {
            throw new UnsupportedOperationException("JENKINS-26535: do not know how to handle " + type);
        }
        return instantiate(clazz.asSubclass((Class<?>) type), m);
    } else if (o instanceof String && type instanceof Class && ((Class) type).isEnum()) {
        return Enum.valueOf(((Class) type).asSubclass(Enum.class), (String) o);
    } else if (o instanceof String && type == URL.class) {
        return new URL((String) o);
    } else if (o instanceof String && (type == char.class || type == Character.class)
            && ((String) o).length() == 1) {
        return ((String) o).charAt(0);
    } else if (o instanceof List && type instanceof Class && ((Class) type).isArray()) {
        Class<?> componentType = ((Class) type).getComponentType();
        List<Object> list = mapList(context, componentType, (List) o);
        return list.toArray((Object[]) Array.newInstance(componentType, list.size()));
    } else if (o instanceof List && acceptsList(type)) {
        return mapList(context, ((ParameterizedType) type).getActualTypeArguments()[0], (List) o);
    } else {
        throw new ClassCastException(context + " expects " + type + " but received " + o.getClass());
    }
}

From source file:de.xaniox.heavyspleef.addon.AddOnManager.java

@SuppressWarnings("unchecked")
private void enableAddOn(AddOn addOn) {
    if (addOn.isEnabled()) {
        throw new IllegalStateException("Add-On is already enabled");
    }//from  w  w w.  j  a  v a  2s.c o  m

    AddOnProperties properties = addOn.getProperties();

    List<String> commands = properties.getCommands();
    List<String> flags = properties.getFlags();
    List<String> extensions = properties.getExtensions();
    ClassLoader loader = ((BasicAddOn) addOn).getClassLoader();

    logger.log(Level.INFO, "Enabling add-on " + properties.getName() + " v" + properties.getVersion());

    if (commands != null) {
        for (String clazzStr : commands) {
            Class<?> clazz;

            try {
                clazz = Class.forName(clazzStr, true, loader);
            } catch (ClassNotFoundException e) {
                throw new IllegalArgumentException(
                        "Add-On " + addOn.getName() + " defines an unknown command class", e);
            }

            commandManagerAccess.registerSpleefCommand(clazz, addOn);
        }
    }

    if (flags != null) {
        for (String flagClassName : flags) {
            Class<?> clazz;

            try {
                clazz = Class.forName(flagClassName, true, loader);
            } catch (ClassNotFoundException e) {
                throw new IllegalArgumentException(
                        "Add-On " + addOn.getName() + " defines an unknown flag class", e);
            }

            Class<? extends AbstractFlag<?>> flagClass;

            try {
                flagClass = (Class<? extends AbstractFlag<?>>) clazz.asSubclass(AbstractFlag.class);
            } catch (ClassCastException e) {
                throw new IllegalArgumentException(
                        "Class " + clazz.getName() + " does not extend AbstractFlag");
            }

            flagRegistryAccess.registerFlag(flagClass, addOn);
        }
    }

    if (extensions != null) {
        for (String extensionClassName : extensions) {
            Class<?> clazz;

            try {
                clazz = Class.forName(extensionClassName, true, loader);
            } catch (ClassNotFoundException e) {
                throw new IllegalArgumentException(
                        "Add-On " + addOn.getName() + " defines an unknown extension class", e);
            }

            Class<? extends GameExtension> extClass;

            try {
                extClass = clazz.asSubclass(GameExtension.class);
            } catch (ClassCastException e) {
                throw new IllegalArgumentException(
                        "Class " + clazz.getName() + " does not extend GameExtension");
            }

            extensionRegistryAccess.registerExtension(extClass, addOn);
        }
    }

    try {
        addOn.enable();
    } catch (Throwable t) {
        getLogger().log(Level.SEVERE, "Unexpected exception while enabling Add-On " + addOn.getName() + " v"
                + addOn.getProperties().getVersion() + ". Is it up to date?", t);
    }

    addOn.setEnabled(true);
}

From source file:org.kuali.rice.krad.uif.widget.QuickFinder.java

/**
 * Adjusts the id for the quickfinder action, and then adds action parameters for passing along the
 * quickfinder configuration to the lookup view.
 *
 * @param view view instance the quickfinder is associated with
 * @param model object containing the view data
 * @param parent component instance the quickfinder is associated with
 *//* w ww. j ava 2s  .  c  o  m*/
protected void setupQuickfinderAction(View view, Object model, LifecycleElement parent) {
    quickfinderAction.setId(getId() + UifConstants.IdSuffixes.ACTION);

    if ((lightBox != null) && lightBox.isRender()) {
        String lightboxScript = UifConstants.JsFunctions.CREATE_LIGHTBOX_POST + "(\""
                + quickfinderAction.getId() + "\"," + lightBox.getTemplateOptionsJSString() + ","
                + returnByScript + ");";

        quickfinderAction.setActionScript(lightboxScript);
    }

    quickfinderAction.addActionParameter(UifParameters.BASE_LOOKUP_URL, baseLookupUrl);

    Class dataObjectClass = getDataObjectClass(dataObjectClassName);
    ModuleService responsibleModuleService = KRADServiceLocatorWeb.getKualiModuleService()
            .getResponsibleModuleService(dataObjectClass);
    if (responsibleModuleService != null && responsibleModuleService.isExternalizable(dataObjectClass)) {
        if (ExternalizableBusinessObject.class.isAssignableFrom(dataObjectClass)) {
            Class implementationClass = responsibleModuleService.getExternalizableBusinessObjectImplementation(
                    dataObjectClass.asSubclass(ExternalizableBusinessObject.class));
            if (implementationClass != null) {
                dataObjectClassName = implementationClass.getName();
            }
        }
    }

    quickfinderAction.addActionParameter(UifParameters.DATA_OBJECT_CLASS_NAME, dataObjectClassName);

    if (!fieldConversions.isEmpty()) {
        quickfinderAction.addActionParameter(UifParameters.CONVERSION_FIELDS,
                KRADUtils.buildMapParameterString(fieldConversions));
    }

    if (!lookupParameters.isEmpty()) {
        quickfinderAction.addActionParameter(UifParameters.LOOKUP_PARAMETERS,
                KRADUtils.buildMapParameterString(lookupParameters));
    }

    addActionParameterIfNotNull(UifParameters.VIEW_NAME, viewName);
    addActionParameterIfNotNull(UifParameters.READ_ONLY_FIELDS, readOnlyLookupFields);
    addActionParameterIfNotNull(UifParameters.RENDER_RETURN_LINK, renderReturnLink);
    addActionParameterIfNotNull(UifParameters.RENDER_RESULT_ACTIONS, renderResultActions);
    addActionParameterIfNotNull(UifParameters.REFERENCES_TO_REFRESH, referencesToRefresh);
    addActionParameterIfNotNull(UifParameters.AUTO_SEARCH, autoSearch);
    addActionParameterIfNotNull(UifParameters.RENDER_LOOKUP_CRITERIA, renderLookupCriteria);
    addActionParameterIfNotNull(UifParameters.RENDER_CRITERIA_ACTIONS, renderCriteriaActions);
    addActionParameterIfNotNull(UifParameters.HIDE_CRITERIA_ON_SEARCH, hideCriteriaOnSearch);
    addActionParameterIfNotNull(UifParameters.RENDER_MAINTENANCE_LINKS, renderMaintenanceLinks);
    addActionParameterIfNotNull(UifParameters.MULTIPLE_VALUES_SELECT, multipleValuesSelect);
    addActionParameterIfNotNull(UifParameters.LOOKUP_COLLECTION_NAME, lookupCollectionName);
    addActionParameterIfNotNull(UifParameters.LOOKUP_COLLECTION_ID, lookupCollectionId);
    addActionParameterIfNotNull(UifParameters.QUICKFINDER_ID, getId());

    //insert additional lookup parameters.
    if (additionalLookupParameters != null) {
        //copy additional parameters to actionParameters
        Map<String, String> actionParameters = quickfinderAction.getActionParameters();
        actionParameters.putAll(additionalLookupParameters);
        quickfinderAction.setActionParameters(actionParameters);
    }
}

From source file:org.apache.nifi.controller.service.StandardControllerServiceProvider.java

@Override
public ControllerServiceNode createControllerService(final String type, final String id,
        final boolean firstTimeAdded) {
    if (type == null || id == null) {
        throw new NullPointerException();
    }// w ww .  ja  va2s. co  m

    final ClassLoader currentContextClassLoader = Thread.currentThread().getContextClassLoader();
    try {
        final ClassLoader cl = ExtensionManager.getClassLoader(type, id);
        final Class<?> rawClass;

        try {
            if (cl == null) {
                rawClass = Class.forName(type);
            } else {
                Thread.currentThread().setContextClassLoader(cl);
                rawClass = Class.forName(type, false, cl);
            }
        } catch (final Exception e) {
            logger.error("Could not create Controller Service of type " + type + " for ID " + id
                    + "; creating \"Ghost\" implementation", e);
            Thread.currentThread().setContextClassLoader(currentContextClassLoader);
            return createGhostControllerService(type, id);
        }

        final Class<? extends ControllerService> controllerServiceClass = rawClass
                .asSubclass(ControllerService.class);

        final ControllerService originalService = controllerServiceClass.newInstance();
        final AtomicReference<ControllerServiceNode> serviceNodeHolder = new AtomicReference<>(null);
        final InvocationHandler invocationHandler = new InvocationHandler() {
            @Override
            public Object invoke(final Object proxy, final Method method, final Object[] args)
                    throws Throwable {

                final String methodName = method.getName();
                if ("initialize".equals(methodName) || "onPropertyModified".equals(methodName)) {
                    throw new UnsupportedOperationException(
                            method + " may only be invoked by the NiFi framework");
                }

                final ControllerServiceNode node = serviceNodeHolder.get();
                final ControllerServiceState state = node.getState();
                final boolean disabled = state != ControllerServiceState.ENABLED; // only allow method call if service state is ENABLED.
                if (disabled && !validDisabledMethods.contains(method)) {
                    // Use nar class loader here because we are implicitly calling toString() on the original implementation.
                    try (final NarCloseable narCloseable = NarCloseable.withComponentNarLoader(
                            originalService.getClass(), originalService.getIdentifier())) {
                        throw new IllegalStateException("Cannot invoke method " + method
                                + " on Controller Service " + originalService.getIdentifier()
                                + " because the Controller Service is disabled");
                    } catch (final Throwable e) {
                        throw new IllegalStateException(
                                "Cannot invoke method " + method + " on Controller Service with identifier "
                                        + id + " because the Controller Service is disabled");
                    }
                }

                try (final NarCloseable narCloseable = NarCloseable
                        .withComponentNarLoader(originalService.getClass(), originalService.getIdentifier())) {
                    return method.invoke(originalService, args);
                } catch (final InvocationTargetException e) {
                    // If the ControllerService throws an Exception, it'll be wrapped in an InvocationTargetException. We want
                    // to instead re-throw what the ControllerService threw, so we pull it out of the InvocationTargetException.
                    throw e.getCause();
                }
            }
        };

        final ControllerService proxiedService;
        if (cl == null) {
            proxiedService = (ControllerService) Proxy.newProxyInstance(getClass().getClassLoader(),
                    getInterfaces(controllerServiceClass), invocationHandler);
        } else {
            proxiedService = (ControllerService) Proxy.newProxyInstance(cl,
                    getInterfaces(controllerServiceClass), invocationHandler);
        }
        logger.info("Created Controller Service of type {} with identifier {}", type, id);

        final ComponentLog serviceLogger = new SimpleProcessLogger(id, originalService);
        originalService.initialize(new StandardControllerServiceInitializationContext(id, serviceLogger, this,
                getStateManager(id), nifiProperties));

        final ComponentLog logger = new SimpleProcessLogger(id, originalService);
        final ValidationContextFactory validationContextFactory = new StandardValidationContextFactory(this,
                variableRegistry);

        final ControllerServiceNode serviceNode = new StandardControllerServiceNode(proxiedService,
                originalService, id, validationContextFactory, this, variableRegistry, logger);
        serviceNodeHolder.set(serviceNode);
        serviceNode.setName(rawClass.getSimpleName());

        if (firstTimeAdded) {
            try (final NarCloseable x = NarCloseable.withComponentNarLoader(originalService.getClass(),
                    originalService.getIdentifier())) {
                ReflectionUtils.invokeMethodsWithAnnotation(OnAdded.class, originalService);
            } catch (final Exception e) {
                throw new ComponentLifeCycleException(
                        "Failed to invoke On-Added Lifecycle methods of " + originalService, e);
            }
        }

        return serviceNode;
    } catch (final Throwable t) {
        throw new ControllerServiceInstantiationException(t);
    } finally {
        if (currentContextClassLoader != null) {
            Thread.currentThread().setContextClassLoader(currentContextClassLoader);
        }
    }
}

From source file:org.canova.api.conf.Configuration.java

/**
 * Get the value of the <code>name</code> property as a <code>Class</code>
 * implementing the interface specified by <code>xface</code>.
 *
 * If no such property is specified, then <code>defaultValue</code> is
 * returned.//w  w w . ja  va 2  s . c  o m
 *
 * An exception is thrown if the returned class does not implement the named
 * interface.
 *
 * @param name the class name.
 * @param defaultValue default value.
 * @param xface the interface implemented by the named class.
 * @return property value as a <code>Class</code>,
 *         or <code>defaultValue</code>.
 */
public <U> Class<? extends U> getClass(String name, Class<? extends U> defaultValue, Class<U> xface) {
    try {
        Class<?> theClass = getClass(name, defaultValue);
        if (theClass != null && !xface.isAssignableFrom(theClass))
            throw new RuntimeException(theClass + " not " + xface.getName());
        else if (theClass != null)
            return theClass.asSubclass(xface);
        else
            return null;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:io.coala.json.DynaBean.java

/**
 * @param referenceType/*  w  w w  . j a  v a  2s .c o  m*/
 * @param <S>
 * @param <T>
 * @return
 */
static final <S, T> JsonDeserializer<T> createJsonDeserializer(final ObjectMapper om, final Class<T> resultType,
        final Properties... imports) {
    return new JsonDeserializer<T>() {

        @Override
        public T deserializeWithType(final JsonParser jp, final DeserializationContext ctxt,
                final TypeDeserializer typeDeserializer) throws IOException, JsonProcessingException {
            return deserialize(jp, ctxt);
        }

        @Override
        public T deserialize(final JsonParser jp, final DeserializationContext ctxt)
                throws IOException, JsonProcessingException {
            if (jp.getCurrentToken() == JsonToken.VALUE_NULL)
                return null;

            //            if( Wrapper.class.isAssignableFrom( resultType ) )
            //            {
            //               // FIXME
            //               LOG.trace( "deser wrapper intf of {}", jp.getText() );
            //               return (T) Wrapper.Util.valueOf( jp.getText(),
            //                     resultType.asSubclass( Wrapper.class ) );
            //            } 
            if (Config.class.isAssignableFrom(resultType)) {
                final Map<String, Object> entries = jp.readValueAs(new TypeReference<Map<String, Object>>() {
                });

                final Iterator<Entry<String, Object>> it = entries.entrySet().iterator();
                for (Entry<String, Object> next = null; it.hasNext(); next = it.next())
                    if (next != null && next.getValue() == null) {
                        LOG.trace("Ignoring null value: {}", next);
                        it.remove();
                    }
                return resultType.cast(ConfigFactory.create(resultType.asSubclass(Config.class), entries));
            }
            // else if (Config.class.isAssignableFrom(resultType))
            // throw new JsonGenerationException(
            // "Config does not extend "+Mutable.class.getName()+" required for deserialization: "
            // + Arrays.asList(resultType
            // .getInterfaces()));

            // can't parse directly to interface type
            final DynaBean bean = new DynaBean();
            final TreeNode tree = jp.readValueAsTree();

            // override attributes as defined in interface getters
            final Set<String> attributes = new HashSet<>();
            for (Method method : resultType.getMethods()) {
                if (method.getReturnType().equals(Void.TYPE) || method.getParameterTypes().length != 0)
                    continue;

                final String attribute = method.getName();
                if (attribute.equals("toString") || attribute.equals("hashCode"))
                    continue;

                attributes.add(attribute);
                final TreeNode value = tree.get(attribute);// bean.any().get(attributeName);
                if (value == null)
                    continue;

                bean.set(method.getName(),
                        om.treeToValue(value, JsonUtil.checkRegistered(om, method.getReturnType(), imports)));
            }
            if (tree.isObject()) {
                // keep superfluous properties as TreeNodes, just in case
                final Iterator<String> fieldNames = tree.fieldNames();
                while (fieldNames.hasNext()) {
                    final String fieldName = fieldNames.next();
                    if (!attributes.contains(fieldName))
                        bean.set(fieldName, tree.get(fieldName));
                }
            } else if (tree.isValueNode()) {
                for (Class<?> type : resultType.getInterfaces())
                    for (Method method : type.getDeclaredMethods()) {
                        //                     LOG.trace( "Scanning {}", method );
                        if (method.isAnnotationPresent(JsonProperty.class)) {
                            final String property = method.getAnnotation(JsonProperty.class).value();
                            //                        LOG.trace( "Setting {}: {}", property,
                            //                              ((ValueNode) tree).textValue() );
                            bean.set(property, ((ValueNode) tree).textValue());
                        }
                    }
            } else
                throw ExceptionFactory.createUnchecked("Expected {} but parsed: {}", resultType,
                        tree.getClass());

            return DynaBean.proxyOf(om, resultType, bean, imports);
        }
    };
}

From source file:edu.ku.brc.af.ui.forms.ViewFactory.java

/**
 * Creates an ImageDisplay control,/*from   w ww . j  a v  a  2 s  .c  om*/
 * @param cellField FormCellField info
 * @param isViewMode indicates whether in Edit or View mode
 * @param isRequired whether the field is required or not
 * @return the control
 */
protected static UIPluginable createPlugin(final MultiView parent, final FormValidator validator,
        final FormCellField cellField, final boolean isViewMode, final boolean isRequired) {
    String pluginName = cellField.getProperty("name");
    if (StringUtils.isEmpty(pluginName)) {
        String msg = "Creating plugin and the name property was missing. [" + cellField.getName() + "]";
        log.error(msg);
        FormDevHelper.appendFormDevError(msg);
        return null;
    }

    // We should refactor the plugin manager.
    Class<?> pluginClass = TaskMgr.getUIPluginClassForName(pluginName);
    if (pluginClass != null && UIPluginable.class.isAssignableFrom(pluginClass)) {
        try {
            // instantiate the plugin object
            UIPluginable uiPlugin = pluginClass.asSubclass(UIPluginable.class).newInstance();

            uiPlugin.setCellName(cellField.getName());

            Properties props = (Properties) cellField.getProperties().clone();

            //log.debug(cellField.getName());
            if (uiPlugin instanceof WebLinkButton) {
                //if (StringUtils.isNotEmpty((String)props.get("weblink")))
                {
                    DBTableInfo tInfo = DBTableIdMgr.getInstance()
                            .getByClassName(parent.getView().getClassName());
                    if (tInfo != null) {
                        //log.debug(cellField.getName());
                        DBFieldInfo fInfo = tInfo.getFieldByName(cellField.getName());
                        if (fInfo != null) {
                            //log.debug(fInfo.getFormatStr() + " weblink: "+fInfo.getWebLinkName());
                            if (StringUtils.isEmpty((String) props.get("weblink"))
                                    && StringUtils.isNotEmpty(fInfo.getWebLinkName())) {
                                props.put("weblink", fInfo.getWebLinkName());
                            }
                        }
                    }
                }
            }

            // This needs to be done before the initialize.
            if (uiPlugin instanceof UIValidatable) {
                ((UIValidatable) uiPlugin).setRequired(isRequired);
            }

            // initialize the plugin object

            uiPlugin.initialize(props, isViewMode);

            // get the UI component provided by the plugin object
            JComponent pluginUI = uiPlugin.getUIComponent();

            // check for another required interface (GetSetValueIFace)
            if (!(uiPlugin instanceof GetSetValueIFace)) {
                FormDevHelper.appendFormDevError("Plugin of class [" + pluginClass.getName()
                        + "] doesn't implement the GetSetValueIFace!");
                return null;
            }

            if (validator != null) {
                DataChangeNotifier dcn = validator.hookupComponent(pluginUI, cellField.getIdent(),
                        parseValidationType(cellField.getValidationType()), cellField.getValidationRule(),
                        false);
                uiPlugin.addChangeListener(dcn);
            }

            return uiPlugin;

        } catch (Exception ex) {
            log.error(ex);
            ex.printStackTrace();
            FormDevHelper.appendFormDevError(ex);
        }
    }
    log.error("Couldn't find plugin by name[" + pluginName + "]");
    return null;
}

From source file:de.zib.sfs.StatisticsFileSystem.java

@Override
public synchronized void initialize(URI name, Configuration conf) throws IOException {
    if (this.initialized) {
        LOG.warn("Ignoring attempt to re-initialize file system.");
        return;/*from   w  w  w.jav  a 2  s.c  o  m*/
    }

    super.initialize(name, conf);
    setConf(conf);

    String hostname = System.getProperty("de.zib.sfs.hostname");
    if (hostname == null) {
        LOG.warn("'de.zib.sfs.hostname' not set, did the agent start properly?");

        // Obtain hostname, preferably via executing hostname
        Process hostnameProcess = Runtime.getRuntime().exec("hostname");
        try {
            int exitCode = hostnameProcess.waitFor();
            if (exitCode != 0) {
                LOG.warn("'hostname' returned " + exitCode + ", using $HOSTNAME instead.");
                hostname = System.getenv("HOSTNAME");
            } else {
                try (BufferedReader reader = new BufferedReader(
                        new InputStreamReader(hostnameProcess.getInputStream()))) {

                    StringBuilder hostnameBuilder = new StringBuilder();
                    String line = "";
                    while ((line = reader.readLine()) != null) {
                        hostnameBuilder.append(line);
                    }
                    hostname = hostnameBuilder.toString();
                }
            }
        } catch (InterruptedException e) {
            LOG.warn("Error executing 'hostname', using $HOSTNAME instead.", e);
            hostname = System.getenv("HOSTNAME");
        }

        System.setProperty("de.zib.sfs.hostname", hostname);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Running on " + hostname + ".");
    }

    if (System.getProperty("de.zib.sfs.pid") == null) {
        LOG.warn("'de.zib.sfs.pid' not set, did the agent start properly?");

        // use negative random number to indicate it's no real PID
        int pid = -new Random().nextInt(Integer.MAX_VALUE);
        System.setProperty("de.zib.sfs.pid", Integer.toString(pid));
    }

    if (System.getProperty("de.zib.sfs.key") == null) {
        LOG.warn("'de.zib.sfs.key' not set, did the agent start properly?");
        System.setProperty("de.zib.sfs.key", "sfs");
    }

    if (System.getProperty("de.zib.sfs.timeBin.duration") == null) {
        LOG.warn("'de.zib.sfs.timeBin.duration' not set, did the agent start properly?");
        System.setProperty("de.zib.sfs.timeBin.duration", "1000");
    }

    if (System.getProperty("de.zib.sfs.timeBin.cacheSize") == null) {
        LOG.warn("'de.zib.sfs.timeBin.cacheSize' not set, did the agent start properly?");
        System.setProperty("de.zib.sfs.timeBin.cacheSize", "30");
    }

    if (System.getProperty("de.zib.sfs.output.directory") == null) {
        LOG.warn("'de.zib.sfs.output.directory' not set, did the agent start properly?");
        System.setProperty("de.zib.sfs.output.directory", getConf().get(SFS_OUTPUT_DIRECTORY_KEY, "/tmp"));
    }

    if (System.getProperty("de.zib.sfs.output.format") == null) {
        LOG.warn("'de.zib.sfs.output.format' not set, did the agent start properly?");
        OutputFormat outputFormat = OutputFormat
                .valueOf(getConf().get(SFS_OUTPUT_FORMAT_KEY, OutputFormat.BB.name()).toUpperCase());
        System.setProperty("de.zib.sfs.output.format", outputFormat.name());
    }

    if (System.getProperty("de.zib.sfs.traceFds") == null) {
        LOG.warn("'de.zib.sfs.traceFds' not set, did the agent start properly?");
        System.setProperty("de.zib.sfs.traceFds",
                getConf().getBoolean(SFS_TRACE_FDS_KEY, false) ? "true" : "false");
    }

    LiveOperationStatisticsAggregator.instance.initialize();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Initialized file system statistics aggregator.");
    }

    // Obtain the file system class we want to wrap
    String wrappedFSClassName = getConf().get(SFS_WRAPPED_FS_CLASS_NAME_KEY);
    if (wrappedFSClassName == null) {
        throw new RuntimeException(SFS_WRAPPED_FS_CLASS_NAME_KEY + " not specified");
    }
    this.wrappedFSScheme = getConf().get(SFS_WRAPPED_FS_SCHEME_KEY);
    if (this.wrappedFSScheme == null) {
        throw new RuntimeException(SFS_WRAPPED_FS_SCHEME_KEY + " not specified");
    }

    Class<?> wrappedFSClass;
    try {
        wrappedFSClass = Class.forName(wrappedFSClassName);
    } catch (Exception e) {
        throw new RuntimeException("Error obtaining class '" + wrappedFSClassName + "'", e);
    }

    // Figure out what kind of file system we are wrapping.
    if (wrappedFSClassName.startsWith("org.apache.hadoop")
            || wrappedFSClassName.startsWith("org.xtreemfs.common.clients.hadoop")) {
        try {
            // Wrap Hadoop file system directly.
            this.wrappedFS = wrappedFSClass.asSubclass(FileSystem.class).newInstance();
        } catch (Exception e) {
            throw new RuntimeException("Error instantiating Hadoop class '" + wrappedFSClassName + "'", e);
        }
    } else {
        throw new RuntimeException("Unsupported file system class '" + wrappedFSClassName + "'");
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Wrapping file system '" + this.wrappedFS.getClass().getName() + "' with scheme '"
                + this.wrappedFSScheme + "' as '" + getScheme() + "'.");
        LOG.debug("You can change it by setting '" + SFS_WRAPPED_FS_CLASS_NAME_KEY + "'.");
    }

    if (name.getAuthority() != null) {
        this.fileSystemUri = URI.create(getScheme() + "://" + name.getAuthority() + "/");
    } else {
        this.fileSystemUri = URI.create(getScheme() + ":///");
    }

    // Finally initialize the wrapped file system with the unwrapped name.
    URI wrappedFSUri = replaceUriScheme(name, getScheme(), this.wrappedFSScheme);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Initializing wrapped file system with URI '" + wrappedFSUri + "'.");
    }
    this.wrappedFS.initialize(wrappedFSUri, conf);

    // Add shutdown hook that closes this file system
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Running shutdown hook.");
            }

            try {
                StatisticsFileSystem.this.close(true);
            } catch (IOException e) {
                LOG.error("Could not close file system.", e);
            }
        }
    });

    String instrumentationSkip = getConf().get(SFS_INSTRUMENTATION_SKIP_KEY);
    if (instrumentationSkip != null) {
        this.skipRead = instrumentationSkip.contains("r");
        this.skipWrite = instrumentationSkip.contains("w");
        this.skipOther = instrumentationSkip.contains("o");
    }

    this.initialized = true;
}

From source file:co.cask.cdap.common.conf.Configuration.java

/**
 * Get the value of the <code>name</code> property as a <code>Class</code>
 * implementing the interface specified by <code>xface</code>.
 *
 * If no such property is specified, then <code>defaultValue</code> is
 * returned.// www.ja  v a2  s  .  co  m
 *
 * An exception is thrown if the returned class does not implement the named
 * interface.
 *
 * @param name the class name.
 * @param defaultValue default value.
 * @param xface the interface implemented by the named class.
 * @return property value as a <code>Class</code>,
 *         or <code>defaultValue</code>.
 */
public <U> Class<? extends U> getClass(String name, Class<? extends U> defaultValue, Class<U> xface) {
    try {
        Class<?> theClass = getClass(name, defaultValue);
        if (theClass != null && !xface.isAssignableFrom(theClass)) {
            throw new RuntimeException(theClass + " not " + xface.getName());
        } else if (theClass != null) {
            return theClass.asSubclass(xface);
        } else {
            return null;
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.kuali.rice.krms.impl.rule.AgendaEditorBusRule.java

@Override
protected boolean primaryKeyCheck(MaintenanceDocument document) {
    // default to success if no failures
    boolean success = true;
    Class<?> dataObjectClass = document.getNewMaintainableObject().getDataObjectClass();

    // Since the dataObject is a wrapper class we need to return the agendaBo instead.
    Object oldBo = ((AgendaEditor) document.getOldMaintainableObject().getDataObject()).getAgenda();
    Object newDataObject = ((AgendaEditor) document.getNewMaintainableObject().getDataObject()).getAgenda();

    // We dont do primaryKeyChecks on Global Business Object maintenance documents. This is
    // because it doesnt really make any sense to do so, given the behavior of Globals. When a
    // Global Document completes, it will update or create a new record for each BO in the list.
    // As a result, there's no problem with having existing BO records in the system, they will
    // simply get updated.
    if (newDataObject instanceof BulkUpdateMaintenanceDataObject) {
        return success;
    }/* w w  w . j av  a  2 s .c o m*/

    // fail and complain if the person has changed the primary keys on
    // an EDIT maintenance document.
    if (document.isEdit()) {
        if (!KRADServiceLocatorWeb.getLegacyDataAdapter().equalsByPrimaryKeys(oldBo, newDataObject)) {
            // add a complaint to the errors
            putDocumentError(KRADConstants.DOCUMENT_ERRORS,
                    RiceKeyConstants.ERROR_DOCUMENT_MAINTENANCE_PRIMARY_KEYS_CHANGED_ON_EDIT,
                    getHumanReadablePrimaryKeyFieldNames(dataObjectClass));
            success &= false;
        }
    }

    // fail and complain if the person has selected a new object with keys that already exist
    // in the DB.
    else if (document.isNew()) {

        // TODO: when/if we have standard support for DO retrieval, do this check for DO's
        if (newDataObject instanceof PersistableBusinessObject) {

            // get a map of the pk field names and values
            Map<String, ?> newPkFields = KRADServiceLocatorWeb.getLegacyDataAdapter()
                    .getPrimaryKeyFieldValues(newDataObject);

            // TODO: Good suggestion from Aaron, dont bother checking the DB, if all of the
            // objects PK fields dont have values. If any are null or empty, then
            // we're done. The current way wont fail, but it will make a wasteful
            // DB call that may not be necessary, and we want to minimize these.

            // attempt to do a lookup, see if this object already exists by these Primary Keys
            PersistableBusinessObject testBo = findSingleMatching(getDataObjectService(),
                    dataObjectClass.asSubclass(PersistableBusinessObject.class), newPkFields);

            // if the retrieve was successful, then this object already exists, and we need
            // to complain
            if (testBo != null) {
                putDocumentError(KRADConstants.DOCUMENT_ERRORS,
                        RiceKeyConstants.ERROR_DOCUMENT_MAINTENANCE_KEYS_ALREADY_EXIST_ON_CREATE_NEW,
                        getHumanReadablePrimaryKeyFieldNames(dataObjectClass));
                success &= false;
            }
        }
    }

    return success;
}