Example usage for java.sql Date Date

List of usage examples for java.sql Date Date

Introduction

In this page you can find the example usage for java.sql Date Date.

Prototype

public Date(long date) 

Source Link

Document

Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.

Usage

From source file:edu.ku.kuali.kra.negotiations.service.NegotiationServiceImpl.java

private boolean isDateBetween(Date checkDate, Date rangeStart, Date rangeEnd) {
    if (rangeStart == null) {
        return false;
    }/*from ww w. jav  a  2  s  . co m*/
    if (checkDate == null) {
        checkDate = new Date(Calendar.getInstance().getTimeInMillis());
    }
    if (rangeEnd == null) {
        rangeEnd = new Date(Calendar.getInstance().getTimeInMillis());
    }
    boolean startOk = rangeStart.equals(checkDate) || rangeStart.before(checkDate);
    boolean endOk = rangeEnd.equals(checkDate) || rangeEnd.after(checkDate);
    return startOk && endOk;
}

From source file:com.chenxin.authority.common.logback.DBAppender.java

void bindLoggingEventWithInsertStatement(PreparedStatement stmt, ILoggingEvent event) throws SQLException {
    stmt.setString(TIMESTMP_INDEX,/*  w  w  w.j  a  va 2 s .c  o  m*/
            DateFormatUtils.format(new Date(event.getTimeStamp()), "yyyy-MM-dd HH:mm:ss"));
    stmt.setString(FORMATTED_MESSAGE_INDEX, event.getFormattedMessage());
    stmt.setString(LOGGER_NAME_INDEX, event.getLoggerName());
    stmt.setString(LEVEL_STRING_INDEX, event.getLevel().toString());
    stmt.setString(THREAD_NAME_INDEX, event.getThreadName());
    stmt.setShort(REFERENCE_FLAG_INDEX, DBHelper.computeReferenceMask(event));
}

From source file:gov.nih.nci.integration.caaers.CaAERSAdverseEventStrategyTest.java

/**
 * Tests createAdverseEvent using the ServiceInvocationStrategy class for the failure scenario
 * /*  w  ww .  j  ava2 s  .  c om*/
 * @throws IntegrationException - IntegrationException
 * @throws JAXBException - JAXBException
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void createAdverseEventFailure() throws IntegrationException, JAXBException {
    final Date stTime = new Date(new java.util.Date().getTime());

    xsltTransformer.transform(null, null, null);
    EasyMock.expectLastCall().andAnswer(new IAnswer() {

        public Object answer() {
            // return the value to be returned by the method (null for void)
            return getAEXMLString();
        }
    });

    final CreateProvisionalAdverseEventsResponse caaersresponse = getWSResponse(FAILURE);
    EasyMock.expect(wsClient.createProvisionalAdverseEvents((String) EasyMock.anyObject()))
            .andReturn(caaersresponse);
    EasyMock.replay(wsClient);

    final ServiceInvocationMessage serviceInvocationMessage = prepareServiceInvocationMessage(REFMSGID,
            getAEInterimMessage(), stTime, caAERSAdverseEventServiceInvocationStrategy.getStrategyIdentifier());
    final ServiceInvocationResult result = caAERSAdverseEventServiceInvocationStrategy
            .invoke(serviceInvocationMessage);
    Assert.assertNotNull(result);
}

From source file:gov.nih.nci.integration.caaers.CaAERSParticipantStrategyTest.java

