Exemplo n.º 1
0
 /**
  * @param v The synsets
  * @param t The Topic
  * @return The number of words in the synset also found in the topic
  */
 public static int checkAmbig(Vector<Synset> v, Topic t) {
   int count = 0;
   boolean result = false;
   if (v == null) return count;
   for (Synset set : v) {
     Word[] w = set.getWords();
     for (Word word : w) {
       String rec = word.getLemma();
       String toLookup = WNLookup.getStaticStem(rec);
       result = t.containsKey(toLookup);
       if (result || t.containsKey(rec)) {
         count++;
         Log.logger.debug(
             "[found a related word on my mind: '"
                 + toLookup
                 + "', recent count for this topic '"
                 + t.getName()
                 + "' is: "
                 + count
                 + "]");
       }
     }
   }
   return count;
 }
Exemplo n.º 2
0
  @Override
  public Page getPage(int pageNum, String lastMod)
      throws ContentGetException, ContentParseException {
    String[] wgetReply = this.wgetText(this.linkPage(pageNum), lastMod);
    String pageText = wgetReply[0];
    String newLastMod = wgetReply[1];

    Page p = new Page(pageNum);
    Topic t = null;

    Matcher mat = postGetPattern.matcher(pageText);

    while (mat.find()) {
      String text = mat.group(1);
      String type = mat.group(2);

      if (type.equals("opContainer")) {
        t = this.parseThread(text);
        p.addThread(t);
      } else {
        if (t != null) t.addPost(this.parsePost(text, t.getNum()));
      }
    }

    p.setLastMod(newLastMod);
    return p;
  }
Exemplo n.º 3
0
  public static String getTopicRss(String htmlPath, PreparedTopic preparedTopic)
      throws IOException, BadImageException {
    StringBuilder buf = new StringBuilder();

    Topic topic = preparedTopic.getMessage();

    if (preparedTopic.getSection().isImagepost()) {
      buf.append(NewsViewer.showMediumImage(htmlPath, topic, true));

      ImageInfo info =
          new ImageInfo(
              htmlPath + topic.getUrl(),
              ImageInfo.detectImageType(new File(htmlPath + topic.getUrl())));

      buf.append(preparedTopic.getProcessedMessage());
      buf.append(
          "<p><i>"
              + info.getWidth()
              + 'x'
              + info.getHeight()
              + ", "
              + info.getSizeString()
              + "</i>");
    } else if (topic.isVotePoll()) {
      PreparedPoll poll = preparedTopic.getPoll();
      buf.append(poll.renderPoll());
    } else {
      buf.append(preparedTopic.getProcessedMessage());
    }

    return buf.toString();
  }
Exemplo n.º 4
0
  public void testTopic() throws Exception {
    char[] text;
    AttributesImpl attributes = new AttributesImpl();
    AttributesImpl topicAtts = new AttributesImpl();
    topicAtts.addAttribute(null, "name", null, "String", "TEST TOPIC");
    handler.startElement(null, null, "topic", topicAtts);
    handler.startElement(null, null, "category", attributes);
    handler.startElement(null, null, "pattern", attributes);
    handler.characters(text = toCharArray("HELLO ALICE I AM *"), 0, text.length);
    handler.endElement(null, null, "pattern");
    handler.startElement(null, null, "template", attributes);
    handler.characters(text = toCharArray("Hello "), 0, text.length);
    handler.startElement(null, null, "star", attributes);
    handler.characters(text = toCharArray(", nice to meet you."), 0, text.length);
    handler.endElement(null, null, "template");
    handler.endElement(null, null, "category");
    handler.endElement(null, null, "topic");

    Topic actual = (Topic) stack.peek();
    Topic expected =
        new Topic(
            "TEST TOPIC",
            new Category(
                new Pattern("HELLO ALICE I AM *"),
                new Template("Hello ", new Star(1), ", nice to meet you.")));
    assertEquals(expected, actual);
    assertEquals("TEST TOPIC", actual.getName());
  }
