Exemple #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);
  }
  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;
  }
Exemple #3
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());
  }
  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);
  }
Exemple #5
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;
 }
Exemple #6
0
 private static void addProjectNotDupped(List<Project> target, List<Project> foundProjects) {
   for (Project project : foundProjects) {
     if (!target.contains(project)) {
       target.add(project);
     }
   }
 }
 private static void showPage(String custId, String errMsg) {
   // Obviously this is inefficient -- the list of customer and products never changes,
   // so we could cache it.
   List<Customer> customers = Customer.find("order by name").fetch();
   List<Product> products = Product.find("order by name").fetch();
   Customer currentCustomer;
   if (custId == null || custId.trim().length() == 0) currentCustomer = customers.get(0);
   else currentCustomer = Customer.findById(new Long(custId));
   renderTemplate("Application/index.html", customers, currentCustomer, products, errMsg);
 }
  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);
  }
  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;
  }
Exemple #10
0
 public TweetListener(List<String> terms, Client esClient, String esIndex, String esType) {
   this.terms = terms;
   this.esClient = esClient;
   StringBuilder query = new StringBuilder();
   for (int i = 0; i < terms.size(); i++) {
     if (i > 0) query.append("|");
     // query.append("(").append(Pattern.quote(terms.get(i))).append(")");
     // query.append("(").append(terms.get(i)).append(")");
     query.append(terms.get(i));
   }
   Logger.info("Query match pattern: " + query.toString());
   this.matchPattern = Pattern.compile(query.toString(), Pattern.CASE_INSENSITIVE);
   Logger.info("Query match pattern: " + matchPattern.toString());
 }
 public static void ajaxDeleteDocument(Long documentId) {
   // If it is not the root document we are going to delete
   if (documentId != 0L) {
     Document document = Document.findById(documentId);
     List<Document> children =
         Document.find("select p from Document p where p.parentId=?", document.id).fetch();
     // If target document contains children documents
     // then remove all children, don't leave scala documents
     int i = 0;
     for (i = 0; i < children.size(); i++) {
       children.get(i).delete();
     }
     document.delete();
   }
 }
Exemple #12
0
  private static void startStream(List<String> terms) throws TwitterException {
    if (twitter != null) {
      twitter.cleanUp();
    }
    if (esClient != null) {
      esClient.close();
      esClient = null;
    }

    play.Configuration pconf = Play.application().configuration();
    String elasticSearchCluster = pconf.getString("tweet.elasticsearch.cluster.name");
    if (elasticSearchCluster != null) {
      Logger.info("Configuring ElasticSearch...");
      Settings settings =
          ImmutableSettings.settingsBuilder().put("cluster.name", elasticSearchCluster).build();

      esClient =
          new TransportClient(settings)
              .addTransportAddress(
                  new InetSocketTransportAddress(
                      pconf.getString("tweet.elasticsearch.transport.host"),
                      pconf.getInt("tweet.elasticsearch.transport.port")));
    } else {
      esClient = null;
    }

    twitter4j.conf.Configuration tconf = Application.getTwitterConfiguration();
    TwitterStreamFactory tf = new TwitterStreamFactory(tconf);
    twitter = tf.getInstance();
    StatusListener l =
        new TweetListener(
            terms,
            esClient,
            pconf.getString("tweet.elasticsearch.index"),
            pconf.getString("tweet.elasticsearch.type"));
    twitter.addListener(l);

    String[] tracks = new String[terms.size()];
    StringBuffer termsString = new StringBuffer();
    for (int i = 0; i < terms.size(); i++) {
      tracks[i] = terms.get(i);
      if (i != 0) termsString.append(",");
      termsString.append(terms.get(i));
    }
    FilterQuery q = new FilterQuery().track(tracks);
    twitter.filter(q);
    Logger.info("Starting listening for tweets using terms " + termsString.toString() + "...");
  }
Exemple #13
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;
  }
Exemple #14
0
 private static void collectDatum(
     List<Project> projects,
     List<Posting> postings,
     List<Issue> issues,
     List<PullRequest> pullRequests,
     List<Milestone> milestones,
     int daysAgo) {
   // collect all postings, issues, pullrequests and milesotnes that are contained in the projects.
   for (Project project : projects) {
     if (AccessControl.isAllowed(UserApp.currentUser(), project.asResource(), Operation.READ)) {
       postings.addAll(Posting.findRecentlyCreatedByDaysAgo(project, daysAgo));
       issues.addAll(Issue.findRecentlyOpendIssuesByDaysAgo(project, daysAgo));
       pullRequests.addAll(PullRequest.findOpendPullRequestsByDaysAgo(project, daysAgo));
       milestones.addAll(Milestone.findOpenMilestones(project.id));
     }
   }
 }
Exemple #15
0
 private static StreamConfig getConfig() {
   List<StreamConfig> configs = StreamConfig.find.findList();
   if (configs.size() > 1) {
     Logger.error("Multiple stream configurations present!");
   }
   StreamConfig config;
   if (configs.isEmpty()) {
     String[] tracks = new String[3];
     tracks[0] = "nl-alert";
     tracks[1] = "nlalert";
     tracks[2] = "\"nl alert\"";
     config = new StreamConfig(tracks);
     config.save();
   } else {
     config = configs.get(0);
   }
   return config;
 }
Exemple #16
0
  public static List sortByValue(Map map) {
    List list = new LinkedList(map.entrySet());
    Collections.sort(
        list,
        new Comparator() {
          public int compare(Object o1, Object o2) {
            return ((Comparable) ((Map.Entry) (o1)).getValue())
                .compareTo(((Map.Entry) (o2)).getValue());
          }
        });

    Map result = new LinkedHashMap();
    for (Iterator it = list.iterator(); it.hasNext(); ) {
      Map.Entry entry = (Map.Entry) it.next();
      result.put(entry.getKey(), entry.getValue());
    }
    Collections.reverse(list);
    return list;
  }
Exemple #17
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));
  }
Exemple #18
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());
      }
    }
  }
Exemple #19
0
 public void addRecommendation(Recommendation rec) {
   recommendations.add(rec);
 }
  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();
    }
  }
  /**
   * 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;
  }
Exemple #22
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);
  }