Beispiel #1
1
 public Set<Sport> getSports() {
   Set<Sport> sports = new HashSet<Sport>();
   for (SeasonalTeam st : getSeasonalTeams()) {
     Sport sport = Sport.getInstance(st);
     if (!ObjectUtils.isBlank(sport)) {
       sports.add(sport);
     }
   }
   return sports;
 }
Beispiel #2
1
  public Long getEventsPlayedCount(Sport sport) {

    if (ObjectUtils.isBlank(sport)) {
      return null;
    }

    ObjectType seasonalAthleteType = ObjectType.getInstance(sport.getSeasonalAthleteClass());

    Query<SeasonalAthlete> seasonalAthleteQuery =
        Query.from(SeasonalAthlete.class)
            .where("typeId = ? && athlete = ?", seasonalAthleteType, this);
    return Query.from(Event.class).where("seasonalAthletes = ?", seasonalAthleteQuery).count();
  }
Beispiel #3
0
  public void beforeSave(Database database) {
    if (ObjectUtils.isBlank(getNaturalKey()) && !ObjectUtils.isBlank(this.getSchool())) {
      String schoolNaturalKey = this.getSchool().getNaturalKey();

      this.setNaturalKey(schoolNaturalKey + "/" + getFirstLastNameNaturalDiscriminator());
    }
  }
    /** Adds the given {@code type} to all type cache maps. */
    public void add(ObjectType type) {
      String className = type.getObjectClassName();
      if (!ObjectUtils.isBlank(className)) {
        byClassName.put(className.toLowerCase(Locale.ENGLISH), type);
      }

      byId.put(type.getId(), type);

      String internalName = type.getInternalName();
      if (!ObjectUtils.isBlank(internalName)) {
        byName.put(internalName.toLowerCase(Locale.ENGLISH), type);
      }

      for (String group : type.getGroups()) {
        if (group != null) {
          group = group.toLowerCase(Locale.ENGLISH);
        }

        Set<ObjectType> groupTypes = byGroup.get(group);
        if (groupTypes == null) {
          groupTypes = new HashSet<ObjectType>();
          byGroup.put(group, groupTypes);
        }
        groupTypes.remove(type);
        groupTypes.add(type);
      }
    }
Beispiel #5
0
 public List<SeasonalTeam> getSeasonalTeams() {
   List<SeasonalTeam> seasonalTeams = new ArrayList<SeasonalTeam>();
   for (SeasonalAthlete a : getAllSeasonalAthletes()) {
     if (!ObjectUtils.isBlank(a) && !ObjectUtils.isBlank(a.getTeam())) {
       seasonalTeams.add(a.getTeam());
     }
   }
   return seasonalTeams;
 }
Beispiel #6
0
  public Image getAvatar() {

    if (ObjectUtils.isBlank(avatar)) {

      if (!ObjectUtils.isBlank(photo)) {
        avatar = photo;
      } else if (!ObjectUtils.isBlank(getSchool())
          && !ObjectUtils.isBlank(getSchool().getAvatar())) {
        avatar = getSchool().getAvatar();
      }
    }

    return avatar;
  }
        @Override
        protected List<DynamicProperty> create() {
          List<DynamicProperty> properties = new ArrayList<DynamicProperty>();

          for (ObjectType type : getTypes()) {
            if (type.getObjectClass() == null) {
              continue;
            }

            String beanProperty = type.getJavaBeanProperty();

            if (ObjectUtils.isBlank(beanProperty)) {
              continue;
            }

            try {
              properties.add(
                  new DynamicProperty(type, beanProperty, beanPropertyIndexes.get(beanProperty)));

            } catch (Exception error) {
              // Failed introspection so probably not a valid bean
              // property.
            }
          }

          return ImmutableList.copyOf(properties);
        }
Beispiel #8
0
  /** Returns a table of all the widgets with the given {@code positionName}. */
  public List<List<Widget>> findWidgets(String positionName) {

    Map<Double, Map<Double, Widget>> widgetsMap = new TreeMap<Double, Map<Double, Widget>>();
    for (Widget widget : findPlugins(Widget.class)) {
      for (Widget.Position position : widget.getPositions()) {
        if (ObjectUtils.equals(position.getName(), positionName)) {
          double column = position.getColumn();
          Map<Double, Widget> widgets = widgetsMap.get(column);
          if (widgets == null) {
            widgets = new TreeMap<Double, Widget>();
            widgetsMap.put(column, widgets);
          }
          widgets.put(position.getRow(), widget);
          break;
        }
      }
    }

    List<List<Widget>> widgetsTable = new ArrayList<List<Widget>>();
    for (Map<Double, Widget> map : widgetsMap.values()) {
      List<Widget> widgets = new ArrayList<Widget>();
      widgets.addAll(map.values());
      widgetsTable.add(widgets);
    }

    return widgetsTable;
  }
  @Override
  protected void doInitialize(String settingsKey, Map<String, Object> settings) {
    String clusterName = ObjectUtils.to(String.class, settings.get(CLUSTER_NAME_SUB_SETTING));

    Preconditions.checkNotNull(clusterName);

    String indexName = ObjectUtils.to(String.class, settings.get(INDEX_NAME_SUB_SETTING));

    Preconditions.checkNotNull(indexName);

    String typeName = ObjectUtils.to(String.class, settings.get(TYPE_NAME_SUB_SETTING));

    this.indexName = indexName;
    this.typeName = typeName;
    this.node = NodeBuilder.nodeBuilder().clusterName(clusterName).client(true).node();
  }
