private Document buildDoc(EntityBaseBean bean) throws IcatException {
    Map<Field, Integer> stringFields = ei.getStringFields(bean.getClass());
    StringBuilder sb = new StringBuilder();
    for (Entry<Field, Integer> item : stringFields.entrySet()) {
      Field field = item.getKey();
      Method getter = ei.getGetters(bean.getClass()).get(field);
      try {
        String text = (String) getter.invoke(bean);
        if (text != null) {
          if (sb.length() != 0) {
            sb.append(' ');
          }
          sb.append(text);
        }
      } catch (IllegalArgumentException e) {
        throw new IcatException(IcatExceptionType.INTERNAL, e.getMessage());
      } catch (IllegalAccessException e) {
        throw new IcatException(IcatExceptionType.INTERNAL, e.getMessage());
      } catch (InvocationTargetException e) {
        throw new IcatException(IcatExceptionType.INTERNAL, e.getMessage());
      }
    }

    Document doc = new Document();
    String id = bean.getClass().getSimpleName() + ":" + bean.getId();
    doc.add(new StringField("id", id, Store.YES));
    doc.add(new StringField("entity", bean.getClass().getSimpleName(), Store.NO));
    doc.add(new TextField("all", sb.toString(), Store.NO));
    logger.debug("Created document '" + sb.toString() + "' to index for " + id);
    return doc;
  }
 /*
  * If this method is overridden it should be called as well by super.addToClone()
  */
 void addToClone(EntityBaseBean clone) {
   clone.createId = createId;
   clone.createTime = createTime;
   clone.id = id;
   clone.modId = modId;
   clone.modTime = modTime;
 }
 /*
  * If this method is overridden it should be called as well by super.preparePersist(). Note that
  * it recurses down though all to-many relationships.
  */
 public void preparePersist(String modId, EntityManager manager, GateKeeper gateKeeper)
     throws IcatException {
   this.id = null;
   this.modId = modId;
   Class<? extends EntityBaseBean> klass = this.getClass();
   Set<Relationship> rs = eiHandler.getRelatedEntities(klass);
   Map<Field, Method> getters = eiHandler.getGetters(klass);
   for (Relationship r : rs) {
     if (r.isCollection()) {
       Method m = getters.get(r.getField());
       try {
         @SuppressWarnings("unchecked")
         List<EntityBaseBean> collection = (List<EntityBaseBean>) m.invoke(this);
         if (!collection.isEmpty()) {
           Method rev = r.getInverseSetter();
           for (EntityBaseBean bean : collection) {
             bean.preparePersist(modId, manager, gateKeeper);
             rev.invoke(bean, this);
           }
         }
       } catch (Exception e) {
         throw new IcatException(IcatExceptionType.INTERNAL, e.getClass() + " " + e.getMessage());
       }
     }
   }
 }
 public void updateDocument(EntityBaseBean bean) throws IcatException {
   Document doc = buildDoc(bean);
   String id = bean.getClass().getSimpleName() + ":" + bean.getId();
   try {
     iwriter.updateDocument(new Term("id", id), doc);
   } catch (IOException e) {
     throw new IcatException(IcatExceptionType.INTERNAL, e.getMessage());
   }
 }
 public void deleteDocument(EntityBaseBean bean) throws IcatException {
   String id = bean.getClass().getSimpleName() + ":" + bean.getId();
   try {
     iwriter.deleteDocuments(new Term("id", id));
     logger.debug("Deleted document: " + id);
   } catch (IOException e) {
     throw new IcatException(IcatExceptionType.INTERNAL, e.getMessage());
   }
 }
 public void addToLucene(LuceneSingleton lucene) throws IcatException {
   lucene.addDocument(this);
   Class<? extends EntityBaseBean> klass = this.getClass();
   Set<Relationship> rs = eiHandler.getRelatedEntities(klass);
   Map<Field, Method> getters = eiHandler.getGetters(klass);
   for (Relationship r : rs) {
     if (r.isCollection()) {
       Method m = getters.get(r.getField());
       try {
         @SuppressWarnings("unchecked")
         List<EntityBaseBean> collection = (List<EntityBaseBean>) m.invoke(this);
         if (!collection.isEmpty()) {
           for (EntityBaseBean bean : collection) {
             bean.addToLucene(lucene);
           }
         }
       } catch (Exception e) {
         throw new IcatException(IcatExceptionType.INTERNAL, e.getMessage());
       }
     }
   }
 }
 /**
  * Clone a pruned copy of tree
  *
  * @param one true if INCLUDE 1 specified
  * @param hereVarNum current idVarNum. If steps is null this value is irrelevant.
  * @param steps list of steps to consider. This may be null. Steps starting with hereVarNum will
  *     be followed. Steps hold the starting idVarNum, the field to navigate and the destination
  *     idVarNum.
  * @param manager
  * @param userId
  * @return
  * @throws IcatException
  */
 public EntityBaseBean pruned(
     boolean one,
     int hereVarNum,
     List<Step> steps,
     GateKeeper gateKeeper,
     String userId,
     EntityManager manager)
     throws IcatException {
   Class<? extends EntityBaseBean> klass = this.getClass();
   if (logger.isDebugEnabled()) {
     if (one) {
       logger.debug("Pruning " + klass.getSimpleName() + " INCLUDE 1");
     } else if (steps != null) {
       logger.debug("Pruning " + klass.getSimpleName() + " INCLUDE from " + hereVarNum);
     } else {
       logger.debug("Pruning " + klass.getSimpleName());
     }
   }
   try {
     Constructor<? extends EntityBaseBean> con = eiHandler.getConstructor(klass);
     EntityBaseBean clone = con.newInstance();
     clone.id = this.id;
     clone.createTime = this.createTime;
     clone.createId = this.createId;
     clone.modTime = this.modTime;
     clone.modId = this.modId;
     Set<Field> atts = eiHandler.getAttributes(klass);
     Map<Field, Method> getters = eiHandler.getGetters(klass);
     Map<Field, Method> setters = eiHandler.getSettersForUpdate(klass);
     for (Field att : atts) {
       Object value = getters.get(att).invoke(this);
       if (value != null) {
         setters.get(att).invoke(clone, new Object[] {value});
       }
     }
     if (one) {
       for (Relationship r : eiHandler.getOnes(klass)) {
         Field att = r.getField();
         EntityBaseBean value = allowedOne(r, getters.get(att), gateKeeper, userId, manager);
         if (value != null) {
           value = value.pruned(false, 0, null, gateKeeper, userId, manager);
           setters.get(att).invoke(clone, new Object[] {value});
         }
       }
     } else if (steps != null) {
       for (Step step : steps) {
         if (step.getHereVarNum() == hereVarNum) {
           Relationship r = step.getRelationship();
           Field field = r.getField();
           if (r.isCollection()) {
             List<EntityBaseBean> values = allowedMany(step, getters, gateKeeper, userId, manager);
             @SuppressWarnings("unchecked")
             List<EntityBaseBean> cloneList =
                 (List<EntityBaseBean>) getters.get(field).invoke(clone);
             for (EntityBaseBean value : values) {
               value =
                   value.pruned(false, step.getThereVarNum(), steps, gateKeeper, userId, manager);
               cloneList.add(value);
             }
           } else {
             EntityBaseBean value = allowedOne(r, getters.get(field), gateKeeper, userId, manager);
             if (value != null) {
               value =
                   value.pruned(false, step.getThereVarNum(), steps, gateKeeper, userId, manager);
               setters.get(field).invoke(clone, new Object[] {value});
             }
           }
         }
       }
     }
     return clone;
   } catch (Exception e) {
     reportUnexpected(e);
     throw new IcatException(IcatException.IcatExceptionType.INTERNAL, "" + e);
   }
 }
