Example #1
1
  public static void viewAd(String id) {

    Ad ad = Ad.findById(Long.parseLong(id));
    List<Category> cats = Category.find("categorytype_id=?1 order by id", "1").fetch();

    EntityManager entityManager = play.db.jpa.JPA.em();
    List<BigInteger> bCounts =
        entityManager
            .createNativeQuery(
                "select count(*) as maxCount from Ad as a group by category_id order by maxCount")
            .getResultList();
    int min = bCounts.get(0).intValue();
    int max = bCounts.get(bCounts.size() - 1).intValue();
    bCounts =
        entityManager
            .createNativeQuery(
                "select count(*) as maxCount from Ad as a group by category_id order by category_id ")
            .getResultList();
    List<String> fonts = new ArrayList<String>();
    for (int i = 0; i < bCounts.size(); i++) {
      BigInteger count = bCounts.get(i);
      int x = Ads.getFontSize(count.intValue(), min, max);
      fonts.add(String.valueOf(x));
    }

    render(ad, fonts, min, max, cats);
  }
Example #2
0
 private static void addProjectNotDupped(List<Project> target, List<Project> foundProjects) {
   for (Project project : foundProjects) {
     if (!target.contains(project)) {
       target.add(project);
     }
   }
 }
  public static void showPicasaGallery(Long id, String name) {
    notFoundIfNull(id);
    PicasaGallery gallery = PicasaGallery.findById(id);
    notFoundIfNull(gallery);

    PicasawebService service = new PicasawebService("portfolio");
    List<PhotoEntry> photoEntries = Collections.emptyList();
    try {
      java.net.URL feedUrl = new java.net.URL(gallery.getFeedUrl());

      AlbumFeed feed = service.getFeed(feedUrl, AlbumFeed.class);
      photoEntries = feed.getPhotoEntries();
    } catch (MalformedURLException e) {
      Logger.error("Service URL for Picasa is not well formed");
      e.printStackTrace();
    } catch (IOException e) {
      Logger.error("Error I/O while communicating with Picasa Service");
      e.printStackTrace();
    } catch (ServiceException e) {
      Logger.error("Picasa service error");
      e.printStackTrace();
    }

    List<ImageView> images = new ArrayList<ImageView>();
    for (PhotoEntry entry : photoEntries) {
      ImageView image = new ImageView();
      // We take the largest
      image.thumbnail =
          entry.getMediaThumbnails().get(entry.getMediaThumbnails().size() - 1).getUrl();
      image.url = entry.getMediaContents().get(0).getUrl();
      images.add(image);
    }

    render("Application/gallery.html", images, gallery);
  }
Example #4
0
  private List<Medication> searchRegnr(String lang, String regnr) {
    List<Medication> med_auth = new ArrayList<>();

    try {
      Connection conn = lang.equals("de") ? german_db.getConnection() : french_db.getConnection();
      Statement stat = conn.createStatement();
      String query =
          "select "
              + SHORT_TABLE
              + " from "
              + DATABASE_TABLE
              + " where "
              + KEY_REGNRS
              + " like "
              + "'%, "
              + regnr
              + "%' or "
              + KEY_REGNRS
              + " like "
              + "'"
              + regnr
              + "%'";
      ResultSet rs = stat.executeQuery(query);
      if (rs != null) {
        while (rs.next()) {
          med_auth.add(cursorToShortMedi(rs));
        }
      }
      conn.close();
    } catch (SQLException e) {
      System.err.println(">> SqlDatabase: SQLException in searchRegnr!");
    }

    return med_auth;
  }
Example #5
0
  public static Result start() {
    java.util.Map<String, String[]> map = request().body().asFormUrlEncoded();

    List<String> terms = new ArrayList<>(map.size());
    for (int i = 0; i < map.size(); i++) {
      String key = "terms[" + i + "]";
      if (map.containsKey(key)) {
        String[] values = map.get(key);
        if ((values != null) && (values.length >= 1)) {
          terms.add(values[0]);
        }
      }
    }

    StreamConfig config = getConfig();
    config.putTerms(terms);
    config.update();

    StringBuilder sb = new StringBuilder();
    for (String t : terms) {
      sb.append(t);
      sb.append(", ");
    }
    sb.delete(sb.length() - 2, sb.length());

    try {
      startStream(terms);
      flash("success", "Twitter stream started (" + sb.toString() + ")");
    } catch (TwitterException e) {
      Logger.info("Error starting twitter stream", e);
      flash("error", "Error starting Twitter stream" + e.getMessage());
    }
    return redirect(routes.Streams.listAll());
  }