Beispiel #10
0
  @Override
  public void format(HtmlWriter writer) throws IOException {
    writer.writeStart("pre");

    State state = getState();
    ObjectType type = state.getType();
    if (type != null) {
      writer.writeHtml(type.getInternalName());
      writer.writeHtml(": ");
    }

    writer.writeStart(
        "a",
        "target",
        "_blank",
        "href",
        StringUtils.addQueryParameters(
            "/_debug/query", "where", "id = " + state.getId(), "action", "Run"));
    writer.writeHtml(getLabel());
    writer.writeEnd();
    writer.writeElement("br");

    writer.writeHtml(ObjectUtils.toJson(state.getSimpleValues(), true));

    writer.writeEnd();
  }
Beispiel #11
0
  public String getSchedulePermalink() {
    String permalink = "/athlete/schedule/" + getId();
    String key = getNaturalKey();
    if (!ObjectUtils.isBlank(key)) {
      permalink = getSeoFriendlyPermalink() + "/" + SCORES_SCHEDULES_PATH;
    }

    return permalink;
  }
Beispiel #12
0
 private boolean evaluateOne(State state, Object keyValue, List<Object> values) {
   if (!(keyValue instanceof Recordable || keyValue instanceof UUID)) {
     Class<?> keyValueClass = keyValue.getClass();
     for (ListIterator<Object> i = values.listIterator(); i.hasNext(); ) {
       i.set(ObjectUtils.to(keyValueClass, i.next()));
     }
   }
   return compare(state, keyValue, values);
 }
Beispiel #13
0
 @Override
 protected boolean compare(State state, Object keyValue, List<Object> values) {
   for (Object value : values) {
     if (ObjectUtils.compare(keyValue, value, false) > 0) {
       return false;
     }
   }
   return true;
 }
Beispiel #14
0
  public String getVideoMediaPermalink() {
    String permalink = "/athlete/media/video/" + getId();
    String key = getNaturalKey();
    if (!ObjectUtils.isBlank(key)) {
      permalink = getSeoFriendlyPermalink() + "/" + MEDIA_PATH;
    }

    return permalink;
  }
Beispiel #15
0
  public String getNewsPermalink() {
    String permalink = "/athlete/news/" + getId();
    String key = getNaturalKey();
    if (!ObjectUtils.isBlank(key)) {
      permalink = getSeoFriendlyPermalink() + "/" + NEWS_PATH;
    }

    return permalink;
  }
Beispiel #16
0
  public String getFollowersPermalink() {
    String permalink = "/athlete/followers/" + getId();
    String key = getNaturalKey();
    if (!ObjectUtils.isBlank(key)) {
      permalink = getSeoFriendlyPermalink() + "/" + FOLLOWERS_PATH;
    }

    return permalink;
  }
  @Override
  public int compare(Object x, Object y) {
    State xState = State.getInstance(x);
    State yState = State.getInstance(y);

    Object xValue = xState != null ? filter(xState.getByPath(field)) : null;
    Object yValue = yState != null ? filter(yState.getByPath(field)) : null;

    return ObjectUtils.compare(xValue, yValue, isNullGreatest);
  }
Beispiel #18
0
  /**
   * Synchronizes the given {@code plugin} with the existing one in the database if it can be found.
   */
  private void synchronizePlugin(Plugin plugin) {

    State pluginState = plugin.getState();
    Database database = getState().getDatabase();
    pluginState.setDatabase(database);

    UUID typeId = pluginState.getTypeId();
    Tool tool = plugin.getTool();
    String internalName = plugin.getInternalName();

    for (Plugin p : getAllPlugins(database)) {
      if (ObjectUtils.equals(typeId, p.getState().getTypeId())
          && ObjectUtils.equals(tool, p.getTool())
          && ObjectUtils.equals(internalName, p.getInternalName())) {
        pluginState.setId(p.getId());
        break;
      }
    }
  }
Beispiel #19
0
  public List<SeasonalAthlete> findSeasonalAthletes(Sport sport) {

    if (ObjectUtils.isBlank(sport)) {
      return null;
    }

    ObjectType seasonalAthleteType = ObjectType.getInstance(sport.getSeasonalAthleteClass());

    return Query.from(SeasonalAthlete.class)
        .where("typeId = ? && athlete = ?", seasonalAthleteType, this)
        .selectAll();
  }