Exemplo n.º 5
0
  @Override
  public Topic getThread(int threadNum, String lastMod)
      throws ContentGetException, ContentParseException {
    String[] wgetReply = this.wgetText(this.linkThread(threadNum), lastMod);
    String threadText = wgetReply[0];
    String newLastMod = wgetReply[1];

    Topic t = null;

    Matcher mat = postGetPattern.matcher(threadText);

    while (mat.find()) {
      String text = mat.group(1);
      String type = mat.group(2);
      if (type.equals("opContainer")) {
        if (t == null) {
          t = this.parseThread(text);
        } else {
          throw new ContentParseException("Two OP posts in thread in " + threadNum);
        }
      } else {
        if (t != null) {
          t.addPost(this.parsePost(text, t.getNum()));
        } else {
          throw new ContentParseException("Thread without OP post in " + threadNum);
        }
      }
    }

    t.setLastMod(newLastMod);
    return t;
  }
  public void printTopic(int topicID) throws IOException {

    Topic topicToPrint = readTopic(topicID);
    System.out.println("id:" + topicToPrint.getId());
    System.out.println("title:" + topicToPrint.getTitle());
    System.out.println("desc:" + topicToPrint.getDescription());
    System.out.println("narr:" + topicToPrint.getNarrative());
  }
Exemplo n.º 7
0
 @Override
 protected int calculateRemainingLength() {
   int length = 2;
   for (Topic topic : topics) {
     length = length + 2 + topic.getTopicName().getBytes().length + 1;
   }
   return length;
 }
Exemplo n.º 8
0
 public void setTopicSelectedByUser(String topicName) {
   if (getTopics() == null) throw new IllegalStateException();
   for (Topic topic : getTopics())
     if (topic.getTopicName().equals(topicName)) {
       setSelectedTopic(topic);
       break;
     }
 }
Exemplo n.º 9
0
  @Test
  public void testTopic() throws Exception {
    final Channel<String> channel1 = newChannel();
    final Channel<String> channel2 = newChannel();
    final Channel<String> channel3 = newChannel();

    final Topic<String> topic = new Topic<String>();

    topic.subscribe(channel1);
    topic.subscribe(channel2);
    topic.subscribe(channel3);

    Fiber f1 =
        new Fiber(
                fjPool,
                new SuspendableRunnable() {
                  @Override
                  public void run() throws SuspendExecution, InterruptedException {
                    assertThat(channel1.receive(), equalTo("hello"));
                    assertThat(channel1.receive(), equalTo("world!"));
                  }
                })
            .start();

    Fiber f2 =
        new Fiber(
                fjPool,
                new SuspendableRunnable() {
                  @Override
                  public void run() throws SuspendExecution, InterruptedException {
                    assertThat(channel2.receive(), equalTo("hello"));
                    assertThat(channel2.receive(), equalTo("world!"));
                  }
                })
            .start();

    Fiber f3 =
        new Fiber(
                fjPool,
                new SuspendableRunnable() {
                  @Override
                  public void run() throws SuspendExecution, InterruptedException {
                    assertThat(channel3.receive(), equalTo("hello"));
                    assertThat(channel3.receive(), equalTo("world!"));
                  }
                })
            .start();

    Thread.sleep(100);
    topic.send("hello");
    Thread.sleep(100);
    topic.send("world!");

    f1.join();
    f2.join();
    f3.join();
  }
Exemplo n.º 10
0
 public TocEntry lookupTopic(String href) {
   if (href.equals(getHref())) {
     return this;
   }
   for (Topic topic : getChildren()) {
     if (href.equals(topic.getHref())) return topic;
     TocEntry r = topic.lookupTopic(href);
     if (r != null) return r;
   }
   return null;
 }
Exemplo n.º 11
0
 public static List<String> getTopicIds(Set<Topic> topics) {
   List<String> ids = Collections.emptyList();
   if (topics != null && !topics.isEmpty()) {
     ids = new ArrayList<>();
     for (Topic topic : topics) {
       String id = getStringId(topic.getId());
       if (id != null) {
         ids.add(id);
       }
     }
   }
   return ids;
 }
