@Test
  public void testTopLevelManyToOneChangedToNewEntity() {
    Item item1 = new Item();
    item1.setName("item1 name");
    Category category = new Category();
    category.setName("category");

    item1.setCategory(category);
    category.setExampleItem(item1);

    Session s = openSession();
    Transaction tx = s.beginTransaction();
    s.persist(item1);
    tx.commit();
    s.close();

    // get another representation of item1
    s = openSession();
    tx = s.beginTransaction();
    Item item1_1 = (Item) s.get(Item.class, item1.getId());
    tx.commit();
    s.close();

    // change many-to-one in top level to be a new (transient)
    Category categoryNewer = new Category();
    categoryNewer.setName("newer category");
    item1.setCategory(categoryNewer);

    // put the other representation in categoryNewer
    categoryNewer.setExampleItem(item1_1);

    s = openSession();
    tx = s.beginTransaction();
    Item item1Merged = (Item) s.merge(item1);
    // the many-to-one from the top level item will win.
    assertEquals(categoryNewer.getName(), item1Merged.getCategory().getName());
    assertSame(item1Merged, item1Merged.getCategory().getExampleItem());
    tx.commit();
    s.close();

    s = openSession();
    tx = s.beginTransaction();
    item1 = (Item) s.get(Item.class, item1.getId());
    assertEquals(categoryNewer.getName(), item1.getCategory().getName());
    assertSame(item1, item1.getCategory().getExampleItem());
    // make sure original category is still there
    Category categoryQueried =
        (Category) s.createQuery("from Category c where c.name='category'").uniqueResult();
    assertNotNull(categoryQueried);
    // make sure original category has the same item.
    assertSame(item1, categoryQueried.getExampleItem());
    // set exampleItem to null to avoid constraint violation on cleanup.
    categoryQueried.setExampleItem(null);
    tx.commit();
    s.close();

    cleanup();
  }
  /** @return */
  public String toXML() {
    OptetPlugin optetPluginJAXB = new OptetPlugin();

    for (Iterator iterator = categoriesList.iterator(); iterator.hasNext(); ) {
      Categories cates = (Categories) iterator.next();

      com.thalesgroup.optet.plugin.template.jaxb.OptetPlugin.Categories categoriesJAXB =
          new com.thalesgroup.optet.plugin.template.jaxb.OptetPlugin.Categories();
      categoriesJAXB.setName(cates.getName());
      System.out.println("JAXB " + cates.getName());

      Collection<Category> listcategory = cates.getCategories().values();
      for (Iterator iterator2 = listcategory.iterator(); iterator2.hasNext(); ) {
        Category cat = (Category) iterator2.next();

        com.thalesgroup.optet.plugin.template.jaxb.OptetPlugin.Categories.Category catJAXB =
            new com.thalesgroup.optet.plugin.template.jaxb.OptetPlugin.Categories.Category();
        catJAXB.setName(cat.getName());
        System.out.println("JAXB " + cat.getName());

        Collection<Evidence> listevidence = cat.getMetrics().values();
        for (Iterator iterator3 = listevidence.iterator(); iterator3.hasNext(); ) {
          Evidence evidence = (Evidence) iterator3.next();
          com.thalesgroup.optet.plugin.template.jaxb.OptetPlugin.Categories.Category.Evidence
              evidenceJAXB =
                  new com.thalesgroup.optet.plugin.template.jaxb.OptetPlugin.Categories.Category
                      .Evidence();
          evidenceJAXB.setName(evidence.getSummary());
          System.out.println("JAXB " + evidence.getSummary());
          catJAXB.getEvidence().add(evidenceJAXB);
        }
        categoriesJAXB.getCategory().add(catJAXB);
      }
      optetPluginJAXB.getCategories().add(categoriesJAXB);
    }

    JAXBContext jaxbContext;
    StringWriter stringWriter = new StringWriter();
    try {
      jaxbContext = JAXBContext.newInstance(OptetPlugin.class);
      Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

      // output pretty printed
      jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

      jaxbMarshaller.marshal(optetPluginJAXB, stringWriter);

      System.out.println("res " + stringWriter);
    } catch (JAXBException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    // TODO Auto-generated method stub
    return stringWriter.toString();
  }
  @Test
  public void testNestedManyToOneChangedToNewEntity() {
    Item item1 = new Item();
    item1.setName("item1 name");
    Category category = new Category();
    category.setName("category");

    item1.setCategory(category);
    category.setExampleItem(item1);

    Session s = openSession();
    Transaction tx = s.beginTransaction();
    s.persist(item1);
    tx.commit();
    s.close();

    // get another representation of item1
    s = openSession();
    tx = s.beginTransaction();
    Item item1_1 = (Item) s.get(Item.class, item1.getId());
    tx.commit();
    s.close();

    // change many-to-one in nested entity to a new (transient) value
    Category categoryNew = new Category();
    categoryNew.setName("new category");
    item1_1.setCategory(categoryNew);
    item1.getCategory().setExampleItem(item1_1);

    s = openSession();
    tx = s.beginTransaction();
    Item item1Merged = (Item) s.merge(item1);
    // the many-to-one from the top level item will win.
    assertEquals(category.getName(), item1Merged.getCategory().getName());
    assertSame(item1Merged, item1Merged.getCategory().getExampleItem());
    tx.commit();
    s.close();

    s = openSession();
    tx = s.beginTransaction();
    item1 = (Item) s.get(Item.class, item1.getId());
    assertEquals(category.getName(), item1.getCategory().getName());
    assertSame(item1, item1.getCategory().getExampleItem());
    // make sure new category got persisted
    Category categoryQueried =
        (Category) s.createQuery("from Category c where c.name='new category'").uniqueResult();
    assertNotNull(categoryQueried);
    tx.commit();
    s.close();

    cleanup();
  }
示例#4
0
  public void createdFormatedShoppingList() {

    this.formatedProductsList = new HashMap<String, List<String>>();
    this.formatedCategoriesList = new ArrayList<String>();

    Iterator<Category> iterateur = categoriesListe.iterator();

    while (iterateur.hasNext()) {
      Category category = iterateur.next();
      String categoryString = category.getName();
      int idCateg = category.getId();

      this.formatedCategoriesList.add(categoryString);

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

      for (int c = 0; c < productsListe.size(); c++) {
        int prod_Idcateg = productsListe.get(c).getIdCateg();
        int prod_IsShop = productsListe.get(c).isShop();

        String unProduit = new String();
        if (prod_Idcateg == idCateg && prod_IsShop == 1) {
          unProduit = productsListe.get(c).getName();
          String quantity = productsListe.get(c).getQuantity();
          if (quantity != "" && quantity != null) {
            unProduit += " : " + quantity;
          }
          donneesCategory.add(unProduit);
        }
      }

      this.formatedProductsList.put(categoryString, donneesCategory);
    }
  }
  @Test
  public void testMergeMultipleEntityCopiesAllowedAndDisallowed() {
    Item item1 = new Item();
    item1.setName("item1 name");
    Category category = new Category();
    category.setName("category");
    item1.setCategory(category);
    category.setExampleItem(item1);

    EntityManager em = getOrCreateEntityManager();
    em.getTransaction().begin();
    em.persist(item1);
    em.getTransaction().commit();
    em.close();

    // get another representation of item1
    em = getOrCreateEntityManager();
    em.getTransaction().begin();
    Item item1_1 = em.find(Item.class, item1.getId());
    // make sure item1_1.category is initialized
    Hibernate.initialize(item1_1.getCategory());
    em.getTransaction().commit();
    em.close();

    em = getOrCreateEntityManager();
    em.getTransaction().begin();
    Item item1Merged = em.merge(item1);

    // make sure item1Merged.category is also managed
    Hibernate.initialize(item1Merged.getCategory());

    item1Merged.setCategory(category);
    category.setExampleItem(item1_1);

    // now item1Merged is managed and it has a nested detached item
    // and there is  multiple managed/detached Category objects
    try {
      // the following should fail because multiple copies of Category objects is not allowed by
      // CustomEntityCopyObserver
      em.merge(item1Merged);
      fail(
          "should have failed because CustomEntityCopyObserver does not allow multiple copies of a Category. ");
    } catch (IllegalStateException ex) {
      // expected
    } finally {
      em.getTransaction().rollback();
    }
    em.close();

    em = getOrCreateEntityManager();
    em.getTransaction().begin();
    item1 = em.find(Item.class, item1.getId());
    assertEquals(category.getName(), item1.getCategory().getName());
    assertSame(item1, item1.getCategory().getExampleItem());
    em.getTransaction().commit();
    em.close();

    cleanup();
  }
  @Test
  public void testNestedManyToOneChangedToNull() {
    Item item1 = new Item();
    item1.setName("item1 name");
    Category category = new Category();
    category.setName("category");

    item1.setCategory(category);
    category.setExampleItem(item1);

    Session s = openSession();
    Transaction tx = s.beginTransaction();
    s.persist(item1);
    tx.commit();
    s.close();

    // get another representation of item1
    s = openSession();
    tx = s.beginTransaction();
    Item item1_1 = (Item) s.get(Item.class, item1.getId());
    tx.commit();
    s.close();

    // change many-to-one in nested entity to null.
    item1_1.setCategory(null);
    item1.getCategory().setExampleItem(item1_1);

    s = openSession();
    tx = s.beginTransaction();
    Item item1Merged = (Item) s.merge(item1);
    // the many-to-one from the top level item will win.
    assertEquals(category.getName(), item1Merged.getCategory().getName());
    assertSame(item1Merged, item1Merged.getCategory().getExampleItem());
    tx.commit();
    s.close();

    s = openSession();
    tx = s.beginTransaction();
    item1 = (Item) s.get(Item.class, item1.getId());
    assertEquals(category.getName(), item1.getCategory().getName());
    assertSame(item1, item1.getCategory().getExampleItem());
    tx.commit();
    s.close();

    cleanup();
  }
  @Test
  public void testTopLevelManyToOneManagedNestedIsDetached() {
    Item item1 = new Item();
    item1.setName("item1 name");
    Category category = new Category();
    category.setName("category");
    item1.setCategory(category);
    category.setExampleItem(item1);

    Session s = openSession();
    Transaction tx = s.beginTransaction();
    s.persist(item1);
    tx.commit();
    s.close();

    // get another representation of item1
    s = openSession();
    tx = s.beginTransaction();
    Item item1_1 = (Item) s.get(Item.class, item1.getId());
    tx.commit();
    s.close();

    s = openSession();
    tx = s.beginTransaction();
    Item item1Merged = (Item) s.merge(item1);

    item1Merged.setCategory(category);
    category.setExampleItem(item1_1);

    // now item1Merged is managed and it has a nested detached item
    s.merge(item1Merged);
    assertEquals(category.getName(), item1Merged.getCategory().getName());
    assertSame(item1Merged, item1Merged.getCategory().getExampleItem());
    tx.commit();
    s.close();

    s = openSession();
    tx = s.beginTransaction();
    item1 = (Item) s.get(Item.class, item1.getId());
    assertEquals(category.getName(), item1.getCategory().getName());
    assertSame(item1, item1.getCategory().getExampleItem());
    tx.commit();
    s.close();

    cleanup();
  }
 @Factory("category9List")
 public void initCategory9List() {
   log.info("initCategory9List");
   category9List = new HashMap<String, String>();
   for (Object o : em.createQuery("from " + "Category").getResultList()) {
     Category p = (Category) o;
     category9List.put(p.getName(), p.getId().toString());
   }
 }
示例#9
0
 @Override
 public boolean equals(Object otherCategory) {
   if (!(otherCategory instanceof Category)) {
     return false;
   } else {
     Category newCategory = (Category) otherCategory;
     return this.getName().equals(newCategory.getName());
   }
 }
示例#10
0
文件: Book.java 项目: proegel/fachdom
 @Override
 public String toString() {
   return "Book [title="
       + title
       + ", releaseDate="
       + releaseDate
       + ", category="
       + category.getName()
       + "]";
 }
  /**
   * Update category.
   *
   * @param category the category
   * @return the int
   */
  public int updateCategory(Category category) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(KEY_CATEGORY_NAME, category.getName());
    values.put(KEY_CATEGORY_COLOR, category.getColor());

    // updating row
    return db.update(
        TABLE_CATEGORY, values, KEY_ID + " = ?", new String[] {String.valueOf(category.getId())});
  }