Beispiel #20
0
  public String getSeoTitle() {

    String firstName = this.getFirstName();
    String lastName = this.getLastName();

    String schoolTitle = null;
    if (!ObjectUtils.isBlank(this.getSchool())) {
      schoolTitle = this.getSchool().createSeoTitle();
    }

    String discriminator = String.format("%1$s %2$s", firstName, lastName);

    return discriminator;
  }
Beispiel #21
0
    /**
     * Returns the main application object as determined by the {@value
     * com.psddev.dari.db.Application#MAIN_CLASS_SETTING} {@linkplain Settings#get setting} within
     * the given {@code database}.
     *
     * @return May be {@code null} if the setting is not set.
     * @throws SettingsException If the class name in the setting is not valid.
     */
    public static Application getMainUsing(Database database) {

      String appClassName = Settings.get(String.class, MAIN_CLASS_SETTING);
      if (ObjectUtils.isBlank(appClassName)) {
        return null;
      }

      Class<?> objectClass = ObjectUtils.getClassByName(appClassName);
      if (objectClass == null) {
        throw new SettingsException(
            MAIN_CLASS_SETTING, String.format("[%s] is not a valid class name!", appClassName));
      }

      if (Application.class.isAssignableFrom(objectClass)) {
        @SuppressWarnings("unchecked")
        Class<? extends Application> appClass = (Class<? extends Application>) objectClass;
        return getInstanceUsing(appClass, database);

      } else {
        throw new SettingsException(
            MAIN_CLASS_SETTING,
            String.format("[%s] is not a [%s] class!", appClassName, Application.class.getName()));
      }
    }
Beispiel #22
0
    /**
     * Returns the singleton application object matching the given {@code applicationClass} within
     * the given {@code database}.
     */
    @SuppressWarnings("unchecked")
    public static <T extends Application> T getInstanceUsing(
        Class<T> applicationClass, Database database) {

      ObjectType type = database.getEnvironment().getTypeByClass(applicationClass);
      Query<T> query =
          Query.from(applicationClass).where("_type = ?", type.getId()).using(database);
      T app = query.first();

      if (app == null) {
        DistributedLock lock =
            DistributedLock.Static.getInstance(database, applicationClass.getName());
        lock.lock();

        try {
          app = query.clone().noCache().first();
          if (app == null) {
            app = (T) type.createObject(null);
            app.setName(type.getDisplayName());
            app.saveImmediately();
            return app;
          }

        } finally {
          lock.unlock();
        }
      }

      String oldName = app.getName();
      String newName = type.getDisplayName();
      if (!ObjectUtils.equals(oldName, newName)) {
        app.setName(newName);
        app.save();
      }

      return app;
    }
  @Override
  public String getLabel() {
    String name = getName();
    StringBuilder label = new StringBuilder();

    if (ObjectUtils.isBlank(name)) {
      Date triggerDate = getTriggerDate();

      label.append(triggerDate != null ? triggerDate.toString() : getId().toString());

    } else {
      label.append(name);
    }

    long draftCount = Query.from(Draft.class).where("schedule = ?", this).count();

    if (draftCount > 1) {
      label.append(" (");
      label.append(draftCount);
      label.append(" items)");
    }

    return label.toString();
  }