/**
 * Tests registerParticipant using the ServiceInvocationStrategy class for success case
 * //from  w  ww. j a  v a  2s. c  om
 * @throws IntegrationException - IntegrationException
 * @throws JAXBException - JAXBException
 * @throws MalformedURLException - MalformedURLException
 * @throws SOAPFaultException - SOAPFaultException
 * 
 * 
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void registerParticipantSuccess()
        throws IntegrationException, SOAPFaultException, MalformedURLException, JAXBException {
    final Date stTime = new Date(new java.util.Date().getTime());

    xsltTransformer.transform(null, null, null);
    EasyMock.expectLastCall().andAnswer(new IAnswer() {

        public Object answer() {
            // return the value to be returned by the method (null for void)
            return getParticipantXMLString();
        }
    }).anyTimes();

    final CaaersServiceResponse caaersServiceResponse = getRegisterParticipantResponse(SUCCESS);
    EasyMock.expect(wsClient.createParticipant((String) EasyMock.anyObject())).andReturn(caaersServiceResponse);
    EasyMock.replay(wsClient);

    final ServiceInvocationMessage serviceInvocationMessage = prepareServiceInvocationMessage(REFMSGID,
            getParticipantInterimMessage(), stTime,
            caAERSRegistrationServiceInvocationStrategy.getStrategyIdentifier());

    final ServiceInvocationResult result = caAERSRegistrationServiceInvocationStrategy
            .invoke(serviceInvocationMessage);

    Assert.assertNotNull(result);
}

From source file:dialog.DialogFunctionUser.java

private void actionEditUserNoController() {
    if (!isValidData()) {
        return;//  w  w  w .  j a  v a  2s. c  o  m
    }
    tfUsername.setEditable(false);
    String username = tfUsername.getText();
    String fullname = tfFullname.getText();
    String password = mUser.getPassword();
    if (tfPassword.getPassword().length == 0) {
        password = new String(tfPassword.getPassword());
        password = LibraryString.md5(password);
    }
    int role = cbRole.getSelectedIndex();
    User objUser;
    if (mAvatar != null) {
        objUser = new User(mUser.getIdUser(), username, password, fullname, role,
                new Date(System.currentTimeMillis()), mAvatar.getPath());
        if ((new ModelUser()).editItem(objUser)) {
            String fileName = FilenameUtils.getBaseName(mAvatar.getName()) + "-" + System.nanoTime() + "."
                    + FilenameUtils.getExtension(mAvatar.getName());
            Path source = Paths.get(mAvatar.toURI());
            Path destination = Paths.get("files/" + fileName);
            Path pathOldAvatar = Paths.get(mUser.getAvatar());
            try {
                Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
                Files.deleteIfExists(pathOldAvatar);
            } catch (IOException ex) {
                Logger.getLogger(DialogFunctionRoom.class.getName()).log(Level.SEVERE, null, ex);
            }
            ImageIcon icon = new ImageIcon(getClass().getResource("/images/ic_success.png"));
            JOptionPane.showMessageDialog(this.getParent(), "Sa thnh cng", "Success",
                    JOptionPane.INFORMATION_MESSAGE, icon);
        } else {
            JOptionPane.showMessageDialog(this.getParent(), "Sa tht bi", "Fail",
                    JOptionPane.ERROR_MESSAGE);
        }
    } else {
        objUser = new User(mUser.getIdUser(), username, password, fullname, role,
                new Date(System.currentTimeMillis()), mUser.getAvatar());
        if (mControllerUser.editItem(objUser, mRow)) {
            ImageIcon icon = new ImageIcon(getClass().getResource("/images/ic_success.png"));
            JOptionPane.showMessageDialog(this.getParent(), "Sa thnh cng", "Success",
                    JOptionPane.INFORMATION_MESSAGE, icon);
        } else {
            JOptionPane.showMessageDialog(this.getParent(), "Sa tht bi", "Fail",
                    JOptionPane.ERROR_MESSAGE);
        }
    }
    mUser = objUser;
    this.dispose();
}

From source file:com.matrimony.database.UserDAO.java

public static int getAgeByBirthday(Date birthday) {
    Calendar now = DateUtils.toCalendar(new Date(System.currentTimeMillis()));
    Calendar before = DateUtils.toCalendar(birthday);
    return now.get(Calendar.YEAR) - before.get(Calendar.YEAR);
}

From source file:de.aw.awlib.preferences.AWPreferencesAllgemein.java

@CallSuper
@Override/*  w w  w  . j  a  va  2 s. c  o  m*/
public void onCreatePreferences(Bundle bundle, String s) {
    mApplication = ((AWApplication) getActivity().getApplicationContext());
    addPreferencesFromResource(R.xml.awlib_preferences_allgemein);
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
    for (int pkKey : mPrefs) {
        String key = getString(pkKey);
        Preference preference = findPreference(key);
        if (pkKey == R.string.pkCompileInfo) {
            java.util.Date date = new Date(BuildConfig.BuildTime);
            DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG);
            StringBuilder buildInfo = new StringBuilder("Compilezeit: ").append(df.format(date));
            preference.setSummary(buildInfo);
        } else if (pkKey == R.string.pkVersionInfo) {
            StringBuilder versionInfo = new StringBuilder("Datenbankversion : ")
                    .append(mApplication.theDatenbankVersion()).append(", Version: ")
                    .append(BuildConfig.VERSION_NAME);
            preference.setSummary(versionInfo);
        } else if (pkKey == R.string.pkServerUID || pkKey == R.string.pkServerURL) {
            String value = prefs.getString(key, null);
            preference.setSummary(value);
        } else if (pkKey == R.string.pkSavePeriodic) {
            long value = prefs.getLong(DODATABASESAVE, Long.MAX_VALUE);
            setRegelmSicherungSummary(preference, prefs, value);
        }
        preference.setOnPreferenceClickListener(this);
    }
}