示例#12
0
  /**
   * @param category
   * @return rowId of category added or -1 if failed to insert
   */
  public long addCategory(Category category) {
    Log.i(TAG, "adding category");
    ContentValues initialValues = new ContentValues();

    initialValues.put(NAME_COLUMN, category.getName());
    initialValues.put(TOTAL_COLUMN, category.getTotal());
    initialValues.put(REMAINING_COLUMN, category.getRemaining());

    return mDb.insert(CATEGORIES_TABLE, null, initialValues);
  }
示例#13
0
  /** @inheritdoc */
  @Override
  protected void bindValues(SQLiteStatement stmt, Category entity) {
    stmt.clearBindings();

    Long id = entity.getId();
    if (id != null) {
      stmt.bindLong(1, id);
    }
    stmt.bindString(2, entity.getName());
  }
  /**
   * Creates the category.
   *
   * @param category the category
   * @return the long
   */
  public long createCategory(Category category) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(KEY_CATEGORY_NAME, category.getName());
    values.put(KEY_CATEGORY_COLOR, category.getColor());

    // insert row
    long category_id = db.insert(TABLE_CATEGORY, null, values);

    return category_id;
  }
示例#15
0
  /**
   * Gets the category map.
   *
   * @return Mapping of subcategories by name of rootcategory
   */
  public Map<String, List<Category>> getCategoryMap() {
    Map<String, List<Category>> toReturn = new HashMap<String, List<Category>>();

    for (Category s : this.categories.findAll()) {
      long currCat = s.getId();
      LinkedList<Category> putList = getChildren(currCat);
      toReturn.put(s.getName(), putList);
    }

    return toReturn;
  }
