/** * Handles the event publication by pushing it to the real subscriber's subscription method. * * @param event The event to publish. */ @Override public void onEvent(final E event) { try { final Object obj = getProxiedSubscriber(); if (obj == null) return; // has been garbage collected getSubscriptionMethod().invoke(obj, event); } catch (final IllegalAccessException exc) { log.error( "Exception during event handling:\n\t[Event] " + event.getClass().getName() + ":" + event + "\n\t[Subscriber] " + getProxiedSubscriber() + "\n\t[Method] " + getSubscriptionMethod(), exc); } catch (final InvocationTargetException exc) { log.error( "Exception during event handling:\n\t[Event] " + event.getClass().getName() + event + "\n\t[Subscriber] " + getProxiedSubscriber() + "\n\t[Method] " + getSubscriptionMethod(), exc.getCause()); } }
public Response toResponse(int status, E e) { if (status >= 500) { // only log real errors as errors logger.error(e.getClass().getCanonicalName() + " 5XX Uncaught Exception (" + status + ")", e); } else { if (logger.isDebugEnabled()) { logger.debug(e.getClass().getCanonicalName() + " Uncaught Exception (" + status + ")", e); } } ApiResponse response = new ApiResponse(); AuthErrorInfo authError = AuthErrorInfo.getForException(e); if (authError != null) { response.setError(authError.getType(), authError.getMessage(), e); } else { response.setError(e); } String jsonResponse = mapToJsonString(response); return toResponse(status, jsonResponse); }
private void ensureUnique(E e) { Object remove = this.uniqueClasses.remove(e.getClass()); if (remove != null) { this.list.remove(remove); } this.uniqueClasses.put(e.getClass(), e); }
// DELETANDO OBJETOS public void delete(E obj) { EntityManager em = getEntityManager(); EntityTransaction tx = em.getTransaction(); Integer id = null; try { try { Method getId = obj.getClass().getDeclaredMethod("getId"); id = (Integer) getId.invoke(obj); } catch (Exception ex) { Logger.getLogger(DAO.class.getName()).log(Level.SEVERE, null, ex); } tx.begin(); E removeObj = (E) em.find(obj.getClass(), id); // if (!em.contains(obj)) { // obj = em.merge(obj); // } em.remove(removeObj); tx.commit(); // System.out.println(""); } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } }
protected E createEntry(String name, E parent) { E entry = null; entry = getByName(clazz, name); if (entry == null) { try { entry = clazz.newInstance(); if (PropertyUtils.isReadable(entry, "name")) { PropertyUtils.setProperty(entry, "name", name); } else { log().warn(String.format("Property name not found on class <%s>", entry.getClass())); } if (parent != null && PropertyUtils.isReadable(entry, "parent")) { PropertyUtils.setProperty(entry, "parent", parent); } else { log().warn(String.format("Property parent not found on class <%s>", entry.getClass())); } } catch (Exception e) { log().error("", e); } } if (!JPA.em().contains(entry)) { JPA.em().persist(entry); } return entry; }
private <E extends AbstractEntity> void fillActionableItem(E entity) { if (entity != null) { actionableItemId = entity.getId(); actionableItemClass = entity.getClass().getCanonicalName(); if (Namable.class.isAssignableFrom(entity.getClass())) { actionableItemName = ((Namable) entity).getUniqueName(); } else { actionableItemName = String.valueOf(entity); } } }
@Override public E put(final E element) { // validate element if (element == null) { throw new NullPointerException("Null element is not supported."); } LinkedElement e = null; try { e = (LinkedElement) element; } catch (ClassCastException ex) { throw new HadoopIllegalArgumentException( "!(element instanceof LinkedElement), element.getClass()=" + element.getClass()); } // find index final int index = getIndex(element); // remove if it already exists final E existing = remove(index, element); // insert the element to the head of the linked list modification++; size++; e.setNext(entries[index]); entries[index] = e; return existing; }
public static <E extends Number> NumberType fromNumber(E value) throws IllegalArgumentException { if (value instanceof Long) { return LONG; } if (value instanceof Double) { return DOUBLE; } if (value instanceof Integer) { return INTEGER; } if (value instanceof Float) { return FLOAT; } if (value instanceof Short) { return SHORT; } if (value instanceof Byte) { return BYTE; } if (value instanceof BigDecimal) { return BIG_DECIMAL; } throw new IllegalArgumentException( "Number class '" + value.getClass().getName() + "' is not supported"); }
/** * 设置实例e中指定field的值 * * @param e * @param name * @param value * @param parameterType * @throws Exception */ public static <E, T> void setField(E e, String name, T value, Class<T> parameterType) throws Exception { if (value != null) { String methodName = "set" + Character.toUpperCase(name.charAt(0)) + name.substring(1); e.getClass().getMethod(methodName, parameterType).invoke(e, value); } }
/** * This function is actually responsible for querying the database. * * @return list of entity objects currently in view * @throws DatabaseException */ private List<E> getData(Database db) throws DatabaseException { // TODO: move the row level security to the entitymapper... FormModel<E> model = getModel(); // set form level rights boolean formReadonly = model.isReadonly() || !model.getLogin().canWrite(model.create().getClass()); model.setReadonly(formReadonly); // load the rows List<E> visibleRecords = new ArrayList<E>(); // load all records and select rows that can be visible // List allRecords = view.getDatabase().find( view.getEntityClass(), // allRules ); List<E> allRecords = pager.getPage(db); for (E record : allRecords) { boolean rowReadonly = formReadonly || !model.getLogin().canWrite(record.getClass()); if (rowReadonly) record.setReadonly(true); // else // recordreadonly = false; visibleRecords.add(record); } return visibleRecords; }
@SuppressWarnings("unchecked") public static <E extends IPoolable> E createProxy(Pool<E> p, E obj, String destroyMethod) { return (E) Proxy.newProxyInstance( PoolableProxy.class.getClassLoader(), obj.getClass().getInterfaces(), new PoolableProxy<E>(p, obj, destroyMethod)); }
public <E> E getGenericProperty(final String key, final E def) { if (def == null || Clazz.isPrimitive(def.getClass())) { return storage.get(key, def); } else { System.out.println("Read " + path + "." + key + (plain ? ".json" : ".ejs")); return JSonStorage.restoreFromFile( new File(path + "." + key + (plain ? ".json" : ".ejs")), def); } }
@Override public Response toResponse(E exception) { if (getStatus().getStatusCode() >= Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()) log.error("System error {}: {}", getStatus(), exception.getClass().getName(), exception); return Response.status(getStatus()) .type("application/x-protobuf+json") .entity(getErrorDto(exception)) .build(); }
private <E extends Event> T getValue(final E e) { if (getters.containsKey(e.getClass())) { final Getter<? extends T, ? super E> g = (Getter<? extends T, ? super E>) getters.get(e.getClass()); return g == null ? null : g.get(e); } for (final Entry<Class<? extends Event>, SerializableGetter<? extends T, ?>> p : getters.entrySet()) { if (p.getKey().isAssignableFrom(e.getClass())) { getters.put(e.getClass(), p.getValue()); return p.getValue() == null ? null : ((Getter<? extends T, ? super E>) p.getValue()).get(e); } } getters.put(e.getClass(), null); return null; }
/** * 获取实例e中指定field的值 * * @param e * @param name * @return * @throws Exception */ public static <E> Object getField(E e, String name) throws Exception { String methodName = "get" + Character.toUpperCase(name.charAt(0)) + name.substring(1); Method method = e.getClass().getMethod(methodName); if (method != null) { Class<?> returnType = method.getReturnType(); return returnType.cast(method.invoke(e)); } else { throw new NoSuchMethodException(); } }
/** * @param entity * @return status when we delete success or fail */ public Boolean removeEntity(E entity) { Boolean isSuccess = false; try { LOGGER.debug("Generic Dao - Remove entity " + entity.getClass().getName() + " successfully."); currentSession().delete(entity); isSuccess = true; } catch (Exception e) { e.printStackTrace(); isSuccess = false; } return isSuccess; }
public Serializable addAndGetId(E entity) { Serializable result = 0; try { LOGGER.debug( "Generic Dao - Save entity " + entity.getClass().getName() + " successfully and return id"); result = currentSession().save(entity); } catch (Exception e) { e.printStackTrace(); } return result; }
public T newInstance(Class<? extends T> clazz) { try { Constructor constructor = clazz.getConstructor(snapshot.getClass()); return CastUtil.safeCast(constructor.newInstance(snapshot)); } catch (NoSuchMethodException e) { throw new InjectorException(e); } catch (InvocationTargetException e) { throw new InjectorException(e); } catch (InstantiationException e) { throw new InjectorException(e); } catch (IllegalAccessException e) { throw new InjectorException(e); } }
public static <E extends Enum<E> & IdentifiedEnum> E enumValueFromId( final int value, final E defaultValue) { requireNonNull(defaultValue, "No default value provided"); try { final Class<E> enumClass = (Class<E>) defaultValue.getClass(); for (final E enumValue : EnumSet.allOf(enumClass)) { if (((IdentifiedEnum) enumValue).getId() == value) { return enumValue; } } } catch (final Exception e) { // Ignore } return defaultValue; }
public void setEndNode(E endNode) { if (this.endNode == endNode) { return; } if (this.endNode != null) { removeIncomingEdgeFromEndNode(this.endNode); this.endNode = null; } if (endNode == null || getEndNodeClass().isAssignableFrom(endNode.getClass())) { this.endNode = endNode; if (this.endNode != null) { addIncomingEdgeToEndNode(endNode); } } }
/** * Valide l'objet <code>o</code> avec son validateur, en mettant <code>prefix</code> devant chaque * erreur et chaque warning. */ @SuppressWarnings("unchecked") // it IS checked!! protected <E extends DataObject> boolean subValidate(String prefix, E o) { GaselValidator<E> subValidator = (GaselValidator<E>) validatorFor(o.getClass()); subValidator.validate(o); boolean retval = true; for (String message : subValidator.errors) { error(prefix + " : " + suitePhrase(message)); retval = false; } for (String message : subValidator.warnings) { warning(prefix + " : " + suitePhrase(message)); // retval = false; } return retval; }
@Override public <E extends ModelEntity, T extends ModelEntity> List<T> getOrdered( E entity, String listMethod, Comparator<T> comparator) { EntityManager entityManager = getEntityManager(); entityManager.getTransaction().begin(); entityManager.merge(entity); List<T> ents; try { ents = (List<T>) entity.getClass().getMethod(listMethod).invoke(entity); } catch (Exception e) { throw new PersistenceException(e); } Collections.sort(ents, comparator); entityManager.getTransaction().commit(); return ents; }
@Override public <E> EntityProxy<E> proxyOf(E entity, boolean forUpdate) { checkClosed(); @SuppressWarnings("unchecked") Type<E> type = (Type<E>) entityModel.typeOf(entity.getClass()); EntityProxy<E> proxy = type.getProxyProvider().apply(entity); if (forUpdate && type.isReadOnly()) { throw new ReadOnlyException(); } if (forUpdate) { EntityTransaction transaction = transactionProvider.get(); if (transaction != null && transaction.active()) { transaction.addToTransaction(proxy); } } return proxy; }
@Override public <E extends EventObject> List<ListPropertyModifierByEvent> getListPropertyModifiersByEventObject(E eventObject) { log.debug( "SimpleListPropertyModifierManager.getListPropertyModifiersByEventObject with parameters " + "eventObject = [" + eventObject + "]"); List<ListPropertyModifierByEvent> list = new ArrayList<>(); for (Class<? extends IChangeEvent> aClass : modifierByEventMap.keySet()) { if (aClass.isInstance(eventObject)) { log.info(eventObject.getClass() + " is equals to " + aClass); list.addAll(modifierByEventMap.get(aClass)); } } return list; }
// 保存 public String save() throws Exception { JSONObject json = new JSONObject(); try { this.beforeSave(e); this.getCrudService().save(e); this.afterSave(e); json.put("success", true); json.put("id", e.getId()); json.put("msg", getText("form.save.success")); } catch (Exception e1) { logger.warn(e1.getMessage(), e1); json.put("success", false); json.put("msg", getSaveExceptionMsg(e1)); json.put("e", e.getClass().getSimpleName()); } this.json = json.toString(); return "json"; }
public static <E extends Enum<E>> E enumValue(final String value, final E defaultValue) { requireNonNull(defaultValue, "No default value provided"); E enumValue; if (value == null) { enumValue = defaultValue; } else { try { Class<?> enumClass = defaultValue.getClass(); if (enumClass.getEnclosingClass() != null) { enumClass = enumClass.getEnclosingClass(); } enumValue = Enum.valueOf((Class<E>) enumClass, value); } catch (final Exception e) { enumValue = defaultValue; } } return enumValue; }
@SuppressWarnings("unchecked") private <E> E put(final E entity, String atURI, String withSessionKey) { String thePath = atURI; String queryParams = ""; WebTarget resource = resource(); if (thePath.contains("?")) { String[] pathParts = thePath.split("\\?"); thePath = pathParts[0]; queryParams = pathParts[1]; } Invocation.Builder resourcePutter = applyQueryParameters(queryParams, resource.path(thePath)) .request(MediaType.APPLICATION_JSON); if (isDefined(withSessionKey)) { resourcePutter = resourcePutter.header(HTTP_SESSIONKEY, withSessionKey); } Class<E> c = (Class<E>) entity.getClass(); return resourcePutter.put(Entity.entity(entity, MediaType.APPLICATION_JSON), c); }
/** * 设置实例e中指定field的值 * * @param e * @param name * @param value * @throws Exception */ public static <E> void setField(E e, String name, Object value) throws Exception { if (value != null) { String methodName = "set" + Character.toUpperCase(name.charAt(0)) + name.substring(1); Method[] methods = e.getClass().getMethods(); if (methods != null && methods.length > 0) { for (Method method : methods) { if (method.getName().equals(methodName)) { Class<?>[] parameterTypes = method.getParameterTypes(); if (parameterTypes != null && parameterTypes.length == 1) { method.invoke(e, parameterTypes[0].cast(value)); break; } } } } else { throw new NoSuchMethodException(); } } }
protected void updateEntity(File file, E model) { try { if (PropertyUtils.isReadable(model, "geometry")) { Geometry geo = (Geometry) PropertyUtils.getProperty(model, "geometry"); if (geo == null || geo.getUdate() == null || geo.getUdate().getTime() < file.lastModified()) { Geometry newGeo = parseGeometryFile(file); newGeo = syncGeometry(geo, newGeo); PropertyUtils.setProperty(model, "geometry", newGeo); updateGeo = true; } } else { log().warn(String.format("Property geometry not found on class <%s>", model.getClass())); } updateByOpts(file, model); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { log().error(String.format("Failed to update %s with %s", file, model), e); } }
/** * @param object L'objet référence, qui sera ignoré dans la requète. * @param fieldsAndValues Les couples champ/valeur à vérifier. * @return <code>true</code> ssi il n'y a pas de double dans la base de données. */ protected <E extends DataObject> boolean checkUnicity(E object, Object... fieldsAndValues) { assert fieldsAndValues.length % 2 == 0; List<Expression> exprs = new LinkedList<Expression>(); for (int i = 0; i < fieldsAndValues.length; i += 2) { String[] fields = ((String) fieldsAndValues[i]).split("\\s*,\\s*"); Object value = fieldsAndValues[i + 1]; Expression[] fieldExprs = new Expression[fields.length]; for (int j = 0; j < fields.length; j++) { fieldExprs[j] = createEquals(fields[j], value); } exprs.add(createOr(fieldExprs)); } if (!object.getObjectId().isTemporary()) { exprs.add(createNot(createEquals("db:id", intPKForObject(object)))); } Expression expr = createAnd(exprs); return createDataContext().performQuery(new SelectQuery(object.getClass(), expr)).isEmpty(); }