Example usage for java.lang Class getCanonicalName

List of usage examples for java.lang Class getCanonicalName

Introduction

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

Prototype

public String getCanonicalName() 

Source Link

Document

Returns the canonical name of the underlying class as defined by the Java Language Specification.

Usage

From source file:org.web4thejob.web.panel.DefaultListViewPanel.java

private String getDroppableTypes() {

    List<String> types = new ArrayList<String>();
    RenderScheme renderScheme = (RenderScheme) listbox.getAttribute(ListboxRenderer.ATTRIB_RENDER_SCHEME);
    if (renderScheme != null) {
        for (RenderElement renderElement : renderScheme.getElements()) {
            if (!renderElement.getPropertyPath().isMultiStep()
                    && renderElement.getPropertyPath().getLastStep().isAssociationType()) {
                Class<? extends Entity> entityType = renderElement.getPropertyPath().getLastStep()
                        .getAssociatedEntityMetadata().getEntityType();
                if (isMasterDetail()) {
                    if (!entityType.equals(getMasterType())) {
                        types.add(entityType.getCanonicalName());
                    }/* www .j  a va  2 s  .  com*/
                } else {
                    types.add(entityType.getCanonicalName());
                }
            }
        }
    }

    if (!types.isEmpty()) {
        return StringUtils.collectionToCommaDelimitedString(types);
    } else {
        return null;
    }
}

From source file:com.thinkbiganalytics.spark.validation.HCatDataType.java

private HCatDataType(Class clazz) {

    this.convertibleType = clazz;
    if (clazz == Date.class || clazz == Timestamp.class || clazz == byte[].class) {
        this.isnumeric = false;
    } else {//from   ww  w. j  a va  2s.c  o m
        this.isnumeric = true;
        BigDecimal minDecimal = new BigDecimal(Long.MIN_VALUE);
        BigDecimal maxDecimal = new BigDecimal(Long.MAX_VALUE);
        if (clazz == BigInteger.class) {
            this.min = minDecimal.toBigInteger();
            this.max = maxDecimal.toBigInteger();
        } else if (clazz == BigDecimal.class) {
            this.min = null;
            this.max = null;
        } else {
            throw new RuntimeException("Invalid class for constructor " + clazz.getCanonicalName());
        }
    }

}

From source file:gov.va.vinci.leo.ae.LeoBaseAnnotator.java

/**
 * Returns parameters defined in a static class named Param with static ConfigurationParameter objects.
 * <p/>//from w  w w.j  a  va 2 s  . c  o  m
 * For Example:
 * <p/>
 * <pre>
 * {@code
 * protected String parameterName = "parameter value";
 *
 * public static class Param {
 *      public static ConfigurationParameter PARAMETER_NAME
 *          = new ConfigurationParameterImpl(
 *              "parameterName", "Description", "String", false, true, new String[] {}
 *          );
 * }
 * }</pre>
 *
 * @return  the annotator parameters this annotator can accept.
 * @throws IllegalAccessException  if there is an exception trying to get annotator parameters via reflection.
 */
protected ConfigurationParameter[] getAnnotatorParams() throws IllegalAccessException {
    ConfigurationParameter params[] = null;

    for (Class c : this.getClass().getDeclaredClasses()) {
        if (c.isEnum() && Arrays.asList(c.getInterfaces()).contains(ConfigurationParameter.class)) {
            params = new ConfigurationParameter[EnumSet.allOf(c).size()];
            int counter = 0;
            for (Object o : EnumSet.allOf(c)) {
                params[counter] = ((ConfigurationParameter) o);
                counter++;
            }
            break;
        } else if (c.getCanonicalName().endsWith(".Param")) {
            Field[] fields = c.getFields();
            List<ConfigurationParameter> paramList = new ArrayList<ConfigurationParameter>();

            for (Field f : fields) {
                if (ConfigurationParameter.class.isAssignableFrom(f.getType())) {
                    paramList.add((ConfigurationParameter) f.get(null));
                }
            }
            params = paramList.toArray(new ConfigurationParameter[paramList.size()]);
        }
    }
    return params;
}

From source file:org.springjutsu.validation.namespace.ValidationEntityDefinitionParser.java

