Example usage for java.sql Timestamp getTime

List of usage examples for java.sql Timestamp getTime

Introduction

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

Prototype

public long getTime() 

Source Link

Document

Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Timestamp object.

Usage

From source file:de.hybris.platform.test.HJMPTest.java

@Test
public void testWriteReadValues() {
    LOG.debug(">>> testWriteReadValues()");

    final Float floatValue = new Float(1234.5678f);
    /* conv-LOG */LOG.debug(">>> Float (" + floatValue + ") <<<");
    remote.setFloat(floatValue);/* ww w  . j a v  a2  s . c  om*/
    assertEquals(floatValue, remote.getFloat());

    final Double doubleValue = new Double(2234.5678d);
    /* conv-LOG */LOG.debug(">>> Double (" + doubleValue + ") <<<");
    remote.setDouble(doubleValue);
    assertEquals(doubleValue, remote.getDouble());

    final Character characterValue = Character.valueOf('g');
    /* conv-LOG */LOG.debug(">>> Character (" + characterValue + ") <<<");
    remote.setCharacter(characterValue);
    assertEquals(characterValue, remote.getCharacter());

    final Integer integerValue = Integer.valueOf(3357);
    /* conv-LOG */LOG.debug(">>> Integer (" + integerValue + ") <<<");
    remote.setInteger(integerValue);
    assertEquals(integerValue, remote.getInteger());

    final Long longValue = Long.valueOf(4357L);
    /* conv-LOG */LOG.debug(">>> Long (" + longValue + ") <<<");
    remote.setLong(longValue);
    assertEquals(longValue, remote.getLong());

    final Calendar now = Utilities.getDefaultCalendar();
    now.set(Calendar.MILLISECOND, 0);

    /* conv-LOG */LOG.debug(">>> Date (" + now + ", ms=" + now.getTime() + ")<<<");
    remote.setDate(now.getTime());
    final java.util.Date got = remote.getDate();
    /* conv-LOG */LOG.debug(">>> found (" + got.getTime() + ")<<<");
    assertEquals(now.getTime(), got);

    // try to get 123,4567 as big decimal
    final BigDecimal bigDecimalValue = BigDecimal.valueOf(1234567, 4);
    /* conv-LOG */LOG.debug(">>> BigDecimal (" + bigDecimalValue + ")<<<");
    remote.setBigDecimal(bigDecimalValue);
    assertTrue(remote.getBigDecimal().compareTo(bigDecimalValue) == 0);

    final java.sql.Timestamp timestamp = new java.sql.Timestamp(now.getTime().getTime());
    /* conv-LOG */LOG.debug(">>> Timestamp (" + timestamp + ", ms=" + timestamp.getTime() + ")<<<");
    remote.setDate(timestamp);
    final java.util.Date got2 = remote.getDate();
    /* conv-LOG */LOG.debug(">>> found (" + got2.getTime() + ")<<<");
    assertEquals(now.getTime(), got2);

    final String str = "Alles wird gut!";
    /* conv-LOG */LOG.debug(">>> String (" + str + ")<<<");
    remote.setString(str);
    assertEquals(str, remote.getString());

    final String longstr = "Alles wird lange gut!";
    /* conv-LOG */LOG.debug(">>> Long String (" + longstr + ")<<<");
    remote.setLongString(longstr);
    assertEquals(longstr, remote.getLongString());

    //put 50000 chars into it
    String longstr2 = "";
    for (int i2 = 0; i2 < 5000; i2++) {
        longstr2 += "01234567890";
    }
    remote.setLongString(longstr2);
    assertEquals(longstr2, remote.getLongString());

    /*
     * remote.setString( "" ); assertEquals( "" , remote.getString() ); remote.setString( null ); assertNull(
     * remote.getString() ); remote.setLongString( "" ); assertEquals( "" , remote.getLongString() );
     * remote.setLongString( null ); assertNull( remote.getLongString() );
     */

    final Boolean booleanValue = Boolean.TRUE;
    /* conv-LOG */LOG.debug(">>> Boolean (" + booleanValue + ")<<<");
    remote.setBoolean(booleanValue);
    assertEquals(booleanValue, remote.getBoolean());

    final float floatValue2 = 5234.5678f;
    /* conv-LOG */LOG.debug(">>> float (" + floatValue2 + ") <<<");
    remote.setPrimitiveFloat(floatValue2);
    assertTrue(">>> float (" + floatValue2 + ") <<<", floatValue2 == remote.getPrimitiveFloat());

    final double doubleValue2 = 6234.5678d;
    /* conv-LOG */LOG.debug(">>> double (" + doubleValue2 + ") <<<");
    remote.setPrimitiveDouble(doubleValue2);
    assertTrue(">>> double (" + doubleValue2 + ") <<<", doubleValue2 == remote.getPrimitiveDouble());

    final int integerValue2 = 7357;
    /* conv-LOG */LOG.debug(">>> int (" + integerValue2 + ") <<<");
    remote.setPrimitiveInteger(integerValue2);
    assertTrue(integerValue2 == remote.getPrimitiveInteger());

    final long longValue2 = 8357L;
    /* conv-LOG */LOG.debug(">>> long (" + longValue2 + ") <<<");
    remote.setPrimitiveLong(longValue2);
    assertTrue(">>> long (" + longValue2 + ") <<<", longValue2 == remote.getPrimitiveLong());

    final byte byteValue = 123;
    /* conv-LOG */LOG.debug(">>> byte (" + byteValue + ") <<<");
    remote.setPrimitiveByte(byteValue);
    assertTrue(">>> byte (" + byteValue + ") <<<", byteValue == remote.getPrimitiveByte());

    final boolean booleanValue2 = true;
    /* conv-LOG */LOG.debug(">>> boolean (" + booleanValue2 + ") <<<");
    remote.setPrimitiveBoolean(booleanValue2);
    assertTrue(">>> boolean (" + booleanValue2 + ") <<<", booleanValue2 == remote.getPrimitiveBoolean());

    final char characterValue2 = 'g';
    /* conv-LOG */LOG.debug(">>> char (" + characterValue2 + ") <<<");
    remote.setPrimitiveChar(characterValue2);
    assertTrue(">>> char (" + characterValue2 + ") <<<", characterValue2 == remote.getPrimitiveChar());

    final ArrayList list = new ArrayList();
    LOG.debug(">>> Serializable with standard classes (" + list + ") <<<");
    remote.setSerializable(list);
    assertEquals(list, remote.getSerializable());

    if (!Config.isOracleUsed()) {
        try {
            final HashMap bigtest = new HashMap();
            LOG.debug(">>> Serializable with standard classes (big thing) <<<");
            final byte[] byteArray = new byte[100000];
            bigtest.put("test", byteArray);
            remote.setSerializable(bigtest);
            final Map longtestret = (Map) remote.getSerializable();
            assertTrue(longtestret.size() == 1);
            final byte[] byteArray2 = (byte[]) longtestret.get("test");
            assertTrue(byteArray2.length == 100000);
        } catch (final Exception e) {
            throw new JaloSystemException(e,
                    "Unable to write big serializable object, db: " + Config.getDatabase() + ".", 0);
        }
    }

    /* conv-LOG */LOG.debug(">>> Serializable (null) <<<");
    remote.setSerializable(null);
    assertNull(remote.getSerializable());

    //         try
    //         {
    //            final Dummy dummy = new Dummy();
    //            /*conv-LOG*/ LOG.debug(">>> Serializable with custom classes ("+dummy+") <<<");
    //            remote.setSerializable( dummy );
    //            final Serializable x = remote.getSerializable();
    //            assertTrue( dummy.equals( x ) || x == null );
    //            if( x == null )
    //               /*conv-LOG*/ LOG.debug(">>> ok, we're still unable of writing non-serverside classes to database : read NULL ");
    //         }
    //         catch( Exception e )
    //         {
    //            /*conv-LOG*/ LOG.debug(">>> ok, we're still unable of writing non-serverside classes to database : " + e );
    //         }

    //
    // search
    //

    try {
        /* conv-LOG */LOG.debug(">>> Search ( " + str + ", " + integerValue2 + " ) <<<");
        home.finderTest(str, integerValue2);
    } catch (final Exception e) {
        e.printStackTrace();
        fail("TestItem not found!");
    }

    //
    // 'null' tests
    //

    /* conv-LOG */LOG.debug(">>> String (null) <<<");
    remote.setString(null);
    assertNull(remote.getString());

    /* conv-LOG */LOG.debug(">>> Character (null) <<<");
    remote.setCharacter(null);
    assertNull(remote.getCharacter());

    /* conv-LOG */LOG.debug(">>> Integer (null) <<<");
    remote.setInteger(null);
    assertNull(remote.getInteger());

    /* conv-LOG */LOG.debug(">>> Date (null) <<<");
    remote.setDate(null);
    assertNull(remote.getDate());

    /* conv-LOG */LOG.debug(">>> Double (null) <<<");
    remote.setDouble(null);
    assertNull(remote.getDouble());

    /* conv-LOG */LOG.debug(">>> Float (null) <<<");
    remote.setFloat(null);
    assertNull(remote.getFloat());
}

