コード例 #1
1
ファイル: Ads.java プロジェクト: habib123/SEBA
  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);
  }
コード例 #2
0
  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);
  }
コード例 #3
0
ファイル: Streams.java プロジェクト: janpascal/tweet-play2
  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());
  }
コード例 #4
0
 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);
 }
コード例 #5
0
  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);
  }
コード例 #6
0
ファイル: Streams.java プロジェクト: janpascal/tweet-play2
 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());
 }
コード例 #7
0
 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();
   }
 }
コード例 #8
0
ファイル: Servers.java プロジェクト: thenodon/bisconf
  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;
  }
コード例 #9
0
ファイル: Streams.java プロジェクト: janpascal/tweet-play2
  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() + "...");
  }
コード例 #10
0
ファイル: Streams.java プロジェクト: janpascal/tweet-play2
 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;
 }
コード例 #11
0
ファイル: Application.java プロジェクト: D-Roch/Cabster
  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;
  }
コード例 #12
0
ファイル: Servers.java プロジェクト: thenodon/bisconf
  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());
      }
    }
  }
コード例 #13
0
  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();
    }
  }
コード例 #14
0
ファイル: Ads.java プロジェクト: habib123/SEBA
  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);
  }
コード例 #15
0
ファイル: Choice.java プロジェクト: Vitamen/surveyApp
 public void addRecommendation(Recommendation rec) {
   recommendations.add(rec);
 }