Example #1
0
 public List<T> findAll(Integer number, Integer offset, String orderByPropertyName, boolean asc) {
   Session session = openSession(true);
   List<T> results = Lists.newArrayList();
   try {
     Criteria criteria = criteria().setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
     if (number != 1) {
       criteria.setFirstResult(number - 1);
     }
     if (offset != 0) {
       criteria.setMaxResults(offset);
     }
     if (asc) {
       criteria.addOrder(Order.asc(orderByPropertyName));
     } else {
       criteria.addOrder(Order.desc(orderByPropertyName));
     }
     results = list(criteria);
     for (T result : results) {
       result.init();
     }
     commitTransaction(session, true);
   } catch (Exception e) {
     rollbackTransaction(session, true);
   } finally {
     closeSession(session);
   }
   return results;
 }
Example #2
0
  @Override
  public T instantiateDummy(final Relationship entity, final String entityType)
      throws FrameworkException {

    Map<String, Class<? extends RelationshipInterface>> entities =
        StructrApp.getConfiguration().getRelationshipEntities();
    Class<T> relClass = (Class<T>) entities.get(entityType);
    T newRel = null;

    if (relClass != null) {

      try {

        newRel = relClass.newInstance();
        newRel.init(factoryProfile.getSecurityContext(), entity);

        // let rel. know of its instantiation so it can cache its start- and end node ID.
        newRel.onRelationshipInstantiation();

      } catch (Throwable t) {

        newRel = null;
      }
    }

    return newRel;
  }
Example #3
0
 public List<T> namedQueryListResult(
     String namedQuery, int maxSize, Map<String, Object> parameters) {
   Session session = openSession(true);
   List<T> results = Lists.newArrayList();
   try {
     Query query = namedQuery(namedQuery);
     for (Map.Entry<String, Object> entry : parameters.entrySet()) {
       query.setParameter(entry.getKey(), entry.getValue());
     }
     if (maxSize != -1) {
       query.setMaxResults(maxSize);
     }
     results = query.list();
     for (T result : results) {
       if (result != null) {
         result.init();
       }
     }
     commitTransaction(session, true);
   } catch (Exception e) {
     rollbackTransaction(session, true);
   } finally {
     closeSession(session);
   }
   return results;
 }
Example #4
0
  <T extends FramedElement> T frameElement(Element e, Class<T> kind) {

    Class<T> frameType =
        (kind == TVertex.class || kind == TEdge.class) ? kind : resolver.resolve(e, kind);

    T framedElement = builder.create(e, frameType);
    framedElement.init(this, e);
    return framedElement;
  }
  /** {@inheritDoc} */
  public void init(final SpacecraftState s0, final AbsoluteDate t) {

    // delegate to raw detector
    rawDetector.init(s0, t);

    // initialize events triggering logic
    forward = t.compareTo(s0.getDate()) >= 0;
    extremeT = forward ? AbsoluteDate.PAST_INFINITY : AbsoluteDate.FUTURE_INFINITY;
    extremeG = Double.NaN;
    Arrays.fill(transformers, Transformer.UNINITIALIZED);
    Arrays.fill(updates, extremeT);
  }
 @Override
 public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height) {
   super.onSurfaceChanged(holder, format, width, height);
   if (mRs != null) {
     mRs.setSurface(holder, width, height);
   }
   if (mRenderer == null) {
     mRenderer = createScene(width, height);
     mRenderer.init(mRs, getResources(), isPreview());
     mRenderer.start();
   } else {
     mRenderer.resize(width, height);
   }
 }
Example #7
0
  private <T extends MapControls> T init(final T c, FrameLayout parent, int gravity) {
    c.setGravity(gravity);
    c.init(parent);
    allControls.add(c);
    c.setNotifyClick(
        new Runnable() {

          @Override
          public void run() {
            notifyClicked(c);
          }
        });
    return c;
  }
Example #8
0
 public T findById(S id) {
   Session session = openSession(true);
   T entity = null;
   try {
     entity = get(id);
     if (entity != null) {
       entity.init();
     }
     commitTransaction(session, true);
   } catch (Exception e) {
     rollbackTransaction(session, true);
   } finally {
     closeSession(session);
   }
   return entity;
 }
