/** This method tests the {@code hasNumberOfModifiedColumnsLessThan} assertion method. */
 @Test
 public void test_has_number_of_modified_columns_less_than() throws Exception {
   WritableAssertionInfo info = new WritableAssertionInfo();
   Table table = new Table();
   TableAssert tableAssert = assertThat(table);
   Row rowAtStartPoint =
       getRow(
           null,
           Arrays.asList("ID", "NAME", "FIRSTNAME", "BIRTH"),
           Arrays.asList(
               getValue(null, 1),
               getValue(null, "Weaver"),
               getValue(null, "Sigourney"),
               getValue(null, Date.valueOf("1949-10-08"))));
   Row rowAtEndPoint =
       getRow(
           null,
           Arrays.asList("ID", "NAME", "FIRSTNAME", "BIRTH"),
           Arrays.asList(
               getValue(null, 1),
               getValue(null, "Weaverr"),
               getValue(null, "Sigourneyy"),
               getValue(null, Date.valueOf("1949-10-08"))));
   Change change =
       getChange(DataType.TABLE, "test", ChangeType.MODIFICATION, rowAtStartPoint, rowAtEndPoint);
   TableAssert tableAssert2 =
       AssertionsOnModifiedColumns.hasNumberOfModifiedColumnsLessThan(
           tableAssert, info, change, 3);
   Assertions.assertThat(tableAssert2).isSameAs(tableAssert);
 }
Esempio n. 2
0
    @Override
    protected Boolean doInBackground(Void... params) {
      ResourcesMan.quitarJuntas();
      JSONObject result = SMEDClient.getAllMeetings(groupId, parentId);

      try {
        juntas = result.getJSONArray("juntas");

        for (int i = 0; i < juntas.length(); ++i) {
          junta = null;
          junta = juntas.getJSONObject(i);
          id_junta = junta.getString("id_junta");
          id_padre = junta.getString("id_padre");
          id_grupo = junta.getString("id_grupo");
          fecha = junta.getString("fecha");
          motivo = junta.getString("motivo");
          esgrupal = junta.getString("esgrupal");

          if (esgrupal.equals("1"))
            ResourcesMan.addJunta(
                new Junta(
                    motivo, descripcion, Integer.parseInt(id_grupo), Date.valueOf(fecha), true));
          if (esgrupal.equals("0"))
            ResourcesMan.addJunta(
                new Junta(
                    motivo, descripcion, Integer.parseInt(id_grupo), Date.valueOf(fecha), false));
        }
        return true;
      } catch (JSONException e) {
        e.printStackTrace();
      } catch (NullPointerException e) {
        e.printStackTrace();
      }
      return false;
    }