Esempio n. 8
0
  private void jsonise(EntityBaseBean bean, JsonGenerator gen) throws IcatException {

    gen.write("id", bean.getId())
        .write("createId", bean.getCreateId())
        .write("createTime", bean.getCreateTime().toString())
        .write("modId", bean.getModId())
        .write("modTime", bean.getModTime().toString());

    Class<? extends EntityBaseBean> klass = bean.getClass();
    Map<Field, Method> getters = eiHandler.getGetters(klass);
    Set<Field> atts = eiHandler.getAttributes(klass);
    Set<Field> updaters = eiHandler.getSettersForUpdate(klass).keySet();

    for (Field field : eiHandler.getFields(klass)) {
      Object value = null;
      try {
        value = getters.get(field).invoke(bean);
      } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
        throw new IcatException(IcatExceptionType.INTERNAL, e.getClass() + " " + e.getMessage());
      }
      if (value == null) {
        // Ignore null values
      } else if (atts.contains(field)) {
        String type = field.getType().getSimpleName();
        if (type.equals("String")) {
          gen.write(field.getName(), (String) value);
        } else if (type.equals("Integer")) {
          gen.write(field.getName(), value.toString());
        } else if (type.equals("Double")) {
          gen.write(field.getName(), value.toString());
        } else if (type.equals("Long")) {
          gen.write(field.getName(), value.toString());
        } else if (type.equals("boolean")) {
          gen.write(field.getName(), value.toString());
        } else if (field.getType().isEnum()) {
          gen.write(field.getName(), value.toString());
        } else if (type.equals("Date")) {
          synchronized (df8601) {
            gen.write(field.getName(), df8601.format((Date) value));
          }
        } else {
          throw new IcatException(
              IcatExceptionType.INTERNAL, "Don't know how to jsonise field of type " + type);
        }
      } else if (updaters.contains(field)) {
        gen.writeStartObject(field.getName());
        jsonise((EntityBaseBean) value, gen);
        gen.writeEnd();
      } else {
        gen.writeStartArray(field.getName());
        @SuppressWarnings("unchecked")
        List<EntityBaseBean> beans = (List<EntityBaseBean>) value;
        for (EntityBaseBean b : beans) {
          gen.writeStartObject();
          jsonise(b, gen);
          gen.writeEnd();
        }
        gen.writeEnd();
      }
    }
  }
