Example usage for java.lang String getClass

List of usage examples for java.lang String getClass

Introduction

In this page you can find the example usage for java.lang String getClass.

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:com.stormpath.spring.security.example.controller.CustomDataManager.java

private void addField(CustomData customData, String key, String value) {
    Object existingValue = customData.get(key);
    if (existingValue == null) {
        customData.put(key, value);//from   w w w. jav a2s  .  c om
    } else if (existingValue instanceof String) {
        Set<String> set = new LinkedHashSet<String>();
        set.add((String) existingValue);
        set.add(value);
        customData.put(key, set);
    } else if (existingValue instanceof List) {
        ((List) existingValue).add(value);
        customData.put(key, existingValue);
    } else {
        String msg = "Unable to recognize CustomData field '" + key + "' value of type "
                + value.getClass().getName() + ".  Expected type: String or List<String>";
        throw new IllegalArgumentException(msg);
    }
    customData.save();
}

From source file:microsoft.exchange.webservices.data.property.complex.UserConfigurationDictionary.java

/**
 * Loads an entry, consisting of a key value pair, into this dictionary from
 * the specified reader.//from  ww w.  j a v a  2  s . c  o  m
 *
 * @param reader The reader.
 * @throws Exception the exception
 */
private void loadEntry(EwsServiceXmlReader reader) throws Exception {
    EwsUtilities.ewsAssert(reader != null, "UserConfigurationDictionary.LoadEntry", "reader is null");

    Object key;
    Object value = null;

    // Position at DictionaryKey
    reader.readStartElement(this.getNamespace(), XmlElementNames.DictionaryKey);

    key = this.getDictionaryObject(reader);

    // Position at DictionaryValue
    reader.readStartElement(this.getNamespace(), XmlElementNames.DictionaryValue);

    String nil = reader.readAttributeValue(XmlNamespace.XmlSchemaInstance, XmlAttributeNames.Nil);
    boolean hasValue = (nil == null) || (!nil.getClass().equals(Boolean.TYPE));
    if (hasValue) {
        value = this.getDictionaryObject(reader);
    }
    this.dictionary.put(key, value);
}

From source file:org.openmeetings.app.data.basic.Configurationmanagement.java

/**
 * Return a object using a custom type and a default value if the key is not present
 * //from   ww w . j  a  v a  2  s  .c  o m
 * Example: Integer my_key = getConfValue("my_key", Integer.class, "15");
 * 
 * @param CONF_KEY
 * @param typeObject
 * @param defaultValue
 * @return
 */
public <T> T getConfValue(String CONF_KEY, Class<T> typeObject, String defaultValue) {
    try {
        Configuration conf_reminder = getConfKey(3L, CONF_KEY);

        if (conf_reminder == null) {
            log.warn("Could not find key in configuration CONF_KEY: " + CONF_KEY);
        } else {
            // Use the custom value as default value
            defaultValue = conf_reminder.getConf_value();
        }

        // Either this can be directly assigned or try to find a constructor
        // that handles it
        if (typeObject.isAssignableFrom(defaultValue.getClass())) {
            return typeObject.cast(defaultValue);
        }
        Constructor<T> c = typeObject.getConstructor(defaultValue.getClass());
        return c.newInstance(defaultValue);

    } catch (Exception err) {
        log.error("cannot be cast to return type, you have misconfigured your configuration CONF_KEY: "
                + CONF_KEY, err);
        return null;
    }
}

From source file:com.quinsoft.zeidon.utils.JoeUtils.java

/**
 * Returns an input stream for a resource/filename.  Logic will first attempt to find
 * a filename that matches the resourceName (search is case-insensitive).  If a file
 * is found, the stream is for the file.
 *
 * If a file is not found, an attempt is made to find the resource on the classpath.
 *
 * @param task - If not null then the ZEIDON_HOME directory will be searched if all
 *                other attempts fail.//from w  w  w  . j  a va 2 s.  c om
 * @param resourceName - Name of resource to open.
 * @param classLoader - ClassLoader used to find resources.  If null then the system
 *                class loader is used.
 *
 * @return the InputStream or null if it wasn't found.
 */
