/**
   * The system calls this to perform work in the UI thread and delivers the result from
   * doInBackground()
   */
  protected void onPostExecute(final Article result) {
    // Preserve aspect ratio of image
    i.setScaleType(ImageView.ScaleType.CENTER_CROP);
    i.setCropToPadding(true);

    // Set downloaded bitmap
    i.setImageBitmap(result.getBitmap());

    // When clicked, should open webview to article
    i.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            Intent articlePageIntent =
                new Intent(mCWrapper, ArticleActivity.class)
                    .putExtra(Intent.EXTRA_HTML_TEXT, result.getLink())
                    .putExtra(Intent.EXTRA_SHORTCUT_NAME, result.getTitle());
            mFragment.startActivity(articlePageIntent);
          }
        });

    // Title
    textView.setText(result.getTitle());

    // Remove loading bar
    progressBar.setVisibility(ProgressBar.GONE);

    // Make title visible
    textView.setVisibility(TextView.VISIBLE);

    // Save new data to HeadlineFragment
    mFragment.setArticle(result);
  }
Esempio n. 2
0
  @Override
  public String toString() {
    String rs =
        "<xml>"
            + "<ToUserName><![CDATA["
            + this.ToUserName
            + "]]></ToUserName>"
            + "<FromUserName><![CDATA["
            + this.FromUserName
            + "]]></FromUserName>"
            + "<CreateTime>"
            + this.CreateTime
            + "</CreateTime>"
            + "<MsgType><![CDATA[news]]></MsgType>";
    if (null != this.Articles && this.Articles.size() > 0) {
      rs = rs + "<ArticleCount>" + this.Articles.size() + "</ArticleCount>";
      rs += "<Articles>";
      for (Article article : this.Articles) {
        rs += "<item>";
        rs = rs + "<Title><![CDATA[" + article.getTitle() + "]]></Title> ";
        rs = rs + "<Description><![CDATA[" + article.getDescription() + "]]></Description>";
        rs = rs + "<PicUrl><![CDATA[" + article.getPicUrl() + "]]></PicUrl>";
        rs = rs + "<Url><![CDATA[" + article.getUrl() + "]]></Url>";
        rs += "</item>";
      }
      rs += "</Articles>";
    }
    rs += "</xml> ";

    return rs;
  }
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm actionForm,
      HttpServletRequest request,
      HttpServletResponse reponse)
      throws Exception {
    BeanEcrireCommentaire bean = (BeanEcrireCommentaire) actionForm;
    String contenu = bean.getContenu();
    BeanCommentaire beanCommentaire = new BeanCommentaire();
    beanCommentaire.setContenu(contenu);
    Abonne abonne =
        (Abonne)
            bdutil.getUtilisateur(((Integer) request.getSession().getAttribute("id")).intValue());
    beanCommentaire.setIdRedacteur(abonne.getId());

    Article article = bdart.getArticle(Integer.parseInt(request.getParameter("idArticle")));
    beanCommentaire.setIdArticle(article.getId());

    // beanCommentaire.setId(bdart.getIdLibre());

    if (contenu.equals("")) return mapping.findForward("echec");
    else {

      bdcom.addCommentaire(beanCommentaire.getCommentaire());

      //        bdart.addArticle(beanArticle.getArticle());

      //	beanCommentaire.setIdRedacteur(request.getSession(true));
      //	beanCommentaire.setIdArticle(((Article)request.getAttribute("article")).getId());
      //	bean.setId(BDArticles.getIdLibre())
      /// bdart.addArticle(beanCommentaire.getCommentaire());     // /!\ omg!!!

      return mapping.findForward("succes");
    }
  }