Esempio n. 9
0
  @GET
  @Path("entityManager")
  @Produces(MediaType.APPLICATION_JSON)
  public String search(
      @QueryParam("sessionId") String sessionId,
      @QueryParam("query") String query,
      @QueryParam("id") Long id)
      throws IcatException {

    if (sessionId == null) {
      throw new IcatException(IcatExceptionType.BAD_PARAMETER, "sessionId is not set");
    }
    if (query == null) {
      throw new IcatException(IcatExceptionType.BAD_PARAMETER, "query is not set");
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    JsonGenerator gen = Json.createGenerator(baos);

    String userName = beanManager.getUserName(sessionId, manager);
    if (id == null) {
      gen.writeStartArray();

      for (Object result : beanManager.search(userName, query, manager, userTransaction)) {
        if (result == null) {
          gen.writeNull();
        } else if (result instanceof EntityBaseBean) {
          gen.writeStartObject();
          gen.writeStartObject(result.getClass().getSimpleName());
          jsonise((EntityBaseBean) result, gen);
          gen.writeEnd();
          gen.writeEnd();
        } else if (result instanceof Long) {
          gen.write((Long) result);
        } else if (result instanceof Double) {
          if (Double.isNaN((double) result)) {
            gen.writeNull();
          } else {
            gen.write((Double) result);
          }
        } else if (result instanceof String) {
          gen.write((String) result);
        } else if (result instanceof Boolean) {
          gen.write((Boolean) result);
        } else {
          throw new IcatException(
              IcatException.IcatExceptionType.INTERNAL,
              "Don't know how to jsonise " + result.getClass());
        }
      }

      gen.writeEnd();
    } else {
      EntityBaseBean result = beanManager.get(userName, query, id, manager, userTransaction);
      gen.writeStartObject();
      gen.writeStartObject(result.getClass().getSimpleName());
      jsonise(result, gen);
      gen.writeEnd();
      gen.writeEnd();
    }

    gen.close();
    return baos.toString();
  }
Esempio n. 10
0
 // Note that the START_OBJECT has already been swallowed
 private EntityBaseBean parseEntity(EventChecker checker, String beanName) throws IcatException {
   Class<EntityBaseBean> klass = EntityInfoHandler.getClass(beanName);
   Map<Field, Method> getters = eiHandler.getGetters(klass);
   Map<Field, Method> setters = eiHandler.getSetters(klass);
   Set<Field> atts = eiHandler.getAttributes(klass);
   Set<Field> updaters = eiHandler.getSettersForUpdate(klass).keySet();
   Map<String, Field> fieldsByName = eiHandler.getFieldsByName(klass);
   EntityBaseBean bean = null;
   JsonParser parser = checker.parser;
   try {
     bean = klass.newInstance();
     while (true) {
       Event event = checker.get(Event.KEY_NAME, Event.END_OBJECT);
       if (event == Event.END_OBJECT) {
         break;
       }
       Field field = fieldsByName.get(parser.getString());
       if (field == null) {
         throw new IcatException(
             IcatExceptionType.BAD_PARAMETER,
             "Field " + parser.getString() + " not found in " + beanName);
       } else if (field.getName().equals("id")) {
         checker.get(Event.VALUE_NUMBER);
         bean.setId(Long.parseLong(parser.getString()));
       } else if (atts.contains(field)) {
         checker.get(Event.VALUE_NUMBER, Event.VALUE_STRING);
         String type = field.getType().getSimpleName();
         Object arg;
         if (type.equals("String")) {
           arg = parser.getString();
         } else if (type.equals("Integer")) {
           arg = Integer.parseInt(parser.getString());
         } else if (type.equals("Double")) {
           arg = Double.parseDouble(parser.getString());
         } else if (type.equals("Long")) {
           arg = Long.parseLong(parser.getString());
         } else if (type.equals("boolean")) {
           arg = Boolean.parseBoolean(parser.getString());
           // } else if (field.getType().isEnum()) {
           // arg =
           // gen.write(field.getName(), value.toString());
         } else if (type.equals("Date")) {
           synchronized (df8601) {
             try {
               arg = df8601.parse(parser.getString());
             } catch (ParseException e) {
               throw new IcatException(
                   IcatExceptionType.BAD_PARAMETER, "Badly formatted date " + parser.getString());
             }
           }
         } else {
           throw new IcatException(
               IcatExceptionType.BAD_PARAMETER,
               "Don't know how to parseEntity field of type " + type);
         }
         setters.get(field).invoke(bean, arg);
       } else if (updaters.contains(field)) {
         event = checker.get(Event.START_OBJECT);
         EntityBaseBean arg = parseEntity(checker, field.getType().getSimpleName());
         setters.get(field).invoke(bean, arg);
       } else {
         checker.get(Event.START_ARRAY);
         @SuppressWarnings("unchecked")
         List<EntityBaseBean> col = (List<EntityBaseBean>) getters.get(field).invoke(bean);
         while (true) {
           event = checker.get(Event.START_OBJECT, Event.END_ARRAY);
           if (event == Event.END_ARRAY) {
             break;
           }
           EntityBaseBean arg = parseEntity(checker, field.getName());
           col.add(arg);
         }
       }
     }
   } catch (InstantiationException
       | IllegalAccessException
       | IllegalArgumentException
       | InvocationTargetException
       | JsonException e) {
     throw new IcatException(
         IcatExceptionType.BAD_PARAMETER,
         e.getClass()
             + " "
             + e.getMessage()
             + " at "
             + parser.getLocation().getStreamOffset()
             + " in json");
   }
   return bean;
 }