public static ZeidonInputStream getInputStream(Task task, String resourceName, ClassLoader classLoader) {
    // If the resourceName contains a '|' then it is a list of resources.  We'll return the first
    // one that is valid.
    String[] resourceList = PIPE_DELIMITER.split(resourceName);
    if (resourceList.length > 1) {
        for (String resource : resourceList) {
            ZeidonInputStream stream = getInputStream(task, resource.trim(), classLoader);
            if (stream != null)
                return stream;
        }

        // If we get here then none of the resources in the list were found so return null.
        return null;
    }

    try {
        //
        // Default is to assume resourceName is a filename.
        //
        File file = getFile(resourceName);
        if (file.exists())
            return ZeidonInputStream.create(file);

        if (classLoader == null) {
            if (task != null)
                classLoader = task.getClass().getClassLoader();
            if (classLoader == null)
                classLoader = new JoeUtils().getClass().getClassLoader();
            if (classLoader == null)
                classLoader = resourceName.getClass().getClassLoader();
            if (classLoader == null)
                classLoader = ClassLoader.getSystemClassLoader();
        }

        //
        // Try loading as a resource (e.g. from a .jar).
        //
        int count = 0;
        ZeidonInputStream stream = null;
        URL prevUrl = null;
        String md5hash = null;
        for (Enumeration<URL> url = classLoader.getResources(resourceName); url.hasMoreElements();) {
            URL element = url.nextElement();
            if (task != null)
                task.log().debug("Found resource at " + element);
            else
                LOG.debug("--Found resource at " + element);

            count++;
            if (count > 1) {
                // We'll allow duplicate resources if they have the same MD5 hash.
                if (md5hash == null)
                    md5hash = computeHash(prevUrl);

                if (!md5hash.equals(computeHash(element)))
                    throw new ZeidonException("Found multiple different resources that match resourceName %s",
                            resourceName);

                if (task != null)
                    task.log().warn(
                            "Multiple, identical resources found of %s.  This usually means your classpath has duplicates",
                            resourceName);
                else
                    LOG.warn("Multiple, identical resources found of " + resourceName
                            + " This usually means your classpath has duplicates");

            }

            stream = ZeidonInputStream.create(element);
            prevUrl = element;
        }

        if (stream != null)
            return stream;

        //
        // Try loading as a lower-case resource name.
        //
        String name = FilenameUtils.getName(resourceName);
        if (StringUtils.isBlank(name))
            return null;

        String path = FilenameUtils.getPath(resourceName);
        String newName;
        if (StringUtils.isBlank(path))
            newName = name.toLowerCase();
        else
            newName = path + name.toLowerCase();

        stream = ZeidonInputStream.create(classLoader, newName);
        if (stream != null)
            return stream;

        // If task is null then we don't know anything else to try.
        if (task == null)
            return null;

        //
        // Try loading with ZEIDON_HOME prefix.
        //
        newName = task.getObjectEngine().getHomeDirectory() + "/" + resourceName;
        file = getFile(newName);
        if (file.exists())
            return ZeidonInputStream.create(file);

        return null;
    } catch (Exception e) {
        throw ZeidonException.wrapException(e).prependFilename(resourceName);
    }
}

From source file:org.wso2.carbon.event.adapter.rabbitmq.internal.util.RabbitMQOutputEventAdapterPublisher.java