Beispiel #24
0
  private void startQueryEvent(String event, Query<?> query) {
    StackTraceElement caller = null;

    Profiler.Static.pauseThreadEvent();

    try {
      StackTraceElement[] elements = new Throwable().getStackTrace();

      for (int i = 2, length = elements.length; i < length; ++i) {
        StackTraceElement element = elements[i];
        String className = element.getClassName();
        Class<?> c = ObjectUtils.getClassByName(className);

        if (c == null || !(Database.class.isAssignableFrom(c) || Query.class.isAssignableFrom(c))) {
          caller = element;
          break;
        }
      }

    } finally {
      Profiler.Static.resumeThreadEvent();
    }

    Object resolving = query.getOptions().get(State.REFERENCE_RESOLVING_QUERY_OPTION);

    if (resolving != null) {
      Profiler.Static.startThreadEvent(
          event + " (Reference Resolving)",
          resolving,
          query.getOptions().get(State.REFERENCE_FIELD_QUERY_OPTION),
          caller);

    } else {
      Profiler.Static.startThreadEvent(event, caller, query);
    }
  }
 protected void beforeSave() {
   if (ObjectUtils.isBlank(getName()) && getTriggerDate() == null) {
     throw new IllegalArgumentException("Must provide either the name or the trigger date!");
   }
 }
  protected void writeTableHtml(Iterable<?> items) throws IOException {
    HttpServletRequest request = page.getRequest();

    page.putOverride(
        Recordable.class,
        (HtmlWriter writer, Recordable object) -> {
          ToolPageContext page = (ToolPageContext) writer;

          page.writeObjectLabel(object);
        });

    page.putOverride(
        Metric.class,
        (HtmlWriter writer, Metric object) -> {
          writer.write(Double.toString(object.getSum()));
        });

    page.putOverride(
        Content.class,
        (HtmlWriter writer, Content content) -> {
          ToolPageContext page = (ToolPageContext) writer;

          page.writeStart(
              "a", "href", page.objectUrl("/content/edit.jsp", content), "target", "_top");
          page.writeObjectLabel(content);
          page.writeEnd();
        });

    page.putOverride(
        StorageItem.class,
        (HtmlWriter writer, StorageItem item) -> {
          ToolPageContext page = (ToolPageContext) writer;

          page.writeElement(
              "img",
              "height",
              100,
              "src",
              ImageEditor.Static.getDefault() != null
                  ? new ImageTag.Builder(item).setHeight(100).toUrl()
                  : item.getPublicUrl());
        });

    page.writeStart("table", "class", "searchResultTable links table-striped pageThumbnails");
    page.writeStart("thead");
    page.writeStart("tr");
    page.writeStart("th");
    page.writeElement("input", "type", "checkbox", "class", "searchResult-checkAll");
    page.writeEnd();

    if (sortField != null && ObjectField.DATE_TYPE.equals(sortField.getInternalType())) {

      page.writeStart("th", "colspan", 2);
      page.writeHtml(sortField.getDisplayName());
      page.writeEnd();
    }

    if (showSiteLabel) {
      page.writeStart("th");
      page.writeHtml(page.localize(ListSearchResultView.class, "label.site"));
      page.writeEnd();
    }

    if (showTypeLabel) {
      page.writeStart("th");
      page.writeHtml(page.localize(ListSearchResultView.class, "label.type"));
      page.writeEnd();
    }

    page.writeStart("th");
    page.writeHtml(page.localize(ListSearchResultView.class, "label.label"));
    page.writeEnd();

    if (sortField != null && !ObjectField.DATE_TYPE.equals(sortField.getInternalType())) {

      page.writeStart("th");
      page.writeHtml(sortField.getDisplayName());
      page.writeEnd();
    }

    ToolUser user = page.getUser();

    if (user != null) {
      ObjectType selectedType = search.getSelectedType();
      List<String> fieldNames =
          user.getSearchResultFieldsByTypeId()
              .get(selectedType != null ? selectedType.getId().toString() : "");

      if (fieldNames == null) {
        for (Class<? extends SearchResultField> c :
            ClassFinder.Static.findClasses(SearchResultField.class)) {
          if (!c.isInterface() && !Modifier.isAbstract(c.getModifiers())) {
            SearchResultField field = TypeDefinition.getInstance(c).newInstance();

            if (field.isDefault(selectedType) && !ObjectUtils.equals(sortField, field)) {
              field.writeTableHeaderCellHtml(page);
            }
          }
        }

        if (selectedType != null) {
          for (ObjectField field : selectedType.getFields()) {
            if (Boolean.TRUE.equals(field.as(ToolUi.class).getDefaultSearchResult())) {
              writeHeaderCell(field);
            }
          }
        }

      } else {
        for (String fieldName : fieldNames) {
          Class<?> fieldNameClass = ObjectUtils.getClassByName(fieldName);

          if (fieldNameClass != null && SearchResultField.class.isAssignableFrom(fieldNameClass)) {
            @SuppressWarnings("unchecked")
            SearchResultField field =
                TypeDefinition.getInstance((Class<? extends SearchResultField>) fieldNameClass)
                    .newInstance();

            if (field.isSupported(selectedType) && !ObjectUtils.equals(sortField, field)) {
              field.writeTableHeaderCellHtml(page);
            }

          } else {
            ObjectField field = null;
            if (selectedType != null) {
              field = selectedType.getField(fieldName);
            }

            if (field == null) {
              field = Database.Static.getDefault().getEnvironment().getField(fieldName);
            }

            if (field != null && !ObjectUtils.equals(sortField, field)) {
              writeHeaderCell(field);
            }
          }
        }
      }
    }
    page.writeEnd();
    page.writeEnd();

    page.writeStart("tbody");
    for (Object item : items) {
      State itemState = State.getInstance(item);
      String permalink = itemState.as(Directory.ObjectModification.class).getPermalink();
      Integer embedWidth = null;

      if (ObjectUtils.isBlank(permalink)) {
        ObjectType type = itemState.getType();

        if (type != null) {
          Renderer.TypeModification rendererData = type.as(Renderer.TypeModification.class);
          int previewWidth = rendererData.getEmbedPreviewWidth();

          if (previewWidth > 0 && !ObjectUtils.isBlank(rendererData.getEmbedPath())) {

            permalink = "/_preview?_embed=true&_cms.db.previewId=" + itemState.getId();
            embedWidth = 320;
          }
        }
      }

      page.writeStart(
          "tr",
          "data-preview-url",
          permalink,
          "data-preview-embed-width",
          embedWidth,
          "class",
          State.getInstance(item).getId().equals(page.param(UUID.class, "id")) ? "selected" : null);

      page.writeStart("td");
      itemWriter.writeCheckboxHtml(page, search, item);
      page.writeEnd();

      if (sortField != null && ObjectField.DATE_TYPE.equals(sortField.getInternalType())) {

        DateTime dateTime = page.toUserDateTime(itemState.getByPath(sortField.getInternalName()));

        if (dateTime == null) {
          page.writeStart("td", "colspan", 2);
          page.writeHtml("N/A");
          page.writeEnd();

        } else {
          String date = page.formatUserDate(dateTime);

          page.writeStart("td", "class", "date");
          if (!ObjectUtils.equals(date, request.getAttribute(PREVIOUS_DATE_ATTRIBUTE))) {
            request.setAttribute(PREVIOUS_DATE_ATTRIBUTE, date);
            page.writeHtml(date);
          }
          page.writeEnd();

          page.writeStart("td", "class", "time");
          page.writeHtml(page.formatUserTime(dateTime));
          page.writeEnd();
        }
      }

      if (showSiteLabel) {
        page.writeStart("td");
        page.writeObjectLabel(itemState.as(Site.ObjectModification.class).getOwner());
        page.writeEnd();
      }

      if (showTypeLabel) {
        page.writeStart("td");
        page.writeTypeLabel(item);
        page.writeEnd();
      }

      page.writeStart("td", "data-preview-anchor", "");
      itemWriter.writeBeforeHtml(page, search, item);
      page.writeObjectLabel(item);
      itemWriter.writeAfterHtml(page, search, item);
      page.writeEnd();

      if (sortField != null && !ObjectField.DATE_TYPE.equals(sortField.getInternalType())) {

        String sortFieldName = sortField.getInternalName();
        Object value = itemState.getByPath(sortFieldName);

        page.writeStart("td");
        if (value instanceof Metric) {
          page.writeStart("span", "style", page.cssString("white-space", "nowrap"));
          Double maxSum = (Double) request.getAttribute(MAX_SUM_ATTRIBUTE);

          if (maxSum == null) {
            Object maxObject = search.toQuery(page.getSite()).sortDescending(sortFieldName).first();
            maxSum =
                maxObject != null
                    ? ((Metric) State.getInstance(maxObject).get(sortFieldName)).getSum()
                    : 1.0;

            request.setAttribute(MAX_SUM_ATTRIBUTE, maxSum);
          }

          Metric valueMetric = (Metric) value;
          Map<DateTime, Double> sumEntries =
              valueMetric.groupSumByDate(
                  new MetricInterval.Daily(),
                  new DateTime().dayOfMonth().roundFloorCopy().minusDays(7),
                  null);

          double sum = valueMetric.getSum();
          long sumLong = (long) sum;

          if (sumLong == sum) {
            page.writeHtml(String.format("%,2d ", sumLong));

          } else {
            page.writeHtml(String.format("%,2.2f ", sum));
          }

          if (!sumEntries.isEmpty()) {
            long minMillis = Long.MAX_VALUE;
            long maxMillis = Long.MIN_VALUE;

            for (Map.Entry<DateTime, Double> sumEntry : sumEntries.entrySet()) {
              long sumMillis = sumEntry.getKey().getMillis();

              if (sumMillis < minMillis) {
                minMillis = sumMillis;
              }

              if (sumMillis > maxMillis) {
                maxMillis = sumMillis;
              }
            }

            double cumulativeSum = 0.0;
            StringBuilder path = new StringBuilder();
            double xRange = maxMillis - minMillis;
            int width = 35;
            int height = 18;

            for (Map.Entry<DateTime, Double> sumEntry : sumEntries.entrySet()) {
              cumulativeSum += sumEntry.getValue();

              path.append('L');
              path.append((sumEntry.getKey().getMillis() - minMillis) / xRange * width);
              path.append(',');
              path.append(height - cumulativeSum / maxSum * height);
            }

            path.setCharAt(0, 'M');

            page.writeStart(
                "svg",
                "xmlns",
                "http://www.w3.org/2000/svg",
                "width",
                width,
                "height",
                height,
                "style",
                page.cssString(
                    "display", "inline-block",
                    "vertical-align", "middle"));

            page.writeStart("path", "fill", "none", "stroke", "#444444", "d", path.toString());
            page.writeEnd();
            page.writeEnd();
          }
          page.writeEnd();

        } else if (value instanceof Recordable) {
          page.writeHtml(((Recordable) value).getState().getLabel());

        } else {
          for (Iterator<Object> i = CollectionUtils.recursiveIterable(value).iterator();
              i.hasNext(); ) {
            Object collectionValue = i.next();

            page.writeObject(collectionValue);

            if (i.hasNext()) {
              page.writeHtml(", ");
            }
          }
        }
        page.writeEnd();
      }

      if (user != null) {
        ObjectType selectedType = search.getSelectedType();
        List<String> fieldNames =
            user.getSearchResultFieldsByTypeId()
                .get(selectedType != null ? selectedType.getId().toString() : "");
        ObjectType itemType = itemState.getType();

        if (fieldNames == null) {
          for (Class<? extends SearchResultField> c :
              ClassFinder.Static.findClasses(SearchResultField.class)) {
            if (!c.isInterface() && !Modifier.isAbstract(c.getModifiers())) {
              SearchResultField field = TypeDefinition.getInstance(c).newInstance();

              if (field.isDefault(itemType) && !ObjectUtils.equals(sortField, field)) {
                field.writeTableDataCellHtml(page, item);
              }
            }
          }

          if (selectedType != null) {
            for (ObjectField field : selectedType.getFields()) {
              if (Boolean.TRUE.equals(field.as(ToolUi.class).getDefaultSearchResult())) {
                writeDataCell(itemState, field.getInternalName());
              }
            }
          }

        } else {
          for (String fieldName : fieldNames) {
            Class<?> fieldNameClass = ObjectUtils.getClassByName(fieldName);

            if (fieldNameClass != null
                && SearchResultField.class.isAssignableFrom(fieldNameClass)) {
              @SuppressWarnings("unchecked")
              SearchResultField field =
                  TypeDefinition.getInstance((Class<? extends SearchResultField>) fieldNameClass)
                      .newInstance();

              if (field.isSupported(itemState.getType()) && !ObjectUtils.equals(sortField, field)) {
                field.writeTableDataCellHtml(page, item);
              }

            } else {
              ObjectField field = itemState.getField(fieldName);

              if (field == null) {
                field = Database.Static.getDefault().getEnvironment().getField(fieldName);
              }

              if (field != null && !ObjectUtils.equals(sortField, field)) {
                writeDataCell(itemState, fieldName);
              }
            }
          }
        }
      }
      page.writeEnd();
    }
    page.writeEnd();
    page.writeEnd();

    page.writeStart("div", "id", page.createId());
    page.writeEnd();

    page.writeStart("script", "type", "text/javascript");
    page.writeRaw(
        "$('#" + page.getId() + "').siblings('.searchResultTable').find('tr').each(function() {");
    page.writeRaw("    if ($(this).find('td > a').size() > 1) {");
    page.writeRaw(
        "        $(this).closest('.searchResultTable').addClass('multipleLinkedColumns');");
    page.writeRaw("        return false;");
    page.writeRaw("    }");
    page.writeRaw(" });");
    page.writeEnd();
  }