/**
 * Parses nested validation rule and template-ref structures
 * @param ruleNode the ValidationRule node
 * @param modelClass the model class/*from ww  w  . j av  a2 s  . c  o  m*/
 * @return a @link{ValidationStructure} object whose
 *  nested rules and template references are those
 *  rules and template references stemming from the ruleNode.
 */
protected ValidationStructure parseNestedValidation(Element ruleNode, Class<?> modelClass) {

    ValidationStructure structure = new ValidationStructure();

    if (ruleNode == null) {
        return structure;
    }

    List<Element> validationRuleNodes = DomUtils.getChildElementsByTagName(ruleNode, "rule");

    if (validationRuleNodes != null) {
        for (Element rule : validationRuleNodes) {
            String path = rule.getAttribute("path");
            if (path != null && path.length() > 0 && !path.contains("${")
                    && !PathUtils.pathExists(modelClass, path)) {
                throw new ValidationParseException(
                        "Path \"" + path + "\" does not exist on class " + modelClass.getCanonicalName());
            }
            String type = rule.getAttribute("type");
            String value = rule.getAttribute("value");
            String message = rule.getAttribute("message");
            String errorPath = rule.getAttribute("errorPath");
            String collectionStrategy = rule.getAttribute("collectionStrategy");
            String onFail = rule.getAttribute("onFail");
            ValidationRule validationRule = new ValidationRule(path, type, value);
            validationRule.setMessage(message);
            validationRule.setErrorPath(errorPath);
            validationRule.setCollectionStrategy(CollectionStrategy.forXmlValue(collectionStrategy));
            validationRule.setOnFail(RuleErrorMode.forXmlValue(onFail));
            ValidationStructure subStructure = parseNestedValidation(rule, modelClass);
            validationRule.setRules(subStructure.rules);
            validationRule.setTemplateReferences(subStructure.refs);
            validationRule.setValidationContexts(subStructure.contexts);
            structure.rules.add(validationRule);
        }
    }

    List<Element> validationTemplateReferenceNodes = DomUtils.getChildElementsByTagName(ruleNode,
            "template-ref");

    if (validationTemplateReferenceNodes != null) {
        for (Element templateReference : validationTemplateReferenceNodes) {
            String basePath = templateReference.getAttribute("basePath");
            if (basePath != null && basePath.length() > 0 && !basePath.contains("${")
                    && !PathUtils.pathExists(modelClass, basePath)) {
                throw new ValidationParseException(
                        "Path \"" + basePath + "\" does not exist on class " + modelClass.getCanonicalName());
            }
            String templateName = templateReference.getAttribute("templateName");
            ValidationTemplateReference templateRef = new ValidationTemplateReference(basePath, templateName);
            structure.refs.add(templateRef);
        }
    }

    List<Element> formNodes = DomUtils.getChildElementsByTagName(ruleNode, "form");
    if (formNodes != null) {
        for (Element formNode : formNodes) {

            // get form paths.
            String formPaths = formNode.getAttribute("path");
            Set<String> formConstraints = new HashSet<String>();
            for (String formPath : formPaths.split(",")) {
                String candidateFormPath = formPath.trim();
                candidateFormPath = RequestUtils.removeLeadingAndTrailingSlashes(candidateFormPath).trim();
                if (!candidateFormPath.isEmpty()) {
                    formConstraints.add(candidateFormPath);
                }
            }

            ValidationContext formContext = new ValidationContext();
            formContext.setType("form");

            ValidationContext flowContext = new ValidationContext();
            flowContext.setType("webflow");

            for (String formConstraint : formConstraints) {
                if (formConstraint.contains(":")) {
                    flowContext.getQualifiers().add(formConstraint);
                } else {
                    formContext.getQualifiers().add(formConstraint);
                }
            }

            // get rules & templates.
            ValidationStructure formSpecificValidationStructure = parseNestedValidation(formNode, modelClass);
            formContext.setRules(formSpecificValidationStructure.rules);
            formContext.setTemplateReferences(formSpecificValidationStructure.refs);
            formContext.setValidationContexts(formSpecificValidationStructure.contexts);
            flowContext.setRules(formSpecificValidationStructure.rules);
            flowContext.setTemplateReferences(formSpecificValidationStructure.refs);
            flowContext.setValidationContexts(formSpecificValidationStructure.contexts);

            if (!formContext.getQualifiers().isEmpty()) {
                structure.contexts.add(formContext);
            }
            if (!flowContext.getQualifiers().isEmpty()) {
                structure.contexts.add(flowContext);
            }
        }
    }

    List<Element> groupNodes = DomUtils.getChildElementsByTagName(ruleNode, "group");
    if (groupNodes != null) {
        for (Element groupNode : groupNodes) {

            // get form paths.
            String groupQualifiers = groupNode.getAttribute("qualifiers");
            Set<String> groupConstraints = new HashSet<String>();
            for (String qualifier : groupQualifiers.split(",")) {
                groupConstraints.add(qualifier.trim());
            }

            ValidationContext groupContext = new ValidationContext();
            groupContext.setType("group");
            groupContext.setQualifiers(groupConstraints);

            // get rules & templates.
            ValidationStructure groupSpecificValidationStructure = parseNestedValidation(groupNode, modelClass);
            groupContext.setRules(groupSpecificValidationStructure.rules);
            groupContext.setTemplateReferences(groupSpecificValidationStructure.refs);
            groupContext.setValidationContexts(groupSpecificValidationStructure.contexts);
            structure.contexts.add(groupContext);
        }
    }

    List<Element> contextNodes = DomUtils.getChildElementsByTagName(ruleNode, "context");
    if (contextNodes != null) {
        for (Element contextNode : contextNodes) {

            // get form paths.
            String contextQualifiers = contextNode.getAttribute("qualifiers");
            Set<String> contextConstraints = new HashSet<String>();
            for (String qualifier : contextQualifiers.split(",")) {
                contextConstraints.add(qualifier.trim());
            }

            ValidationContext context = new ValidationContext();
            context.setType(contextNode.getAttribute("type"));
            context.setQualifiers(contextConstraints);

            // get rules & templates.
            ValidationStructure contextSpecificValidationStructure = parseNestedValidation(contextNode,
                    modelClass);
            context.setRules(contextSpecificValidationStructure.rules);
            context.setTemplateReferences(contextSpecificValidationStructure.refs);
            context.setValidationContexts(contextSpecificValidationStructure.contexts);
            structure.contexts.add(context);
        }
    }

    return structure;
}