Esempio n. 3
0
  protected void verifyBillingPeriodPriorTo(
      String awardStartDate,
      String currentDate,
      String lastBilledDate,
      String expectedBillingPeriodStart,
      String expectedBillingPeriodEnd,
      boolean expectedBillable,
      String billingFrequencyCode) {
    Date lastBilledDateAsDate = nullSafeDateFromString(lastBilledDate);
    AccountingPeriodService accountingPeriodService = getMockAccountingPeriodService();

    BillingPeriod priorBillingPeriod =
        BillingPeriod.determineBillingPeriodPriorTo(
            Date.valueOf(awardStartDate),
            Date.valueOf(currentDate),
            lastBilledDateAsDate,
            billingFrequencyCode,
            accountingPeriodService);

    Date expectedStartDate = nullSafeDateFromString(expectedBillingPeriodStart);
    Assert.assertEquals(
        "Billing period start wasn't what we thought it was going to be",
        expectedStartDate,
        priorBillingPeriod.getStartDate());
    Date expectedEndDate = nullSafeDateFromString(expectedBillingPeriodEnd);
    Assert.assertEquals(
        "Billing period end wasn't what we thought it was going to be",
        expectedEndDate,
        priorBillingPeriod.getEndDate());
    Assert.assertEquals(
        "Billing period billable wasn't what we thought it was going to be",
        expectedBillable,
        priorBillingPeriod.isBillable());
  }
  public void initialise(RandomiserInstance ri) {
    LinkedHashMap hashmap;
    String sMax, sFromDate, sDateTo, sPercent, sNull, sSelectedDays;
    int iMax;
    Object objValues[] = new Object[3];

    txtName.setText(ri.getName());
    txtDescription.setText(ri.getDescription());

    hashmap = ri.getProperties();
    sMax = (String) hashmap.get("rangesNum");
    try {
      iMax = Integer.parseInt(sMax);
      for (int i = 0; i < iMax; i++) {
        sFromDate = (String) hashmap.get("fromField" + i);
        objValues[0] = Date.valueOf(sFromDate);
        sDateTo = (String) hashmap.get("toField" + i);
        objValues[1] = Date.valueOf(sDateTo);
        sPercent = (String) hashmap.get("percentField" + i);
        objValues[2] = Integer.valueOf(sPercent);

        newModelDates.addRow(objValues);
      }
      sNull = (String) hashmap.get("nullField");
      spinNull.setValue(Integer.parseInt(sNull));
    } catch (Exception e) {
      logger.warn("Error while setting properties:", e);
    }
    sSelectedDays = (String) hashmap.get("selectedDays");
  }
  @Test
  public void findCustomerWithCar() {
    assertTrue(car1.getAvailable());
    assertTrue(car2.getAvailable());
    assertTrue(car3.getAvailable());

    manager.rentCarToCustomer(
        car1, customer1, Date.valueOf("2012-03-21"), Date.valueOf("2012-03-31"));

    assertEquals(customer1, manager.findCustomerWithCar(car1));
    assertCustomerDeepEquals(customer1, manager.findCustomerWithCar(car1));
    assertTrue(car2.getAvailable());
    assertTrue(car3.getAvailable());

    try {
      manager.findCustomerWithCar(null);
      fail();
    } catch (IllegalArgumentException e) {
    }
    try {
      manager.findCustomerWithCar(carWithoutID);
      fail();
    } catch (IllegalArgumentException e) {
    }
  }
Esempio n. 6
0
  @RequestMapping("update.do")
  public void update(Scanner keyScan) {
    try {
      System.out.print("변경할 프로젝트 번호?");
      int no = Integer.parseInt(keyScan.nextLine());

      Project oldProject = projectDao.selectOne(no);
      Project project = new Project();

      System.out.printf("프로젝트명(%s)? ", oldProject.getTitle());
      project.setTitle(keyScan.nextLine());
      System.out.printf("시작일(%s)? ", oldProject.getStartDate());
      project.setStartDate(Date.valueOf(keyScan.nextLine()));
      System.out.printf("종료일(%s)? ", oldProject.getEndDate());
      project.setEndDate(Date.valueOf(keyScan.nextLine()));
      System.out.printf("설명(%s)? ", oldProject.getDescription());
      project.setDescription(keyScan.nextLine());

      if (CommandUtil.confirm(keyScan, "변경하시겠습니까?")) {
        projectDao.update(no, project);
        System.out.println("변경하였습니다.");
      } else {
        System.out.println("변경을 취소하였습니다.");
      }
    } catch (IndexOutOfBoundsException e) {
      System.out.println("유효한 번호가 아닙니다.");
    } catch (Exception e) {
      System.out.println("데이터 로딩에 실패했습니다.");
    }
  }
  @BeforeClass
  public void setUp() {
    MockitoAnnotations.initMocks(this);

    acdc = new Musician();
    acdc.setRealName("Brian Johnson");
    acdc.setArtistName("AC/DC");
    acdc.setDateOfBirth(Date.valueOf("1945-10-15"));

    backInBlackAlbum = new Album();
    backInBlackAlbum.setMusician(acdc);
    backInBlackAlbum.setReleaseDate(Date.valueOf("1980-7-25"));
    backInBlackAlbum.setTitle("Back In Black");

    shootToThrillSong = new Song();
    shootToThrillSong.setTitle("Shoot To Thrill");
    shootToThrillSong.setAlbum(backInBlackAlbum);
    shootToThrillSong.setGenre(progressiveRock);
    shootToThrillSong.setMusician(acdc);
    shootToThrillSong.setAlbumPosition(2);
    shootToThrillSong.setBitrate(320);

    albumDTO = new AlbumDTO();
    albumDTO.setTitle(backInBlackAlbum.getTitle());
    albumDTO.setReleaseDate(backInBlackAlbum.getReleaseDate());
    albumDTO.setMusician(new MusicianDTO());
    albumDTO.setCover(backInBlackAlbum.getCover());

    progressiveRock = new Genre();
    progressiveRock.setTitle("Progressive Rock");
    progressiveRock.setYearOfOrigin(1960);
  }