From source file:org.opencommercesearch.feed.RuleFeed.java

@Override
protected JSONObject repositoryItemToJson(RepositoryItem rule) throws JSONException, RepositoryException {
    //Convert rule to JSON
    JSONObject ruleJsonObj = new JSONObject();
    ruleJsonObj.put(RuleConstants.FIELD_ID, rule.getRepositoryId());
    ruleJsonObj.put(RuleConstants.FIELD_NAME, rule.getItemDisplayName());

    String query = (String) rule.getPropertyValue(RuleProperty.QUERY);
    if (query == null || query.equals("*")) {
        query = RuleConstants.WILDCARD;/* w  w w  . j  a v a  2s.  c  om*/
    } else {
        query = query.toLowerCase();
    }

    ruleJsonObj.put(RuleConstants.FIELD_QUERY, query);
    ruleJsonObj.put(RuleConstants.FIELD_SORT_PRIORITY, rule.getPropertyValue(RuleProperty.SORT_PRIORITY));
    ruleJsonObj.put(RuleConstants.FIELD_COMBINE_MODE, rule.getPropertyValue(RuleProperty.COMBINE_MODE));

    //Add the start and end dates
    Timestamp startDate = (Timestamp) rule.getPropertyValue(RuleProperty.START_DATE);
    if (startDate != null) {
        ruleJsonObj.put(RuleConstants.FIELD_START_DATE, Utils.getISO8601Date(startDate.getTime()));
    }

    Timestamp endDate = (Timestamp) rule.getPropertyValue(RuleProperty.END_DATE);
    if (endDate != null) {
        ruleJsonObj.put(RuleConstants.FIELD_END_DATE, Utils.getISO8601Date(endDate.getTime()));
    }

    String target = (String) rule.getPropertyValue(RuleProperty.TARGET);
    if (target != null) {
        target = StringUtils.replace(target, " ", "");
        ruleJsonObj.put(RuleConstants.FIELD_TARGET, new JSONArray().put(target.toLowerCase()));
    }

    Boolean experimental = (Boolean) rule.getPropertyValue(RuleProperty.EXPERIMENTAL);
    if (experimental != null) {
        ruleJsonObj.put(RuleConstants.FIELD_EXPERIMENTAL, experimental);
    }

    String retailOutlet = (String) rule.getPropertyValue(RuleProperty.SUB_TARGET);
    if (retailOutlet != null && !retailOutlet.equals(BOTH)) {
        ruleJsonObj.put(RuleConstants.FIELD_SUB_TARGET, new JSONArray().put(retailOutlet));
    } else {
        ruleJsonObj.put(RuleConstants.FIELD_SUB_TARGET, new JSONArray().put(RuleConstants.WILDCARD));
    }
    @SuppressWarnings("unchecked")
    Set<RepositoryItem> sites = (Set<RepositoryItem>) rule.getPropertyValue(RuleProperty.SITES);
    if (sites != null && sites.size() > 0) {
        JSONArray siteIds = new JSONArray();
        for (RepositoryItem site : sites) {
            siteIds.add(site.getRepositoryId());
            siteIds.add(site.getPropertyValue("code"));
        }

        ruleJsonObj.put(RuleConstants.FIELD_SITE_ID, siteIds);
    } else {
        ruleJsonObj.put(RuleConstants.FIELD_SITE_ID, new JSONArray().put(RuleConstants.WILDCARD));
    }

    @SuppressWarnings("unchecked")
    Set<RepositoryItem> catalogs = (Set<RepositoryItem>) rule.getPropertyValue(RuleProperty.CATALOGS);
    if (catalogs != null && catalogs.size() > 0) {
        JSONArray catalogIds = new JSONArray();
        for (RepositoryItem catalog : catalogs) {
            catalogIds.add(catalog.getRepositoryId());
        }

        ruleJsonObj.put(RuleConstants.FIELD_CATALOG_ID, catalogIds);
    } else {
        ruleJsonObj.put(RuleConstants.FIELD_CATALOG_ID, new JSONArray().put(RuleConstants.WILDCARD));
    }

    @SuppressWarnings("unchecked")
    Set<RepositoryItem> categories = (Set<RepositoryItem>) rule.getPropertyValue(RuleProperty.CATEGORIES);

    if (categories != null && categories.size() > 0) {
        Boolean includeSubcategories = (Boolean) rule.getPropertyValue(RuleProperty.INCLUDE_SUBCATEGORIES);

        if (includeSubcategories == null) {
            includeSubcategories = Boolean.FALSE;
        }

        try {
            for (RepositoryItem category : categories) {
                if (CategoryProperty.ITEM_DESCRIPTOR
                        .equals(category.getItemDescriptor().getItemDescriptorName())) {
                    setCategorySearchTokens(ruleJsonObj, category, includeSubcategories);
                    setCategoryCategoryPaths(ruleJsonObj, category, includeSubcategories);
                } else {
                    setCategorySearchTokens(ruleJsonObj, category, false);
                    setCategoryCategoryPaths(ruleJsonObj, category, false);
                }
            }
        } catch (RepositoryException e) {
            //Can't load categories
            if (isLoggingError()) {
                logError("Can't load categories for rule " + rule.getRepositoryId(), e);
            }
        }

        if (ruleJsonObj.get(RuleConstants.FIELD_CATEGORY) == null
                || ((JSONArray) ruleJsonObj.get(RuleConstants.FIELD_CATEGORY)).isEmpty()) {
            //Don't index this rule, it has no category information.
            if (isLoggingWarning()) {
                logWarning("Rule " + rule.getRepositoryId() + " has no valid category data associated to it.");
                return null;
            }
        }
    } else {
        ruleJsonObj.put(RuleConstants.FIELD_CATEGORY, new JSONArray().put(RuleConstants.WILDCARD));
    }

    @SuppressWarnings("unchecked")
    Set<RepositoryItem> brands = (Set<RepositoryItem>) rule.getPropertyValue(RuleProperty.BRANDS);
    if (brands != null && brands.size() > 0) {
        JSONArray brandIds = new JSONArray();
        for (RepositoryItem brand : brands) {
            brandIds.add(brand.getRepositoryId());
        }
        ruleJsonObj.put(RuleConstants.FIELD_BRAND_ID, brandIds);
    } else {
        ruleJsonObj.put(RuleConstants.FIELD_BRAND_ID, new JSONArray().put(RuleConstants.WILDCARD));
    }

    //Set additional fields required by different rule types.
    String ruleType = (String) rule.getPropertyValue(RuleProperty.RULE_TYPE);
    if (RuleProperty.TYPE_RANKING_RULE.equals(ruleType)) {
        setRankingRuleFields(rule, ruleJsonObj);
    } else if (RuleProperty.TYPE_FACET_RULE.equals(ruleType)) {
        setFacetRuleFields(rule, ruleJsonObj);
    } else if (RuleProperty.TYPE_REDIRECT_RULE.equals(ruleType)) {
        ruleJsonObj.put(RuleConstants.FIELD_REDIRECT_URL, rule.getPropertyValue(RedirectRuleProperty.URL));
    } else if (RuleProperty.TYPE_BLOCK_RULE.equals(ruleType)) {
        Set<RepositoryItem> products = (Set<RepositoryItem>) rule
                .getPropertyValue(BlockRuleProperty.BLOCKED_PRODUCTS);
        if (products != null && products.size() > 0) {
            JSONArray blockedProducts = new JSONArray();
            for (RepositoryItem product : products) {
                blockedProducts.add(product.getRepositoryId());
            }

            ruleJsonObj.put(RuleConstants.FIELD_BLOCKED_PRODUCTS, blockedProducts);
        }
    } else if (RuleProperty.TYPE_BOOST_RULE.equals(ruleType)) {
        List<RepositoryItem> products = (List<RepositoryItem>) rule
                .getPropertyValue(BoostRuleProperty.BOOSTED_PRODUCTS);
        if (products != null && products.size() > 0) {
            JSONArray boostedProducts = new JSONArray();
            for (RepositoryItem product : products) {
                boostedProducts.add(product.getRepositoryId());
            }

            ruleJsonObj.put(RuleConstants.FIELD_BOOSTED_PRODUCTS, boostedProducts);
        }
    }

    ruleJsonObj.put(RuleConstants.FIELD_RULE_TYPE, ruleType);

    return ruleJsonObj;
}