Exemplo n.º 12
0
 /**
  * Returns the topic with highest score from the collection of topics.
  *
  * @param candidateTopics The collection of topics to check.
  * @return Returns the topic with highest score from the collection of topics.
  */
 public static Topic getTopicWithMaxScore(Collection candidateTopics) {
   double maxScore = 0;
   Topic bestTopic = null;
   for (Iterator iter = candidateTopics.iterator(); iter.hasNext(); ) {
     Topic recentTopic = (Topic) iter.next();
     double recentScore = recentTopic.getScore();
     if (recentScore >= maxScore) {
       maxScore = recentScore;
       bestTopic = recentTopic;
     }
   }
   return bestTopic;
 }
Exemplo n.º 13
0
 @Override
 public void validate() {
   if (messageID < 0) {
     throw new IllegalStateException("Negative Message ID.");
   }
   if (topics == null || topics.size() == 0) {
     throw new IllegalStateException("Topics not provided.");
   }
   for (Topic topic : topics) {
     if (!MQTTUtils.isTopicWildcardValid(topic.getTopicName())) {
       throw new IllegalStateException("Topic Name not provided or format incorrect.");
     }
   }
 }
Exemplo n.º 14
0
  private void perform(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String title = request.getParameter("title");
    String content = request.getParameter("content");

    Topic topic = new Topic();
    topic.setTitle(title);
    topic.setContent(content);

    BlogController ctrl = BlogController.getInstance();
    ctrl.postTopic(topic);

    request.getRequestDispatcher("/read").forward(request, response);
  }
Exemplo n.º 15
0
  public Topic parseThread(String text) throws ContentParseException {
    int omPosts = 0;
    Matcher mat = omPostsPattern.matcher(text);
    if (mat.find()) omPosts = Integer.parseInt(mat.group(1));

    int omImages = 0;
    mat = omImagesPattern.matcher(text);
    if (mat.find()) omImages = Integer.parseInt(mat.group(1));

    Post op = this.parsePost(text, 0);
    Topic thread = new Topic(op.getNum(), omPosts, omImages);
    thread.addPost(op);

    return thread;
  }
Exemplo n.º 16
0
  private Topic readTopic(int topicID) throws IOException {

    Topic topic = new Topic();

    record = new String();
    String topicString = "";
    boolean topicFounded = false;
    while ((record = br.readLine()) != null) {

      // System.out.println(record);
      if (record.indexOf("<num>") != -1
          && record.indexOf("Number:") != -1
          && record.indexOf(String.valueOf(topicID)) != -1) {
        topicFounded = true;
      }

      if (topicFounded) {
        topicString += record;
        if (record.indexOf("</top>") != -1) {

          // System.out.println(topicString);
          int titlePos = topicString.indexOf("<title>");
          int descPos = topicString.indexOf("<desc>");
          int narrPos = topicString.indexOf("<narr>");

          String title =
              topicString.substring(titlePos + 7, descPos).replaceFirst("Topic:", "").trim();

          String desc =
              topicString.substring(descPos + 6, narrPos).replaceFirst("Description:", "").trim();
          String narr =
              topicString
                  .substring(narrPos + 6, topicString.length() - 6)
                  .replaceFirst("Narrative:", "")
                  .trim();

          topic.setId(topicID);
          topic.setTitle(title);
          topic.setDescription(desc);
          topic.setNarrative(narr);

          return topic;
        }
      }
    }

    return null;
  }
Exemplo n.º 17
0
 public void addtopic(Topic t) {
   if (!_loaded) {
     load();
     _loaded = true;
   }
   _topic.put(t.getID(), t);
 }
Exemplo n.º 18
0
  /**
   * Changes the topic, and sends a notification to the other clients.
   *
   * @param newTopic The new topic to set.
   * @throws CommandException If there is no connection to the network, or the application user is
   *     away, or the topic is too long.
   */
  public void changeTopic(final String newTopic) throws CommandException {
    if (!isLoggedOn()) {
      throw new CommandException("You can not change the topic without being connected");
    } else if (me.isAway()) {
      throw new CommandException("You can not change the topic while away");
    } else if (Tools.getBytes(newTopic) > Constants.MESSAGE_MAX_BYTES) {
      throw new CommandException(
          "You can not set a topic with more than " + Constants.MESSAGE_MAX_BYTES + " bytes");
    }

    final long time = System.currentTimeMillis();
    final Topic newTopicObj = new Topic(newTopic, me.getNick(), time);
    messages.sendTopicChangeMessage(newTopicObj);
    final Topic topic = getTopic();
    topic.changeTopic(newTopicObj);
  }