示例#16
0
  /*
   * Return a list with the names of the categories that still have items available on the board
   */
  public ArrayList<String> getActiveCategories() {
    // Figure out how many categories are still active
    ArrayList<String> catList = new ArrayList<String>();

    for (Category cat : categories) {
      if (cat.isUsedUp() == false) {
        catList.add(cat.getName());
      }
    }

    return catList;
  }
示例#17
0
  public void init() {
    ApiService apiService = ApiService.getInstance();
    String terminalId = null;
    try {
      terminalId = apiService.register();
      List<Category> categoriesTmp = null;
      System.out.println("getCategories");
      categoriesTmp = apiService.getCategories(terminalId);
      System.out.println("categoriesTmp: " + categoriesTmp);
      List<String> categoryIds = new ArrayList<String>();
      for (int i = 0; i < categoriesTmp.size(); i++) {
        Category category = categoriesTmp.get(i);
        categoryIds.add(category.getId());
        addCategory(category);
        System.out.println("addCategory: " + category.getName());
      }
      HashMap<Long, List<App>> appMapping = null;
      System.out.println("getApps");
      appMapping = apiService.getApps(terminalId, categoryIds);
      System.out.println("appMapping: " + appMapping);
      for (Entry<Long, List<App>> entry : appMapping.entrySet()) {
        List<App> apps = entry.getValue();
        for (App app : apps) {
          addApp(entry.getKey().toString(), app);
          System.out.println("addApp: " + app.getName());
        }
      }

      System.out.println("getUpdateVersion");
      updateVersion = apiService.getUpdateVersion(terminalId);
      System.out.println("updateVersion: " + updateVersion);
    } catch (Exception e) {
      e.printStackTrace();
    }
    // addCategory(new Category("1", "餐饮美食"));
    // addApp("1", new App("1", "订餐易",
    // "http://192.168.101.34:8080/asweb/download/363"));
    // addApp("1", new App("2", "订餐宝",
    // "http://192.168.101.34:8080/asweb/download/363"));
    // addCategory(new Category("2", "数码家电"));
    // addApp("2", new App("3", "家电测试",
    // "http://192.168.101.34:8080/asweb/download/363"));
    // addCategory(new Category("3", "运动健身"));
    // addApp("3", new App("4", "健身测试",
    // "http://192.168.101.34:8080/asweb/download/363"));
    // addCategory(new Category("4", "美容美发"));
    // addApp("4", new App("5", "博卡",
    // "http://192.168.101.34:8080/asweb/download/363"));
    // addCategory(new Category("5", "百货零售"));
    // addCategory(new Category("6", "教育培训"));

  }
示例#18
0
 /**
  * Updates or insert a new a category
  *
  * @param category Category to be updated or inserted
  * @return Rows affected or new inserted category id
  */
 public Category updateCategory(Category category) {
   ContentValues values = new ContentValues();
   values.put(
       KEY_CATEGORY_ID,
       category.getId() != null ? category.getId() : Calendar.getInstance().getTimeInMillis());
   values.put(KEY_CATEGORY_NAME, category.getName());
   values.put(KEY_CATEGORY_DESCRIPTION, category.getDescription());
   values.put(KEY_CATEGORY_COLOR, category.getColor());
   getDatabase(true)
       .insertWithOnConflict(
           TABLE_CATEGORY, KEY_CATEGORY_ID, values, SQLiteDatabase.CONFLICT_REPLACE);
   return category;
 }