From source file:com.hichinaschool.flashcards.anki.Preferences.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    // Workaround for bug 4611: http://code.google.com/p/android/issues/detail?id=4611
    if (AnkiDroidApp.SDK_VERSION >= 7 && AnkiDroidApp.SDK_VERSION <= 10) {
        Themes.applyTheme(this, Themes.THEME_ANDROID_DARK);
    }//from   w w w . j a v  a  2s  . com
    super.onCreate(savedInstanceState);

    mCol = AnkiDroidApp.getCol();
    mPrefMan = getPreferenceManager();
    mPrefMan.setSharedPreferencesName(AnkiDroidApp.SHARED_PREFS_NAME);

    addPreferencesFromResource(R.xml.preferences);

    swipeCheckboxPreference = (CheckBoxPreference) getPreferenceScreen().findPreference("swipe");
    zoomCheckboxPreference = (CheckBoxPreference) getPreferenceScreen().findPreference("zoom");
    keepScreenOnCheckBoxPreference = (CheckBoxPreference) getPreferenceScreen().findPreference("keepScreenOn");
    showAnswerCheckBoxPreference = (CheckBoxPreference) getPreferenceScreen().findPreference("timeoutAnswer");
    animationsCheckboxPreference = (CheckBoxPreference) getPreferenceScreen().findPreference("themeAnimations");
    useBackupPreference = (CheckBoxPreference) getPreferenceScreen().findPreference("useBackup");
    asyncModePreference = (CheckBoxPreference) getPreferenceScreen().findPreference("asyncMode");
    eInkDisplayPreference = (CheckBoxPreference) getPreferenceScreen().findPreference("eInkDisplay");
    fadeScrollbars = (CheckBoxPreference) getPreferenceScreen().findPreference("fadeScrollbars");
    //        ListPreference listpref = (ListPreference) getPreferenceScreen().findPreference("theme");
    convertFenText = (CheckBoxPreference) getPreferenceScreen().findPreference("convertFenText");
    fixHebrewText = (CheckBoxPreference) getPreferenceScreen().findPreference("fixHebrewText");
    syncAccount = (Preference) getPreferenceScreen().findPreference("syncAccount");
    showEstimates = (CheckBoxPreference) getPreferenceScreen().findPreference("showEstimates");
    showProgress = (CheckBoxPreference) getPreferenceScreen().findPreference("showProgress");
    learnCutoff = (NumberRangePreference) getPreferenceScreen().findPreference("learnCutoff");
    timeLimit = (NumberRangePreference) getPreferenceScreen().findPreference("timeLimit");
    useCurrent = (ListPreference) getPreferenceScreen().findPreference("useCurrent");
    newSpread = (ListPreference) getPreferenceScreen().findPreference("newSpread");
    dayOffset = (SeekBarPreference) getPreferenceScreen().findPreference("dayOffset");
    //        String theme = listpref.getValue();
    //        animationsCheckboxPreference.setEnabled(theme.equals("2") || theme.equals("3"));
    zoomCheckboxPreference.setEnabled(!swipeCheckboxPreference.isChecked());

    initializeLanguageDialog();
    initializeCustomFontsDialog();

    if (mCol != null) {
        // For collection preferences, we need to fetch the correct values from the collection
        mStartDate = GregorianCalendar.getInstance();
        Timestamp timestamp = new Timestamp(mCol.getCrt() * 1000);
        mStartDate.setTimeInMillis(timestamp.getTime());
        dayOffset.setValue(mStartDate.get(Calendar.HOUR_OF_DAY));
        try {
            JSONObject conf = mCol.getConf();
            learnCutoff.setValue(conf.getInt("collapseTime") / 60);
            timeLimit.setValue(conf.getInt("timeLim") / 60);
            showEstimates.setChecked(conf.getBoolean("estTimes"));
            showProgress.setChecked(conf.getBoolean("dueCounts"));
            newSpread.setValueIndex(conf.getInt("newSpread"));
            useCurrent.setValueIndex(conf.getBoolean("addToCur") ? 0 : 1);
        } catch (JSONException e) {
            throw new RuntimeException();
        } catch (NumberFormatException e) {
            throw new RuntimeException();
        }
    } else {
        // It's possible to open the preferences from the loading screen if no SD card is found.
        // In that case, there will be no collection loaded, so we need to disable the settings
        // that read from and write to the collection.
        dayOffset.setEnabled(false);
        learnCutoff.setEnabled(false);
        timeLimit.setEnabled(false);
        showEstimates.setEnabled(false);
        showProgress.setEnabled(false);
        newSpread.setEnabled(false);
        useCurrent.setEnabled(false);
    }

    for (String key : mShowValueInSummList) {
        updateListPreference(key);
    }
    for (String key : mShowValueInSummSeek) {
        updateSeekBarPreference(key);
    }
    for (String key : mShowValueInSummEditText) {
        updateEditTextPreference(key);
    }
    for (String key : mShowValueInSummNumRange) {
        updateNumberRangePreference(key);
    }

    if (AnkiDroidApp.SDK_VERSION <= 4) {
        fadeScrollbars.setChecked(false);
        fadeScrollbars.setEnabled(false);
    }
}