Esempio n. 8
0
 @Test
 public void testGetDate() throws Exception {
   List<Query.Type> types = Arrays.asList(Query.Type.DATE);
   for (Query.Type type : types) {
     try (Cursor cursor =
         new SimpleCursor(
             QueryResult.newBuilder()
                 .addFields(Field.newBuilder().setName("col1").setType(type).build())
                 .addFields(Field.newBuilder().setName("null").setType(type).build())
                 .addRows(
                     Query.Row.newBuilder()
                         .addLengths("2008-01-02".length())
                         .addLengths(-1) // SQL NULL
                         .setValues(ByteString.copyFromUtf8("2008-01-02")))
                 .build())) {
       Row row = cursor.next();
       Assert.assertNotNull(row);
       Assert.assertEquals(Date.valueOf("2008-01-02"), row.getObject("col1"));
       Assert.assertEquals(Date.valueOf("2008-01-02"), row.getDate("col1"));
       Assert.assertEquals(new Date(1199232000000L), row.getDate("col1", GMT));
       Assert.assertFalse(row.wasNull());
       Assert.assertEquals(null, row.getDate("null"));
       Assert.assertTrue(row.wasNull());
     }
   }
 }
Esempio n. 9
0
  /*
   * (non-Javadoc)
   *
   * @see controleur.AbstractServlet#recupInitParameters()
   */
  @Override
  protected void recupInfos(HttpServletRequest req) {
    idEleve = Integer.parseInt(req.getParameter("idEleve"));

    eleve = (IEleve) FabriquePersistance.getInstance(FabriquePersistance.ELEVE).readByID(idEleve);
    eleve.setNumMat(req.getParameter("numMat"));
    eleve.setNom(req.getParameter("nom"));
    eleve.setPrenom(req.getParameter("prenom"));
    eleve.setSexe(req.getParameter("sexe"));
    if (req.getParameter("boursier") == null) eleve.setBoursier("0");
    else eleve.setBoursier("1");
    if (req.getParameter("aero") == null) eleve.setAero("0");
    else eleve.setAero("1");
    eleve.setIDp("0");
    eleve.setCatSociale(req.getParameter("catSociale"));
    eleve.setSituFamille(req.getParameter("situFamille"));
    eleve.setOldClasse(eleve.getClasse());
    if (req.getParameter("dateNaissance") != "")
      eleve.setDateNaissance(Date.valueOf(req.getParameter("dateNaissance")));
    if (req.getParameter("dateArrivee") != "")
      eleve.setDateArrivee(Date.valueOf(req.getParameter("dateArrivee")));
    if (req.getParameter("nouveau") == null) eleve.setNouveau("0");
    else eleve.setNouveau("1");
    eleve.setAnneeEntree(Integer.parseInt(req.getParameter("anneeEntree")));
    if (req.getParameter("rdc") != "") eleve.setRdc(Date.valueOf(req.getParameter("rdc")));
    eleve.setClasse(
        (IClasse)
            FabriquePersistance.getInstance(FabriquePersistance.CLASSE)
                .readByID(Integer.parseInt(req.getParameter("idClasse"))));
  }
  public boolean alterar(ProdutoPronto pPronto) throws Exception {
    boolean status = false;
    String sql =
        " UPDATE produtopronto SET produtoId=?, encomendaId=?, finalizado=?, dataValidade=?,"
            + " codigo=? where id=?";

    PreparedStatement ps = null;
    try (Connection conn = ConnectionProvider.getInstance().getConnection()) {
      ps = conn.prepareStatement(sql);
      ps.setInt(1, pPronto.getProdutoId());
      ps.setInt(2, pPronto.getEncomendaId());
      ps.setDate(3, Date.valueOf(pPronto.getFinalizado()));
      ps.setDate(4, Date.valueOf(pPronto.getDataValidade()));
      ps.setString(5, pPronto.getCodigo());
      ps.setLong(6, pPronto.getId());

      if (ps.executeUpdate() != 0) {
        status = true;
      }
      ps.close();
      conn.close();
    } catch (SQLException e) {
      System.out.println("Erro ao alterar os produtos Prontos\n" + e);
    }
    return status;
  }
 @Test
 public void testErreurDateNull() {
   final DateMinMaxValidator test =
       new DateMinMaxValidator(Date.valueOf("2012-01-10"), Date.valueOf("2012-08-18"));
   test.check((String) null);
   assertFalse(test.hasError());
 }