public void publish(String payload, String exchange) {

    LOGGER.debug("*** DEBUG RabbitMQOutputEventAdapterPublisher().publish()");

    try {//  www  .  j a v  a 2s  .  co  m
        //create Queue
        createQueue(exchange);
        // Create and configure a message
        if (payload instanceof String) {
            channel.basicPublish("", queue, MessageProperties.PERSISTENT_TEXT_PLAIN,
                    ((String) payload).getBytes());
        } else {
            channel.basicPublish("", queue, MessageProperties.PERSISTENT_TEXT_PLAIN,
                    payload.toString().getBytes());
        }
        LOGGER.debug("*** DEBUG: [x] Sent " + payload.getClass() + " type, '" + payload + "'");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.pentaho.platform.repository.runtime.RuntimeElement.java

/**
 * Sets a property into the paramMap. Special implementation note - Null values aren't supported in the Map. So,
 * if a null value is passed in, this implementation will remove the entry from the map.
 * //from  w  w w .  j a  v  a 2  s.  c  o m
 * @param key
 *          The key into the map.
 * @param value
 *          The value to set.
 */
public void setStringProperty(final String key, final String value) {
    this.updateOk();
    trace(Messages.getInstance().getString("RTREPO.DEBUG_PROPERTY_GETSET", "setString", key)); //$NON-NLS-1$ //$NON-NLS-2$
    checkType(key, value.getClass().getName(), true);
    Map theMapSS = getParamMapSS();
    Map theMapLS = getParamMapLS();
    if (value != null) {
        if (value.length() > RuntimeElement.MAXSSLENGH) {
            theMapSS.remove(key); // Make sure it's not in the short map
            // first.
            theMapLS.put(key, new StringBuffer(value));
        } else {
            theMapLS.remove(key);
            theMapSS.put(key, value);
        }
    } else {
        theMapSS.remove(key);
        theMapLS.remove(key);
    }
}

From source file:com.cloudbees.plugins.credentials.CredentialsProvider.java

/**
 * A common requirement for plugins is to resolve a specific credential by id in the context of a specific run.
 * Given that the credential itself could be resulting from a build parameter expression and the complexities of
 * determining the scope of items from which the credential should be resolved in a chain of builds, this method
 * provides the correct answer.//from ww w .j a va2  s .c  o  m
 *
 * @param id                 either the id of the credential to find or a parameter expression for the id.
 * @param type               the type of credential to find.
 * @param run                the {@link Run} defining the context within which to find the credential.
 * @param domainRequirements the domain requirements of the credential.
 * @param <C>                the credentials type.
 * @return the credential or {@code null} if either the credential cannot be found or the user triggering the run
 * is not permitted to use the credential in the context of the run.
 * @since 1.16
 */
@CheckForNull
public static <C extends IdCredentials> C findCredentialById(@NonNull String id, @NonNull Class<C> type,
        @NonNull Run<?, ?> run, @Nullable List<DomainRequirement> domainRequirements) {
    id.getClass(); // throw NPE if null;
    type.getClass(); // throw NPE if null;
    run.getClass(); // throw NPE if null;

    // first we need to find out if this id is pre-selected or a parameter
    id = id.trim();
    boolean isParameter = false;
    boolean isDefaultValue = false;
    if (id.startsWith("${") && id.endsWith("}")) {
        final ParametersAction action = run.getAction(ParametersAction.class);
        if (action != null) {
            final ParameterValue parameter = action.getParameter(id.substring(2, id.length() - 1));
            if (parameter instanceof CredentialsParameterValue) {
                isParameter = true;
                isDefaultValue = ((CredentialsParameterValue) parameter).isDefaultValue();
                id = ((CredentialsParameterValue) parameter).getValue();
            }
        }
    }
    // non parameters or default parameter values can only come from the job's context
    if (!isParameter || isDefaultValue) {
        // we use the default authentication of the job as those are the only ones that can be configured
        // if a different strategy is in play it doesn't make sense to consider the run-time authentication
        // as you would have no way to configure it
        Authentication runAuth = CredentialsProvider.getDefaultAuthenticationOf(run.getParent());
        List<C> candidates = new ArrayList<C>();
        // we want the credentials available to the user the build is running as
        candidates.addAll(
                CredentialsProvider.lookupCredentials(type, run.getParent(), runAuth, domainRequirements));
        // if that user can use the item's credentials, add those in too
        if (runAuth != ACL.SYSTEM && run.getACL().hasPermission(runAuth, CredentialsProvider.USE_ITEM)) {
            candidates.addAll(CredentialsProvider.lookupCredentials(type, run.getParent(), ACL.SYSTEM,
                    domainRequirements));
        }
        return CredentialsMatchers.firstOrNull(candidates, CredentialsMatchers.withId(id));
    }
    // this is a parameter and not the default value, we need to determine who triggered the build
    final Map.Entry<User, Run<?, ?>> triggeredBy = triggeredBy(run);
    final Authentication a = triggeredBy == null ? Jenkins.ANONYMOUS : triggeredBy.getKey().impersonate();
    List<C> candidates = new ArrayList<C>();
    if (triggeredBy != null && run == triggeredBy.getValue()
            && run.getACL().hasPermission(a, CredentialsProvider.USE_OWN)) {
        // the user triggered this job directly and they are allowed to supply their own credentials, so
        // add those into the list. We do not want to follow the chain for the user's authentication
        // though, as there is no way to limit how far the passed-through parameters can be used
        candidates.addAll(CredentialsProvider.lookupCredentials(type, run.getParent(), a, domainRequirements));
    }
    if (run.getACL().hasPermission(a, CredentialsProvider.USE_ITEM)) {
        // the triggering user is allowed to use the item's credentials, so add those into the list
        // we use the default authentication of the job as those are the only ones that can be configured
        // if a different strategy is in play it doesn't make sense to consider the run-time authentication
        // as you would have no way to configure it
        Authentication runAuth = CredentialsProvider.getDefaultAuthenticationOf(run.getParent());
        // we want the credentials available to the user the build is running as
        candidates.addAll(
                CredentialsProvider.lookupCredentials(type, run.getParent(), runAuth, domainRequirements));
        // if that user can use the item's credentials, add those in too
        if (runAuth != ACL.SYSTEM && run.getACL().hasPermission(runAuth, CredentialsProvider.USE_ITEM)) {
            candidates.addAll(CredentialsProvider.lookupCredentials(type, run.getParent(), ACL.SYSTEM,
                    domainRequirements));
        }
    }
    C result = CredentialsMatchers.firstOrNull(candidates, CredentialsMatchers.withId(id));
    // if the run has not completed yet then we can safely assume that the credential is being used for this run
    // so we will track it's usage. We use isLogUpdated() as it could be used during post production
    return run.isLogUpdated() ? track(run, result) : result;
}

From source file:org.wso2.carbon.identity.entitlement.EntitlementAdminService.java

/**
 * Clears the cache maintained by the resource finder.
 *
 * @param resourceFinder Canonical name of the resource finder class.
 */// www . ja  v a  2  s. co  m
public void clearResourceFinderCache(String resourceFinder) {

    Map<PIPResourceFinder, Properties> resourceConfigs = EntitlementServiceComponent.getEntitlementConfig()
            .getResourceFinders();
    if (resourceConfigs != null && !resourceConfigs.isEmpty()) {
        Set<PIPResourceFinder> resourceFinders = resourceConfigs.keySet();
        for (PIPResourceFinder pipResourceFinder : resourceFinders) {
            if (resourceFinder.getClass().getCanonicalName().equals(resourceFinder)) {
                pipResourceFinder.clearCache();
                break;
            }
        }
    }
}

From source file:org.wso2.carbon.analytics.spark.core.internal.AnalyticsPersistenceManager.java

/**
 * Return all the scripts in the tenant registry space.
 *
 * @param tenantId Id of the tenant./*w w w.  j  a va  2  s  .c om*/
 * @return List of analytics scripts.
 * @throws AnalyticsPersistenceException
 */
public List<AnalyticsScript> getAllAnalyticsScripts(int tenantId) throws AnalyticsPersistenceException {
    try {
        UserRegistry registry = ServiceHolder.getTenantConfigRegistry(tenantId);
        createScriptsCollectionIfNotExists(registry);
        Collection scriptsCollection = (Collection) registry.get(AnalyticsConstants.ANALYTICS_SCRIPTS_LOCATION);
        String[] scripts = scriptsCollection.getChildren();
        if (scripts != null) {
            List<AnalyticsScript> analyticsScripts = new ArrayList<>();
            for (String script : scripts) {
                Object content = registry.get(script).getContent();
                if (content instanceof byte[]) {
                    String configContent = RegistryUtils.decodeBytes((byte[]) content);
                    analyticsScripts.add(getAnalyticsScript(configContent));
                } else {
                    log.error("Failed to load the configuration at: " + script + " for tenant: " + tenantId
                            + ". Resource not in valid format. Required byte[] but found "
                            + script.getClass().getCanonicalName());
                }
            }
            return analyticsScripts;
        }
        return null;
    } catch (RegistryException e) {
        throw new AnalyticsPersistenceException("Error while loading the registry for tenant : " + tenantId, e);
    } catch (JAXBException e) {
        throw new AnalyticsPersistenceException(
                "Error while loading the configuration for scripts for tenant: " + tenantId, e);
    }
}

From source file:org.overlord.rtgov.common.elasticsearch.ElasticsearchClient.java

/**
 * This method adds a new document to ElasticSearch.
 *
 * @param id       The id/*from ww w .  j ava2  s. c  om*/
 * @param document The document
 * @throws Exception Failed to add
 */
public void add(String id, String document) throws Exception {
    if (LOG.isLoggable(Level.FINEST)) {
        LOG.finest(" Adding to elastich search id=" + id + ", doc=" + document);
    }
    if (LOG.isLoggable(Level.FINEST)) {
        LOG.finest("Adding " + document.getClass().toString() + ". for id " + id);
    }
    if (getBulkSize() > 0) {
        addBulk(id, document);
    } else {
        try {
            IndexResponse indexResponse = _client.prepareIndex(_index, _type, id).setSource(document).execute()
                    .actionGet();
            if (!indexResponse.isCreated()) {
                if (LOG.isLoggable(Level.FINE)) {
                    LOG.fine(" Document could not be created for index [" + _index + "/" + _type + "/" + id
                            + "]");
                }
                throw new Exception(
                        "Document could not be created for index [" + _index + "/" + _type + "/" + id + "]");
            }

            if (LOG.isLoggable(Level.FINE)) {
                LOG.fine(" Document successfully created for index [" + _index + "/" + _type + "/" + id + "]");
            }

        } catch (Exception e) {
            LOG.log(Level.SEVERE, "[/" + _index + "/" + _type + "] Could not store json document", e);
            throw new Exception("[/" + _index + "/" + _type + "] Could not store json document", e);
        }
    }
}