List of usage examples for java.lang Class getCanonicalName
public String getCanonicalName()
From source file:info.archinnov.achilles.internal.metadata.parsing.EmbeddedIdParser.java
private int validateNoDuplicateOrderAndType(String embeddedIdClassName, Set<Integer> orders, int orderSum, int order, Class<?> componentType) { log.debug("Validate type and component ordering for embedded id class {} ", embeddedIdClassName); Validator.validateBeanMappingTrue(orders.add(order), "The order '%s' is duplicated in @EmbeddedId class '%s'", order, embeddedIdClassName); orderSum += order;//from w w w . ja va 2s . c o m PropertyParsingValidator.validateAllowedTypes(componentType, PropertyParser.allowedTypes, "The class '" + componentType.getCanonicalName() + "' is not a valid component type for the @EmbeddedId class '" + embeddedIdClassName + "'"); return orderSum; }
From source file:de.decoit.simu.cbor.ifmap.deserializer.ExtendedIdentifierDeserializerManager.java
/** * Deserialize an object of the specified class from the specified data items. * The attributes and nested tags arrays may be empty but never null. * * @param <T> Type of the object to be deserialized, must be a subclass of {@link AbstractExtendedIdentifier} * @param namespace CBOR data item representing the element namespace * @param cborName CBOR data item representing the element name * @param attributes CBOR array data item containing the element's attributes * @param nestedTags CBOR array data item containing the element's nested tags * @param identifierType Type of the object to be deserialized * @return The deserialized object/*from w w w . j ava 2 s . co m*/ * @throws CBORDeserializationException if deserialization failed */ public static <T extends AbstractExtendedIdentifier> T deserialize(final DataItem namespace, final DataItem cborName, final Array attributes, final Array nestedTags, final Class<T> identifierType) throws CBORDeserializationException { if (namespace == null) { throw new IllegalArgumentException("Namespace must not be null"); } if (cborName == null) { throw new IllegalArgumentException("CBOR name must not be null"); } if (attributes == null) { throw new IllegalArgumentException("Attributes array must not be null"); } if (nestedTags == null) { throw new IllegalArgumentException("Nested tags array must not be null"); } if (identifierType == null) { throw new IllegalArgumentException("Target identifier type must not be null"); } try { // If default deserializers were not registered yet, do so if (!initialized) { init(); } // Check if a deserializer for this type was registered if (hasVendorDeserializer(identifierType)) { DictionarySimpleElement elementEntry = getTopLevelElement(namespace, cborName); return identifierType.cast(registeredDeserializers.get(identifierType).deserialize(attributes, nestedTags, elementEntry)); } // If no deserializer was found, fail with exception throw new UnsupportedOperationException( "Cannot deserialize class: " + identifierType.getCanonicalName()); } catch (RuntimeException ex) { throw new CBORDeserializationException( "RuntimeException during deserialization, see nested exception" + "for details", ex); } }
From source file:com.nxttxn.vramel.impl.converter.AnnotationTypeConverterLoader.java
private CachingInjector<?> handleHasFallbackConverterAnnotation(TypeConverterRegistry registry, Class<?> type, CachingInjector<?> injector, Method method) { if (isValidFallbackConverterMethod(method)) { int modifiers = method.getModifiers(); if (isAbstract(modifiers) || !isPublic(modifiers)) { LOG.warn("Ignoring bad fallback converter on type: " + type.getCanonicalName() + " method: " + method + " as a fallback converter method is not a public and concrete method"); } else {//from w ww. ja v a 2 s . com Class<?> toType = method.getReturnType(); if (toType.equals(Void.class)) { LOG.warn("Ignoring bad fallback converter on type: " + type.getCanonicalName() + " method: " + method + " as a fallback converter method returns a void method"); } else { if (isStatic(modifiers)) { registerFallbackTypeConverter(registry, new StaticMethodFallbackTypeConverter(method, registry), method); } else { if (injector == null) { injector = new CachingInjector<Object>(registry, CastUtils.cast(type, Object.class)); } registerFallbackTypeConverter(registry, new InstanceMethodFallbackTypeConverter(injector, method, registry), method); } } } } else { LOG.warn("Ignoring bad fallback converter on type: " + type.getCanonicalName() + " method: " + method + " as a fallback converter method should have one parameter"); } return injector; }
From source file:com.ryantenney.metrics.spring.InjectMetricAnnotationBeanPostProcessor.java
@Override public Object postProcessAfterInitialization(final Object bean, String beanName) { final Class<?> targetClass = AopUtils.getTargetClass(bean); ReflectionUtils.doWithFields(targetClass, new FieldCallback() { @Override// w w w. j a v a2s. c om public void doWith(Field field) throws IllegalAccessException { final InjectMetric annotation = field.getAnnotation(InjectMetric.class); final String metricName = Util.forInjectMetricField(targetClass, field, annotation); final Class<?> type = field.getType(); Metric metric = null; if (Meter.class == type) { metric = metrics.meter(metricName); } else if (Timer.class == type) { metric = metrics.timer(metricName); } else if (Counter.class == type) { metric = metrics.counter(metricName); } else if (Histogram.class == type) { metric = metrics.histogram(metricName); } else { throw new IllegalStateException("Cannot inject a metric of type " + type.getCanonicalName()); } ReflectionUtils.makeAccessible(field); ReflectionUtils.setField(field, bean, metric); LOG.debug("Injected metric {} for field {}.{}", metricName, targetClass.getCanonicalName(), field.getName()); } }, FILTER); return bean; }
From source file:com.rapid.server.RapidServletContextListener.java
public static int loadActions(ServletContext servletContext) throws Exception { // assume no actions int actionCount = 0; // create a list of json actions which we will sort later List<JSONObject> jsonActions = new ArrayList<JSONObject>(); // retain our class constructors in a hashtable - this speeds up initialisation HashMap<String, Constructor> actionConstructors = new HashMap<String, Constructor>(); // build a collection of classes so we can re-initilise the JAXB context to recognise our injectable classes ArrayList<Action> actions = new ArrayList<Action>(); // get the directory in which the control xml files are stored File dir = new File(servletContext.getRealPath("/WEB-INF/actions/")); // create a filter for finding .control.xml files FilenameFilter xmlFilenameFilter = new FilenameFilter() { public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".action.xml"); }/*www .j av a 2 s . c om*/ }; // create a schema object for the xsd Schema schema = _schemaFactory .newSchema(new File(servletContext.getRealPath("/WEB-INF/schemas/") + "/action.xsd")); // create a validator Validator validator = schema.newValidator(); // loop the xml files in the folder for (File xmlFile : dir.listFiles(xmlFilenameFilter)) { // get a scanner to read the file Scanner fileScanner = new Scanner(xmlFile).useDelimiter("\\A"); // read the xml into a string String xml = fileScanner.next(); // close the scanner (and file) fileScanner.close(); // validate the control xml file against the schema validator.validate(new StreamSource(new ByteArrayInputStream(xml.getBytes("UTF-8")))); // convert the string into JSON JSONObject jsonActionCollection = org.json.XML.toJSONObject(xml).getJSONObject("actions"); JSONObject jsonAction; int index = 0; int count = 0; // the JSON library will add a single key of there is a single class, otherwise an array if (jsonActionCollection.optJSONArray("action") == null) { jsonAction = jsonActionCollection.getJSONObject("action"); } else { jsonAction = jsonActionCollection.getJSONArray("action").getJSONObject(index); count = jsonActionCollection.getJSONArray("action").length(); } do { // check this type does not already exist for (int i = 0; i < jsonActions.size(); i++) { if (jsonAction.getString("type").equals(jsonActions.get(i).getString("type"))) throw new Exception(" action type is loaded already. Type names must be unique"); } // add the jsonControl to our array jsonActions.add(jsonAction); // get the named type from the json String type = jsonAction.getString("type"); // get the class name from the json String className = jsonAction.getString("class"); // get the class Class classClass = Class.forName(className); // check the class extends com.rapid.Action if (!Classes.extendsClass(classClass, com.rapid.core.Action.class)) throw new Exception(type + " action class " + classClass.getCanonicalName() + " must extend com.rapid.core.Action."); // check this type is unique if (actionConstructors.get(type) != null) throw new Exception(type + " action already loaded. Type names must be unique."); // add to constructors hashmap referenced by type actionConstructors.put(type, classClass.getConstructor(RapidHttpServlet.class, JSONObject.class)); // add to our jaxb classes collection _jaxbClasses.add(classClass); // inc the control count actionCount++; // inc the count of controls in this file index++; // get the next one if (index < count) jsonAction = jsonActionCollection.getJSONArray("control").getJSONObject(index); } while (index < count); } // sort the list of actions by name Collections.sort(jsonActions, new Comparator<JSONObject>() { @Override public int compare(JSONObject c1, JSONObject c2) { try { return Comparators.AsciiCompare(c1.getString("name"), c2.getString("name"), false); } catch (JSONException e) { return 0; } } }); // create a JSON Array object which will hold json for all of the available controls JSONArray jsonArrayActions = new JSONArray(jsonActions); // put the jsonControls in a context attribute (this is available via the getJsonActions method in RapidHttpServlet) servletContext.setAttribute("jsonActions", jsonArrayActions); // put the constructors hashmapin a context attribute (this is available via the getContructor method in RapidHttpServlet) servletContext.setAttribute("actionConstructors", actionConstructors); _logger.info(actionCount + " actions loaded in .action.xml files"); return actionCount; }
From source file:com.visural.stereotyped.ui.service.StereotypeServiceImpl.java
private Class getComponentClassWithName(String name) { for (Class c : getComponents()) { if (c.getCanonicalName().equals(name)) { return c; }/*from ww w . j ava 2 s. co m*/ } return null; }
From source file:io.stallion.dataAccess.DataAccessRegistry.java
public ModelController registerDbOrFileModel(Class<? extends Model> model, Class<? extends ModelController> controller, String bucket) { Table anno = model.getAnnotation(Table.class); if (anno == null) { throw new UsageException("A @Table annotation is required on the model " + model.getCanonicalName() + " in order to register it."); }/*from ww w . ja v a 2 s. c om*/ bucket = or(bucket, anno.name()); String table = anno.name(); DataAccessRegistration registration = new DataAccessRegistration().setDatabaseBacked(true) .setPersisterClass(DbPersister.class).setBucket(bucket).setTableName(table) .setControllerClass(controller).setStashClass(PartialStash.class).setModelClass(model); if (!DB.available()) { registration.setDatabaseBacked(false).setPersisterClass(JsonFilePersister.class) .setStashClass(LocalMemoryStash.class).setPath(bucket).setUseDataFolder(true) .setShouldWatch(true).setWritable(true); } return register(registration); }
From source file:org.leo.benchmark.Benchmark.java
/** * Create a chartpanel//w w w . j a v a 2 s .com * * @param title title * @param dataName name of the data * @param clazzResult data mapped by classes * @param catItemLabelGenerator label generator * @return the chartPanel */ @SuppressWarnings("serial") private ChartPanel createChart(String title, String dataName, Map<Class<? extends Collection<?>>, Long> clazzResult, AbstractCategoryItemLabelGenerator catItemLabelGenerator) { // sort data by class name List<Class<? extends Collection<?>>> clazzes = new ArrayList<Class<? extends Collection<?>>>( clazzResult.keySet()); Collections.sort(clazzes, new Comparator<Class<? extends Collection<?>>>() { @Override public int compare(Class<? extends Collection<?>> o1, Class<? extends Collection<?>> o2) { return o1.getCanonicalName().compareTo(o2.getCanonicalName()); } }); DefaultCategoryDataset dataSet = new DefaultCategoryDataset(); // add the data to the dataset for (Class<? extends Collection<?>> clazz : clazzes) { dataSet.addValue(clazzResult.get(clazz), clazz.getName(), title.split(" ")[0]); } // create the chart JFreeChart chart = ChartFactory.createBarChart3D(null, null, dataName, dataSet, PlotOrientation.HORIZONTAL, false, true, false); chart.addSubtitle(new TextTitle(title)); // some customization in the style CategoryPlot plot = chart.getCategoryPlot(); plot.setBackgroundPaint(new Color(250, 250, 250)); plot.setDomainGridlinePaint(new Color(255, 200, 200)); plot.setRangeGridlinePaint(Color.BLUE); plot.getDomainAxis().setVisible(false); plot.getRangeAxis().setLabelFont(new Font("arial", Font.PLAIN, 10)); BarRenderer renderer = (BarRenderer) chart.getCategoryPlot().getRenderer(); // display the class name in the bar chart for (int i = 0; i < clazzResult.size(); i++) { renderer.setSeriesItemLabelGenerator(i, new StandardCategoryItemLabelGenerator() { @Override public String generateLabel(CategoryDataset dataset, int row, int column) { String label = " " + dataset.getRowKey(row).toString(); if (dataset.getValue(row, column).equals(timeout * 1000000)) { label += " (Timeout)"; } return label; } }); renderer.setSeriesItemLabelsVisible(i, true); ItemLabelPosition itemPosition = new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER_LEFT, TextAnchor.CENTER_LEFT, 0.0); renderer.setSeriesPositiveItemLabelPosition(i, itemPosition); renderer.setSeriesNegativeItemLabelPosition(i, itemPosition); } ItemLabelPosition itemPosition = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE9, TextAnchor.CENTER_LEFT, TextAnchor.CENTER_LEFT, 0.0); renderer.setPositiveItemLabelPositionFallback(itemPosition); renderer.setNegativeItemLabelPositionFallback(itemPosition); renderer.setShadowVisible(false); // create the chartpanel ChartPanel chartPanel = new ChartPanel(chart); chart.setBorderVisible(true); return chartPanel; }
From source file:au.com.jwatmuff.genericp2p.rmi.RMIPeerManager.java
@Override public <T> void registerService(Class<T> serviceClass, T implementation) { registerService(serviceClass.getCanonicalName(), serviceClass, implementation); }
From source file:com.agileapes.couteau.context.spring.event.impl.AbstractMappedEventsTranslationScheme.java
@Override public ApplicationEvent translate(Event originalEvent) throws EventTranslationException { final Class<? extends ApplicationEvent> eventClass; try {/*from w ww.ja v a 2 s. c o m*/ eventClass = getTargetEvent(originalEvent.getClass()); } catch (ClassNotFoundException e) { throw new EventTranslationException("Failed to locate target class for event", e); } final ApplicationEvent applicationEvent; try { applicationEvent = eventClass.getConstructor(Object.class).newInstance(originalEvent.getSource()); } catch (Exception e) { throw new EventTranslationException( "Failed to instantiate event from " + eventClass.getCanonicalName()); } for (Method method : originalEvent.getClass().getMethods()) { if (!GenericTranslationScheme.isGetter(method)) { continue; } final String fieldName = StringUtils .uncapitalize(method.getName().substring(method.getName().startsWith("get") ? 3 : 2)); final Field field = ReflectionUtils.findField(eventClass, fieldName); if (field == null || !field.getType().isAssignableFrom(method.getReturnType())) { continue; } field.setAccessible(true); try { field.set(applicationEvent, method.invoke(originalEvent)); } catch (Exception e) { throw new EventTranslationException("Failed to set property: " + fieldName, e); } } return applicationEvent; }