示例#19
0
文件: Test.java 项目: Co0sh/BetonTest
 /**
  * Loads a player using specified data.
  *
  * @param player the player to load
  * @param chances amount of chances left
  * @param name name of the category
  * @param paused is the test paused or not
  */
 public void loadTest(Player player, int chances, String name, boolean paused) {
   this.chances.put(player.getUniqueId(), chances);
   if (paused) {
     this.paused.add(player.getUniqueId());
   } else {
     for (Category category : categories) {
       if (category.getName().equals(name)) {
         players.put(player.getUniqueId(), category);
         category.loadPlayer(player);
         return;
       }
     }
   }
 }
  /**
   * Delete category.
   *
   * @param category the category
   * @param should_delete_all_category_events the should_delete_all_category_events
   */
  public void deleteCategory(Category category, boolean should_delete_all_category_events) {
    SQLiteDatabase db = this.getWritableDatabase();

    // before deleting category
    // check if events under this category should also be deleted
    if (should_delete_all_category_events) {
      // get all events under this category
      List<Event> allCategoryEvent = getAllEventsByCategory(category.getName());
      // delete all events
      for (Event event : allCategoryEvent) {
        // delete event
        deleteEvent(event.getId());
      }
    }
    // now delete the category
    db.delete(TABLE_CATEGORY, KEY_ID + " = ?", new String[] {String.valueOf(category.getId())});
  }
示例#21
0
  @Test
  public void testUpdate() {
    System.out.println("------------testUpdate---------------");
    Configuration cfg =
        new Configuration()
            .addClass(com.jike.mobile.browser.model.Item.class)
            .addClass(com.jike.mobile.browser.model.Category.class)
            .setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver")
            .setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/browser")
            .setProperty("hibernate.connection.password", "zxcvbnm")
            .setProperty("hibernate.connection.username", "root");

    SessionFactory sessionFactory = cfg.buildSessionFactory();
    Session session = sessionFactory.openSession();

    Transaction tx = session.beginTransaction();

    Category category = (Category) session.get(Category.class, 1);
    System.out.println(category.getName());

    Item item = new Item(65, "9", "1", "1", 1, "1", "1", "1", "1", "1", category);
    // Object o = session.save(item);

    // System.out.println(o);

    // Item item2 = (Item) session.get(Item.class, 45);

    // session.update(item);

    System.out.println("1: " + item.getId());

    tx.commit();
    System.out.println("2: " + item.getId());
    session.flush();
    System.out.println("3: " + item.getId());
    session.close();
    System.out.println("4: " + item.getId());

    System.out.println("------------testConstruct---------------");

    Item item2 = new Item("", "", "", 0, "", "", "", "", "", null);

    System.out.println("itemid: " + item2.getId());
  }
  public void init() {

    categoriesList = new ArrayList<Categories>();

    Categories categories = new Categories("static");

    Category category = new Category("SoftwareComplexity", categories);
    Evidence evidence = new Evidence("SoftwareComplexityMetric", category);
    category.getMetrics().put(evidence.getSummary(), evidence);

    categories.getCategories().put(category.getName(), category);

    category = new Category("Maintainability", categories);
    categories.getCategories().put(category.getName(), category);
    evidence = new Evidence("MaintainabilityMetric", category);
    category.getMetrics().put(evidence.getSummary(), evidence);

    category = new Category("Reliability", categories);
    categories.getCategories().put(category.getName(), category);
    evidence = new Evidence("ReliabilityMetric", category);
    category.getMetrics().put(evidence.getSummary(), evidence);

    category = new Category("Security", categories);
    categories.getCategories().put(category.getName(), category);
    evidence = new Evidence("SecurityMetric", category);
    category.getMetrics().put(evidence.getSummary(), evidence);

    categoriesList.add(categories);

    categories = new Categories("runtime");

    category = new Category("UnitTest", categories);
    categories.getCategories().put(category.getName(), category);

    category = new Category("CodeCoverage", categories);
    categories.getCategories().put(category.getName(), category);

    categoriesList.add(categories);
  }