From source file:uk.co.techblue.alfresco.client.Service.java

/**
 * Validate response success.//from  ww  w. ja  va2 s  .c  o  m
 * 
 * @param <EX> the generic type
 * @param clientResponse the client response
 * @param exceptionClazz the exception clazz
 * @throws EX the eX
 */
protected <EX extends AlfrescoServiceException> void validateResponseSuccess(
        final ClientResponse<?> clientResponse, final Class<EX> exceptionClazz) throws EX {
    final Family statusFamily = getStatusFamily(clientResponse);
    if (statusFamily != Family.SUCCESSFUL) {
        Object errorResponse = null;
        Exception cause = null;
        try {
            // String error = clientResponse.getEntity(String.class);
            errorResponse = clientResponse.getEntity(ServiceResponse.class);
            if (errorResponse == null) {
                errorResponse = clientResponse.getEntity(String.class);
            }
        } catch (final ClientResponseFailure clientResponseFailure) {
            cause = clientResponseFailure;
        }
        EX exception = null;
        final String genericErrorMsg = "Error occurred while creating new instance of exception class of type "
                + exceptionClazz.getCanonicalName() + " to throw the following error:\n" + errorResponse;
        try {
            if (cause != null) {
                exception = exceptionClazz.getConstructor(String.class, Throwable.class).newInstance(
                        "An error occurred while fetching entity from HTTP response:\n" + errorResponse, cause);
            } else {
                exception = exceptionClazz.getConstructor(String.class)
                        .newInstance("Request processing failed.\n HTTP Status: "
                                + clientResponse.getResponseStatus() + "\n HTTP Status Code:"
                                + clientResponse.getStatus() + " \n Error:" + errorResponse);
            }
            if (exception != null && errorResponse instanceof ServiceResponse) {
                exception.setErrorResponse((ServiceResponse) errorResponse);
            }
        } catch (final IllegalArgumentException illegalArgumentException) {
            throw new IllegalStateException(genericErrorMsg, illegalArgumentException);
        } catch (final SecurityException securityException) {
            throw new IllegalStateException(genericErrorMsg, securityException);
        } catch (final InstantiationException instantiationException) {
            throw new IllegalStateException(genericErrorMsg, instantiationException);
        } catch (final IllegalAccessException illegalAccessException) {
            throw new IllegalStateException(genericErrorMsg, illegalAccessException);
        } catch (final InvocationTargetException invocationTargetException) {
            throw new IllegalStateException(genericErrorMsg, invocationTargetException);
        } catch (final NoSuchMethodException noSuchMethodException) {
            throw new IllegalStateException(genericErrorMsg, noSuchMethodException);
        }
        throw exception;
    }
}