Esempio n. 12
0
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    ProjectDao projectDao = (ProjectDao) this.getServletContext().getAttribute("projectDao");

    try {
      // request.setCharacterEncoding("UTF-8"); // CharSetFilter에서 처리
      Member member = (Member) request.getSession().getAttribute("member");
      Project project =
          new Project()
              .setTitle(request.getParameter("title"))
              .setContent(request.getParameter("content"))
              .setStartDate(Date.valueOf(request.getParameter("startDate")))
              .setEndDate(Date.valueOf(request.getParameter("endDate")))
              .setTag(request.getParameter("tag"))
              .setLeader(member.getEmail());

      projectDao.add(project);

      response.sendRedirect("list");

    } catch (Exception e) {
      e.printStackTrace();
      RequestDispatcher rd = request.getRequestDispatcher("/error.jsp");
      rd.forward(request, response);
    }
  }
  public boolean inserir(ProdutoPronto pPronto) throws Exception {
    boolean status = false;
    String sql =
        " INSERT INTO produtopronto (produtoId, encomendaId, finalizado, dataValidade, codigo)"
            + " VALUES (?, ?, ?, ?, ?)";
    PreparedStatement ps = null;

    try (Connection conn = ConnectionProvider.getInstance().getConnection()) {
      ps = conn.prepareStatement(sql);
      ps.setInt(1, pPronto.getProdutoId());

      if (pPronto.getEncomendaId() != null) {
        ps.setInt(2, pPronto.getEncomendaId());
      }

      ps.setDate(3, Date.valueOf(pPronto.getFinalizado()));

      if (pPronto.getDataValidade() != null) {
        ps.setDate(4, Date.valueOf(pPronto.getDataValidade()));
      }

      ps.setString(5, pPronto.getCodigo());

      if (ps.executeUpdate() != 0) {
        status = true;
      }
      ps.close();
      conn.close();

    } catch (SQLException e) {
      System.out.println("Erro ao inserir produto Pronto\n" + e);
    }
    return status;
  }
  @Test
  public void testErreurEgalSupOK() {

    final DateMinMaxValidator test =
        new DateMinMaxValidator(Date.valueOf("2012-01-10"), true, Date.valueOf("2012-08-18"), true);
    test.check("2012-08-18");
    assertEquals(0, test.getErrors().size());
  }
  @Test
  public void testErreurDateSup() {

    final DateMinMaxValidator test =
        new DateMinMaxValidator(Date.valueOf("2012-01-10"), Date.valueOf("2012-08-18"));
    test.check("2013-11-01");
    assertTrue(test.hasError());
  }
 @Override
 protected boolean isValidDate() {
   Date startDate = Date.valueOf("2005-04-30");
   Date endDate = Date.valueOf("2005-06-01");
   Date parsingDate = Date.valueOf(getYear() + "-" + getMonth() + "-" + "01");
   if (parsingDate.after(startDate) && parsingDate.before(endDate)) return true;
   else return false;
 }
Esempio n. 17
0
 void setValue(String str) {
   String[] tokens = str.split(",");
   if (tokens.length < 4) return;
   title = tokens[0];
   startDate = Date.valueOf(tokens[1]); // yyyy-MM-dd ------> Date 객체
   endDate = Date.valueOf(tokens[2]);
   member = tokens[3];
 }
  @Test
  public void testErreurEgalInfErreur() {

    final DateMinMaxValidator test =
        new DateMinMaxValidator(
            Date.valueOf("2012-01-10"), false, Date.valueOf("2012-08-18"), true);
    test.check("2012-01-10");
    assertTrue(test.hasError());
  }
  @Test
  public void testErreurVerif1() {

    final DateMinMaxValidator test =
        new DateMinMaxValidator(
            Date.valueOf("2012-07-18"), false, Date.valueOf("2012-08-18"), false);
    test.check("badSyntax");
    assertTrue(test.hasError());
  }