示例#23
0
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    HttpSession session = request.getSession();
    String username = (String) session.getAttribute("username");
    String curCategId = (String) session.getAttribute("curCategId");

    response.setContentType("text/html;charset=UTF-8");

    String action = request.getParameter("action");
    PrintWriter out = response.getWriter();

    System.out.println("Action = " + action);

    if (action.equalsIgnoreCase("showCategory")) {
      ArrayList<Category> categories = new ArrayList<Category>(joinOp.GetCategByUsername(username));

      out.println("<div class='kategori'>");
      out.println("<div id='categoryAll' onclick='showTaskList(0);'>All</div>");
      out.println("</div>");

      for (Category categ : categories) {
        out.println("<div class='kategori'>");
        out.println(
            "<div id='category"
                + categ.getId_category()
                + "'"
                + "onclick='showTaskList("
                + categ.getId_category()
                + ");'>"
                + categ.getName()
                + "</div>");
        if (username.equals(categ.getCateg_creator())) {
          out.println(
              "<div class='removeCategory' id='removeCateg"
                  + categ.getId_category()
                  + "' onclick='return removeCategory("
                  + categ.getId_category()
                  + ");'>x</div>");
        }
        out.println("</div>");
      }

    } else if (action.equalsIgnoreCase("addCategory")) {
      String categName = request.getParameter("name");
      String[] authUsers = request.getParameter("authUsers").split(",");

      categoryOp.InsertNewCategory(new Category("", categName, username));

      String newCategId = categoryOp.FetchIdByName(categName);
      caurelationOp.InsertCaurelation(new Caurelation("", newCategId, username));
      ucrelationOp.InsertUcrelation(new Ucrelation("", username, newCategId));

      if (authUsers.length != 0) {
        for (String authUser : authUsers) {
          if (userOp.ListAllUsernames().contains(authUser)) {
            ucrelationOp.InsertUcrelation(new Ucrelation("", authUser.trim(), newCategId));
            caurelationOp.InsertCaurelation(new Caurelation("", newCategId, authUser));
          }
        }
      }

    } else if (action.equalsIgnoreCase("removeCategory")) {
      String categId = request.getParameter("code");
      ArrayList<String> taskIds = new ArrayList<String>(taskOp.FetchIdsByCategId(categId));

      for (String taskId : taskIds) {
        ttrelationOp.DeleteByTaskId(taskId);
        utrelationOp.DeleteByTaskId(taskId);
        tarelationOp.DeleteTarelationByTaskId(taskId);
        commentOp.DeleteCommentByTaskId(taskId);
        taskOp.DeleteById(taskId);
      }

      ucrelationOp.DeleteByCategId(categId, username);
      caurelationOp.DeleteCaurelationByCategId(categId);
      categoryOp.DeleteCategoryById(categId);

    } else if (action.equalsIgnoreCase("showTaskList")) {
      String categId = request.getParameter("code");

      session.setAttribute("curCategId", categId);

      ArrayList<Task> tasks =
          new ArrayList<Task>(joinOp.GetTasksByUsernameAndCategoryId(username, categId));
      ArrayList<String> tags;
      int i = 0;
      for (Task task : tasks) {
        i = 0;
        out.println("<div class='listTugas'>");
        out.println(
            "<a class='listname' id='task"
                + task.getId_task()
                + "'"
                + "onclick='showRinci("
                + task.getId_task()
                + ");'>"
                + task.getName()
                + "</a>");
        out.println("<div class='listdeadline'>Deadline: " + task.getDeadline() + "</div>");

        tags = new ArrayList<String>(joinOp.GetTagNamesByTaskId(task.getId_task()));
        out.println("<div class='listtag'>Tag: ");

        while (i < tags.size()) {
          out.print(tags.get(i));
          i++;
          if (i < tags.size()) {
            out.print(", ");
          }
        }
        out.println("</div>");

        out.println("<div class='liststatus' id='statusTask'>");
        if (task.getStatus().equals("T")) {
          out.println(
              "<input type='checkbox' id='checkboxTask"
                  + task.getId_task()
                  + "' onclick='changeTaskStatus("
                  + task.getId_task()
                  + ", this.checked);' checked>");
        } else if (task.getStatus().equals("F")) {
          out.println(
              "<input type='checkbox' id='checkboxTask"
                  + task.getId_task()
                  + "' onclick='changeTaskStatus("
                  + task.getId_task()
                  + ", this.checked);'>");
        }

        out.println("Done</div>");

        if (username.equals(taskOp.FetchCreatorById(task.getId_task()))) {
          out.println(
              "<div class='removeTask'><input type='submit' id='removeTaskBtn"
                  + task.getId_task()
                  + "' onclick='removeTask("
                  + curCategId
                  + ","
                  + task.getId_task()
                  + ");' value='Remove Task'/></div>");
        }
        out.println("</div>");
      }

      if (caurelationOp.FetchAuthUsersByCategId(categId).contains(username)) {
        out.println("<a onclick='showBuat();' class='addTask'>+task</a>");
      }
    } else if (action.equalsIgnoreCase("showTaskDetail")) {
      String taskId = request.getParameter("code");
      Task task = taskOp.SelectById(taskId);

      out.println("<div id='taskdetail'>");
      // NAME
      out.println("<div id='taskdetail_name'>" + task.getName() + "</div><br>");
      // STATUS
      out.println("<br><div>=======================================================</div>");
      if (task.getStatus().equalsIgnoreCase("T")) {
        out.println(
            "<div id='taskdetail_status'><em>Status : </em>Done "
                + "<input type='checkbox' onclick='changeTaskStatus("
                + task.getId_task()
                + ", this.checked);' checked/>"
                + "</div>");
      } else {
        out.println(
            "<div id='taskdetail_status'>Status : Done "
                + "<input type='checkbox' onclick='changeTaskStatus("
                + task.getId_task()
                + ", this.checked);'/>"
                + "</div>");
      }
      // ATTACHMENT
      ArrayList<Attachment> attachments = joinOp.GetAttachmentFromId_task(task.getId_task());
      int extensionIdx;
      String extension, filename;
      out.println("<br><div>=======================================================</div>");
      out.println("<div><em>Attachment: </em></div>");
      out.println("<div id='taskdetail_attachment'>");
      for (Attachment item : attachments) {
        extensionIdx = item.getPath().lastIndexOf('.');
        if (extensionIdx > 0) {
          filename = item.getPath().substring(item.getPath().lastIndexOf('/') + 1);
          extension = item.getPath().substring(extensionIdx + 1);
          System.out.println(item.getPath() + " has extension " + extension);
          // jika gambar
          if (extension.equalsIgnoreCase("jpg")
              || extension.equalsIgnoreCase("png")
              || extension.equalsIgnoreCase("gif")) {
            System.out.println(filename);
            out.println("<img src='" + item.getPath() + "' height=\"100\" width=\"100\"/><br>");
            out.println("<a href='" + item.getPath() + "'>" + filename + "</a><br>");
            // jika video
          } else if (extension.equalsIgnoreCase("mp4")
              || extension.equalsIgnoreCase("webm")
              || extension.equalsIgnoreCase("ogg")) {
            out.println("<video width=\"320\" height=\"240\" controls>");
            out.println("<source src='" + item.getPath() + "' type='video/" + extension + "'>");
            out.println("</video><br>");
            out.println("<a href='" + item.getPath() + "'>" + filename + "</a><br>");
          } else {
            out.println("<a href='" + item.getPath() + "'>" + filename + "</a><br>");
          }
        }
      }
      out.println("</div>");
      // DEADLINE
      out.println("<br><div>=======================================================</div>");
      out.println(
          "<div id='taskdetail_deadline'><em>Deadline: </em>" + task.getDeadline() + "</div>");
      // ASSIGNEE
      out.println("<br><div>=======================================================</div>");
      ArrayList<String> assignees = utrelationOp.FetchAssigneeByTaskId(task.getId_task());
      out.println("<div id='taskdetail_assignee'><em>Assignee: </em>");
      int i = 0;
      while (i < assignees.size()) {
        out.println(
            "<a href='profile.jsp?userprofile="
                + assignees.get(i)
                + "'>"
                + assignees.get(i)
                + "</a>");
        i++;
        if (i < assignees.size()) {
          out.print("; ");
        }
      }
      out.println("</div>");
      // KOMENTAR
      out.println("<br><div>=======================================================</div>");
      out.println("<div><em>Comment: </em></div>");
      User user;
      String[] timesplit;
      ArrayList<Comment> comments = commentOp.FetchCommentByTaskId(task.getId_task());
      out.println("<div id='ctotal'>" + comments.size() + " comment(s)</div>");
      out.println("<div id='taskdetail_comment'>");
      out.println("<div id='commentlist'>");
      for (Comment item : comments) {
        out.println("<div id='comment" + item.getId_comment() + "'>");
        user = userOp.SelectUserInfoByUsername(item.getUsername());
        timesplit = item.getTimestamp().split(":");
        System.out.println("LALALALALA" + timesplit.length);
        out.println(
            "<img class='cavatar' src='"
                + user.getAvatar()
                + "' style='width:30px; height:30px;'/>");
        out.println(
            "<div class='ctimestamp'>"
                + timesplit[3]
                + ":"
                + timesplit[4]
                + " - "
                + timesplit[2]
                + "/"
                + timesplit[1]
                + "</div>");
        out.println("<div class='ccontent'>" + item.getContent() + "</div>");
        if (username.equals(user.getUsername())) {
          out.println(
              "<input type='button' value='Delete' class='cdelete' onclick='delComment("
                  + item.getId_comment()
                  + ");'/>");
        }
        out.println("</div>");
      }
      out.println("</div>");
      out.println("<div id='commentbox'>");
      out.println("<textarea id='cbox'></textarea></br>");
      out.println("<input type='button' value='Submit' onclick='addComment(" + taskId + ");'/>");
      out.println("</div>");
      out.println("</div>");
      // TAG
      out.println("<br><div>=======================================================</div>");
      ArrayList<Tag> tags = joinOp.GetTagFromId_task(task.getId_task());
      out.println("<div id='taskdetail_tag'><em>Tag: </em>");
      i = 0;
      while (i < tags.size()) {
        out.println(tags.get(i).getName());
        i++;
        if (i < tags.size()) {
          out.print("; ");
        }
      }
      out.println("</div>");
      if (utrelationOp.IsTaskEditable(username, taskId)) {
        out.println(
            "<input type='button' value='Edit task' onclick='editTaskDetail("
                + task.getId_task()
                + ");'/>");
      }
      out.println("<input type='button' value='Back' onclick='restore2();'/>");
      out.println("</div>");
    } else if (action.equalsIgnoreCase("editTaskDetail")) {
      String taskId = request.getParameter("code");
      Task task = taskOp.SelectById(taskId);
      out.println("<div id='editdetail'>");
      out.println("<form>");
      out.println("<big style='font-size: 20pt;'>" + task.getName() + "</big><br/>");
      out.println(
          "<br/>Deadline: <input type='date' id='editDeadline' name='editDeadline' value='"
              + task.getDeadline()
              + "'><br/>");
      out.println(
          "<br/><div class='assignee'>Assignee: <input type='text' id='editAssignee'"
              + "name='editAssignee' value='");

      ArrayList<String> authUsers =
          new ArrayList<String>(utrelationOp.FetchAssigneeByTaskId(taskId));
      int i = 0;
      while (i < authUsers.size()) {
        out.print(authUsers.get(i));
        i++;
        if (i < authUsers.size()) {
          out.print(",");
        }
      }

      out.print(
          "' onkeyup=\"multiAutocomp(this, 'getAllUser.jsp');\" onfocusin='multiAutocompClearAll();'></div><br/>");

      out.println("<div class='tag'>Tag: <input type='text' id='editTag' name='editTag' value='");

      ArrayList<String> tags = new ArrayList<String>(joinOp.GetTagNamesByTaskId(task.getId_task()));
      i = 0;
      while (i < tags.size()) {
        out.print(tags.get(i));
        i++;
        if (i < tags.size()) {
          out.print(",");
        }
      }

      out.print(
          "' onkeyup=\"multiAutocomp(this, 'getAllTag.jsp');\" onfocusin='multiAutocompClearAll();'></div><br/>");

      out.println("</form><br/>");

      if (username.equals(taskOp.FetchCreatorById(task.getId_task()))) {
        out.println(
            "<input type='button' id='editremove' onclick='removeTask("
                + curCategId
                + ", "
                + task.getId_task()
                + ");' class='button' value='Remove Task'/><br>");
      } else if (utrelationOp.FetchAssigneeByTaskId(task.getId_task()).contains(username)) {
        out.println(
            "<input type='button' id='editremove' onclick='removeReference("
                + curCategId
                + ", "
                + task.getId_task()
                + ");' class='button' value='Remove me from this task'/><br>");
      }
      out.println(
          "<input type='button' id='editsave' onclick='saveTaskDetail("
              + task.getId_task()
              + ");' class='button' value='Save'/>");
      out.println(
          "<input type='button' id='editback' onclick='restore4();' class='button' value='Back'/>");
      out.println("</div>");
    } else if (action.equalsIgnoreCase("changeTaskStatus")) {
      String taskId = request.getParameter("code");
      String newStatus = request.getParameter("chkYesNo");

      if (newStatus.equals("0")) {
        taskOp.UpdateStatusWithId("F", taskId);
      } else if (newStatus.equals("1")) {
        taskOp.UpdateStatusWithId("T", taskId);
      }

      out.println("<div>");
      if (newStatus.equals("0")) {
        out.println(
            "<input type='checkbox' id='checkboxTask"
                + taskId
                + "' "
                + "onclick='changeTaskStatus("
                + taskId
                + ", this.checked);' checked>");
      } else if (newStatus.equals("1")) {
        out.println(
            "<input type='checkbox' id='checkboxTask"
                + taskId
                + "' "
                + "onclick='changeTaskStatus("
                + taskId
                + ", this.checked);'>");
      }
      out.println("Done</div>");

    } else if (action.equalsIgnoreCase("saveTaskDetail")) {
      String taskId = request.getParameter("code");
      String deadline = request.getParameter("newDeadline");
      String[] assignees = request.getParameter("newAssignees").split(",");
      String[] tags = request.getParameter("newTags").split(",");

      ArrayList<String> oldAssignees =
          new ArrayList<String>(utrelationOp.FetchAssigneeByTaskId(taskId));
      ArrayList<String> oldTagIds = new ArrayList<String>(joinOp.GetTagsIdByTaskId(taskId));

      taskOp.UpdateDeadlineById(deadline, taskId);
      for (String oldAssignee : oldAssignees) {
        utrelationOp.DeleteByTaskIdAndUsername(taskId, oldAssignee);
      }

      for (String oldTagId : oldTagIds) {
        ttrelationOp.DeleteByTagId(oldTagId);
      }

      for (String assignee : assignees) {
        if (userOp.ListAllUsernames().contains(assignee.trim())) {
          utrelationOp.InsertUtrelation(new Utrelation("", taskId, assignee.trim()));
          if (ucrelationOp.CheckIfUcrelationExists(assignee.trim(), curCategId) == 0) {
            ucrelationOp.InsertUcrelation(new Ucrelation("", assignee.trim(), curCategId));
          }
        }
      }

      for (String tag : tags) {
        if (tagOp.CheckIfTagExists(tag.trim()) == 0) {
          tagOp.InsertTag(tag.trim());
        }
        ttrelationOp.InsertTtrelation(new Ttrelation("", taskId, tagOp.SelectIdByName(tag.trim())));
      }

      ArrayList<Task> temp;
      for (String oldAssignee : oldAssignees) {
        temp = new ArrayList<Task>(joinOp.GetTasksByUsernameAndCategoryId(oldAssignee, curCategId));
        if (temp.isEmpty()) {
          ucrelationOp.DeleteByCategId(curCategId, oldAssignee);
        }
      }

      for (String oldTagId : oldTagIds) {
        if (joinOp.CheckTtrelationByTagId(oldTagId) == 0) {
          tagOp.DeleteById(oldTagId);
        }
      }
    } else if (action.equalsIgnoreCase("addTask")) {
      String[] assignees = request.getParameter("newTaskAssignee").split(",");
      String[] tags = request.getParameter("newTaskTags").split(",");
      String name = request.getParameter("newTaskName");

    } else if (action.equalsIgnoreCase("removeTask")) {
      String taskId = request.getParameter("code");
      tarelationOp.DeleteTarelationByTaskId(taskId);
      ttrelationOp.DeleteByTaskId(taskId);
      commentOp.DeleteCommentByTaskId(taskId);
      utrelationOp.DeleteByTaskId(taskId);
      taskOp.DeleteById(taskId);

      ArrayList<String> allUsers = new ArrayList<String>(userOp.ListAllUsernames());
      ArrayList<Task> temp;
      for (String user : allUsers) {
        if (!user.equals(username)) {
          temp = new ArrayList<Task>(joinOp.GetTasksByUsernameAndCategoryId(user, curCategId));
          if (temp.isEmpty()) {
            ucrelationOp.DeleteByCategId(curCategId, username);
          }
        }
      }
    } else if (action.equalsIgnoreCase("removeReference")) {
      String taskId = request.getParameter("code");

      utrelationOp.DeleteByTaskId(taskId);
      ArrayList<Task> temp =
          new ArrayList<Task>(joinOp.GetTasksByUsernameAndCategoryId(username, curCategId));
      if (temp.isEmpty()) {
        ucrelationOp.DeleteByCategId(curCategId, username);
      }

    } else if (action.equalsIgnoreCase("addComment")) {
      String idtask = request.getParameter("it");
      String content = request.getParameter("c");

      DateFormat dateFormat = new SimpleDateFormat("yyyy:MM:dd:HH:mm");
      Date date = new Date();
      String timestamp = dateFormat.format(date).toString();

      String avatar = userOp.SelectUserInfoByUsername(username).getAvatar();

      commentOp.InsertComment(idtask, username, dateFormat.format(date).toString(), content);
      String idcomment = commentOp.GetIdByOtherAttributes(idtask, username, content);

      String message = avatar + ":" + timestamp + ":" + content + ":" + idcomment;
      out.println(message);
    } else if (action.equalsIgnoreCase("delComment")) {
      String idcomment = request.getParameter("ic");

      commentOp.DeleteCommentByCommentId(idcomment);
      out.println(idcomment);
    } else {
      System.out.println("No command existed");
    }

    out.close();
  }
 /** @param category the category to be registered */
 public void registerCategory(Category category) {
   if (!categories.keySet().contains(category.getName()))
     categories.put(category.getName(), category);
 }