From source file:org.openbel.framework.internal.KAMCatalogDao.java

/**
 *
 * @param rset//from  ww  w  .j ava 2s.  c o  m
 * @return
 * @throws SQLException
 */
private KamInfo getKamInfo(ResultSet rset) throws SQLException {

    Integer kamId = rset.getInt(1);
    String name = rset.getString(2);
    String description = rset.getString(3);

    // handle timestamp as date+time
    Timestamp cts = rset.getTimestamp(4);
    Date lastCompiled = null;
    if (cts != null) {
        lastCompiled = new Date(cts.getTime());
    }

    String schemaName = rset.getString(5);
    return new KamInfo(new KamDbObject(kamId, name, description, lastCompiled, schemaName));
}

From source file:com.antsdb.saltedfish.sql.vdm.FuncDateFormat.java

private String format(String format, Timestamp time) {
    StringBuilder buf = new StringBuilder();
    for (int i = 0; i < format.length(); i++) {
        char ch = format.charAt(i);
        if (ch != '%') {
            buf.append(ch);/* w  w  w .jav a 2 s.c  om*/
            continue;
        }
        if (i >= (format.length() - 1)) {
            buf.append(ch);
            continue;
        }
        char specifier = format.charAt(++i);
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(time.getTime());
        if (specifier == 'a') {
            throw new NotImplementedException();
        } else if (specifier == 'b') {
            throw new NotImplementedException();
        } else if (specifier == 'c') {
            buf.append(calendar.get(Calendar.MONTH + 1));
        } else if (specifier == 'd') {
            int day = calendar.get(Calendar.DAY_OF_MONTH);
            if (day < 10) {
                buf.append('0');
            }
            buf.append(day);
        } else if (specifier == 'D') {
            throw new NotImplementedException();
        } else if (specifier == 'e') {
            buf.append(calendar.get(Calendar.DAY_OF_MONTH));
        } else if (specifier == 'f') {
            buf.append(calendar.get(Calendar.MILLISECOND * 1000));
        } else if (specifier == 'H') {
            buf.append(calendar.get(Calendar.HOUR));
        } else if (specifier == 'h') {
            buf.append(calendar.get(Calendar.HOUR) % 13);
        } else if (specifier == 'i') {
            buf.append(calendar.get(Calendar.MINUTE));
        } else if (specifier == 'I') {
            buf.append(calendar.get(Calendar.HOUR) % 13);
        } else if (specifier == 'j') {
            buf.append(calendar.get(Calendar.DAY_OF_YEAR));
        } else if (specifier == 'k') {
            buf.append(calendar.get(Calendar.HOUR));
        } else if (specifier == 'l') {
            buf.append(calendar.get(Calendar.HOUR) % 13);
        } else if (specifier == 'm') {
            int month = calendar.get(Calendar.MONTH) + 1;
            if (month < 10) {
                buf.append('0');
            }
            buf.append(calendar.get(Calendar.MONTH) + 1);
        } else if (specifier == 'M') {
            buf.append(calendar.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault()));
        } else if (specifier == 'p') {
            int hour = calendar.get(Calendar.HOUR);
            buf.append(hour < 12 ? "AM" : "PM");
        } else if (specifier == 'r') {
            int hour = calendar.get(Calendar.HOUR);
            hour = hour % 13;
            if (hour < 10) {
                buf.append('0');
            }
            buf.append(hour);
            buf.append(':');
            int minute = calendar.get(Calendar.MINUTE);
            if (minute < 10) {
                buf.append('0');
            }
            buf.append(minute);
            buf.append(':');
            int second = calendar.get(Calendar.SECOND);
            if (second < 10) {
                buf.append('0');
            }
            buf.append(second);
            buf.append(hour < 12 ? " AM" : " PM");
        } else if (specifier == 's') {
            buf.append(calendar.get(Calendar.SECOND));
        } else if (specifier == 'S') {
            buf.append(calendar.get(Calendar.SECOND));
        } else if (specifier == 'T') {
            throw new NotImplementedException();
        } else if (specifier == 'u') {
            buf.append(calendar.get(Calendar.WEEK_OF_YEAR));
        } else if (specifier == 'U') {
            throw new NotImplementedException();
        } else if (specifier == 'v') {
            throw new NotImplementedException();
        } else if (specifier == 'V') {
            throw new NotImplementedException();
        } else if (specifier == 'w') {
            throw new NotImplementedException();
        } else if (specifier == 'W') {
            throw new NotImplementedException();
        } else if (specifier == 'x') {
            throw new NotImplementedException();
        } else if (specifier == 'X') {
            throw new NotImplementedException();
        } else if (specifier == 'y') {
            buf.append(calendar.get(Calendar.YEAR) % 100);
        } else if (specifier == 'Y') {
            buf.append(calendar.get(Calendar.YEAR));
        } else if (specifier == '%') {
            buf.append('%');
        } else {
            buf.append(specifier);
        }
    }
    return buf.toString();
}