Esempio n. 20
0
  // Lấy danh sách các quảng cáo
  public ArrayList<QUANGCAO> listAdv(int page, boolean hthi) {
    ArrayList<QUANGCAO> listAdvertise = new ArrayList<QUANGCAO>();
    String sql_select_advertise = "";
    if (hthi)
      sql_select_advertise = "SELECT * FROM quangcao where HienThi='1' order by IdQuangCao desc ";
    else
      sql_select_advertise = "SELECT * FROM quangcao where HienThi='0' order by IdQuangCao desc ";
    db.createMenu("ListAdvertiseServlet?", page, sql_select_advertise);
    ResultSet result_select = null;
    if (page != -1) {
      result_select =
          db.getResultSet(
              sql_select_advertise
                  + " limit "
                  + (page - 1) * db.getNBangGhi()
                  + ","
                  + db.getNBangGhi());
    } else {
      result_select = db.getResultSet(sql_select_advertise);
    }

    Calendar cal = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Calendar c1 = Calendar.getInstance();
    Calendar c2 = Calendar.getInstance();
    // Định nghĩa 2 mốc thời gian ban đầu
    Date date2 = Date.valueOf(sdf.format(cal.getTime()));
    c2.setTime(date2);

    try {
      while (result_select.next()) {
        QUANGCAO advertise = new QUANGCAO();
        advertise.setIdQuangCao(result_select.getInt("IdQuangCao"));
        advertise.setViTri(result_select.getInt("ViTri"));
        advertise.setTrangHienThi(result_select.getInt("TrangHienThi"));
        advertise.setHienThi(result_select.getInt("HienThi"));
        advertise.setLienKet(DinhDangSQL.FomatSQL(result_select.getString("LienKet")));
        advertise.setHinhAnh(DinhDangSQL.FomatSQL(result_select.getString("HinhAnh")));
        advertise.setSoNgay(result_select.getInt("SoNgay"));
        advertise.setNgayDang(result_select.getDate("NgayDang").toString());
        Date date1 = Date.valueOf(advertise.getNgayDang());
        c1.setTime(date1);
        advertise.setSoNgay(
            advertise.getSoNgay()
                - (int) (c2.getTime().getTime() - c1.getTime().getTime()) / (24 * 3600 * 1000));
        advertise.setDonViQuangCao(result_select.getString("DonViQuangCao"));
        listAdvertise.add(advertise);
      }
      return listAdvertise;
    } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      return null;
    }
  }
 // private static double daycount_c;
 // 因为这是出入场图,所以传入的type没有用到,所以这里的type的意思是按日统计(0)还是按月统计(1)
 public CopyOfParkingSystemChartZhu_test(String title, String timefrom, String timeto, int type) {
   super(title);
   this.timefrom = timefrom;
   this.timeto = timeto;
   this.type = type;
   datefrom = java.sql.Date.valueOf(timefrom);
   dateto = java.sql.Date.valueOf(timeto);
   ChartPanel chartPanel = (ChartPanel) createDemoPanel();
   chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
   setContentPane(chartPanel);
 }