示例#25
0
  @SuppressWarnings("deprecation")
  public static Inventory constructInventory(
      TitlesPlugin plugin, Player player, String cat, boolean owned) {
    DataContainer dataContainer = plugin.getDataContainer();
    Inventory inv = null;
    // if there are titles, construct category inventory
    if (!dataContainer.getTitles().isEmpty()) {
      List<String> categories = GetCommands.getCategories(dataContainer);
      List<ItemStack> clickables = new ArrayList<>();

      // get inventory with categories.
      if (cat == null) {

        if (owned) {
          List<Title> unlocked = dataContainer.getUnlockedTitles(player);
          for (Title title : unlocked) {
            ItemStack is;
            String name = title.getName();
            String description = title.getDescription();
            String status;

            if (dataContainer.getCurrentTitle(player) != null
                && dataContainer.getCurrentTitle(player).equals(title)) {
              is = new ItemStack(Material.WOOL, 1, DyeColor.LIME.getData());
              status = "Current";
            } else {
              is = new ItemStack(Material.WOOL, 1, DyeColor.GREEN.getData());
              status = "Unlocked";
            }
            ItemMeta meta = is.getItemMeta();
            meta.setDisplayName(name);
            meta.setLore(
                Arrays.asList(
                    "Description: " + description,
                    "Category: " + title.getCategory().getName(),
                    "Status: " + status));
            is.setItemMeta(meta);
            clickables.add(is);
          }

          int size = ((clickables.size() / 9) + 1) * 9;
          inv =
              Bukkit.createInventory(
                  null, size, ChatColor.DARK_AQUA + "" + ChatColor.BOLD + "Unlocked Titles");

          for (int i = 0; i < clickables.size(); i++) inv.setItem(i, clickables.get(i));

          // back button
          ItemStack is = new ItemStack(Material.WOOL, 1, DyeColor.GRAY.getData());
          ItemMeta meta = is.getItemMeta();
          meta.setDisplayName("Back");
          is.setItemMeta(meta);
          inv.setItem(inv.getSize() - 1, is);
          return inv;
        }

        for (String category : categories) {
          ItemStack is = new ItemStack(Material.WOOL, 1, DyeColor.GRAY.getData());
          ItemMeta meta = is.getItemMeta();
          meta.setDisplayName(category);
          is.setItemMeta(meta);
          clickables.add(is);
        }
        int size = ((clickables.size() / 9) + 1) * 9;
        inv =
            Bukkit.createInventory(
                null, size, ChatColor.DARK_AQUA + "" + ChatColor.BOLD + "Title categories");

        // get inventory with titles from category.
      } else {
        Category category = dataContainer.getCategory(cat);
        if (category == null) return null;
        List<Title> titles = dataContainer.getTitlesFromCategory(category);
        List<Title> ownedTitles = dataContainer.getUnlockedTitles(player);

        for (Title title : titles) {
          ItemStack is;
          String name = title.getName();
          String description = title.getDescription();
          String status;

          if (ownedTitles.contains(title)) {
            if (dataContainer.getCurrentTitle(player) != null
                && dataContainer.getCurrentTitle(player).equals(title)) {
              is = new ItemStack(Material.WOOL, 1, DyeColor.LIME.getData());
              status = "Current";
            } else {
              is = new ItemStack(Material.WOOL, 1, DyeColor.GREEN.getData());
              status = "Unlocked";
            }
          } else {
            Request request = dataContainer.getRequest(player);
            if (request != null
                && request.getTitle().equals(title)
                && request.getStatus() == RequestStatus.pending) {
              is = new ItemStack(Material.WOOL, 1, DyeColor.ORANGE.getData());
              status = "Pending";
            } else {
              is = new ItemStack(Material.WOOL, 1, DyeColor.RED.getData());
              status = "Locked";
            }
          }

          ItemMeta meta = is.getItemMeta();
          meta.setDisplayName(name);
          meta.setLore(
              Arrays.asList(
                  "Description: " + description,
                  "Category: " + category.getName(),
                  "Status: " + status));
          is.setItemMeta(meta);
          clickables.add(is);
        }
        int size = ((clickables.size() / 9) + 1) * 9;
        inv =
            Bukkit.createInventory(
                null, size, ChatColor.DARK_AQUA + "" + ChatColor.BOLD + "Titles in category");
      }

      for (int i = 0; i < clickables.size(); i++) inv.setItem(i, clickables.get(i));

      // back button
      if (cat != null) {
        ItemStack is = new ItemStack(Material.WOOL, 1, DyeColor.GRAY.getData());
        ItemMeta meta = is.getItemMeta();
        meta.setDisplayName("Back");
        is.setItemMeta(meta);
        inv.setItem(inv.getSize() - 1, is);

        // player's unlocked titles
      } else {
        ItemStack is = new ItemStack(Material.WOOL, 1, DyeColor.GREEN.getData());
        ItemMeta meta = is.getItemMeta();
        meta.setDisplayName("Unlocked");
        is.setItemMeta(meta);
        inv.setItem(inv.getSize() - 1, is);
      }

    } else Utils.sendError(player, "There are no titles yet.");
    return inv;
  }