Example #6
0
 // #list-validate
 public List<ValidationError> validate() {
   List<ValidationError> errors = new ArrayList<ValidationError>();
   if (User.byEmail(email) != null) {
     errors.add(new ValidationError("email", "This e-mail is already registered."));
   }
   return errors.isEmpty() ? null : errors;
 }
  public static void showGallery(Long id, String name) {
    notFoundIfNull(id);
    Gallery gallery = Gallery.findById(id);
    notFoundIfNull(gallery);

    List<Picture> pictures = gallery.getPictures();
    List<ImageView> images = new ArrayList<ImageView>();
    for (Picture picture : pictures) images.add(picture.toImageView());

    render("Application/gallery.html", images, gallery);
  }
Example #8
0
  private List<Medication> searchName(String lang, String name) {
    List<Medication> med_titles = new ArrayList<>();

    try {
      Connection conn = lang.equals("de") ? german_db.getConnection() : french_db.getConnection();
      Statement stat = conn.createStatement();
      ResultSet rs;
      // Allow for search to start inside a word...
      if (name.length() > 2) {
        String query =
            "select "
                + SHORT_TABLE
                + " from "
                + DATABASE_TABLE
                + " where "
                + KEY_TITLE
                + " like "
                + "'"
                + name
                + "%' or "
                + KEY_TITLE
                + " like "
                + "'%"
                + name
                + "%'";
        rs = stat.executeQuery(query);
      } else {
        String query =
            "select "
                + SHORT_TABLE
                + " from "
                + DATABASE_TABLE
                + " where "
                + KEY_TITLE
                + " like "
                + "'"
                + name
                + "%'";
        rs = stat.executeQuery(query);
      }
      if (rs != null) {
        while (rs.next()) {
          med_titles.add(cursorToShortMedi(rs));
        }
      }
      conn.close();
    } catch (SQLException e) {
      System.err.println(">> SqlDatabase: SQLException in searchName for " + name);
    }

    return med_titles;
  }
Example #9
0
  private static boolean replaceServerProperties(XMLServer server) {
    Class<?> serverclazz;

    try {
      serverclazz = Class.forName(server.getClazz());
    } catch (ClassNotFoundException e) {
      try {
        serverclazz = Class.forName("com.ingby.socbox.bischeck.servers." + server.getClazz());
      } catch (Exception ret) {
        return false;
      }
    }

    java.util.Properties defaultproperties = null;
    Method method;
    try {
      method = serverclazz.getMethod("getServerProperties");
      defaultproperties = (java.util.Properties) method.invoke(null);
    } catch (Exception ret) {
      return false;
    }

    Iterator<XMLProperty> iter = server.getProperty().iterator();
    // Update the default properties with what is currently set
    // in the server property
    while (iter.hasNext()) {
      XMLProperty xmlprop = iter.next();
      if (defaultproperties.containsKey(xmlprop.getKey()))
        defaultproperties.setProperty(xmlprop.getKey(), xmlprop.getValue());
    }

    // Create a new server property list
    List<XMLProperty> serverproperty = new ArrayList<XMLProperty>();
    Iterator<Object> keyiter = defaultproperties.keySet().iterator();

    while (keyiter.hasNext()) {
      String key = (String) keyiter.next();
      XMLProperty xmlprop = new XMLProperty();
      xmlprop.setKey(key);
      xmlprop.setValue((String) defaultproperties.get(key));
      serverproperty.add(xmlprop);
    }

    server.getProperty().clear();
    server.getProperty().addAll(serverproperty);

    return true;
  }
Example #10
0
  /**
   * ajax 를 이용한 사용자 검색 요청 헤더의 accept 파라미터에 application/json 값이 없으면 406 응답 응답에 포함되는 데이터 수는
   * MAX_FETCH_USERS 로 제한된다 입력 파라미터 query 가 부분매칭 되는 loginId 목록을 json 형태로 응답
   *
   * @param query 검색어
   * @return
   */
  public static Result users(String query) {
    if (!request().accepts("application/json")) {
      return status(Http.Status.NOT_ACCEPTABLE);
    }

    ExpressionList<User> el = User.find.select("loginId").where().contains("loginId", query);
    int total = el.findRowCount();
    if (total > MAX_FETCH_USERS) {
      el.setMaxRows(MAX_FETCH_USERS);
      response().setHeader("Content-Range", "items " + MAX_FETCH_USERS + "/" + total);
    }

    List<String> loginIds = new ArrayList<>();
    for (User user : el.findList()) {
      loginIds.add(user.loginId);
    }

    return ok(toJson(loginIds));
  }