Exemplo n.º 19
0
 public static com.umeng.comm.core.beans.FeedItem toValueOf(FeedItem feedItem) {
   if (feedItem == null) return null;
   com.umeng.comm.core.beans.FeedItem newFeedItem = new com.umeng.comm.core.beans.FeedItem();
   newFeedItem.id = feedItem.id;
   newFeedItem.text = feedItem.text;
   newFeedItem.sourceFeed = FeedItem.toValueOf(feedItem.sourceFeed);
   newFeedItem.addTime = feedItem.addTime;
   newFeedItem.atFriends = new ArrayList<>();
   for (User atUser : feedItem.atFriends) {
     newFeedItem.atFriends.add(User.toValue(atUser));
   }
   newFeedItem.creator = User.toValue(feedItem.creator);
   newFeedItem.imageUrls = new ArrayList<>();
   for (String imageUrl : feedItem.imageUrls) {
     newFeedItem.imageUrls.add(new ImageItem("", imageUrl, imageUrl));
   }
   newFeedItem.topics = new ArrayList<>();
   for (Topic newTopic : feedItem.topics) {
     newFeedItem.topics.add(Topic.toValue(newTopic));
   }
   newFeedItem.commentCount = feedItem.commentCount;
   newFeedItem.likeCount = feedItem.likeCount;
   newFeedItem.forwardCount = feedItem.forwardCount;
   newFeedItem.locationAddr = feedItem.locationAddr;
   newFeedItem.publishTime = feedItem.publishTime;
   return newFeedItem;
 }
Exemplo n.º 20
0
 public static FeedItem valueOf(com.umeng.comm.core.beans.FeedItem feedItem, int feedType) {
   if (feedItem == null) return null;
   FeedItem newFeedItem = new model.FeedItem();
   newFeedItem.id = feedItem.id;
   newFeedItem.text = feedItem.text;
   newFeedItem.sourceFeed = FeedItem.valueOf(feedItem.sourceFeed, -1);
   newFeedItem.addTime = feedItem.addTime;
   newFeedItem.atFriends = new ArrayList<>();
   for (CommUser atUser : feedItem.atFriends) {
     newFeedItem.atFriends.add(User.valueOf(atUser));
   }
   newFeedItem.creator = User.valueOf(feedItem.creator);
   newFeedItem.imageUrls = new ArrayList<>();
   for (ImageItem imageUrl : feedItem.imageUrls) {
     newFeedItem.imageUrls.add(imageUrl.originImageUrl);
   }
   newFeedItem.topics = new ArrayList<>();
   for (com.umeng.comm.core.beans.Topic newTopic : feedItem.topics) {
     newFeedItem.topics.add(Topic.valueOf(newTopic));
   }
   newFeedItem.commentCount = feedItem.commentCount;
   newFeedItem.likeCount = feedItem.likeCount;
   newFeedItem.forwardCount = feedItem.forwardCount;
   newFeedItem.locationAddr = feedItem.locationAddr;
   newFeedItem.feedType = feedType;
   newFeedItem.publishTime = feedItem.publishTime;
   return newFeedItem;
 }
Exemplo n.º 21
0
 public void destroy() {
   if (consumer != null) {
     consumer.shutdown();
     logger.info(
         "consumer shutdown! topic={0},subExpression={1},group={2}",
         topic.getTopic(), subExpression, group);
   }
 }