From source file:org.osaf.cosmo.migrate.ZeroPointFiveToZeroPointSixMigration.java

private void migrateItems(Connection conn) throws Exception {
    PreparedStatement stmt = null;
    PreparedStatement updateStmt = null;
    ResultSet rs = null;/*from   w ww .  ja  v  a2 s .com*/
    long count = 0;
    log.debug("starting migrateItems()");

    try {
        stmt = conn.prepareStatement("select id, datecreated, datemodified from item");
        updateStmt = conn.prepareStatement("update item set createdate=?, modifydate=? where id=?");
        rs = stmt.executeQuery();

        while (rs.next()) {
            count++;
            long itemId = rs.getLong(1);
            Timestamp createTs = rs.getTimestamp(2);
            Timestamp modifyTs = rs.getTimestamp(3);

            updateStmt.setLong(1, createTs.getTime());
            updateStmt.setLong(2, modifyTs.getTime());
            updateStmt.setLong(3, itemId);

            updateStmt.executeUpdate();
        }
    } finally {
        if (rs != null)
            rs.close();
        if (stmt != null)
            stmt.close();
        if (updateStmt != null)
            updateStmt.close();
    }

    log.debug("processed " + count + " items");
}

From source file:org.gnucash.android.ui.export.ExportFormFragment.java