Esempio n. 22
0
  public Paint[] getBarColors() {
    DBManager dbM = DBManager.instance();
    PreparedStatement stat1 = null;
    PreparedStatement stat2 = null;
    try {
      stat1 =
          dbM.getConnection()
              .prepareStatement(
                  "SELECT Estado FROM ValorIndicador WHERE IdIndicador = ? And Fecha >= ? And Fecha <= ? ORDER BY Fecha");
      stat1.setInt(1, idIndicador);
      stat1.setDate(2, java.sql.Date.valueOf(inicio_periodo.toString()));
      stat1.setDate(3, java.sql.Date.valueOf(fin_periodo.toString()));
      stat1.execute();
      stat2 =
          dbM.getConnection()
              .prepareStatement(
                  "SELECT Count(*) AS Cuenta FROM ValorIndicador WHERE IdIndicador = ? And Fecha >= ? And Fecha <= ?");
      stat2.setInt(1, idIndicador);
      stat2.setDate(2, java.sql.Date.valueOf(inicio_periodo.toString()));
      stat2.setDate(3, java.sql.Date.valueOf(fin_periodo.toString()));
      stat2.execute();
      ResultSet count = stat2.getResultSet();
      count.next();
      int size = count.getInt("Cuenta");
      ResultSet res = stat1.getResultSet();
      Paint[] colores = new Paint[size];
      int i = 0;
      while (res.next() && i < size) {
        switch (res.getString("Estado")) {
          case "VERDE":
            colores[i] = Color.green;
            break;
          case "ROJO":
            colores[i] = Color.red;
            break;
          case "AMARILLO":
            colores[i] = Color.yellow;
            break;
          case "NARANJA":
            colores[i] = Color.orange;
            break;
        }

        i++;
      }
      return colores;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
Esempio n. 23
0
  @RequestMapping(value = "add", method = RequestMethod.POST)
  public String add(String title, String startDate, String endDate, String member)
      throws Exception {

    Project project = new Project();
    project.setTitle(title);
    project.setStartDate(Date.valueOf(startDate));
    project.setEndDate(Date.valueOf(endDate));
    project.setMember(member);

    projectDao.insert(project);

    return "redirect:list.do";
  }
  public boolean alterar(MateriaPrima materiaPrima) throws Exception {
    boolean status = false;

    // string query do banco
    String sql =
        " UPDATE materiaprima SET codigo=?, nome=?, estoque=?, unidade=?, fabricacao=?,"
            + " vencimento=?, descricao=? where id=?";
    PreparedStatement ps = null;

    // chama uma instância da Connection e tenta realizar uma conexão com o banco através do
    // AutoCloseable
    try (Connection conn = ConnectionProvider.getInstance().getConnection()) {
      // seta os atributos do objeto matéria-prima, fazendo a alteração.
      ps = conn.prepareStatement(sql);
      ps.setString(1, materiaPrima.getCodigo());
      ps.setString(2, materiaPrima.getNome());
      ps.setDouble(3, materiaPrima.getEstoque());
      ps.setLong(4, materiaPrima.getUnidade());

      if (materiaPrima.getFabricacao() != null) {
        ps.setDate(5, Date.valueOf(materiaPrima.getFabricacao()));
      } else {
        ps.setNull(5, Types.DATE);
      }

      if (materiaPrima.getVencimento() != null) {
        ps.setDate(6, Date.valueOf(materiaPrima.getVencimento()));
      } else {
        ps.setNull(6, Types.DATE);
      }

      ps.setString(7, materiaPrima.getDescricao());
      ps.setLong(8, materiaPrima.getId());

      if (ps.executeUpdate() != 0) {
        status = true;
      }

      // fecha as conexões
      ps.close();
      conn.close();
    }
    // trata, caso de uma exceção
    catch (SQLException e) {
      System.out.println("Erro ao alterar a materiaPrima\n" + e);
    }
    // retorna true ou false, dizendo se o metodo foi executado com sucesso.
    return status;
  }
  @Before
  public void setUp() throws Exception {

    //	mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
    //			.build();
    message = new Message();
    event = new Event();
    message.setMessageString("data successfully inserted!!!");
    event.setEventTitle("test event");
    event.setEventDate(Date.valueOf("2011-02-02"));
    event.setEventDesc("this is test event description");

    Image photo = new Image();
    /*MockMultipartFile file = new MockMultipartFile("image",
    "FooBar".getBytes());*/

    /* FileInputStream test = new FileInputStream("EventManagment/Event_Image/Desert.png");
     System.out.println("test image:"+test);
    MockMultipartFile file = new MockMultipartFile(
                "eventPhoto", test);*/

    //	multiPartRequest.addFile(new MockMultipartFile("dummyImage", "Desert.jpg","image/jpeg", new
    // byte[20971524] ));

    //	System.out.println("test image file:"+file);
    //	photo.setEventPhoto(file);
    event.setPhoto(photo);
  }
  /** Test of setObject method, of inteface java.sql.CallableStatement. */
  public void testSetObject_DATE() throws Exception {
    println("setObject - DATE");

    setUpDualTable();

    setObjectTest("date", Date.valueOf("2005-12-13"), Types.DATE);
  }
Esempio n. 27
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 {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
      /* TODO output your page here. You may use following sample code. */

      HttpSession session = request.getSession();
      HashMap<String, Integer> rights = (HashMap<String, Integer>) session.getAttribute("login");
      Employee emp = new Employee();
      emp.setUserId(rights.get("userId"));
      DAOFactory db = DAOFactory.getDAOFactory(1);
      EmployeeDAO empDB = db.getEmployeeDAO();
      emp = empDB.getEmployeeById(emp);

      String[] Products = request.getParameterValues("checkedRows");
      String[] Quantity = request.getParameterValues("orderquantity");
      PurchaseOrder order = new PurchaseOrder();
      Date d = java.sql.Date.valueOf(request.getParameter("orderdate"));
      order.setOrder_date(d);
      order.setEmployeeID(emp.getEmployeeId());
      order.setStatus("P");
      PurchaseOrderDAO poDB = db.getPurchaseOrderDAO();
      int ordernumber = poDB.addPurchaseOrder(order);
      order.setPurchaseOrderID(ordernumber);
      order.setProducts(Products);
      order.setQuantity(Quantity);
      poDB.addProducts(order);
      response.sendRedirect("ToReqSlip");
    }
  }
  @Override
  public boolean create(ImpiegatoTO impiegato) {
    Connection conn = MySqlConnectionFactory.getConnection();
    PreparedStatement statement = null;

    int result = 0;
    boolean response = false;

    try {
      statement = conn.prepareStatement(queryFactory.getQuery("create_impiegato"));
      int i = 1;
      statement.setString(i++, impiegato.getCf());
      statement.setString(i++, impiegato.getNome());
      statement.setString(i++, impiegato.getCognome());
      statement.setDate(i++, java.sql.Date.valueOf(impiegato.getDataNascita()));
      statement.setString(i++, impiegato.getTelefono());
      statement.setString(i++, impiegato.getAgenzia());
      statement.setString(i++, impiegato.getUsername());
      statement.setString(i++, "attivo");

      result = statement.executeUpdate();

      if (result > 0) response = true;

    } catch (SQLException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      DbEntityCloser.close(statement);
      DbEntityCloser.close(conn);
    }

    return response;
  }
  @Override
  protected boolean isValid() {
    boolean result = true;

    try {
      java.sql.Date targetDate = java.sql.Date.valueOf(fieldValue.toString());

      try {

        if (ifEqual) {
          if (DateUtil.compare(
                  targetDate, DateUtil.parseToDate(dateStr, DateUtil.FORMAT.YYYYMMDDHyphen))
              > 0) {
            result = false;
            errorCode = M10220CM;
          }
        } else {
          if (DateUtil.compare(
                  targetDate, DateUtil.parseToDate(dateStr, DateUtil.FORMAT.YYYYMMDDHyphen))
              >= 0) {
            result = false;
            errorCode = M10240CM;
          }
        }
      } catch (Exception e) {
        result = false;
      }
    } catch (Exception e) {
      result = false;
      errorCode = com.maxiaohua.genealogy.fw.core.validator.type.DateSql.DEFAULT_ERROR_CODE;
      errortype = 1;
    }

    return result;
  }
 @Test(groups = {HIVE_CONNECTOR, POST_HIVE_1_0_1})
 @Requires(AllSimpleTypesTables.class)
 public void testInsertIntoSelectToHiveTableAllHiveSimpleTypes() {
   String tableNameInDatabase = mutableTablesState().get(TABLE_NAME).getNameInDatabase();
   assertThat(query("SELECT * FROM " + tableNameInDatabase)).hasNoRows();
   assertThat(query("INSERT INTO " + tableNameInDatabase + " SELECT * from textfile_all_types"))
       .containsExactly(row(1));
   assertThat(query("SELECT * FROM " + tableNameInDatabase))
       .containsOnly(
           row(
               127,
               32767,
               2147483647,
               9223372036854775807L,
               123.345f,
               234.567,
               new BigDecimal("346"),
               new BigDecimal("345.67800"),
               parseTimestampInUTC("2015-05-10 12:15:35.123"),
               Date.valueOf("2015-05-10"),
               "ala ma kota",
               "ala ma kot",
               "ala ma    ",
               true,
               "kot binarny".getBytes()));
 }