Exemplo n.º 22
0
  @RequestMapping(
      value = "/{section}/{group}/{id}/comments",
      produces = "application/json; charset=UTF-8",
      method = RequestMethod.GET)
  @ResponseBody
  public Map<String, Object> getComments(
      @PathVariable("section") String sectionName,
      @PathVariable("group") String groupName,
      @PathVariable("id") int msgid,
      @RequestParam(value = "page", defaultValue = "0") int page,
      HttpServletRequest request)
      throws Exception {
    Topic topic = topicDao.getById(msgid);
    Group group = groupDao.getGroup(topic.getGroupId());
    Section section = sectionService.getSection(group.getSectionId());

    if (!section.getUrlName().equals(sectionName)
        || !group.getUrlName().equals(groupName)
        || page < 0) {
      throw new MessageNotFoundException(msgid);
    }

    permissionService.checkView(topic, AuthUtil.getCurrentUser());

    CommentList comments = commentService.getCommentList(topic, false);

    CommentFilter cv = new CommentFilter(comments);

    int messagesPerPage = AuthUtil.getProfile().getMessages();

    List<Comment> commentsFiltered =
        cv.getCommentsForPage(false, page, messagesPerPage, ImmutableSet.<Integer>of());

    List<PreparedComment> preparedComments =
        prepareService.prepareCommentList(
            comments, commentsFiltered, request.isSecure(), Template.getTemplate(request), topic);

    return ImmutableMap.of(
        "comments",
        preparedComments,
        "topic",
        new ApiCommentTopicInfo(
            topic.getId(),
            topic.getLink(),
            permissionService.isCommentsAllowed(topic, AuthUtil.getCurrentUser())));
  }
Exemplo n.º 23
0
 @Override
 public int hashCode() {
   final int prime = 31;
   int result = super.hashCode();
   result = prime * result + ((mode == null) ? 0 : mode.hashCode());
   result = prime * result + ((name == null) ? 0 : name.hashCode());
   result = prime * result + ((type == null) ? 0 : type.hashCode());
   result = prime * result + ((topic == null) ? 0 : topic.hashCode());
   return result;
 }
Exemplo n.º 24
0
        public void call(final Object... args) {
          JSONObject data = (JSONObject) args[0];
          Log.d("JSON", data.toString());
          try {

            socket.emit("recevied", "");
            // Add the new topic to the view
            String title = data.getString("title");
            String description = data.getString("description");
            Boolean interesting = data.getBoolean("interesting");
            Boolean difficulty = data.getBoolean("difficulty");

            Boolean quiz = data.getBoolean("quiz");
            Topic theTopic = new Topic(title, description, interesting, difficulty, quiz);

            if (difficulty) {
              int maxDifficulty = data.getInt("maxDifficulty");
              int minDifficulty = data.getInt("minDifficulty");
              theTopic.maxDifficulty = maxDifficulty;
              theTopic.minDifficulty = minDifficulty;
            }

            if (quiz) {
              theTopic.questionType = data.getJSONObject("question").getString("type");
              theTopic.questionText = data.getJSONObject("question").getString("text");
              JSONArray answersArray = data.getJSONArray("answers");
              for (int i = 0; i < answersArray.length(); i++) {
                JSONObject a = (JSONObject) answersArray.get(i);
                String text = a.getString("text");
                Boolean correct = a.getBoolean("correct");
                Answer answer = new Answer(text, correct);

                theTopic.answers.add(theTopic.answers.size(), answer);
              }
            }

            add(theTopic);

          } catch (Exception e) {
            e.printStackTrace();
          }
        }
Exemplo n.º 25
0
 private void load() {
   try (Connection con = L2DatabaseFactory.getInstance().getConnection();
       PreparedStatement statement = con.prepareStatement(GET_FORUMS)) {
     statement.setInt(1, _sqlDPId);
     statement.setInt(2, _forumId);
     try (ResultSet result = statement.executeQuery()) {
       if (result.next()) {
         _forumName = result.getString("forum_name");
         _forumType = Integer.parseInt(result.getString("forum_type"));
         _ownerID = Integer.parseInt(result.getString("forum_owner_id"));
       }
     }
   } catch (Exception e) {
     _log.warning("data error on Forum " + _forumId + " : " + e);
     e.printStackTrace();
   }
   try (Connection con = L2DatabaseFactory.getInstance().getConnection();
       PreparedStatement statement = con.prepareStatement(GET_TOPICS)) {
     statement.setInt(1, _sqlDPId);
     statement.setInt(2, _forumId);
     try (ResultSet result = statement.executeQuery()) {
       while (result.next()) {
         Topic t =
             new Topic(
                 Topic.ConstructorType.RESTORE,
                 _sqlDPId,
                 Integer.parseInt(result.getString("topic_id")),
                 Integer.parseInt(result.getString("topic_forum_id")),
                 result.getString("topic_name"),
                 Integer.parseInt(result.getString("topic_ownerid")),
                 Integer.parseInt(result.getString("topic_permissions")));
         _topic.put(t.getID(), t);
       }
     }
   } catch (Exception e) {
     _log.warning("data error on Forum " + _forumId + " : " + e);
     e.printStackTrace();
   }
 }