From source file:net.nicholaswilliams.java.licensing.licensor.interfaces.cli.ConsoleLicenseGenerator.java

private <T> T getObjectAsClass(String className, Class<T> castClass) {
    try {/*from w w w.j a va  2  s  .  com*/
        Class<?> objectClass = Class.forName(className);
        return objectClass.asSubclass(castClass).newInstance();
    } catch (ClassNotFoundException e) {
        throw new RuntimeException("The class [" + className + "] could not be located.");
    } catch (ClassCastException e) {
        throw new RuntimeException("The class [" + className + "] does not implement interface ["
                + castClass.getCanonicalName() + "].");
    } catch (Exception e) {
        throw new RuntimeException("Unable to instantiate class [" + className + "].", e);
    }
}

From source file:com.elastica.helper.FileUtility.java

public static void extractJar(final String storeLocation, final Class<?> clz) throws IOException {
    File firefoxProfile = new File(storeLocation);
    String location = clz.getProtectionDomain().getCodeSource().getLocation().getFile();

    JarFile jar = new JarFile(location);
    System.out.println("Extracting jar file::: " + location);
    firefoxProfile.mkdir();/*from w  ww .ja v  a  2s .c o m*/

    Enumeration<?> jarFiles = jar.entries();
    while (jarFiles.hasMoreElements()) {
        ZipEntry entry = (ZipEntry) jarFiles.nextElement();
        String currentEntry = entry.getName();
        File destinationFile = new File(storeLocation, currentEntry);
        File destinationParent = destinationFile.getParentFile();

        // create the parent directory structure if required
        destinationParent.mkdirs();
        if (!entry.isDirectory()) {
            BufferedInputStream is = new BufferedInputStream(jar.getInputStream(entry));
            int currentByte;

            // buffer for writing file
            byte[] data = new byte[BUFFER];

            // write the current file to disk
            FileOutputStream fos = new FileOutputStream(destinationFile);
            BufferedOutputStream destination = new BufferedOutputStream(fos, BUFFER);

            // read and write till last byte
            while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
                destination.write(data, 0, currentByte);
            }

            destination.flush();
            destination.close();
            is.close();
        }
    }

    FileUtils.deleteDirectory(new File(storeLocation + "\\META-INF"));
    if (OSUtility.isWindows()) {
        new File(storeLocation + "\\" + clz.getCanonicalName().replaceAll("\\.", "\\\\") + ".class").delete();
    } else {
        new File(storeLocation + "/" + clz.getCanonicalName().replaceAll("\\.", "/") + ".class").delete();
    }
}

From source file:com.ctriposs.rest4j.internal.server.model.ResourceModelEncoder.java