Example #9
0
 public List<T> list(Query query) {
   Session session = openSession(true);
   List<T> results = Lists.newArrayList();
   try {
     results = query.list();
     for (T result : results) {
       result.init();
     }
     commitTransaction(session, true);
   } catch (Exception e) {
     rollbackTransaction(session, true);
   } finally {
     closeSession(session);
   }
   return results;
 }
  @Override
  public void addingEntries(Bundle bundle, List<String> resources) {
    for (String fileName : resources) {
      // extract the format from the file name
      File file = new File(fileName);
      String format = file.getName().substring(0, file.getName().lastIndexOf("."));
      Hashtable<String, String> properties = new Hashtable<String, String>();

      LOGGER.debug("Found started bundle with name: {}", fileName);

      // setup the properties for the service
      properties.put(Constants.SERVICE_SHORTNAME, format);
      properties.put(
          Constants.SERVICE_TITLE,
          "View as " + (format.length() > 4 ? capitalize(format) : format.toUpperCase()) + "...");
      properties.put(Constants.SERVICE_DESCRIPTION, "Transforms query results into " + format);

      // define a transformer object that points to the xsl
      T xmt = null;
      try {
        xmt = transformerClass.newInstance();
        xmt.init(bundle, fileName);
      } catch (InstantiationException e) {
        LOGGER.debug("InstantiationException", e);
        continue;
      } catch (IllegalAccessException e) {
        LOGGER.debug("IllegalAccessException", e);
        continue;
      }

      // register the service
      ServiceRegistration sr = bundleContext.registerService(publishedInterface, xmt, properties);

      // store the service registration object
      if (serviceRegistrationMap.containsKey(bundle)) {
        // if it's already in the map, add the sr to the appropriate
        // list
        serviceRegistrationMap.get(bundle).add(sr);
      } else {
        // if it's not in the map, make the initial list and put it in
        // the map
        List<ServiceRegistration> srList = new ArrayList<ServiceRegistration>();
        srList.add(sr);
        serviceRegistrationMap.put(bundle, srList);
      }
    }
  }
Example #11
0
 public T update(T entity) {
   Session session = openSession(false);
   try {
     T original = get(entity.getId());
     if (original != null) {
       original.init();
     }
     if (original instanceof MergeSupport) {
       ((MergeSupport) original).merge((MergeSupport) entity, sessionFactory);
     }
     original.beforeUpdate();
     entity = persist(original);
     commitTransaction(session, false);
   } catch (Exception e) {
     rollbackTransaction(session, false);
   } finally {
     closeSession(session);
   }
   return entity;
 }
Example #12
0
 public T namedQueryUniqueResult(String namedQuery, Map<String, Object> parameters) {
   Session session = openSession(true);
   T result = null;
   try {
     Query query = namedQuery(namedQuery);
     for (Map.Entry<String, Object> entry : parameters.entrySet()) {
       query.setParameter(entry.getKey(), entry.getValue());
     }
     result = (T) query.uniqueResult();
     if (result != null) {
       result.init();
     }
     commitTransaction(session, true);
   } catch (Exception e) {
     rollbackTransaction(session, true);
   } finally {
     closeSession(session);
   }
   return result;
 }
Example #13
0
  /**
   * Initializes and returns page class instance
   *
   * @param page - page class
   * @throws PageObjectException
   */
  protected <T extends AbstractPageObject> T initPage(T page) throws PageObjectException {
    // get locators
    Locale locale;
    try {
      locale = new Locale(AutomationMain.getConfigProperties().getContentLanguage());
    } catch (AutomationFrameworkException e) {
      throw new PageObjectException("Main factory initialization exception.", e);
    }

    try {
      Browser browser = Browser.getCurrentBrowser();
      LOG.info("Current URL: " + getCurrentUrl());
      if (StringUtils.isNotBlank(page.getPageUrl())
          && !browser.getCurrentUrl().contains(page.getPageUrl())) {
        LOG.error("Navigate to URL: " + page.getPageUrl());
        throw new PageObjectException(
            "Page validation exception. Expected page URL is "
                + page.getPageUrl()
                + "  URL in fact "
                + getCurrentUrl());
      }
      page.setPageFactory(this);
      page.init(browser, locale);
      LOG.info(page.getClass().getName() + " page created.");
    } catch (Exception e) {
      throw new PageObjectException(
          "Unable initialize "
              + page.getClass().getName()
              + " page by URL: "
              + page.getPageUrl()
              + "\n"
              + e.getMessage(),
          e);
    }
    return page;
  }