/**
 * Bind views to actions when initializing the export form
 *//*from  w w  w  . j ava2  s . c  om*/
private void bindViewListeners() {
    // export destination bindings
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
            R.array.export_destinations, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    mDestinationSpinner.setAdapter(adapter);
    mDestinationSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            View recurrenceOptionsView = getView().findViewById(R.id.recurrence_options);
            switch (position) {
            case 0:
                mExportTarget = ExportParams.ExportTarget.SD_CARD;
                recurrenceOptionsView.setVisibility(View.VISIBLE);
                break;
            case 1:
                recurrenceOptionsView.setVisibility(View.VISIBLE);
                mExportTarget = ExportParams.ExportTarget.DROPBOX;
                String dropboxAppKey = getString(R.string.dropbox_app_key,
                        BackupPreferenceFragment.DROPBOX_APP_KEY);
                String dropboxAppSecret = getString(R.string.dropbox_app_secret,
                        BackupPreferenceFragment.DROPBOX_APP_SECRET);

                if (!DropboxHelper.hasToken()) {
                    Auth.startOAuth2Authentication(getActivity(), dropboxAppKey);
                }
                break;
            case 2:
                recurrenceOptionsView.setVisibility(View.VISIBLE);
                mExportTarget = ExportParams.ExportTarget.GOOGLE_DRIVE;
                BackupPreferenceFragment.mGoogleApiClient = BackupPreferenceFragment
                        .getGoogleApiClient(getActivity());
                BackupPreferenceFragment.mGoogleApiClient.connect();
                break;
            case 3:
                recurrenceOptionsView.setVisibility(View.VISIBLE);
                mExportTarget = ExportParams.ExportTarget.OWNCLOUD;
                if (!(PreferenceManager.getDefaultSharedPreferences(getActivity())
                        .getBoolean(getString(R.string.key_owncloud_sync), false))) {
                    OwnCloudDialogFragment ocDialog = OwnCloudDialogFragment.newInstance(null);
                    ocDialog.show(getActivity().getSupportFragmentManager(), "ownCloud dialog");
                }
                break;
            case 4:
                mExportTarget = ExportParams.ExportTarget.SHARING;
                recurrenceOptionsView.setVisibility(View.GONE);
                break;

            default:
                mExportTarget = ExportParams.ExportTarget.SD_CARD;
                break;
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

    int position = PreferenceManager.getDefaultSharedPreferences(getActivity())
            .getInt(getString(R.string.key_last_export_destination), 0);
    mDestinationSpinner.setSelection(position);

    //**************** export start time bindings ******************
    Timestamp timestamp = PreferencesHelper.getLastExportTime();
    mExportStartCalendar.setTimeInMillis(timestamp.getTime());

    final Date date = new Date(timestamp.getTime());
    mExportStartDate.setText(TransactionFormFragment.DATE_FORMATTER.format(date));
    mExportStartTime.setText(TransactionFormFragment.TIME_FORMATTER.format(date));

    mExportStartDate.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            long dateMillis = 0;
            try {
                Date date = TransactionFormFragment.DATE_FORMATTER.parse(mExportStartDate.getText().toString());
                dateMillis = date.getTime();
            } catch (ParseException e) {
                Log.e(getTag(), "Error converting input time to Date object");
            }
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(dateMillis);

            int year = calendar.get(Calendar.YEAR);
            int monthOfYear = calendar.get(Calendar.MONTH);
            int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
            CalendarDatePickerDialogFragment datePickerDialog = new CalendarDatePickerDialogFragment();
            datePickerDialog.setOnDateSetListener(ExportFormFragment.this);
            datePickerDialog.setPreselectedDate(year, monthOfYear, dayOfMonth);
            datePickerDialog.show(getFragmentManager(), "date_picker_fragment");
        }
    });

    mExportStartTime.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            long timeMillis = 0;
            try {
                Date date = TransactionFormFragment.TIME_FORMATTER.parse(mExportStartTime.getText().toString());
                timeMillis = date.getTime();
            } catch (ParseException e) {
                Log.e(getTag(), "Error converting input time to Date object");
            }

            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(timeMillis);

            RadialTimePickerDialogFragment timePickerDialog = new RadialTimePickerDialogFragment();
            timePickerDialog.setOnTimeSetListener(ExportFormFragment.this);
            timePickerDialog.setStartTime(calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE));
            timePickerDialog.show(getFragmentManager(), "time_picker_dialog_fragment");
        }
    });

    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
    mExportAllSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            mExportStartDate.setEnabled(!isChecked);
            mExportStartTime.setEnabled(!isChecked);
            int color = isChecked ? android.R.color.darker_gray : android.R.color.black;
            mExportStartDate.setTextColor(getResources().getColor(color));
            mExportStartTime.setTextColor(getResources().getColor(color));
        }
    });

    mExportAllSwitch.setChecked(sharedPrefs.getBoolean(getString(R.string.key_export_all_transactions), false));
    mDeleteAllCheckBox.setChecked(
            sharedPrefs.getBoolean(getString(R.string.key_delete_transactions_after_export), false));

    mRecurrenceTextView.setOnClickListener(
            new RecurrenceViewClickListener((AppCompatActivity) getActivity(), mRecurrenceRule, this));

    //this part (setting the export format) must come after the recurrence view bindings above
    String defaultExportFormat = sharedPrefs.getString(getString(R.string.key_default_export_format),
            ExportFormat.QIF.name());
    mExportFormat = ExportFormat.valueOf(defaultExportFormat);

    View.OnClickListener radioClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            onRadioButtonClicked(view);
        }
    };

    View v = getView();
    assert v != null;

    mOfxRadioButton.setOnClickListener(radioClickListener);
    mQifRadioButton.setOnClickListener(radioClickListener);
    mXmlRadioButton.setOnClickListener(radioClickListener);

    ExportFormat defaultFormat = ExportFormat.valueOf(defaultExportFormat.toUpperCase());
    switch (defaultFormat) {
    case QIF:
        mQifRadioButton.performClick();
        break;
    case OFX:
        mOfxRadioButton.performClick();
        break;
    case XML:
        mXmlRadioButton.performClick();
        break;
    }

    if (GnuCashApplication.isDoubleEntryEnabled()) {
        mOfxRadioButton.setVisibility(View.GONE);
    } else {
        mXmlRadioButton.setVisibility(View.GONE);
    }

}