Beispiel #27
0
    public static void writeContents(
        Database database,
        BootstrapPackage pkg,
        Set<ObjectType> additionalTypes,
        Writer writer,
        String projectName)
        throws IOException {
      boolean first = true;
      boolean needsObjectTypeMap = false;
      Set<ObjectType> typeMaps = new HashSet<ObjectType>();
      ObjectType objType = database.getEnvironment().getTypeByClass(ObjectType.class);
      Set<ObjectType> exportTypes = new HashSet<ObjectType>();
      Query<?> query = Query.fromAll().using(database);
      Set<ObjectType> allTypeMappableTypes = new HashSet<ObjectType>();
      Set<UUID> concreteTypeIds = new HashSet<UUID>();

      for (ObjectType type : database.getEnvironment().getTypes()) {
        if (!type.as(TypeData.class).getTypeMappableGroups().isEmpty()
            && type.as(TypeData.class).getTypeMappableUniqueKey() != null) {
          allTypeMappableTypes.add(type);
        }
      }

      // Package:
      writer.write(PACKAGE_NAME_HEADER + ": ");
      writer.write(pkg.getName());
      writer.write('\n');
      // Project:
      writer.write(PROJECT_HEADER + ": ");
      writer.write(projectName);
      writer.write('\n');
      // Date:
      writer.write(DATE_HEADER + ": ");
      writer.write(new DateTime().toString("yyyy-MM-dd HH:mm:ss z"));
      writer.write('\n');

      // Types:
      writer.write(TYPES_HEADER + ": ");
      if (pkg.isInit()) {
        writer.write(ALL_TYPES_HEADER_VALUE);
        writer.write('\n');
      } else {
        exportTypes.addAll(getAllTypes(database, pkg));
        exportTypes.addAll(getAllTypes(database, additionalTypes));
        for (ObjectType typeMappableType : allTypeMappableTypes) {
          GETTYPEMAPPABLETYPE:
          for (ObjectType type : exportTypes) {
            for (String group : typeMappableType.as(TypeData.class).getTypeMappableGroups()) {
              if (type.getGroups().contains(group)) {
                typeMaps.add(typeMappableType);
                break GETTYPEMAPPABLETYPE;
              }
            }
          }
        }
        GETOBJECTTYPE:
        for (ObjectType type : exportTypes) {
          for (ObjectField field : type.getFields()) {
            if (field.getTypes().contains(objType)) {
              needsObjectTypeMap = true;
              break GETOBJECTTYPE;
            }
          }
        }

        for (ObjectType exportType : exportTypes) {
          String clsName = exportType.getObjectClassName();
          if (!ObjectUtils.isBlank(clsName)) {
            for (ObjectType concreteType : database.getEnvironment().getTypesByGroup(clsName)) {
              if (!concreteType.isAbstract()) {
                concreteTypeIds.add(concreteType.getId());
              }
            }
          }
        }

        if (exportTypes.contains(objType)) {
          if (!first) {
            writer.write(',');
          } else {
            first = false;
          }
          writer.write(objType.getInternalName());
        }
        for (ObjectType type : exportTypes) {
          if (type.equals(objType)) {
            continue;
          }
          if (!first) {
            writer.write(',');
          } else {
            first = false;
          }
          writer.write(type.getInternalName());
        }
        writer.write('\n');
      }

      // Determine if there are any fields that need references followed
      Map<UUID, Map<String, ObjectType>> followReferences =
          new HashMap<UUID, Map<String, ObjectType>>();
      if (!pkg.isInit()) {
        for (ObjectType type : exportTypes) {
          for (String fieldName : type.as(TypeData.class).getFollowReferencesFields()) {
            ObjectField field = type.getField(fieldName);
            if (field != null) {
              for (ObjectType fieldType : field.getTypes()) {
                if (!exportTypes.contains(fieldType)) {
                  if (!followReferences.containsKey(type.getId())) {
                    followReferences.put(type.getId(), new HashMap<String, ObjectType>());
                  }
                  followReferences.get(type.getId()).put(fieldName, fieldType);
                }
              }
            }
          }
        }
      }

      if (!typeMaps.isEmpty()) {
        for (ObjectType typeMapType : typeMaps) {
          String clsName = typeMapType.getObjectClassName();
          if (!ObjectUtils.isBlank(clsName)) {
            for (ObjectType type : database.getEnvironment().getTypesByGroup(clsName)) {
              concreteTypeIds.remove(type.getId());
            }
          }
        }
      }

      // Mapping Types:
      if (pkg.isInit() || needsObjectTypeMap || !typeMaps.isEmpty()) {
        first = true;
        writer.write(TYPE_MAP_HEADER + ": ");
        if (pkg.isInit() || needsObjectTypeMap) {
          writer.write(objType.getInternalName());
          writer.write("/internalName");
          first = false;
        }
        for (ObjectType typeMapType : typeMaps) {
          if (!first) {
            writer.write(',');
          } else {
            first = false;
          }
          writer.write(typeMapType.getInternalName());
          writer.write('/');
          writer.write(typeMapType.as(TypeData.class).getTypeMappableUniqueKey());
        }
        writer.write('\n');
      }

      // Row Count:
      Long count = 0L;
      try {
        if (concreteTypeIds.isEmpty()) {
          count = Query.fromAll().using(database).noCache().count();
        } else {
          for (UUID concreteTypeId : concreteTypeIds) {
            long concreteCount =
                Query.fromAll()
                    .using(database)
                    .noCache()
                    .where("_type = ?", concreteTypeId)
                    .count();
            count = count + concreteCount;
          }
          if (needsObjectTypeMap) {
            long objectCount =
                Query.fromAll().using(database).noCache().where("_type = ?", objType).count();
            count = count + objectCount;
          }
          if (!typeMaps.isEmpty()) {
            for (ObjectType typeMapType : typeMaps) {
              long typeMapCount =
                  Query.fromAll().using(database).noCache().where("_type = ?", typeMapType).count();
              count = count + typeMapCount;
            }
          }
        }
        writer.write(ROW_COUNT_HEADER + ": ");
        writer.write(ObjectUtils.to(String.class, count));
        writer.write('\n');
      } catch (RuntimeException e) {
        // Count query timed out. Just don't write the row count header.
        count = null;
      }

      // blank line between headers and data
      writer.write('\n');
      writer.flush();

      // ObjectType records first
      if (exportTypes.isEmpty() || exportTypes.contains(objType) || needsObjectTypeMap) {
        for (Object r :
            Query.fromType(objType)
                .using(database)
                .noCache()
                .resolveToReferenceOnly()
                .iterable(100)) {
          writer.write(ObjectUtils.toJson(((Recordable) r).getState().getSimpleValues(true)));
          writer.write('\n');
        }
      }

      // Then other mapping types
      for (ObjectType typeMapType : typeMaps) {
        for (Object r :
            Query.fromType(typeMapType)
                .using(database)
                .noCache()
                .resolveToReferenceOnly()
                .iterable(100)) {
          writer.write(ObjectUtils.toJson(((Recordable) r).getState().getSimpleValues(true)));
          writer.write('\n');
        }
      }

      // Then everything else
      if (pkg.isInit()) {
        concreteTypeIds.clear(); // should already be empty
        concreteTypeIds.add(null);
      }
      UUID lastTypeId = null;
      Set<UUID> seenIds = new HashSet<UUID>();
      query.getOptions().put(SqlDatabase.USE_JDBC_FETCH_SIZE_QUERY_OPTION, false);
      for (UUID typeId : concreteTypeIds) {
        Query<?> concreteQuery = query.clone();
        if (typeId != null) {
          concreteQuery.where("_type = ?", typeId);
        }
        for (Object o : concreteQuery.noCache().resolveToReferenceOnly().iterable(100)) {
          if (o instanceof Recordable) {
            Recordable r = (Recordable) o;
            writer.write(ObjectUtils.toJson(r.getState().getSimpleValues(true)));
            writer.write('\n');
            if (!pkg.isInit()) {
              if (lastTypeId == null || !lastTypeId.equals(r.getState().getTypeId())) {
                seenIds.clear();
              } else if (seenIds.size() > MAX_SEEN_REFERENCE_IDS_SIZE) {
                seenIds.clear();
              }
              lastTypeId = r.getState().getTypeId();
              Map<String, ObjectType> followReferencesFieldMap;
              if ((followReferencesFieldMap = followReferences.get(r.getState().getTypeId()))
                  != null) {
                for (Map.Entry<String, ObjectType> entry : followReferencesFieldMap.entrySet()) {
                  Object reference = r.getState().getRawValue(entry.getKey());
                  Set<UUID> referenceIds = new HashSet<UUID>();
                  if (reference instanceof Collection) {
                    for (Object referenceObj : ((Collection<?>) reference)) {
                      if (referenceObj instanceof Recordable) {
                        UUID referenceUUID =
                            ObjectUtils.to(
                                UUID.class, ((Recordable) referenceObj).getState().getId());
                        if (referenceUUID != null) {
                          if (!seenIds.contains(referenceUUID)) {
                            referenceIds.add(referenceUUID);
                          }
                        }
                      }
                    }
                  } else if (reference instanceof Recordable) {
                    UUID referenceUUID =
                        ObjectUtils.to(UUID.class, ((Recordable) reference).getState().getId());
                    if (referenceUUID != null) {
                      if (!seenIds.contains(referenceUUID)) {
                        referenceIds.add(referenceUUID);
                      }
                    }
                  }
                  if (!referenceIds.isEmpty()) {
                    for (Object ref :
                        Query.fromType(entry.getValue())
                            .noCache()
                            .using(database)
                            .where("_id = ?", referenceIds)
                            .selectAll()) {
                      if (ref instanceof Recordable) {
                        Recordable refr = (Recordable) ref;
                        seenIds.add(refr.getState().getId());
                        writer.write(ObjectUtils.toJson(refr.getState().getSimpleValues(true)));
                        writer.write('\n');
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }

      writer.flush();
    }
 public String getTypeName() {
   return !ObjectUtils.isBlank(typeName) ? typeName : "dari";
 }
Beispiel #29
0
  // Reads: key operator value
  private Predicate readComparison(Queue<String> tokens, ParameterList parameters) {
    String key = tokens.poll();
    if (key == null) {
      return null;
    }

    String realKey = Query.Static.getCanonicalKey(key);
    if (realKey != null) {
      key = realKey;
    }

    String operator = tokens.poll();
    boolean isIgnoreCase = false;
    if (operator == null) {
      throw new IllegalArgumentException(String.format("No operator after [%s] key!", key));
    } else {
      operator = operator.toLowerCase(Locale.ENGLISH);
      if (operator.endsWith("[c]")) {
        operator = operator.substring(0, operator.length() - 3);
        isIgnoreCase = true;
      }
    }

    Object value = readValue(tokens);
    if (value == null) {
      throw new IllegalArgumentException(
          String.format("No value after [%s] key and [%s] operator!", key, operator));

    } else if (value instanceof String) {
      String valueString = (String) value;

      if (valueString.startsWith("?")) {
        if (valueString.length() == 1) {
          value = parameters.poll();

        } else {
          String path = valueString.substring(1);
          int slashAt = path.indexOf('/');
          String splitIndex;
          String splitPath;

          if (slashAt > -1) {
            splitIndex = path.substring(0, slashAt);
            splitPath = path.substring(slashAt + 1);
          } else {
            splitIndex = path;
            splitPath = "";
          }

          Integer index = ObjectUtils.to(Integer.class, splitIndex);

          if (index == null) {
            index = 0;
          } else {
            path = splitPath;
          }

          value = index < parameters.size() ? parameters.get(index) : null;

          if (value != null && path.length() > 0) {
            if (value instanceof Recordable) {
              value = ((Recordable) value).getState().getByPath(path);
            } else {
              value = CollectionUtils.getByPath(value, path);
            }
          }
        }

      } else if ("true".equalsIgnoreCase(valueString)) {
        value = Boolean.TRUE;

      } else if ("false".equalsIgnoreCase(valueString)) {
        value = Boolean.FALSE;

      } else if ("null".equalsIgnoreCase(valueString)) {
        value = null;

      } else if ("missing".equalsIgnoreCase(valueString)) {
        value = Query.MISSING_VALUE;
      }
    }

    String comparisonOperator = getComparisonOperators().get(operator);
    if (comparisonOperator != null) {
      return new ComparisonPredicate(
          comparisonOperator, isIgnoreCase, key, ObjectUtils.to(Iterable.class, value));

    } else {
      throw new IllegalArgumentException(
          String.format("[%s] isn't a valid comparison operator!", operator));
    }
  }
Beispiel #30
0
 @Override
 public int compareTo(Record other) {
   return ObjectUtils.compare(getLabel(), other.getLabel(), true);
 }