private void appendCommon(final ResourceModel resourceModel, final ResourceSchema resourceSchema) {
    resourceSchema.setName(resourceModel.getName());
    if (!resourceModel.getNamespace().isEmpty()) {
        resourceSchema.setNamespace(resourceModel.getNamespace());
    }/* w  w w .j ava  2s  .  c o  m*/
    resourceSchema.setPath(buildPath(resourceModel));

    final Class<?> valueClass = resourceModel.getValueClass();
    if (valueClass != null) {
        resourceSchema.setSchema(DataTemplateUtil.getSchema(valueClass).getUnionMemberKey());
    }

    final Class<?> resourceClass = resourceModel.getResourceClass();
    final String doc = _docsProvider.getClassDoc(resourceClass);
    final StringBuilder docBuilder = new StringBuilder();
    if (doc != null) {
        docBuilder.append(doc).append("\n\n");
    }
    docBuilder.append("generated from: ").append(resourceClass.getCanonicalName());

    final String deprecatedDoc = _docsProvider.getClassDeprecatedTag(resourceClass);
    if (deprecatedDoc != null) {
        DataMap customAnnotationData = resourceModel.getCustomAnnotationData();
        if (customAnnotationData == null) {
            customAnnotationData = new DataMap();
            resourceModel.setCustomAnnotation(customAnnotationData);
        }
        customAnnotationData.put(DEPRECATED_ANNOTATION_NAME, deprecateDocToAnnotationMap(deprecatedDoc));
    }

    resourceSchema.setDoc(docBuilder.toString());
}

From source file:com.xiovr.unibot.bot.impl.BotGameConfigImpl.java

private Properties createSettings(Class<?> clazz, String fn, String comment) {

    Properties props = new SortedProperties();
    try {/*from   ww  w. ja  va  2s  .  c om*/
        //         File file = new File("/" + DIR_PATH + "/" + fn);
        File file = new File(fn);
        Method[] methods = clazz.getMethods();
        for (Method method : methods) {
            // Find setters
            if (method.getName().startsWith("set")) {
                if (method.isAnnotationPresent(Param.class)) {
                    Annotation annotation = method.getAnnotation(Param.class);
                    Param param = (Param) annotation;
                    if (param.name().equals("") || param.values().length == 0) {
                        throw new RuntimeException("Wrong param in class " + clazz.getCanonicalName()
                                + " with method " + method.getName());
                    }
                    Class<?>[] paramClazzes = method.getParameterTypes();
                    if (paramClazzes.length != 1) {
                        throw new RuntimeException("Error contract design in class " + clazz.getCanonicalName()
                                + " with method " + method.getName());
                    }
                    // Check param belongs to List
                    Class<?> paramClazz = paramClazzes[0];
                    if (List.class.isAssignableFrom(paramClazz)) {
                        // Oh, its array...
                        // May be its InetSocketAddress?
                        Type[] gpt = method.getGenericParameterTypes();
                        if (gpt[0] instanceof ParameterizedType) {
                            ParameterizedType type = (ParameterizedType) gpt[0];
                            Type[] typeArguments = type.getActualTypeArguments();

                            for (Type typeArgument : typeArguments) {
                                Class<?> classType = ((Class<?>) typeArgument);
                                if (InetSocketAddress.class.isAssignableFrom(classType)) {
                                    String[] vals = param.values();
                                    for (int i = 0; i < vals.length / 2; ++i) {
                                        props.setProperty(param.name() + "." + String.valueOf(i) + ".ip",
                                                vals[i * 2]);
                                        props.setProperty(param.name() + "." + String.valueOf(i) + ".port",
                                                vals[i * 2 + 1]);
                                    }
                                    props.setProperty(param.name() + ".count", String.valueOf(vals.length / 2));

                                } else {
                                    throw new RuntimeException("Settings param in class "
                                            + clazz.getCanonicalName() + " with method " + method.getName()
                                            + " not implementes yet");
                                }
                            }

                        }
                    } else if (paramClazz.isPrimitive()) {
                        props.setProperty(param.name(), param.values()[0]);

                    } else if (String.class.isAssignableFrom(paramClazz)) {

                        props.setProperty(param.name(), param.values()[0]);

                    } else {
                        throw new RuntimeException("Settings param in class " + clazz.getCanonicalName()
                                + " with method " + method.getName() + " not implemented yet");
                    }

                }
            }
        }

        BotUtils.saveProperties(file, props, comment);
    } catch (IOException e) {
        logger.error("Error save file " + fn);
    }
    return props;
}

From source file:adalid.core.programmers.AbstractJavaProgrammer.java

@Override
public String getJavaTypeCanonicalName(Artifact artifact) {
    Class<?> dataType = getDataType(artifact);
    return dataType == null ? null : dataType.getCanonicalName();
}