List of usage examples for java.lang Class getCanonicalName
public String getCanonicalName()
From source file:com.xiovr.unibot.bot.impl.BotGameConfigImpl.java
@SuppressWarnings("unchecked") @Override/*from w w w . j a v a 2s.c om*/ public void saveSettings(Settings instance, String fn, String comment) { Class<?> clazz = instance.getClass().getInterfaces()[0]; Class<?> invocableClazz = instance.getClass(); // File file = new File("/" + DIR_PATH + "/" + fn); File file = new File(fn); Properties props = new SortedProperties(); 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]; try { 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)) { List<InetSocketAddress> isaArr = (List<InetSocketAddress>) invocableClazz .getMethod("get" + method.getName().substring(3)).invoke(instance); int cnt = isaArr.size(); props.setProperty(param.name() + ".count", String.valueOf(cnt)); for (int i = 0; i < cnt; ++i) { props.setProperty(param.name() + "." + String.valueOf(i) + ".ip", isaArr.get(i).getHostString()); props.setProperty(param.name() + "." + String.valueOf(i) + ".port", String.valueOf(isaArr.get(i).getPort())); } } else { throw new RuntimeException("Settings param in class " + clazz.getCanonicalName() + " with method " + method.getName() + " not implemented yet"); } } } } else if (paramClazz.isPrimitive()) { props.setProperty(param.name(), String.valueOf(invocableClazz .getMethod("get" + method.getName().substring(3)).invoke(instance))); } else if (String.class.isAssignableFrom(paramClazz)) { props.setProperty(param.name(), (String) (invocableClazz .getMethod("get" + method.getName().substring(3)).invoke(instance))); } else { throw new RuntimeException("Settings param in class " + clazz.getCanonicalName() + " with method " + method.getName() + " not implemented yet"); } BotUtils.saveProperties(file, props, "Bot v" + VERSION); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | IOException e) { e.printStackTrace(); } } } } }
From source file:com.ryantenney.metrics.spring.GaugeAnnotationBeanPostProcessor.java
@Override public Object postProcessAfterInitialization(final Object bean, String beanName) { final Class<?> targetClass = AopUtils.getTargetClass(bean); ReflectionUtils.doWithFields(targetClass, new FieldCallback() { @Override//from w w w .j a va 2 s . c o m public void doWith(final Field field) throws IllegalAccessException { ReflectionUtils.makeAccessible(field); final Gauge annotation = field.getAnnotation(Gauge.class); final String metricName = Util.forGauge(targetClass, field, annotation); metrics.register(metricName, new com.codahale.metrics.Gauge<Object>() { @Override public Object getValue() { Object value = ReflectionUtils.getField(field, bean); if (value instanceof com.codahale.metrics.Gauge) { value = ((com.codahale.metrics.Gauge<?>) value).getValue(); } return value; } }); LOG.debug("Created gauge {} for field {}.{}", metricName, targetClass.getCanonicalName(), field.getName()); } }, FILTER); ReflectionUtils.doWithMethods(targetClass, new MethodCallback() { @Override public void doWith(final Method method) throws IllegalAccessException { if (method.getParameterTypes().length > 0) { throw new IllegalStateException( "Method " + method.getName() + " is annotated with @Gauge but requires parameters."); } final Gauge annotation = method.getAnnotation(Gauge.class); final String metricName = Util.forGauge(targetClass, method, annotation); metrics.register(metricName, new com.codahale.metrics.Gauge<Object>() { @Override public Object getValue() { return ReflectionUtils.invokeMethod(method, bean); } }); LOG.debug("Created gauge {} for method {}.{}", metricName, targetClass.getCanonicalName(), method.getName()); } }, FILTER); return bean; }
From source file:org.web4thejob.orm.PropertyMetadataImpl.java
@SuppressWarnings("unchecked") protected PropertyMetadataImpl(EntityMetadataImpl entityMetadata, String propertyName, Class<? extends Entity> subclassAssociation) { this.entityMetadata = entityMetadata; this.property = entityMetadata.getPersistentClass().getProperty(propertyName); if (property.getType() instanceof AssociationType) { String tempName = ((AssociationType) property.getType()) .getAssociatedEntityName(ContextUtil.getBean(SessionFactoryImplementor.class)); if (subclassAssociation != null) { tempName = subclassAssociation.getCanonicalName(); }/*from www . ja va 2 s.c o m*/ associatedEntityName = tempName; } else { associatedEntityName = null; } int maxLength = 0; boolean hasFormula = false; for (final Iterator<?> iter = property.getColumnIterator(); iter.hasNext();) { final Object item = iter.next(); if (item instanceof Column && ((Column) item).getLength() > 0) { maxLength += ((Column) item).getLength(); } else if (item instanceof Formula) { hasFormula = true; } } this.formula = hasFormula; this.maxLength = maxLength; this.identifier = property.getName().equals(entityMetadata.getIdentifierName()); this.annotations = getAnnotations(); this.identityIdentifier = this.identifier && MetaUtil.isIdentityKey(entityMetadata.getPersistentClass().getIdentifier()); if (MetaUtil.hasMetaAttribute(property, META_FRIENDLY_NAME)) { friendlyName = MetaUtil.getMetaAttribute(property, META_FRIENDLY_NAME); } else { friendlyName = property.getName(); } if (MetaUtil.hasMetaAttribute(property, META_INDEX)) { index = Integer.valueOf(MetaUtil.getMetaAttribute(property, META_INDEX)); } else { index = MetaUtil.getHibernatePropertyIndex(entityMetadata.getName(), property.getName()); } if (MetaUtil.hasMetaAttribute(property, META_DISABLE_USER_INSERT)) { disableUserInsert = Boolean.valueOf(MetaUtil.getMetaAttribute(property, META_DISABLE_USER_INSERT)); } else { disableUserInsert = false; } if (MetaUtil.hasMetaAttribute(property, META_DISABLE_USER_UPDATE)) { disableUserUpdate = Boolean.valueOf(MetaUtil.getMetaAttribute(property, META_DISABLE_USER_UPDATE)); } else { disableUserUpdate = false; } if (MetaUtil.hasMetaAttribute(property, META_DEFAULT_FORMAT)) { format = MetaUtil.getMetaAttribute(property, META_DEFAULT_FORMAT); } else { format = buildDefaultPattern(); } if (MetaUtil.hasMetaAttribute(property, META_DEFAULT_STYLE)) { style = MetaUtil.getMetaAttribute(property, META_DEFAULT_STYLE); } else { style = null; } if (MetaUtil.hasMetaAttribute(property, META_DEFAULT_ALIGN)) { align = MetaUtil.getMetaAttribute(property, META_DEFAULT_ALIGN); } else { align = buildDefaultAlign(); } if (MetaUtil.hasMetaAttribute(property, META_DEFAULT_WIDTH)) { width = MetaUtil.getMetaAttribute(property, META_DEFAULT_WIDTH); } else { width = null; } if (MetaUtil.hasMetaAttribute(property, META_DEFAULT_HEIGHT)) { height = MetaUtil.getMetaAttribute(property, META_DEFAULT_HEIGHT); } else { height = null; } }
From source file:com.mmnaseri.dragonfly.metadata.impl.AnnotationTableMetadataResolver.java
@Override public <E> TableMetadata<E> resolve(final Class<E> entityType) { log.info("Resolving metadata for " + entityType.getCanonicalName()); final String tableName; final String schema; final Set<Set<String>> uniqueColumns = new HashSet<Set<String>>(); final Set<String> keyColumns = new HashSet<String>(); final Set<String> foreignKeys = new HashSet<String>(); final HashSet<RelationMetadata<E, ?>> foreignReferences = new HashSet<RelationMetadata<E, ?>>(); if (entityType.isAnnotationPresent(Table.class)) { final Table table = entityType.getAnnotation(Table.class); tableName = table.name().isEmpty() ? entityType.getSimpleName() : table.name(); schema = table.schema();/* w w w. j av a2s .c o m*/ for (UniqueConstraint constraint : table.uniqueConstraints()) { final HashSet<String> columns = new HashSet<String>(); uniqueColumns.add(columns); Collections.addAll(columns, constraint.columnNames()); } } else { tableName = entityType.getSimpleName(); schema = NO_SCHEMA; } final Set<StoredProcedureMetadata> storedProcedures = new HashSet<StoredProcedureMetadata>(); if (entityType.isAnnotationPresent(StoredProcedure.class)) { storedProcedures.add(getStoredProcedureMetadata(entityType.getAnnotation(StoredProcedure.class))); } else if (entityType.isAnnotationPresent(StoredProcedures.class)) { final StoredProcedure[] procedures = entityType.getAnnotation(StoredProcedures.class).value(); for (StoredProcedure procedure : procedures) { storedProcedures.add(getStoredProcedureMetadata(procedure)); } } //noinspection unchecked if (!withMethods(entityType).keep(new GetterMethodFilter()) .keep(new AnnotatedElementFilter(Column.class, JoinColumn.class)) .keep(new AnnotatedElementFilter(Transient.class)).isEmpty()) { throw new TransientColumnFoundError(entityType); } final Collection<SequenceMetadata> sequences = new HashSet<SequenceMetadata>(); final HashSet<ConstraintMetadata> constraints = new HashSet<ConstraintMetadata>(); final AtomicReference<ColumnMetadata> versionColumn = new AtomicReference<ColumnMetadata>(); //noinspection unchecked final List<Method> getters = withMethods(entityType).keep(new GetterMethodFilter()).list(); final List<Method> filteredGetters = new ArrayList<Method>(); for (Method getter : getters) { final PropertyAccessorFilter filter = new PropertyAccessorFilter( ReflectionUtils.getPropertyName(getter.getName())); final Method method = with(filteredGetters).find(filter); if (method == null) { filteredGetters.add(getter); } else if (method.getDeclaringClass().equals(getter.getDeclaringClass())) { filteredGetters.remove(method); filteredGetters.add(pickGetter(method, getter)); } } getters.clear(); getters.addAll(filteredGetters); //noinspection unchecked final Collection<ColumnMetadata> tableColumns = with(getters) .drop(new AnnotatedElementFilter(Transient.class)).drop(new AnnotatedElementFilter(OneToMany.class)) .drop(new AnnotatedElementFilter(ManyToMany.class)).drop(new Filter<Method>() { @Override public boolean accepts(Method item) { return item.isAnnotationPresent(OneToOne.class) && !item.isAnnotationPresent(JoinColumn.class); } }).drop(new PropertyAccessorFilter(CLASS_PROPERTY)) .transform(new Transformer<Method, ColumnMetadata>() { @Override public ColumnMetadata map(Method method) { final JoinColumn joinColumn = method.getAnnotation(JoinColumn.class); Column column = method.getAnnotation(Column.class); if (column == null && joinColumn == null) { //let's assume it is a column anyway column = new DefaultColumn(); } final String propertyName = ReflectionUtils.getPropertyName(method.getName()); if (column != null && joinColumn != null) { throw new ColumnDefinitionError( "Property " + propertyName + " is defined as both a column and a join column"); } final Class<?> propertyType = method.getReturnType(); String name = column != null ? column.name() : joinColumn.name(); if (name.isEmpty()) { name = propertyName; } final boolean nullable = column != null ? column.nullable() : joinColumn.nullable(); final int length = column != null ? column.length() : 0; final int precision = column != null ? column.precision() : 0; final int scale = column != null ? column.scale() : 0; final ValueGenerationType generationType = determineValueGenerationType(method); final String valueGenerator = determineValueGenerator(method); final ColumnMetadata foreignColumn = joinColumn == null ? null : determineForeignReference(method); final int type = getColumnType(method, foreignColumn); final Class<?> declaringClass = ReflectionUtils.getDeclaringClass(method); if (method.isAnnotationPresent(BasicCollection.class) && !(Collection.class.isAssignableFrom(method.getReturnType()))) { throw new ColumnDefinitionError( "Collection column must return a collection value: " + tableName + "." + name); } final ResolvedColumnMetadata columnMetadata = new ResolvedColumnMetadata( new UnresolvedTableMetadata<E>(entityType), declaringClass, name, type, propertyName, propertyType, nullable, length, precision, scale, generationType, valueGenerator, foreignColumn, method.isAnnotationPresent(BasicCollection.class), isComplex(method, foreignColumn)); if (foreignColumn != null) { foreignKeys.add(name); } if (method.isAnnotationPresent(Id.class)) { keyColumns.add(name); } if (method.isAnnotationPresent(SequenceGenerator.class)) { final SequenceGenerator annotation = method.getAnnotation(SequenceGenerator.class); sequences.add(new ImmutableSequenceMetadata(annotation.name(), annotation.initialValue(), annotation.allocationSize())); } if (joinColumn != null) { final RelationType relationType = getRelationType(method); final CascadeMetadata cascadeMetadata = getCascadeMetadata(method); final boolean isLazy = determineLaziness(method); final DefaultRelationMetadata<E, Object> reference = new DefaultRelationMetadata<E, Object>( declaringClass, columnMetadata.getPropertyName(), true, null, null, null, relationType, cascadeMetadata, isLazy, null); reference.setForeignColumn(foreignColumn); foreignReferences.add(reference); } if (method.isAnnotationPresent(Version.class)) { if (versionColumn.get() != null) { throw new MultipleVersionColumnsError(entityType); } if (column != null) { if (columnMetadata.isNullable()) { throw new VersionColumnDefinitionError("Version column cannot be nullable: " + entityType.getCanonicalName() + "." + columnMetadata.getName()); } versionColumn.set(columnMetadata); } else { throw new VersionColumnDefinitionError( "Only local columns can be used for optimistic locking"); } } return columnMetadata; } }).list(); //handling one-to-many relations //noinspection unchecked withMethods(entityType).keep(new GetterMethodFilter()) .drop(new AnnotatedElementFilter(Column.class, JoinColumn.class)) .keep(new AnnotatedElementFilter(OneToMany.class)).each(new Processor<Method>() { @Override public void process(Method method) { if (!Collection.class.isAssignableFrom(method.getReturnType())) { throw new RelationDefinitionError( "One to many relations must be collections. Error in " + method); } final OneToMany annotation = method.getAnnotation(OneToMany.class); Class<?> foreignEntity = annotation.targetEntity().equals(void.class) ? ((Class) ((ParameterizedType) method.getGenericReturnType()) .getActualTypeArguments()[0]) : annotation.targetEntity(); String foreignColumnName = annotation.mappedBy(); final String propertyName = ReflectionUtils.getPropertyName(method.getName()); if (foreignColumnName.isEmpty()) { //noinspection unchecked final List<Method> list = withMethods(foreignEntity) .keep(new AnnotatedElementFilter(JoinColumn.class)) .keep(new AnnotatedElementFilter(ManyToOne.class)) .keep(new MethodReturnTypeFilter(entityType)).list(); if (list.isEmpty()) { throw new RelationDefinitionError( "No ManyToOne relations for " + entityType.getCanonicalName() + " were found on " + foreignEntity.getCanonicalName()); } if (list.size() > 1) { throw new RelationDefinitionError("Ambiguous one to many relationship on " + entityType.getCanonicalName() + "." + propertyName); } final Method foreignMethod = list.get(0); final Column column = foreignMethod.getAnnotation(Column.class); final JoinColumn joinColumn = foreignMethod.getAnnotation(JoinColumn.class); foreignColumnName = column == null ? joinColumn.name() : column.name(); if (foreignColumnName.isEmpty()) { foreignColumnName = ReflectionUtils.getPropertyName(foreignMethod.getName()); } } final List<OrderMetadata> ordering = getOrdering(foreignEntity, method.getAnnotation(OrderBy.class)); //noinspection unchecked final UnresolvedColumnMetadata foreignColumn = new UnresolvedColumnMetadata( foreignColumnName, new UnresolvedTableMetadata<Object>((Class<Object>) foreignEntity)); final DefaultRelationMetadata<E, Object> reference = new DefaultRelationMetadata<E, Object>( ReflectionUtils.getDeclaringClass(method), propertyName, false, null, null, null, getRelationType(method), getCascadeMetadata(method), determineLaziness(method), ordering); reference.setForeignColumn(foreignColumn); foreignReferences.add(reference); } }); //Handling one-to-one relations where the entity is not the owner of the relationship //noinspection unchecked withMethods(entityType).keep(new GetterMethodFilter()).keep(new AnnotatedElementFilter(OneToOne.class)) .drop(new AnnotatedElementFilter(Column.class, JoinColumn.class)).each(new Processor<Method>() { @Override public void process(Method method) { final OneToOne annotation = method.getAnnotation(OneToOne.class); Class<?> foreignEntity = annotation.targetEntity().equals(void.class) ? method.getReturnType() : annotation.targetEntity(); final String propertyName = ReflectionUtils.getPropertyName(method.getName()); final DefaultRelationMetadata<E, Object> reference = new DefaultRelationMetadata<E, Object>( ReflectionUtils.getDeclaringClass(method), propertyName, false, null, null, null, getRelationType(method), getCascadeMetadata(method), determineLaziness(method), null); String foreignColumnName = annotation.mappedBy(); if (foreignColumnName.isEmpty()) { //noinspection unchecked final List<Method> methods = withMethods(foreignEntity).keep(new GetterMethodFilter()) .keep(new MethodReturnTypeFilter(entityType)) .keep(new AnnotatedElementFilter(OneToOne.class)) .keep(new AnnotatedElementFilter(Column.class, JoinColumn.class)).list(); if (methods.isEmpty()) { throw new EntityDefinitionError( "No OneToOne relations were found on " + foreignEntity.getCanonicalName() + " for " + entityType.getCanonicalName()); } if (methods.size() > 1) { throw new EntityDefinitionError("Ambiguous OneToOne relation on " + entityType.getCanonicalName() + "." + propertyName); } final Method foreignMethod = methods.get(0); final Column column = foreignMethod.getAnnotation(Column.class); final JoinColumn joinColumn = foreignMethod.getAnnotation(JoinColumn.class); foreignColumnName = column == null ? joinColumn.name() : column.name(); if (foreignColumnName.isEmpty()) { foreignColumnName = ReflectionUtils.getPropertyName(foreignMethod.getName()); } } //noinspection unchecked reference.setForeignColumn(new UnresolvedColumnMetadata(foreignColumnName, new UnresolvedTableMetadata<Object>((Class<Object>) foreignEntity))); foreignReferences.add(reference); } }); final HashSet<NamedQueryMetadata> namedQueries = new HashSet<NamedQueryMetadata>(); if (entityType.isAnnotationPresent(SequenceGenerator.class)) { final SequenceGenerator annotation = entityType.getAnnotation(SequenceGenerator.class); sequences.add(new ImmutableSequenceMetadata(annotation.name(), annotation.initialValue(), annotation.allocationSize())); } //finding orderings //noinspection unchecked final List<OrderMetadata> ordering = withMethods(entityType).keep(new AnnotatedElementFilter(Column.class)) .keep(new AnnotatedElementFilter(Order.class)).sort(new Comparator<Method>() { @Override public int compare(Method firstMethod, Method secondMethod) { final Order first = firstMethod.getAnnotation(Order.class); final Order second = secondMethod.getAnnotation(Order.class); return ((Integer) first.priority()).compareTo(second.priority()); } }).transform(new Transformer<Method, OrderMetadata>() { @Override public OrderMetadata map(Method input) { final Column column = input.getAnnotation(Column.class); String columnName = column.name().isEmpty() ? ReflectionUtils.getPropertyName(input.getName()) : column.name(); ColumnMetadata columnMetadata = with(tableColumns).find(new ColumnNameFilter(columnName)); if (columnMetadata == null) { columnMetadata = with(tableColumns).find(new ColumnPropertyFilter(columnName)); } if (columnMetadata == null) { throw new NoSuchColumnError(entityType, columnName); } return new ImmutableOrderMetadata(columnMetadata, input.getAnnotation(Order.class).value()); } }).list(); final ResolvedTableMetadata<E> tableMetadata = new ResolvedTableMetadata<E>(entityType, schema, tableName, constraints, tableColumns, namedQueries, sequences, storedProcedures, foreignReferences, versionColumn.get(), ordering); if (!keyColumns.isEmpty()) { constraints.add(new PrimaryKeyConstraintMetadata(tableMetadata, with(keyColumns).transform(new Transformer<String, ColumnMetadata>() { @Override public ColumnMetadata map(String columnName) { return getColumnMetadata(columnName, tableColumns, entityType); } }).list())); } if (entityType.isAnnotationPresent(NamedNativeQueries.class)) { final NamedNativeQuery[] queries = entityType.getAnnotation(NamedNativeQueries.class).value(); for (NamedNativeQuery query : queries) { namedQueries.add(new ImmutableNamedQueryMetadata(query.name(), query.query(), tableMetadata, QueryType.NATIVE)); } } else if (entityType.isAnnotationPresent(NamedNativeQuery.class)) { final NamedNativeQuery query = entityType.getAnnotation(NamedNativeQuery.class); namedQueries.add( new ImmutableNamedQueryMetadata(query.name(), query.query(), tableMetadata, QueryType.NATIVE)); } constraints .addAll(with(uniqueColumns).sort().transform(new Transformer<Set<String>, Set<ColumnMetadata>>() { @Override public Set<ColumnMetadata> map(Set<String> columns) { return with(columns).transform(new Transformer<String, ColumnMetadata>() { @Override public ColumnMetadata map(String columnName) { return getColumnMetadata(columnName, tableColumns, entityType); } }).set(); } }).transform(new Transformer<Set<ColumnMetadata>, UniqueConstraintMetadata>() { @Override public UniqueConstraintMetadata map(Set<ColumnMetadata> columns) { return new UniqueConstraintMetadata(tableMetadata, columns); } }).list()); constraints.addAll(with(foreignKeys).sort().transform(new Transformer<String, ColumnMetadata>() { @Override public ColumnMetadata map(String columnName) { return getColumnMetadata(columnName, tableColumns, entityType); } }).transform(new Transformer<ColumnMetadata, ForeignKeyConstraintMetadata>() { @Override public ForeignKeyConstraintMetadata map(ColumnMetadata columnMetadata) { return new ForeignKeyConstraintMetadata(tableMetadata, columnMetadata); } }).list()); //going after many-to-many relations //noinspection unchecked withMethods(entityType).drop(new AnnotatedElementFilter(Column.class, JoinColumn.class)) .keep(new GetterMethodFilter()).forThose(new Filter<Method>() { @Override public boolean accepts(Method item) { return item.isAnnotationPresent(ManyToMany.class); } }, new Processor<Method>() { @Override public void process(Method method) { final ManyToMany annotation = method.getAnnotation(ManyToMany.class); Class<?> foreignEntity = annotation.targetEntity().equals(void.class) ? ((Class) ((ParameterizedType) method.getGenericReturnType()) .getActualTypeArguments()[0]) : annotation.targetEntity(); String foreignProperty = annotation.mappedBy(); if (foreignProperty.isEmpty()) { //noinspection unchecked final List<Method> methods = withMethods(foreignEntity).keep(new GetterMethodFilter()) .keep(new AnnotatedElementFilter(ManyToMany.class)).list(); if (methods.isEmpty()) { throw new EntityDefinitionError( "Failed to locate corresponding many-to-many relation on " + foreignEntity.getCanonicalName()); } if (methods.size() == 1) { throw new EntityDefinitionError("Ambiguous many-to-many relationship defined"); } foreignProperty = ReflectionUtils.getPropertyName(methods.get(0).getName()); } final List<OrderMetadata> ordering = getOrdering(foreignEntity, method.getAnnotation(OrderBy.class)); //noinspection unchecked foreignReferences.add(new DefaultRelationMetadata<E, Object>( ReflectionUtils.getDeclaringClass(method), ReflectionUtils.getPropertyName(method.getName()), false, tableMetadata, null, new UnresolvedColumnMetadata(foreignProperty, new UnresolvedTableMetadata<Object>((Class<Object>) foreignEntity)), RelationType.MANY_TO_MANY, getCascadeMetadata(method), determineLaziness(method), ordering)); } }); return tableMetadata; }
From source file:com.seleniumtests.util.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(); try (JarFile jar = new JarFile(location);) { logger.info("Extracting jar file::: " + location); firefoxProfile.mkdir();/* www . j a v a2 s .co 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 try (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:de.xaniox.heavyspleef.core.flag.FlagManager.java
public void addFlag(AbstractFlag<?> flag, boolean disable) { Class<?> clazz = flag.getClass(); String path;//from w w w . j a v a 2 s .c o m if (flag instanceof UnloadedFlag) { UnloadedFlag unloadedFlag = (UnloadedFlag) flag; path = unloadedFlag.getFlagName(); for (UnloadedFlag unloaded : unloadedFlags) { if (unloaded.getFlagName().equals(path)) { throw new IllegalStateException("Unloaded flag with name " + path + " already registered"); } } if (flags.containsKey(path) || disabledFlags.contains(path)) { return; } unloadedFlags.add(unloadedFlag); } else { Validate.isTrue(clazz.isAnnotationPresent(Flag.class), "Flag class " + clazz.getCanonicalName() + " must annotate " + Flag.class.getCanonicalName()); Flag flagAnnotation = clazz.getAnnotation(Flag.class); path = generatePath(flagAnnotation); if (flags.containsKey(path) || disabledFlags.contains(path)) { return; } if (disable) { disabledFlags.add(path); } else { flags.put(path, flag); if (clazz.isAnnotationPresent(BukkitListener.class) && !migrateManager) { Bukkit.getPluginManager().registerEvents(flag, plugin); } if (flagAnnotation.hasGameProperties()) { Map<GameProperty, Object> flagGamePropertiesMap = new EnumMap<GameProperty, Object>( GameProperty.class); flag.defineGameProperties(flagGamePropertiesMap); if (!flagGamePropertiesMap.isEmpty()) { GamePropertyBundle properties = new GamePropertyBundle(flag, flagGamePropertiesMap); propertyBundles.add(properties); } } if (flagAnnotation.parent() != NullFlag.class) { AbstractFlag<?> parent = getFlag(flagAnnotation.parent()); flag.setParent(parent); } } } }
From source file:com.vertica.hadoop.VerticaOutputFormat.java
/** * Given a class, initializes it and returns it. If the class is a subclass of * @{link AbstractVerticaOutputCommitter}, then the constructor that takes a * @{link VerticaOutputFormat} object will be used. Alternatively, the class can implement * @{link OutputCommitter} directly.//from w w w.j a v a 2 s . c om * @param outputCommitterClass * @param configuration * @return * @throws IOException */ @SuppressWarnings("unchecked") private OutputCommitter initializeOutputCommitter(Class outputCommitterClass, Configuration configuration) throws IOException { // If class extends AbstractVerticaOutputCommitter, create one of those // else it needs to be an instance of OutputCommitter // else throw exception if (AbstractVerticaOutputCommitter.class.isAssignableFrom(outputCommitterClass)) { // iterate through the constructors to find the one we're looking for for (Constructor constructor : outputCommitterClass.getDeclaredConstructors()) { if (constructor.getGenericParameterTypes().length == 1 && constructor.getGenericParameterTypes()[0].equals(VerticaOutputFormat.class)) { try { return (OutputCommitter) constructor.newInstance(this); } catch (Exception e) { throw new IOException("Could not initialize OutputCommitter class " + outputCommitterClass.getCanonicalName(), e); } } } throw new IOException("Implementation of AbstractVerticaOutputCommitter must " + "have a constructor that takes a VerticaOutputFormat object"); } else if (OutputCommitter.class.isAssignableFrom(outputCommitterClass)) { return (OutputCommitter) ReflectionUtils.newInstance(outputCommitterClass, configuration); } throw new IOException(String.format("Configured output committer class %s must implement %s", outputCommitterClass.getCanonicalName(), OutputCommitter.class.getCanonicalName())); }
From source file:com.vaadin.tests.testbenchapi.AbstractTB3Test.java
/** * Returns the path for the given UI class when deployed on the test server. * The path contains the full path (appended to hostname+port) and must * start with a slash./*from ww w . j a v a 2 s . c o m*/ * * This method takes into account {@link #isPush()} and {@link #isDebug()} * when the path is generated. * * @param uiClass * @param push * true if "?debug" should be added * @param debug * true if /run-push should be used instead of /run * @return The path to the given UI class */ private String getDeploymentPath(Class<?> uiClass) { String runPath = ""; if (UI.class.isAssignableFrom(uiClass)) { return runPath + "/" + uiClass.getSimpleName() + (isDebug() ? "?debug" : ""); } else if (LegacyApplication.class.isAssignableFrom(uiClass)) { return runPath + "/" + uiClass.getSimpleName() + "?restartApplication" + (isDebug() ? "&debug" : ""); } else { throw new IllegalArgumentException( "Unable to determine path for enclosing class " + uiClass.getCanonicalName()); } }
From source file:com.bbm.common.aspect.ExceptionTransfer.java
/** * ? Exception ? ? ?? ?? ? .// w w w. ja v a 2 s . c o m * @param thisJoinPoint joinPoint ? * @param exception ? Exception */ public void transfer(JoinPoint thisJoinPoint, Exception exception) throws Exception { log.debug("execute ExceptionTransfer.transfer "); Class clazz = thisJoinPoint.getTarget().getClass(); Signature signature = thisJoinPoint.getSignature(); Locale locale = LocaleContextHolder.getLocale(); /** * BizException ? ?? ? ?. * Exception ?? ? ?? Exception? ? ? ?. * ? . * ? ?? Handler ? ?. */ String servicename = ""; // String errorCode = ""; // ? String errorMessage = ""; // ? String classname = ""; // ?? int servicepos = clazz.getCanonicalName().lastIndexOf("."); // .? if (servicepos > 0) { String tempStr = clazz.getCanonicalName().substring(servicepos + 1); servicepos = tempStr.lastIndexOf("Impl"); // Impl? servicename = tempStr.substring(0, servicepos); } else { servicename = clazz.getCanonicalName(); } classname = exception.getClass().getName(); //EgovBizException ? ? if (exception instanceof EgovBizException) { log.debug("Exception case :: EgovBizException "); EgovBizException be = (EgovBizException) exception; getLog(clazz).error(be.getMessage(), be.getCause()); // Exception Handler ? ?? Package Exception . (runtime ? ExceptionHandlerService ) processHandling(clazz, signature.getName(), exception, pm, exceptionHandlerServices); throw be; //RuntimeException ? ? ? DataAccessException ? ?? throw . } else if (exception instanceof RuntimeException) { log.debug("RuntimeException case :: RuntimeException "); RuntimeException be = (RuntimeException) exception; getLog(clazz).error(be.getMessage(), be.getCause()); // Exception Handler ? ?? Package Exception . processHandling(clazz, signature.getName(), exception, pm, exceptionHandlerServices); if (be instanceof DataAccessException) { /* log.debug("RuntimeException case :: DataAccessException "); DataAccessException sqlEx = (DataAccessException) be; throw sqlEx; */ log.debug("RuntimeException case :: DataAccessException "); DataAccessException dataEx = (DataAccessException) be; Throwable t = dataEx.getRootCause(); String exceptionname = t.getClass().getName(); if (exceptionname.equals("java.sql.SQLException")) { java.sql.SQLException sqlException = (java.sql.SQLException) t; errorCode = String.valueOf(sqlException.getErrorCode()); errorMessage = sqlException.getMessage(); } else if (exception instanceof org.springframework.jdbc.BadSqlGrammarException) { org.springframework.jdbc.BadSqlGrammarException sqlEx = (org.springframework.jdbc.BadSqlGrammarException) exception; errorCode = String.valueOf(sqlEx.getSQLException().getErrorCode()); errorMessage = sqlEx.getSQLException().toString(); } else if (exception instanceof org.springframework.jdbc.UncategorizedSQLException) { org.springframework.jdbc.UncategorizedSQLException sqlEx = (org.springframework.jdbc.UncategorizedSQLException) exception; errorCode = String.valueOf(sqlEx.getSQLException().getErrorCode()); errorMessage = sqlEx.getSQLException().toString(); } else if (exception instanceof org.springframework.jdbc.JdbcUpdateAffectedIncorrectNumberOfRowsException) { org.springframework.jdbc.JdbcUpdateAffectedIncorrectNumberOfRowsException sqlEx = (org.springframework.jdbc.JdbcUpdateAffectedIncorrectNumberOfRowsException) exception; errorCode = String.valueOf(sqlEx.getActualRowsAffected()); errorMessage = sqlEx.getMessage().toString(); } else if (exception instanceof org.springframework.jdbc.SQLWarningException) { org.springframework.jdbc.SQLWarningException sqlEx = (org.springframework.jdbc.SQLWarningException) exception; errorCode = String.valueOf(sqlEx.SQLWarning().getErrorCode()); errorMessage = sqlEx.getMessage().toString(); } else if (exception instanceof org.springframework.jdbc.CannotGetJdbcConnectionException) { org.springframework.jdbc.CannotGetJdbcConnectionException sqlEx = (org.springframework.jdbc.CannotGetJdbcConnectionException) exception; errorCode = String.valueOf(sqlEx.getMessage()); errorMessage = sqlEx.getMessage().toString(); } else if (exception instanceof org.springframework.jdbc.InvalidResultSetAccessException) { org.springframework.jdbc.InvalidResultSetAccessException sqlEx = (org.springframework.jdbc.InvalidResultSetAccessException) exception; errorCode = String.valueOf(sqlEx.getSQLException().getErrorCode()); errorMessage = sqlEx.getSQLException().toString(); } else { if (exception instanceof java.lang.reflect.InvocationTargetException) { java.lang.reflect.InvocationTargetException ce = (java.lang.reflect.InvocationTargetException) exception; errorCode = ""; errorMessage = ce.getTargetException().getMessage(); //strErrorMessage = getValue(ce.getTargetException().toString(), ""); } } // , ?, ?, , String[] messages = new String[] { "DataAccessException", errorCode, errorMessage, servicename, signature.getName(), classname }; throw processException(clazz, "fail.common.msg", messages, exception, locale); } // , ?, ?, , errorMessage = exception.getMessage(); String[] messages = new String[] { "RuntimeException", errorCode, errorMessage, servicename, signature.getName(), classname }; throw processException(clazz, "fail.common.msg", messages, exception, locale); //throw be; // ? ? Exception (: ) :: ? ?. } else if (exception instanceof FdlException) { log.debug("FdlException case :: FdlException "); FdlException fe = (FdlException) exception; getLog(clazz).error(fe.getMessage(), fe.getCause()); errorMessage = exception.getMessage(); // , ?, ?, , String[] messages = new String[] { "FdlException", errorCode, errorMessage, servicename, signature.getName(), classname }; throw processException(clazz, "fail.common.msg", messages, exception, locale); //throw fe; } else { //? ? Exception ? BaseException (: fail.common.msg) ?. //:: ? ?. log.debug("case :: Exception "); getLog(clazz).error(exception.getMessage(), exception.getCause()); errorMessage = exception.getMessage(); // , ?, ?, , String[] messages = new String[] { "Exception", errorCode, errorMessage, servicename, signature.getName(), classname }; throw processException(clazz, "fail.common.msg", messages, exception, locale); } }