Esempio n. 4
0
  @WebMethod
  public void deleteArticle(User user, String title) {
    SocialApp app = null;
    try {
      app = getSocialApp();
    } catch (JAXBException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    for (Article article : user.getBlog()) {
      if (article.getTitle().equals(title)) user.getBlog().remove(article);
    }

    try {
      app.save();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (JAXBException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  /** Tests the getArticle function */
  public void testGetArticle() {
    Newsletter newsletter = new Newsletter("BFH Newsletter", "blablabla", 6);
    Article article1 =
        newsletter.addArticle("Article 1", "The newsletter project is really funny ;)");

    assertTrue(article1.equals(newsletter.getArticle(article1.getId())));
  }
Esempio n. 6
0
  public static void main(String[] args) {

    // 建立xml文件對象,其儲存在E碟的根目錄下的article.xml檔案
    File xmlFile = new File("D:\\J2EE\\SQL_statement\\article.xml");
    // 宣告JAXBContext上下文對像
    JAXBContext context;
    try {
      // 透過指定映射的類建立上下文
      context = JAXBContext.newInstance(ArticleData.class);
      // 透過上下文建立xml轉化java的對象Unmarshaller
      Unmarshaller u = context.createUnmarshaller();
      // 將xml資料轉換成java對像
      ArticleData data = (ArticleData) u.unmarshal(xmlFile);
      // 獲得所有的article資料
      List<Article> articles = data.getArticle();
      for (Article a : articles) {
        System.out.println("-------------------------");
        System.out.println(a.getAuthor());
        System.out.println(a.getDate());
        System.out.println(a.getEmail());
        System.out.println(a.getTitle());
      }
    } catch (JAXBException e) {
      e.printStackTrace();
    }
  }
  /** Tests the addArticle function */
  public void testAddArticle() {
    Newsletter newsletter = new Newsletter("BFH Newsletter", "blablabla", 6);
    Article article =
        newsletter.addArticle("NewsletterArticle", "The newsletter project is really funny ;)");

    assertTrue("NewsletterArticle".equals(newsletter.getArticle(article.getId()).getTitle()));
  }
  /** Tests the setArticleToOpenIssue function */
  public void testLinkArticles() {

    Newsletter newsletter = new Newsletter("BFH Newsletter", "blablabla", 6);
    Issue issue = newsletter.compileIssueAndCreateNew(2007, new Date());

    Article article1 =
        newsletter.addArticle("Article 1", "The newsletter project is really funny ;)");
    Article article2 =
        newsletter.addArticle("Article 2", "The newsletter project is really funny ;)");
    Article article3 =
        newsletter.addArticle("Article 3", "The newsletter project is really funny ;)");

    newsletter.setArticleToOpenIssue(article1.getId());
    newsletter.setArticleToOpenIssue(article2.getId());

    Map unlinkedArticles = newsletter.getUnlinkedArticles();
    Map issueArticles = issue.getArticles();

    assertFalse(unlinkedArticles.containsValue(article1));
    assertFalse(unlinkedArticles.containsValue(article2));
    assertTrue(unlinkedArticles.containsValue(article3));
    assertTrue(unlinkedArticles.size() == 1);

    assertTrue(issueArticles.containsValue(article1));
    assertTrue(issueArticles.containsValue(article2));
    assertFalse(issueArticles.containsValue(article3));
    assertTrue(issueArticles.size() == 2);
  }
Esempio n. 9
0
  /** tests the PB.retrieveAllReferences() feature */
  public void testRetrieveAllReferences() {
    String name = "testRetrieveAllReferences_" + System.currentTimeMillis();

    // ensure there is an item to find
    Article tmpArticle = createArticle(name);
    ProductGroup pg = createProductGroup(name);
    tmpArticle.setProductGroup(pg);

    broker.beginTransaction();
    broker.store(pg);
    broker.store(tmpArticle);
    broker.commitTransaction();
    Identity tmpOID = broker.serviceIdentity().buildIdentity(tmpArticle);
    broker.clearCache();
    ObjectReferenceDescriptor ord = null;
    try {
      // switch to shallow retrieval
      ClassDescriptor cld = broker.getClassDescriptor(Article.class);
      ord = (ObjectReferenceDescriptor) cld.getObjectReferenceDescriptors().get(0);
      ord.setCascadeRetrieve(false);

      Article article = (Article) broker.getObjectByIdentity(tmpOID);
      assertNull("now reference should be null", article.getProductGroup());

      // now force loading:
      broker.retrieveAllReferences(article);
      assertNotNull("now reference should NOT be null", article.getProductGroup());

      // clean up cld
      ord.setCascadeRetrieve(true);
    } finally {
      // restore old value
      if (ord != null) ord.setCascadeRetrieve(true);
    }
  }
Esempio n. 10
0
  /**
   * Creates an order from the given items. Note that the suggested price for each item must be
   * equal to or exceed the current article price. Also, note that orders which exhaust the
   * available article capacity are rejected.
   *
   * @param alias the customer alias
   * @param passwordHash the customer password-hash
   * @param items the items
   * @return the order identity
   * @throws NullPointerException if one of the given values is {@code null}
   * @throws IllegalArgumentException if items is empty, or if any of the given items is priced too
   *     low
   * @throws IllegalStateException if the login data is invalid, or the order creation fails
   * @throws SQLException if there is a problem with the underlying JDBC connection
   */
  public long insertOrder(
      final String alias,
      final byte[] passwordHash,
      final double taxRate,
      final Collection<OrderItem> items)
      throws SQLException {
    final long purchaseIdentity;
    final Customer customer = this.queryCustomer(alias, passwordHash);

    synchronized (this.connection) {
      try (PreparedStatement statement =
          this.connection.prepareStatement(SQL_INSERT_PURCHASE, Statement.RETURN_GENERATED_KEYS)) {
        statement.setLong(1, customer.getIdentity());
        statement.setLong(2, System.currentTimeMillis());
        statement.setDouble(3, taxRate);
        if (statement.executeUpdate() != 1)
          throw new IllegalStateException("purchase creation failed.");

        try (ResultSet resultSet = statement.getGeneratedKeys()) {
          if (!resultSet.next()) throw new IllegalStateException("purchase key generation failed.");
          purchaseIdentity = resultSet.getLong(1);
        }
      }
    }

    if (items.isEmpty()) throw new IllegalArgumentException("missing items.");
    for (final OrderItem item : items) {
      if (item.getCount() <= 0) throw new IllegalArgumentException("item count too low.");
      final Article article = this.queryArticle(item.getArticleIdentity());
      if (article.getPrice() > item.getArticleGrossPrice())
        throw new IllegalArgumentException("price offer too low.");

      synchronized (this.connection) {
        try (PreparedStatement statement =
            this.connection.prepareStatement(SQL_RESERVE_ARTICLE_UNITS)) {
          statement.setLong(1, item.getCount());
          statement.setLong(2, article.getIdentity());
          statement.setLong(3, item.getCount());
          if (statement.executeUpdate() != 1)
            throw new IllegalStateException("too few article units on stock.");
        }
      }

      synchronized (this.connection) {
        try (PreparedStatement statement =
            this.connection.prepareStatement(SQL_INSERT_PURCHASE_ITEM)) {
          statement.setLong(1, purchaseIdentity);
          statement.setLong(2, item.getArticleIdentity());
          statement.setLong(3, item.getArticleGrossPrice());
          statement.setInt(4, item.getCount());
          if (statement.executeUpdate() != 1)
            throw new IllegalStateException("purchase item creation failed.");
        }
      }
    }

    return purchaseIdentity;
  }
  @RequestMapping(method = RequestMethod.POST, value = "/charge")
  @ResponseBody
  public Charge charge(HttpServletRequest request) {
    // 获取请求body中的参数
    JSONObject params = Tools.getParams(request);
    // 文章的标识
    String articleId = params.getString("articleId");
    // 付款读者的标识
    String wechat = params.getString("wgateid");
    // 付款的渠道
    String channel = params.getString("channel");
    // 当前页面的URL
    String url = params.getString("url");
    // 付款的金额
    int amount = params.getInt("amount");
    // 获取请求的IP地址
    String ip = Tools.getIP(request);

    Deal deal = new Deal(wechat, articleId);
    deal.setDealPayment(amount);
    deal.setClientIp(ip);
    if (dealService.queryDealRecord(deal).getResponseCode() == ResponseCode.RESPONSE_NULL) {
      ResultData createMessage = dealService.createDealRecord(deal);
      if (createMessage.getResponseCode() == ResponseCode.RESPONSE_OK) {
        logger.debug("Insert a deal record successfully.");
      } else {
        logger.debug("Fail to insert a deal record.");
        return null;
      }
    }

    // 设置订单的ID
    String orderNo = deal.getDealId();

    // 根据文章的标识查询文章的信息
    Article article = new Article();
    article.setArticleId(articleId);
    article = (Article) articleService.queryArticle(article).getData();

    Reader reader = new Reader();
    if (!StringUtils.isEmpty(wechat)) {
      reader.setReaderWechat(wechat);
      ResultData readerExistMessage = readerService.queryReader(reader);
      if (readerExistMessage.getResponseCode() == ResponseCode.RESPONSE_NULL) {
        readerService.createReader(reader);
      } else if (readerExistMessage.getResponseCode() == ResponseCode.RESPONSE_ERROR) {
        return null;
      }
    }

    ChargeForm form = new ChargeForm(orderNo, article, reader, channel, amount, ip, url);
    ResultData result = dealService.charge(form);

    Charge charge = (Charge) result.getData();
    logger.debug(charge.toString());
    return charge;
  }
  /** test the getArticleText function */
  public void testGetArticleText() {
    NewsletterCollection newsletterCollection = NewsletterCollection.getInstance();

    String newsletter1 = newsletterCollection.add("Newsletter1", "blablabla", 6);
    Article article =
        newsletterCollection.getNewsletter(newsletter1).addArticle("Article1", "blablabla");

    ArticleController controller = new ArticleController();
    assertTrue("blablabla".equals(controller.getArticleText(newsletter1, article.getId())));
  }
Esempio n. 13
0
 @Override
 public String toString() {
   StringBuilder sb = new StringBuilder();
   for (Article article : articles) {
     sb.append("{title=").append(article.getTitle());
     sb.append(" ,description=").append(article.getDesc());
     sb.append(" ,picUrl=").append(article.getPicUrl());
     sb.append(" ,url=").append(article.getUrl()).append("}");
   }
   return sb.toString();
 }
Esempio n. 14
0
  public void testLoad() {
    Article article = (Article) hibernateTemplate.get(Article.class, Integer.valueOf(1));
    assertNotNull(article);
    LOG.debug(article);
    assertEquals(2, article.getComments().size());

    ArticleRepository repos = (ArticleRepository) context.getBean("articlesRepository");
    assertEquals(1, repos.loadAll().size());

    assertNotNull(repos.load("1"));
  }
Esempio n. 15
0
  @Test
  public void testAdd() {
    Article article =
        new Article(
            null,
            "test.home",
            "测试",
            "一个测试",
            "article.state.recommand",
            "推荐",
            "visible.true",
            "可见",
            "0",
            DateUtils.getSystemTime(),
            "admin",
            "管理员");
    assertEquals(1, Article.add(article));

    article = Article.getAll(article, "0", "1", "id", "desc").getList().get(0);
    String id = article.getId();

    assertNotNull(article);
    assertNotNull(id);

    article.setCid("test.home1");
    assertEquals(1, Article.edit(article));
    assertEquals("test.home1", Article.get(id).getCid());

    assertEquals(1, Article.remove(id));
  }
Esempio n. 16
0
  private String path(UriComponentsBuilder builder, Article article, boolean encode) {
    Map<String, Object> params = new HashMap<>();
    builder.path("/{year}/{month}/{day}/{code}");
    params.put("year", String.format("%04d", article.getDate().getYear()));
    params.put("month", String.format("%02d", article.getDate().getMonthOfYear()));
    params.put("day", String.format("%02d", article.getDate().getDayOfMonth()));
    params.put("code", article.getCode());

    UriComponents components = builder.buildAndExpand(params);
    if (encode) {
      components = components.encode();
    }
    return components.toUriString();
  }
Esempio n. 17
0
 Article createArticle(String name) {
   Article a = new Article();
   a.setArticleName(name);
   a.setIsSelloutArticle(true);
   a.setMinimumStock(100);
   a.setOrderedUnits(17);
   a.setPrice(0.45);
   a.setStock(234);
   a.setSupplierId(4);
   a.setUnit("bottle");
   return a;
 }
 public String getAbstraction(Resources res) {
   return String.format(
       res.getString(R.string.abstract_format),
       author.getName(),
       article.getTitle(),
       res.getString(type.stringRes));
 }
 @RequestMapping(value = "Publish", method = RequestMethod.POST)
 public ModelAndView publish(Article article) {
   ModelAndView mv = new ModelAndView("redirect:/ContestSystem/Administrator/AdminArticle");
   System.out.println(article.getContent());
   this.articleService.create(article);
   return mv;
 }
 @Override
 public void write(ContentValues values) {
   values.put("type", type.value);
   values.put("author_id", author.getId());
   values.put("article_id", article.getId());
   values.put("updated_time", time);
 }
Esempio n. 21
0
  public ErrorType saveAsDraft(final Article article) {
    if (null == article) {
      logger.error("saveAsDraft can't accept empty article.");
      return ErrorType.Params;
    }

    if (!(null == article.getStatus() || Status.Draft == article.getStatus())) {
      logger.error(
          "Article[{}] can't be save as draft from status[{}]",
          article.getOid(),
          article.getStatus());
      return ErrorType.Status;
    }

    return null;
  }
Esempio n. 22
0
  @Override
  protected void onListItemClick(ListView l, View v, int position, long id) {

    super.onListItemClick(l, v, position, id);

    // ListView Clicked item index
    int itemPosition = position;

    // ListView Clicked item value
    Article article = (Article) l.getItemAtPosition(position);
    Log.d("Test_articles", article.toString());

    Intent i = new Intent(this, ArticleWeb.class);
    String url = article.url;
    i.putExtra("URL", url);
    startActivity(i);
  }
Esempio n. 23
0
  /**
   * Returns the article data for the given identity.
   *
   * @param articleIdentity the article identity
   * @throws IllegalStateException if there is no article with the given identity
   * @throws SQLException if there is a problem with the underlying JDBC connection
   */
  public Article queryArticle(final long articleIdentity) throws SQLException {
    final Article article = new Article();

    synchronized (this.connection) {
      try (PreparedStatement statement = this.connection.prepareStatement(SQL_SELECT_ARTICLE)) {
        statement.setLong(1, articleIdentity);
        try (ResultSet resultSet = statement.executeQuery()) {
          if (!resultSet.next()) throw new IllegalStateException("article doesn't exist.");
          article.setIdentity(resultSet.getLong("identity"));
          article.setDescription(resultSet.getString("description"));
          article.setCount(resultSet.getInt("count"));
          article.setPrice(resultSet.getLong("price"));
        }
      }
    }

    return article;
  }
Esempio n. 24
0
 @Override
 public int hashCode() {
   int result = (int) getId();
   result = 31 * result + getName().hashCode();
   result = 31 * result + getSurname().hashCode();
   result = 31 * result + (int) (mArticle == null ? 0 : mArticle.getId());
   result = 31 * result + (getSource() != null ? getSource().hashCode() : 0);
   return result;
 }
Esempio n. 25
0
  public void testShallowAndDeepRetrieval() throws Exception {
    String name = "testShallowAndDeepRetrieval_" + System.currentTimeMillis();

    ObjectReferenceDescriptor ord = null;

    try {
      // prepare test, create article with ProductGroup
      Article tmpArticle = createArticle(name);
      ProductGroup pg = createProductGroup(name);
      tmpArticle.setProductGroup(pg);
      pg.add(tmpArticle);

      broker.beginTransaction();
      // in repository Article 1:1 refererence to PG hasn't enabled auto-update,
      // so first store the PG. PG has enabled auto-update and will store the
      // article automatic
      broker.store(pg);
      broker.commitTransaction();
      // after insert we can build the Article identity
      Identity tmpOID = broker.serviceIdentity().buildIdentity(tmpArticle);
      broker.clearCache();

      // switch to shallow retrieval
      ClassDescriptor cld = broker.getClassDescriptor(Article.class);
      ord = cld.getObjectReferenceDescriptorByName("productGroup");
      ord.setCascadeRetrieve(false);

      Article article = (Article) broker.getObjectByIdentity(tmpOID);
      assertNull("now reference should be null", article.getProductGroup());

      // now switch to deep retrieval
      ord.setCascadeRetrieve(true);
      // should work without setting cld
      // broker.setClassDescriptor(cld);
      broker.clearCache();
      article = (Article) broker.getObjectByIdentity(tmpOID);
      assertNotNull("now reference should NOT be null", article.getProductGroup());
    } finally {
      // restore old value
      if (ord != null) ord.setCascadeRetrieve(true);
    }
  }
Esempio n. 26
0
  /**
   * Returns all article data.
   *
   * @throws IllegalStateException if the login data is invalid
   * @throws SQLException if there is a problem with the underlying JDBC connection
   */
  public SortedSet<Article> queryArticles() throws SQLException {
    final SortedSet<Article> articles = new TreeSet<Article>();

    synchronized (this.connection) {
      try (PreparedStatement statement = this.connection.prepareStatement(SQL_SELECT_ARTICLES)) {
        try (ResultSet resultSet = statement.executeQuery()) {
          while (resultSet.next()) {
            final Article article = new Article();
            article.setIdentity(resultSet.getLong("identity"));
            article.setDescription(resultSet.getString("description"));
            article.setCount(resultSet.getInt("count"));
            article.setPrice(resultSet.getLong("price"));
            articles.add(article);
          }
        }
      }
    }

    return articles;
  }
  private static void processFile(String fileName, String outDir) throws Exception {
    // read file into a String
    String fileContent = readFileAsString(fileName);

    // extract different articles
    List<Article> articles = new LinkedList<Article>();
    Matcher matcher = DOC_PATTERN.matcher(fileContent);
    while (matcher.find()) {
      int id = Integer.parseInt(matcher.group(1));
      String text = stripAnchorTags(matcher.group(2));
      articles.add(new Article(id, text));
    }
    // for each article strip all anchor tags and write the article in
    // separate file
    for (Article article : articles) {
      String outFileName = outDir + "/" + article.getId();
      new File(outDir).mkdirs();
      writeStringToFile(article.getText(), outFileName);
    }
  }
  /**
   * Tests that @DocumentId can be specified on a field other than the @Id annotated one. See
   * HSEARCH-574.
   *
   * @throws Exception in case the test fails.
   */
  @Test
  public void testExplicitDocumentIdSingleResult() throws Exception {
    Article hello = new Article();
    hello.setDocumentId(1);
    hello.setText("Hello World");

    Session s = openSession();
    Transaction tx = s.beginTransaction();
    s.save(hello);
    tx.commit();
    s.clear();

    tx = s.beginTransaction();
    List results =
        Search.getFullTextSession(s)
            .createFullTextQuery(new TermQuery(new Term("text", "world")))
            .list();
    assertEquals(1, results.size());
    tx.commit();
    s.close();
  }
Esempio n. 29
0
  @Test
  public void putObjectSingle() {
    Article article = Article.newInstance(null, "test");

    Single<PutResult> putResultSingle =
        storIOContentResolver()
            .put()
            .object(article)
            .withPutResolver(ArticleMeta.PUT_RESOLVER)
            .prepare()
            .asRxSingle();
  }
Esempio n. 30
0
  @Test
  public void putObjectBlocking() {
    Article article = Article.newInstance(null, "test");

    PutResult putResult =
        storIOContentResolver()
            .put()
            .object(article)
            .withPutResolver(ArticleMeta.PUT_RESOLVER)
            .prepare()
            .executeAsBlocking();
  }