Example #11
0
  public static void saveProperty() {
    String servername = params.get("servername");
    String key = params.get("key");
    String value = params.get("value");

    boolean existingKey = false;
    XMLServers serversconfig = getCache();
    Iterator<XMLServer> servers = serversconfig.getServer().iterator();

    while (servers.hasNext()) {
      XMLServer server = servers.next();

      if (server.getName().equals(servername)) {

        Iterator<XMLProperty> propertiesIter = server.getProperty().iterator();
        while (propertiesIter.hasNext()) {

          XMLProperty xmlprop = propertiesIter.next();

          if (xmlprop.getKey().equals(key)) {
            existingKey = true;
            xmlprop.setValue(value);
          }
        }
        if (!existingKey) {
          List<XMLProperty> propertiesList = server.getProperty();
          XMLProperty property = new XMLProperty();
          property.setKey(key);
          property.setValue(value);
          propertiesList.add(property);
        }
        flash.success(Messages.get("SaveServerPropertySuccess"));
        edit(server.getName());
      }
    }
  }
  public static void upload(String imei, File data) {

    try {

      File pbFile =
          new File(
              Play.configuration.getProperty("application.uploadDataDirectory"),
              imei + "_" + new Date().getTime() + ".pb");
      Logger.info(pbFile.toString());
      data.renameTo(pbFile);

      byte[] dataFrame = new byte[(int) pbFile.length()];
      ;
      DataInputStream dataInputStream =
          new DataInputStream(new BufferedInputStream(new FileInputStream(pbFile)));

      dataInputStream.read(dataFrame);
      Upload upload = Upload.parseFrom(dataFrame);

      Phone phone = Phone.find("imei = ?", imei).first();
      if (phone == null) badRequest();

      for (Upload.Route r : upload.getRouteList()) {

        if (r.getPointList().size() <= 1) continue;

        Agency a = Agency.find("gtfsAgencyId = ?", "DEFAULT").first();
        Route route = new Route("", r.getRouteName(), RouteType.BUS, r.getRouteDescription(), a);
        route.phone = phone;
        route.routeNotes = r.getRouteNotes();
        route.vehicleCapacity = r.getVehicleCapacity();
        route.vehicleType = r.getVehicleType();
        route.captureTime = new Date(r.getStartTime());
        route.save();

        List<String> points = new ArrayList<String>();

        Integer pointSequence = 1;
        for (Upload.Route.Point p : r.getPointList()) {
          points.add(new Double(p.getLon()).toString() + " " + new Double(p.getLat()).toString());
          RoutePoint.addRoutePoint(p, route.id, pointSequence);
          pointSequence++;
        }

        String linestring = "LINESTRING(" + StringUtils.join(points, ", ") + ")";

        BigInteger tripShapeId = TripShape.nativeInsert(TripShape.em(), "", linestring, 0.0);

        TripPattern tp = new TripPattern();
        tp.route = route;
        tp.headsign = r.getRouteName();
        tp.shape = TripShape.findById(tripShapeId.longValue());
        tp.save();

        Integer sequenceId = 0;

        for (Upload.Route.Stop s : r.getStopList()) {
          BigInteger stopId = Stop.nativeInsert(Stop.em(), s);

          TripPatternStop tps = new TripPatternStop();
          tps.stop = Stop.findById(stopId.longValue());
          tps.stopSequence = sequenceId;
          tps.defaultTravelTime = s.getArrivalTimeoffset();
          tps.defaultDwellTime = s.getDepartureTimeoffset() - s.getArrivalTimeoffset();
          tps.pattern = tp;
          tps.board = s.getBoard();
          tps.alight = s.getAlight();
          tps.save();

          sequenceId++;
        }

        // ProcessGisExport gisExport = new ProcessGisExport(tp.id);
        // gisExport.doJob();
      }

      Logger.info("Routes uploaded: " + upload.getRouteList().size());

      dataInputStream.close();

      ok();
    } catch (Exception e) {
      e.printStackTrace();
      badRequest();
    }
  }