Exemplo n.º 26
0
  @Override
  public int compare(Object o1, Object o2) {

    LOG.trace("compare");
    Topic t1 = (Topic) o1;
    Topic t2 = (Topic) o2;

    if (t1.getType() < t2.getType()) {
      return 1;
    } else if (t1.getType() == t2.getType()) {
      return t2.getLastPostDate().compareTo(t1.getLastPostDate());
    }

    return -1;
  }
Exemplo n.º 27
0
 /**
  * @param currentUser
  * @param currentTopic
  */
 public TextConf(User currentUser, Topic currentTopic, TextConfObserver obs) {
   this.currentUser = currentUser;
   this.currentTopic = currentTopic;
   this.observer = obs;
   this.setLogging(Level.WARNING);
   UserConfiguration.setUserName(this.currentUser.getUserName());
   _namespaceStr = BASE_NAMESPACE + "/" + currentTopic.getTopicName();
   _userToDigestHash = new HashMap<PublisherPublicKeyDigest, User>();
   try {
     _namespace = ContentName.fromURI(_namespaceStr);
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
  @Override
  public Page processRequest(HttpServletRequest request) {
    Page result = this;

    if ("new".equals(request.getParameter("action"))) {
      Member member = (Member) request.getSession().getAttribute("user");

      result = new TopicEdit(this, new Topic(member));
    } else if ("previous".equals(request.getParameter("action"))) {
      if (page > 1) {
        page--;
      }
    } else if ("next".equals(request.getParameter("action"))) {
      if (page < getNumberOfPages()) {
        page++;
      }
    } else if (isAction("edit")) {
      long id = Long.parseLong(request.getParameter("actionValue"));

      result = new TopicEdit(this, dao.find(id));
    } else if (isAction("remove")) {
      long topicId = Long.parseLong(request.getParameter("actionValue"));

      Topic topic = dao.find(topicId);

      CommentDao commentDao = new CommentDao();

      for (Comment comment : topic.getComments()) {
        commentDao.remove(comment);
      }

      dao.remove(topicId);
    }

    return result;
  }
Exemplo n.º 29
0
 /**
  * Check how good a given Vector of words matches a given topic by counting how many of the words
  * in the vector are keywords for the given topic.
  *
  * @param v The Vector of words to check for applicability to the topic
  * @param t The topic to check for applicability on the words
  * @param isWordNetEnabled If true words are stemmed
  * @return Returns a score, the number of words in the Vector that are keywords for the topic
  * @throws JWNLException If sometinhg goes wrong during the WordNet-lookup
  */
 public static int checkSimple(Vector<String> v, Topic t, boolean isWordNetEnabled) {
   int count = 0;
   boolean result = false;
   if (v == null) return count;
   for (String rec : v) {
     String toLookup = rec;
     if (isWordNetEnabled) {
       toLookup = WNLookup.getStaticStem(rec);
     }
     result = t.containsKey(toLookup);
     if (result || t.containsKey(rec)) {
       count++;
       Log.logger.debug(
           "[found a related word on my mind: '"
               + toLookup
               + "', recent count for this topic '"
               + t.getName()
               + "' is: "
               + count
               + "]");
     }
   }
   return count;
 }
Exemplo n.º 30
0
 @Override
 public boolean equals(Object obj) {
   if (this == obj) return true;
   if (!super.equals(obj)) return false;
   if (getClass() != obj.getClass()) return false;
   Question other = (Question) obj;
   if (mode == null) {
     if (other.mode != null) return false;
   } else if (!mode.equals(other.mode)) return false;
   if (name == null) {
     if (other.name != null) return false;
   } else if (!name.equals(other.name)) return false;
   if (type == null) {
     if (other.type != null) return false;
   } else if (!type.equals(other.type)) return false;
   if (topic == null) {
     if (other.topic != null) return false;
   } else if (!topic.equals(other.topic)) return false;
   return true;
 }