From source file:su90.mybatisdemo.dao.Job_HistoryMapperTest.java

@Test(groups = { "find" })
public void testFindByRawType() {
    try {//ww  w.java2s  .c  om
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        java.util.Date start_util_date = formatter.parse("20020701");
        Job_History search = job_HistoryMapper.findByIdRaw(200L, new Date(start_util_date.getTime()));

        List<Job_History> result = job_HistoryMapper.findByRawType(search);

        assertEquals(result.size(), 1);
        assertNotNull(result.get(0));
        assertNotNull(result.get(0).getEmployee());
        assertNotNull(result.get(0).getJob());
        assertNotNull(result.get(0).getDepartment());
    } catch (ParseException ex) {
        assertTrue(false);
    }
}

From source file:io.github.sislivros.persistencia.UsuarioBdDao.java

@Override
public boolean salvar(Usuario usuario) {

    try {/*from w  w w.j a va  2  s. c  om*/

        if (getConnection() == null || getConnection().isClosed()) {
            conectar();
        }

        String sql = "INSERT INTO usuario (email, senha, apelido, data_nascimento, "
                + "cidade, estado, nome, foto_perfil, foto_capa, tipo, data_cadastro) "
                + "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        PreparedStatement ps = getConnection().prepareStatement(sql);
        Date dataNascimento = null;
        if (usuario.getDataNascimento() != null) {
            dataNascimento = new Date(usuario.getDataNascimento().getTime());
        }

        ps.setString(1, usuario.getEmail());
        ps.setString(2, DigestUtils.sha1Hex(usuario.getSenha()));
        ps.setString(3, usuario.getApelido());
        ps.setDate(4, dataNascimento);
        ps.setString(5, usuario.getCidade());
        ps.setString(6, usuario.getEstado());
        ps.setString(7, usuario.getNome());
        ps.setString(8, usuario.getFotoPerfil());
        ps.setString(9, usuario.getFotoCapa());
        ps.setInt(10, usuario.getTipo().id);
        ps.setTimestamp(11, new Timestamp(System.currentTimeMillis()));
        ps.executeUpdate();

        TimeLineEvent timeLineEvent = new TimeLineEvent();
        timeLineEvent.setData(new Timestamp(System.currentTimeMillis()));
        timeLineEvent.setNome("Criou uma conta");
        timeLineEvent.setDescricao("Conta criada com sucesso !");
        timeLineEvent.setTipo(TimeLineEventType.CRIACAO_CONTA);
        timeLineEvent.setEmailUsuario(usuario.getEmail());

        TimeLineEventBdDao timeDao = new TimeLineEventBdDao();
        timeDao.salvar(timeLineEvent);

        return true;
    } catch (SQLException | URISyntaxException | IOException | ClassNotFoundException ex) {
        ex.printStackTrace();

        return false;
    } finally {
        desconectar();
    }
}

From source file:org.apache.phoenix.hive.util.HiveTypeUtil.java

/**
 * This method returns the most appropriate Writable associated with the incoming sql type name.
 * @param hiveType,Object//from  ww  w.  ja v  a 2s  .  c  o m
 * @return Wrtiable
 */
// TODO awkward logic revisit
public static Writable SQLType2Writable(String hiveType, Object o) throws SerDeException {
    String lctype = hiveType.toLowerCase();
    if ("string".equals(lctype))
        return new Text(o.toString());
    if ("varchar".equals(lctype))
        return new HiveVarcharWritable(new HiveVarchar(o.toString(), o.toString().length()));
    if ("char".equals(lctype))
        return new HiveCharWritable(new HiveChar(o.toString(), o.toString().length()));
    if ("float".equals(lctype))
        return new FloatWritable(((Float) o).floatValue());
    if ("double".equals(lctype))
        return new DoubleWritable(((Double) o).doubleValue());
    if ("boolean".equals(lctype))
        return new BooleanWritable(((Boolean) o).booleanValue());
    if ("tinyint".equals(lctype))
        return new ShortWritable(((Integer) o).shortValue());
    if ("smallint".equals(lctype))
        return new ShortWritable(((Integer) o).shortValue());
    if ("int".equals(lctype))
        return new IntWritable(((Integer) o).intValue());
    if ("bigint".equals(lctype))
        return new LongWritable(((Long) o).longValue());
    if ("timestamp".equals(lctype))
        return new TimestampWritable((Timestamp) o);
    if ("binary".equals(lctype))
        return new Text(o.toString());
    if ("date".equals(lctype))
        return new DateWritable(new Date((long) o));
    if ("array".equals(lctype))
        ;
    throw new SerDeException("Phoenix unrecognized column type: " + hiveType);
}