Example #13
0
  public static void list(
      String search, int category, Integer size, Integer page, int firstPage, int lastPage) {
    List<Ad> ads = null;

    List<Category> cats = Category.find("categorytype_id=?1", "1").fetch();

    EntityManager entityManager = play.db.jpa.JPA.em();
    List<BigInteger> bCounts =
        entityManager
            .createNativeQuery(
                "select count(*) as maxCount from Ad as a group by category_id order by maxCount")
            .getResultList();
    int min = bCounts.get(0).intValue();
    int max = bCounts.get(bCounts.size() - 1).intValue();
    bCounts =
        entityManager
            .createNativeQuery(
                "select count(*) as maxCount from Ad as a group by category_id order by category_id ")
            .getResultList();
    List<String> fonts = new ArrayList<String>();
    for (int i = 0; i < bCounts.size(); i++) {
      BigInteger count = bCounts.get(i);
      int x = Ads.getFontSize(count.intValue(), min, max);
      fonts.add(String.valueOf(x));
    }

    int pagesCount = 0;

    page = page != null ? page : 1;
    if (search.trim().length() == 0) {
      Long l = null;
      if (category == 0) {

        ads = Ad.find("order by createDate desc").fetch(page, size);
        l = Ad.count();
      } else {

        ads = Ad.find(" category_id=?1 order by createDate desc", category).fetch(page, size);
        l = Ad.count(" category_id=?1 ", category);
      }

      Long l2 = (l / 10);
      if ((l % 10) > 0) l2 = (long) (Math.floor(l2) + 1);
      pagesCount = Integer.valueOf(l2.intValue());

    } else {
      search = search.toLowerCase();
      Long l = null;
      if (category == 0) {
        ads =
            Ad.find(
                    "(lower(headline) like ?1 OR lower(description) like ?2)",
                    "%" + search + "%",
                    "%" + search + "%")
                .fetch(page, size);
        l =
            Ad.count(
                "(lower(headline) like ?1 OR lower(description) like ?2)",
                "%" + search + "%",
                "%" + search + "%");
      } else {
        ads =
            Ad.find(
                    " category_id=?1 and (lower(headline) like ?2 OR lower(description) like ?3)",
                    category,
                    "%" + search + "%",
                    "%" + search + "%")
                .fetch(page, size);
        l =
            Ad.count(
                "category_id=?1 and (lower(headline) like ?2 OR lower(description) like ?3)",
                category,
                "%" + search + "%",
                "%" + search + "%");
      }

      Long l2 = (l / 10);
      if ((l % 10) > 0) l2 = (long) (Math.floor(l2) + 1);
      pagesCount = Integer.valueOf(l2.intValue());
    }

    if ((lastPage - page) <= 2) {
      firstPage = page - 2;
      lastPage = page + 7;
      if (lastPage > pagesCount) lastPage = pagesCount;

    } else if ((page - firstPage) <= 2) {
      firstPage = page - 7;
      lastPage = page + 2;
      if (firstPage < 1) {
        firstPage = 1;
        lastPage = 10;
      }
    }

    if (lastPage > pagesCount) lastPage = pagesCount;

    render(ads, search, size, page, pagesCount, firstPage, lastPage, cats, fonts);
  }
Example #14
0
  /**
   * Utility method loads all of the workflow form definitions from yaml files contained in the
   * workflow directory.
   *
   * @return
   */
  public static List<FormDefinition> loadWorkflowFormDefinitions() {
    //        List<FormDefinition> formDefs = new ArrayList<>();
    //
    //        URL path = Play.application().classloader().getResource(WORKFLOWS_PATH);
    //        try {
    //            File dir = new File(path.toURI());
    //
    //            File[] workflows = dir.listFiles(new FilenameFilter() {
    //                public boolean accept(File dir, String name) {
    //                    return name.toLowerCase().endsWith(".yaml");
    //                }
    //            });
    //
    //            for (File file : workflows) {
    //                formDefs.add(loadFormDefinition(file.getAbsolutePath()));
    //            }
    //        } catch (URISyntaxException e) { /* Should not occur */ }

    List<FormDefinition> formDefs = new ArrayList<>();

    Collection<config.WorkflowConfig> workflows = ConfigManager.getInstance().getWorkflowConfigs();

    for (config.WorkflowConfig workflow : workflows) {
      FormDefinition formDef = new FormDefinition();
      formDef.name = workflow.getName();
      formDef.title = workflow.getTitle();
      formDef.yamlFile = workflow.getYaml();
      formDef.documentation = workflow.getDocumentation();
      formDef.instructions = workflow.getInstructions();
      formDef.summary = workflow.getSummary();

      for (ParameterConfig parameter : workflow.getParameters()) {
        if (parameter.isTyped()) {
          String type = parameter.getType();

          switch (type) {
            case "text":
              TextField textField = new TextField();
              textField.name = parameter.getName();
              textField.label = parameter.getLabel();
              textField.tooltip = parameter.getDescription();
              formDef.addField(textField);
              break;
            case "select":
              SelectField selectField = new SelectField();
              selectField.name = parameter.getName();
              selectField.label = parameter.getLabel();
              selectField.options = parameter.getOptions();
              selectField.tooltip = parameter.getDescription();
              formDef.addField(selectField);
              break;
            case "upload":
              FileInput fileInput = new FileInput();
              fileInput.name = parameter.getName();
              fileInput.label = parameter.getLabel();
              fileInput.tooltip = parameter.getDescription();
              formDef.addField(fileInput);
              break;
          }
        }
      }

      formDefs.add(formDef);
    }
    return formDefs;
  }
Example #15
0
 public void addRecommendation(Recommendation rec) {
   recommendations.add(rec);
 }