示例#26
0
 private MapSqlParameterSource createCategoryParameterSource(Category category) {
   return new MapSqlParameterSource()
       .addValue("id", category.getId())
       .addValue("name", category.getName())
       .addValue("showOnSalesScreen", category.isShowOnSalesScreen());
 }
 void appendCategory(Category category) {
   categories.put(category.getName(), category);
   currentCategory = category;
 }
 @Test
 public void itFindsCategoryByName() {
   Category category = categoryDAO.findByName("Dinner");
   assertNotNull(category);
   assertEquals("Dinner", category.getName());
 }
 public CategoryNode(Category category) {
   super(Children.create(new ShapeChildFactory(category), true));
   setDisplayName(category.getName());
 }
示例#30
0
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

      ViewHolder holder = null;
      // Log.v("ConvertView", String.valueOf(position));
      // Log.v("AddEditCatActivity", "convertView" + convertView);

      if (convertView == null) {
        LayoutInflater vi =
            (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        // TODO: Should I set null to parent? It errors if I do but I can't call the one below if i
        // do.
        convertView = vi.inflate(R.layout.fragment_category_list_view, null);

        holder = new ViewHolder();
        holder.category_list_text_view =
            (TextView) convertView.findViewById(R.id.category_list_text_view);
        holder.category_list_text_view_type =
            (TextView) convertView.findViewById(R.id.category_list_text_view_type);

        convertView.setTag(holder);

        View.OnClickListener categoryClickListener;
        categoryClickListener =
            new View.OnClickListener() {
              public void onClick(View v) {
                TextView tv = (TextView) v;
                Category category = (Category) tv.getTag();
                // showList(category.getID());
                // Log.v("CategoryViewFragment.MyCatListCustomAdapter", "category.getID(): " +
                // category.getID());
                sCategoryCallback.onCategorySelected(category.getID());
              }
            };
        holder.category_list_text_view.setOnClickListener(categoryClickListener);
      } else {
        holder = (ViewHolder) convertView.getTag();
      }

      Category category = categoryList.get(position);
      // TODO: Make a function in ListManager to get and hold the category type names in memory
      // int categoryTypeID = category.getType();
      // String categoryDescription = category.getDescription();
      String categoryName = category.getName();
      String type = "(C)";
      // if (category.getFilterID() == 0) {
      //	type = "(C)";
      // }
      // String categoryTypeName = myListMan.getItemTypeName(categoryTypeID);

      // Log.v("MyCatListCustomAdapter", "categoryTypeID:" + categoryTypeID);
      // Log.v("MyCatListCustomAdapter", "category.getDescription(): " + category.getDescription());
      // Log.v("MyCatListCustomAdapter", "myListMan.getCategoryTypeName(): " +
      // myListMan.getItemTypeName(categoryTypeID));

      holder.category_list_text_view.setText(type + " " + categoryName);
      holder.category_list_text_view_type.setText("");
      holder.category_list_text_view.setTag(category);
      // TODO: Link this to type type editing activity later
      holder.category_list_text_view_type.setTag(category);

      return convertView;
    }