From source file:fr.paris.lutece.plugins.genericalert.service.TaskNotifyReminder.java

@Override
public void processTask(int nIdResourceHistory, HttpServletRequest request, Locale locale) {

    ResourceHistory resourceHistory = _resourceHistoryService.findByPrimaryKey(nIdResourceHistory);
    Action action = _actionService.findByPrimaryKey(resourceHistory.getAction().getId());

    State stateBefore = action.getStateBefore();

    Date date = new Date();
    Calendar calendar = new GregorianCalendar();
    calendar.setTime(date);/*from www . ja v a  2  s  .co  m*/
    Timestamp timestampDay = new Timestamp(calendar.getTimeInMillis());

    List<AppointmentForm> listForms = AppointmentFormHome.getActiveAppointmentFormsList();

    for (AppointmentForm form : listForms) {
        int nIdForm = form.getIdForm();

        TaskNotifyReminderConfig config = TaskNotifyReminderConfigHome.findByIdForm(this.getId(), nIdForm);

        if (config != null) {
            List<ReminderAppointment> listReminders = null;
            List<Appointment> listAppointments = getListAppointment(form);

            for (Appointment appointment : listAppointments) {
                Calendar cal2 = new GregorianCalendar();
                Date startAppointment = appointment.getStartAppointment();
                cal2.setTime(startAppointment);
                Timestamp timeStartDate = new Timestamp(cal2.getTimeInMillis());

                State stateAppointment = _stateService.findByResource(appointment.getIdAppointment(),
                        Appointment.APPOINTMENT_RESOURCE_TYPE, form.getIdWorkflow());

                if (timeStartDate.getTime() > timestampDay.getTime() && stateAppointment != null
                        && stateAppointment.getId() == stateBefore.getId()) {
                    long lDiffTimeStamp = Math.abs(timestampDay.getTime() - timeStartDate.getTime());
                    int nDays = (int) lDiffTimeStamp / (1000 * 60 * 60 * 24);
                    int nDiffHours = ((int) lDiffTimeStamp / (60 * 60 * 1000) % 24) + (nDays * 24);
                    int nDiffMin = (nDiffHours * 60) + (int) (lDiffTimeStamp / (60 * 1000) % 60);

                    ResourceHistory appointHistory = _resourceHistoryService.getLastHistoryResource(
                            appointment.getIdAppointment(), Appointment.APPOINTMENT_RESOURCE_TYPE,
                            form.getIdWorkflow());
                    Calendar cal = new GregorianCalendar();
                    if (appointHistory != null) {
                        cal.setTime(appointHistory.getCreationDate());
                    }
                    Timestamp timestampCreationDate = new Timestamp(cal.getTimeInMillis());

                    long nDiff = Math.abs(timestampDay.getTime() - timestampCreationDate.getTime());
                    int nDaysCreationDate = (int) nDiff / (1000 * 60 * 60 * 24);
                    int nDiffHoursCreationDate = ((int) nDiff / (60 * 60 * 1000) % 24)
                            + (nDaysCreationDate * 24);
                    int nDiffCreationDate = (nDiffHoursCreationDate * 60) + (int) (nDiff / (60 * 1000) % 60);

                    if (config.getNbAlerts() > 0) {
                        listReminders = config.getListReminderAppointment();
                    }

                    for (ReminderAppointment reminder : listReminders) {
                        if (nDiffCreationDate > 2 && timestampDay.getTime() > timestampCreationDate.getTime())
                            sendReminder(appointment, reminder, startAppointment, nDiffMin, form, config);
                    }
                }
            }
        }
    }
}