Example #14
0
  @Override
  public T instantiateWithType(
      final Relationship relationship, final Class<T> relClass, final boolean isCreation)
      throws FrameworkException {

    logger.log(Level.FINEST, "Instantiate relationship with type {0}", relClass.getName());

    SecurityContext securityContext = factoryProfile.getSecurityContext();
    T newRel = null;

    try {

      newRel = relClass.newInstance();

    } catch (Throwable t) {
      newRel = null;
    }

    if (newRel == null) {
      newRel = (T) StructrApp.getConfiguration().getFactoryDefinition().createGenericRelationship();
    }

    newRel.init(securityContext, relationship);

    // try to set correct type property on relationship entity
    final String type = newRel.getProperty(GraphObject.type);
    if (type == null || (type != null && !type.equals(relClass.getSimpleName()))) {

      newRel.unlockReadOnlyPropertiesOnce();
      newRel.setProperty(GraphObject.type, relClass.getSimpleName());
    }

    newRel.onRelationshipInstantiation();

    return newRel;
  }
  /**
   * Creates a new entity of the specified type with the optionally specified initial parameters.
   * This method actually inserts a row into the table represented by the entity type and returns
   * the entity instance which corresponds to that row.
   *
   * <p>The {@link DBParam} object parameters are designed to allow the creation of entities which
   * have non-null fields which have no defalut or auto-generated value. Insertion of a row without
   * such field values would of course fail, thus the need for db params. The db params can also be
   * used to set the values for any field in the row, leading to more compact code under certain
   * circumstances.
   *
   * <p>Unless within a transaction, this method will commit to the database immediately and exactly
   * once per call. Thus, care should be taken in the creation of large numbers of entities. There
   * doesn't seem to be a more efficient way to create large numbers of entities, however one should
   * still be aware of the performance implications.
   *
   * <p>This method delegates the action INSERT action to {@link
   * DatabaseProvider#insertReturningKey(EntityManager, Connection, Class, String, boolean, String,
   * DBParam...)}. This is necessary because not all databases support the JDBC <code>
   * RETURN_GENERATED_KEYS</code> constant (e.g. PostgreSQL and HSQLDB). Thus, the database provider
   * itself is responsible for handling INSERTion and retrieval of the correct primary key value.
   *
   * @param type The type of the entity to INSERT.
   * @param params An optional varargs array of initial values for the fields in the row. These
   *     values will be passed to the database within the INSERT statement.
   * @return The new entity instance corresponding to the INSERTed row.
   * @see net.java.ao.DBParam
   * @see net.java.ao.DatabaseProvider#insertReturningKey(EntityManager, Connection, Class, String,
   *     boolean, String, DBParam...)
   */
  public <T extends RawEntity<K>, K> T create(Class<T> type, DBParam... params)
      throws SQLException {
    T back = null;
    String table = null;

    tableNameConverterLock.readLock().lock();
    try {
      table = tableNameConverter.getName(type);
    } finally {
      tableNameConverterLock.readLock().unlock();
    }

    Set<DBParam> listParams = new HashSet<DBParam>();
    listParams.addAll(Arrays.asList(params));

    fieldNameConverterLock.readLock().lock();
    try {
      for (Method method : MethodFinder.getInstance().findAnnotation(Generator.class, type)) {
        Generator genAnno = method.getAnnotation(Generator.class);
        String field = fieldNameConverter.getName(method);
        ValueGenerator<?> generator;

        valGenCacheLock.writeLock().lock();
        try {
          if (valGenCache.containsKey(genAnno.value())) {
            generator = valGenCache.get(genAnno.value());
          } else {
            generator = genAnno.value().newInstance();
            valGenCache.put(genAnno.value(), generator);
          }
        } catch (InstantiationException e) {
          continue;
        } catch (IllegalAccessException e) {
          continue;
        } finally {
          valGenCacheLock.writeLock().unlock();
        }

        listParams.add(new DBParam(field, generator.generateValue(this)));
      }
      // <ian>
      Version version = type.getAnnotation(Version.class);
      if (version != null) {
        // Initialize version upon creation.
        String field = version.value();
        int initial = version.initial();
        listParams.add(new DBParam(field, initial));
      }
      // </ian>
    } finally {
      fieldNameConverterLock.readLock().unlock();
    }

    Connection conn = getProvider().getConnection();
    try {
      Method pkMethod = Common.getPrimaryKeyMethod(type);
      back =
          peer(
              type,
              provider.insertReturningKey(
                  this,
                  conn,
                  Common.getPrimaryKeyClassType(type),
                  Common.getPrimaryKeyField(type, getFieldNameConverter()),
                  pkMethod.getAnnotation(AutoIncrement.class) != null,
                  table,
                  listParams.toArray(new DBParam[listParams.size()])));
    } finally {
      conn.close();
    }

    relationsCache.remove(type);

    back.init();

    return back;
  }
Example #16
0
 /**
  * Add a vertex to the graph
  *
  * @param kind The kind of the frame.
  * @return The framed vertex.
  */
 public <T extends FramedVertex> T addVertex(Class<T> kind) {
   T framedVertex = frameNewElement(delegate.addVertex(null), kind);
   framedVertex.init();
   return framedVertex;
 }