From source file:org.n52.ifgicopter.spf.input.PostgisInputPlugin.java

/**
 * @param resultSet/*w ww .j  a va2s. c  o  m*/
 * @param columnNames
 * @return
 * @throws SQLException
 */
protected Map<String, Object> getDataElement(ResultSet resultSet, ArrayList<String> columnNames)
        throws SQLException {
    Map<String, Object> dataElem = new HashMap<String, Object>();

    for (String c : columnNames) {
        Object o = resultSet.getObject(c);
        if (log.isDebugEnabled() && this.extensiveLog)
            log.debug("Adding " + c + " = " + o);

        if (o instanceof Timestamp) {
            Timestamp t = (Timestamp) o;
            this.lastDataTimestamp = t;
            if (log.isDebugEnabled() && this.extensiveLog)
                log.debug("Latest data as of " + this.lastDataTimestamp);

            // dataElem.put(c, t);
            dataElem.put("time", Long.valueOf(t.getTime()));
        } else if (o instanceof PGgeometry) {
            PGgeometry geom = (PGgeometry) o;
            Geometry geometry = geom.getGeometry();

            if (geometry.getType() == Geometry.POINT) {
                Point p = (Point) geometry;
                dataElem.put("x", Double.valueOf(p.getX()));
                dataElem.put("y", Double.valueOf(p.getY()));
                dataElem.put("z", Double.valueOf(p.getZ()));
                dataElem.put("SRID", Integer.valueOf(p.getSrid()));
            } else
                log.warn("unhandled geometry: " + geom);

            // dataElem.put(c, geometry);
        } else
            dataElem.put(c, o);
    }

    if (log.isDebugEnabled() && this.extensiveLog)
        log.debug("Added new data element: " + Arrays.toString(dataElem.entrySet().toArray()));
    return dataElem;
}

From source file:com.alibaba.wasp.jdbc.TestPreparedStatement.java

public void testDate() throws SQLException {
    PreparedStatement prep = conn.prepareStatement("SELECT ?");
    Timestamp ts = Timestamp.valueOf("2001-02-03 04:05:06");
    prep.setObject(1, new java.util.Date(ts.getTime()));
    ResultSet rs = prep.executeQuery();
    rs.next();// w  w w .j ava  2s  .  c  om
    Timestamp ts2 = rs.getTimestamp(1);
    assertEquals(ts.toString(), ts2.toString());
}