示例#1
0
  // @Ignore
  @Test
  public void allTimeZoneTest() {

    String[] tzIds = TimeZone.getAvailableIDs();

    System.out.printf(
        "NUM) %32s, %5s \t,%15s\t,%15s,%6s\n",
        "Time Zone", "inDST", "offset", "DSTSavings", "useDST");
    for (int i = 0; i < tzIds.length; i++) {
      String string = tzIds[i];
      TimeZone timezone = TimeZone.getTimeZone(string);
      Date date = new Date();
      // System.out.println(i + ") " + timezone.getID() + ", offset " +
      // timezone.getOffset(date.getTime()) + ", DSTSavings " +
      // timezone.getDSTSavings());
      System.out.printf(
          "%3d) %32s, %5s \t,%15d\t,%15d,%6s\n",
          i,
          timezone.getID(),
          timezone.inDaylightTime(date),
          timezone.getOffset(date.getTime()),
          timezone.getDSTSavings(),
          timezone.useDaylightTime());
    }

    assertTrue(true);
  }
 /**
  * Sanity test for time zone generation. Most important, make sure that we can run through all of
  * the time zones without generating an exception. Second, make sure that we're finding rules for
  * at least 90% of time zones that use daylight time (empirically, it's more like 95%). Log those
  * without rules.
  *
  * @throws IOException
  */
 public void testTimeZoneToVTimezone() throws IOException {
   SimpleIcsWriter writer = new SimpleIcsWriter();
   int rule = 0;
   int nodst = 0;
   int norule = 0;
   ArrayList<String> norulelist = new ArrayList<String>();
   for (String tzs : TimeZone.getAvailableIDs()) {
     TimeZone tz = TimeZone.getTimeZone(tzs);
     writer = new SimpleIcsWriter();
     CalendarUtilities.timeZoneToVTimezone(tz, writer);
     String vc = writer.toString();
     boolean hasRule = vc.indexOf("RRULE") > 0;
     if (hasRule) {
       rule++;
     } else if (tz.useDaylightTime()) {
       norule++;
       norulelist.add(tz.getID());
     } else {
       nodst++;
     }
   }
   assertTrue(norule < rule / 10);
   Log.d("TimeZoneGeneration", "Rule: " + rule + ", No DST: " + nodst + ", No rule: " + norule);
   for (String nr : norulelist) {
     Log.d("TimeZoneGeneration", "No rule: " + nr);
   }
 }
 private static TimeZone[] getAvailableTimezones() {
   final Collection<TimeZone> availableTimezones = new TreeSet<TimeZone>(new TimeZoneComparator());
   for (final String id : TimeZone.getAvailableIDs()) {
     availableTimezones.add(TimeZone.getTimeZone(id));
   }
   return availableTimezones.toArray(new TimeZone[availableTimezones.size()]);
 }
  /**
   * Tests that the escape tokenizer converts timestamp values wrt. timezones when useTimezone=true.
   *
   * @throws Exception if the test fails.
   */
  public void testTimestampConversion() throws Exception {
    TimeZone currentTimezone = TimeZone.getDefault();
    String[] availableIds =
        TimeZone.getAvailableIDs(currentTimezone.getRawOffset() + (3600 * 1000 * 2));
    String newTimezone = null;

    if (availableIds.length > 0) {
      newTimezone = availableIds[0];
    } else {
      newTimezone = "UTC"; // punt
    }

    Properties props = new Properties();

    props.setProperty("useTimezone", "true");
    props.setProperty("serverTimezone", newTimezone);
    Connection tzConn = null;

    try {
      String escapeToken = "SELECT {ts '2002-11-12 10:00:00'} {t '05:11:02'}";
      tzConn = getConnectionWithProps(props);
      assertTrue(!tzConn.nativeSQL(escapeToken).equals(this.conn.nativeSQL(escapeToken)));
    } finally {
      if (tzConn != null) {
        tzConn.close();
      }
    }
  }
示例#5
0
  private ComboBox createTimeZoneSelect() {
    ComboBox s = new ComboBox("Timezone");
    s.addContainerProperty("caption", String.class, "");
    s.setItemCaptionPropertyId("caption");
    s.setFilteringMode(FilteringMode.CONTAINS);

    Item i = s.addItem(DEFAULT_ITEMID);
    i.getItemProperty("caption").setValue("Default (" + TimeZone.getDefault().getID() + ")");
    for (String id : TimeZone.getAvailableIDs()) {
      if (!s.containsId(id)) {
        i = s.addItem(id);
        i.getItemProperty("caption").setValue(id);
      }
    }

    if (testBench) {
      s.select("America/New_York");
    } else {
      s.select(DEFAULT_ITEMID);
    }
    s.setImmediate(true);
    s.addValueChangeListener(
        new ValueChangeListener() {

          private static final long serialVersionUID = 1L;

          @Override
          public void valueChange(ValueChangeEvent event) {

            updateCalendarTimeZone(event.getProperty().getValue());
          }
        });

    return s;
  }
 public void test_getAvailableIDsI() {
   String[] str = TimeZone.getAvailableIDs(0);
   assertNotNull(str);
   assertTrue(str.length != 0);
   for (int i = 0; i < str.length; i++) {
     assertNotNull(TimeZone.getTimeZone(str[i]));
   }
 }
示例#7
0
 @PostConstruct
 public void setup() {
   for (String id : TimeZone.getAvailableIDs()) {
     TimeZone tz = TimeZone.getTimeZone(id);
     timeZoneMap.put(id, tz);
     timeZoneMap.put(tz.getDisplayName(Locale.ENGLISH).toLowerCase(), tz);
   }
 }
示例#8
0
 private static Calendar getCalendar() {
   String[] ids = TimeZone.getAvailableIDs(0);
   if (ids.length < 1) {
     return null;
   }
   TimeZone gmt = new SimpleTimeZone(0, ids[0]);
   return new GregorianCalendar(gmt);
 }
 public void testDifferentTimeZones() {
   for (String timeZone : TimeZone.getAvailableIDs()) {
     Calendar cal = Calendar.getInstance(TimeZone.getTimeZone(timeZone));
     Date expected = cal.getTime();
     String json = gson.toJson(expected);
     // System.out.println(result + ": " + timeZone);
     Date actual = gson.fromJson(json, Date.class);
     assertEquals(expected.getTime(), actual.getTime());
   }
 }
示例#10
0
 public static void main(String[] args) throws Exception {
   String[] tzids = TimeZone.getAvailableIDs();
   Set<TimeZone> tzset = new TreeSet<TimeZone>(new TZComparatorByOffset()); // TreeSet for sorting.
   for (String tzid : tzids) {
     tzset.add(TimeZone.getTimeZone(tzid));
   }
   for (TimeZone tz : tzset) {
     printTZ(tz);
   }
 }
示例#11
0
  /**
   * Sanitiy test: the current Date and a random date. TODO test against a reg exp?
   *
   * @throws XMPException
   */
  public void testRenderCurrentTime() throws XMPException {
    GregorianCalendar cal = new GregorianCalendar();
    cal.setTimeInMillis(new Random().nextLong());

    // restrict date to 0000 - 9999?
    cal.set(Calendar.YEAR, cal.get(Calendar.YEAR) % 10000);

    // select random Timezone
    String[] zones = TimeZone.getAvailableIDs();
    String zone = zones[new Random().nextInt(zones.length) + 1];
    cal.setTimeZone(TimeZone.getTimeZone(zone));
    XMPDateTimeFactory.createFromCalendar(cal);
  }
  void test1() {
    Locale[] available = Locale.getAvailableLocales();
    List<Locale> jreimplloc =
        Arrays.asList(
            LocaleProviderAdapter.forJRE().getTimeZoneNameProvider().getAvailableLocales());
    List<Locale> providerLocales = Arrays.asList(tznp.getAvailableLocales());
    String[] ids = TimeZone.getAvailableIDs();

    for (Locale target : available) {
      // pure JRE implementation
      OpenListResourceBundle rb =
          ((ResourceBundleBasedAdapter) LocaleProviderAdapter.forJRE())
              .getLocaleData()
              .getTimeZoneNames(target);
      boolean jreSupportsTarget = jreimplloc.contains(target);

      for (String id : ids) {
        // the time zone
        TimeZone tz = TimeZone.getTimeZone(id);

        // JRE string array for the id
        String[] jrearray = null;
        if (jreSupportsTarget) {
          try {
            jrearray = rb.getStringArray(id);
          } catch (MissingResourceException mre) {
          }
        }

        for (int i = 1; i <= (tz.useDaylightTime() ? 4 : 2); i++) {
          // the localized name
          String name = tz.getDisplayName(i >= 3, i % 2, target);

          // provider's name (if any)
          String providersname = null;
          if (providerLocales.contains(target)) {
            providersname = tznp.getDisplayName(id, i >= 3, i % 2, target);
          }

          // JRE's name
          String jresname = null;
          if (jrearray != null) {
            jresname = jrearray[i];
          }

          checkValidity(
              target, jresname, providersname, name, jreSupportsTarget && jresname != null);
        }
      }
    }
  }
 private static TimeZone getDifferentTimeZone() {
   TimeZone localTimeZone = TimeZone.getDefault();
   int offset = (localTimeZone.getRawOffset() / 3600 / 1000 - 6);
   // 6h to the West, full hour. Now get back to a sane range:
   if (offset < -12) {
     offset += 24;
   }
   String[] zoneIds = TimeZone.getAvailableIDs(offset * 3600 * 1000);
   if (zoneIds.length == 0) {
     // Huh?
     return localTimeZone;
   }
   return TimeZone.getTimeZone(zoneIds[0]);
 }
示例#14
0
 /** This code borrowed from Piesquared on irc.nexuswar.com */
 private TimeZone tZF(String search) {
   if (search.equals("")) return TimeZone.getTimeZone("GMT");
   search = search.toLowerCase();
   search = search.replace("+", "\\+");
   search = search.replace("*", "\\*");
   search = search.replace("?", "\\?");
   String[] zones = TimeZone.getAvailableIDs();
   for (int i = 0; i < zones.length; i++)
     if (zones[i].toLowerCase().equals(search)) return TimeZone.getTimeZone(zones[i]);
   for (int i = 0; i < zones.length; i++)
     if (zones[i].toLowerCase().matches(".*" + search + ".*"))
       return TimeZone.getTimeZone(zones[i]);
   return TimeZone.getTimeZone("GMT");
 }
  /**
   * Handle Request and return the appropriate response.
   *
   * @return response http servlet response.
   * @throws eu.uberdust.rest.exception.InvalidTestbedIdException invalid testbed id exception.
   * @throws eu.uberdust.rest.exception.TestbedNotFoundException testbed not found exception.
   * @throws java.io.IOException IO exception.
   */
  @Loggable
  @RequestMapping(method = RequestMethod.PUT)
  // @RequestMapping("///theta/{theta}/ctype/{ctype}/")
  public ResponseEntity<String> handle(
      @PathVariable("testbedName") String testbedName,
      @PathVariable("prefix") String prefix,
      @PathVariable("capabilityPrefix") String capabilityPrefix)
      throws InvalidTestbedIdException, TestbedNotFoundException, IOException {
    final long start = System.currentTimeMillis();
    initialize(SecurityContextHolder.getContext().getAuthentication().getPrincipal());

    Testbed testbed = new Testbed();
    testbed.setName(testbedName);
    testbed.setDescription("");
    testbed.setTimeZone(TimeZone.getTimeZone(TimeZone.getAvailableIDs()[0]));

    testbed.setUrnPrefix(prefix);
    testbed.setUrnCapabilityPrefix(capabilityPrefix);
    // set the testbed of the setup to be imported
    Setup setup = new Setup();
    testbed.setSetup(setup);
    Origin origin = new Origin();
    origin.setPhi(Float.valueOf(0));
    origin.setTheta(Float.valueOf(0));
    origin.setX(Float.valueOf(0));
    origin.setY(Float.valueOf(0));
    origin.setZ(Float.valueOf(0));
    setup.setOrigin(origin);
    setup.setTimeinfo(new TimeInfo());
    setup.setCoordinateType("Absolute");
    setup.setDescription("description");

    testbedManager.add(testbed);

    setup.setTestbed(testbed);

    setupManager.add(setup);

    LOGGER.info(testbed);

    HttpHeaders responseHeaders = new HttpHeaders();

    responseHeaders.add("Content-Type", "text/plain; charset=utf-8");
    return new ResponseEntity<String>(
        "Inserted " + testbed.toString() + " and " + setup.toString() + ". OK",
        responseHeaders,
        HttpStatus.OK);
  }
示例#16
0
 private static List<TimeZoneListItem> gatherTimeZones() {
   final String[] availableIds = TimeZone.getAvailableIDs();
   final TimeZone defaultTimeZone = TimeZone.getDefault();
   // Put the default time zone at the top of the list...
   final List<TimeZoneListItem> result = new ArrayList<TimeZoneListItem>(availableIds.length);
   result.add(new TimeZoneListItem(defaultTimeZone));
   // ...followed by all the others.
   for (String id : availableIds) {
     if (Thread.currentThread().isInterrupted()) return null;
     final TimeZone timeZone = TimeZone.getTimeZone(id);
     if (!timeZone.equals(defaultTimeZone)) {
       result.add(new TimeZoneListItem(timeZone));
     }
   }
   return result;
 }
示例#17
0
  public static void main(String[] args) {

    for (String s : TimeZone.getAvailableIDs()) {
      System.out.println(s);
    }

    // 타임 존을 한국표준시로 한다.
    // 설정하지 않으면 그리니치표준시가 된다.
    TimeZone tz = new SimpleTimeZone(9 * 60 * 60 * 1000, "KST"); // +9 hours
    TimeZone.setDefault(tz);

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

    // Calendar date = Calendar.getInstance();
    Calendar date = new GregorianCalendar();

    // TimeZone tzLA = TimeZone.getTimeZone("America/Los_Angeles");
    // TimeZone tzEU = TimeZone.getTimeZone("Europe/Copenhagen");
    // TimeZone tzAU = TimeZone.getTimeZone("Australia/Canberra");
    // TimeZone tzKo = TimeZone.getTimeZone("Asia/Seoul");
    // date.setTimeZone(tzKo);

    System.out.println(date.getTimeZone().getDisplayName());

    // 마지막 날
    // date.add(Calendar.MONTH, 1);
    // date.set(Calendar.DAY_OF_MONTH, 1);
    // date.add(Calendar.DAY_OF_MONTH , -1);

    // 첫째날
    // date.set(Calendar.DAY_OF_MONTH, 1);

    String firstDay = sdf.format(date.getTime());

    System.out.println(firstDay);

    Date m = new Date();
    String dTime = sdf.format(m);
    System.out.println("----------------------------");
    System.out.println(dTime);
    System.out.println("----------------------------");

    String ch = null;
    date.add(Calendar.DAY_OF_MONTH, -7);
    ch = sdf.format(date.getTime());
    System.out.println(ch);
  }
示例#18
0
 @Action
 public void timezonePopupClicked(NSPopUpButton sender) {
   String selected = sender.selectedItem().representedObject();
   if (selected.equals(AUTO)) {
     host.setTimezone(null);
   } else {
     String[] ids = TimeZone.getAvailableIDs();
     for (String id : ids) {
       TimeZone tz;
       if ((tz = TimeZone.getTimeZone(id)).getID().equals(selected)) {
         host.setTimezone(tz);
         break;
       }
     }
   }
   this.itemChanged();
 }
示例#19
0
  @Test
  public void producedZipFilesAreTimezoneAgnostic() throws Exception {
    HashCode referenceHash = writeSimpleJarAndGetHash();
    TimeZone previousDefault = TimeZone.getDefault();
    try {
      String[] availableIDs = TimeZone.getAvailableIDs();
      assertThat(availableIDs.length, Matchers.greaterThan(1));

      for (String timezoneID : availableIDs) {
        TimeZone timeZone = TimeZone.getTimeZone(timezoneID);
        TimeZone.setDefault(timeZone);

        assertThat(writeSimpleJarAndGetHash(), Matchers.equalTo(referenceHash));
      }
    } finally {
      TimeZone.setDefault(previousDefault);
    }
  }
 /**
  * This method returns a collection of all available timezones in the system. The tests in this
  * {@link CalendarBasedTimeoutTestCase} will then be run against each of these timezones
  */
 private static List<TimeZone> getTimezones() {
   String[] candidates = TimeZone.getAvailableIDs();
   List<TimeZone> timeZones = new ArrayList<TimeZone>(candidates.length);
   for (String timezoneID : candidates) {
     TimeZone timeZone = TimeZone.getTimeZone(timezoneID);
     boolean different = true;
     for (int i = timeZones.size() - 1; i >= 0; i--) {
       TimeZone testee = timeZones.get(i);
       if (testee.hasSameRules(timeZone)) {
         different = false;
         break;
       }
     }
     if (different) {
       timeZones.add(timeZone);
     }
   }
   return timeZones;
 }
示例#21
0
  /**
   * Gets an Olson ID corresponding to the transitions and offsets saved. First it looks for a
   * cached ID. If it is not found, it looks for a matching ID among the favorite ones. Otherwise it
   * looks for it among all available IDs with the same basic offset.
   *
   * @return a string containing the Olson ID or null if no matching ID is found
   */
  public String toID() {

    if (cachedID) {
      return id;
    }

    for (String idGuess : FAVORITE_TIME_ZONE_IDS) {
      if (matchesID(idGuess)) {
        return cacheID(idGuess);
      }
    }

    for (String idGuess : TimeZone.getAvailableIDs(getBasicOffset())) {
      if (matchesID(idGuess)) {
        return cacheID(idGuess);
      }
    }
    return cacheID(null); // No matching time zone found
  }
示例#22
0
  // @Ignore
  @Test
  public void createTimeZoneTest() {

    String[] availableIds = TimeZone.getAvailableIDs();
    TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
    Date today = new Date();
    for (String id : availableIds) {
      tz = TimeZone.getTimeZone(id);
      m_logger.info(
          "tz info: "
              + tz.getDisplayName()
              + "/"
              + tz.getDSTSavings()
              + "/"
              + tz.getOffset(today.getTime()));
    }

    assertTrue(true);
  }
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == R.id.action_set_time_zone) {
      AlertDialog.Builder b = new AlertDialog.Builder(this);
      b.setTitle("Select your Time Zone");
      b.setCancelable(false);
      b.setNegativeButton(
          "Cancel",
          new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {}
          });
      String[] TZ = TimeZone.getAvailableIDs();
      ArrayList<String> TZ1 = new ArrayList<>();
      for (int i = 0; i < TZ.length; i++) {
        if (!(TZ1.contains(TimeZone.getTimeZone(TZ[i]).getDisplayName()))) {
          TZ1.add(TimeZone.getTimeZone(TZ[i]).getDisplayName());
        }
      }
      final String[] TZ2 = TZ1.toArray(new String[TZ1.size()]);
      Arrays.sort(TZ2);
      b.setItems(
          TZ2,
          new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int pos) {
              db.execSQL("DELETE FROM mytimezone;");
              Snackbar.make(
                      findViewById(R.id.mainCoordinatorLayout),
                      "Your Time Zone is set to " + TZ2[pos],
                      Snackbar.LENGTH_LONG)
                  .show();
              db.execSQL("INSERT INTO mytimezone VALUES('" + TZ2[pos] + "');");
            }
          });
      b.show();
      return true;
    }
    return super.onOptionsItemSelected(item);
  }
示例#24
0
  public static TimeZone parseTimeZone(String tzId) {
    tzId = tzId.trim();

    TimeZone tz = TimeZone.getTimeZone(tzId);

    // getTimeZone returns GMT if it doesn't understand tzId, so if it does return
    // GMT, we need to check if it's lying to us
    if (gmtTimeZoneNames == null) {
      gmtTimeZoneNames = TimeZone.getAvailableIDs(0);

      // use a dummy value to get the "punt" timezone
      androidPuntTimeZone = TimeZone.getTimeZone("android y u so weird");
    }
    if (tz.hasSameRules(androidPuntTimeZone)
        && Arrays.binarySearch(gmtTimeZoneNames, 0, gmtTimeZoneNames.length, tzId) < 0
        && !TIME_ZONE_EXTRA_PATTERN.matcher(tzId).matches()) {
      return null; // I think android punted
    }

    return tz;
  }
  @SuppressWarnings("checkstyle:indentation")
  private void validateTimeZone(List<String> timezones) {
    valueloop:
    for (String timezone : timezones) {
      for (String tzid : TimeZone.getAvailableIDs()) {
        if (tzid.equalsIgnoreCase(timezone)) {
          continue valueloop; // Valid time zone
        }
      }

      TimeZone result = TimeZone.getTimeZone(timezone.toUpperCase());

      String tzid = result.getID();
      if (tzid.equals("GMT") && !timezone.equals(tzid)) {
        throw new ParameterValidationException(
            this.name,
            i18n.tr(
                "Invalid time zone string. Time zones must be recognized time zone names "
                    + "or offsets specified in the form of \"GMT[+-]HH:?MM\"."));
      }
    }
  }
  @Test
  public void test() throws ParseException {
    // Fairfieldの公式ベースの確認
    for (String timeZoneId : TimeZone.getAvailableIDs()) {
      if (timeZoneId.contains("/")) {
        assertFairfieldDays("yyyyMMdd", TimeZone.getTimeZone(timeZoneId), false);
      }
    }

    // TimeZone確認
    for (String timeZoneId : new String[] {"UTC", "GMT+9", "JST", "America/New_York"}) {
      String pattern = "yyyy/MM/dd-HH:mm:ss.SSS";
      TimeZone timeZone = TimeZone.getTimeZone(timeZoneId);
      SimpleDateFormat sdf = new SimpleDateFormat(pattern);
      sdf.setTimeZone(timeZone);
      SafeDateFormat safe = SafeDateFormat.getInstance(pattern, timeZone);

      String date = sdf.format(new Date());
      long msDate = sdf.parse(date).getTime();
      assertEquals(timeZoneId, msDate, safe.parse(date));
      assertEquals(timeZoneId, date, safe.format(msDate));
    }
  }
示例#27
0
  private void writeTimeZone(MarkupWriter writer) {
    if (timeZone == TimeZoneVisibility.NONE) return;

    TimeZone tz = timeZoneTracker.getClientTimeZone();

    writer.element("span", "class", "tx-datefield-timezone");

    switch (timeZone) {
      case DISPLAY:
        writer.write(" ");
        writer.write(tz.getDisplayName(locale));
        break;

      case SELECT:
        writer.element("select", "name", getControlName() + "$timezone");

        for (TimeZone option :
            F.flow(TimeZone.getAvailableIDs()).map(ID_TO_TIME_ZONE).sort(timeZoneComparator)) {
          writer.element("option", "value", option.getID());

          if (tz.equals(option)) writer.attributes("selected", "selected");

          int offset = option.getRawOffset() / (1000 * 60 * 60);

          writer.write(String.format("UTC%+03d %s", offset, option.getID()));

          writer.end();
        }

        writer.end();

      default:
        break;
    }

    writer.end();
  }
示例#28
0
 public void setTimezonePopup(NSPopUpButton timezonePopup) {
   this.timezonePopup = timezonePopup;
   this.timezonePopup.setTarget(this.id());
   this.timezonePopup.setAction(Foundation.selector("timezonePopupClicked:"));
   this.timezonePopup.removeAllItems();
   final List<String> timezones = Arrays.asList(TimeZone.getAvailableIDs());
   this.timezonePopup.addItemWithTitle(UTC.getID());
   this.timezonePopup.lastItem().setRepresentedObject(UTC.getID());
   this.timezonePopup.menu().addItem(NSMenuItem.separatorItem());
   Collections.sort(
       timezones,
       new Comparator<String>() {
         @Override
         public int compare(String o1, String o2) {
           return TimeZone.getTimeZone(o1).getID().compareTo(TimeZone.getTimeZone(o2).getID());
         }
       });
   for (String tz : timezones) {
     if (tz.matches(TIMEZONE_CONTINENT_PREFIXES)) {
       this.timezonePopup.addItemWithTitle(String.format("%s", tz));
       this.timezonePopup.lastItem().setRepresentedObject(tz);
     }
   }
 }
示例#29
0
  private void testDatetimeWithCalendar() throws SQLException {
    trace("Test DATETIME with Calendar");
    ResultSet rs;

    stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, " + "D DATE, T TIME, TS TIMESTAMP)");
    PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST VALUES(?, ?, ?, ?)");
    Calendar regular = Calendar.getInstance();
    Calendar other = null;
    // search a locale that has a _different_ raw offset
    long testTime = java.sql.Date.valueOf("2001-02-03").getTime();
    for (String s : TimeZone.getAvailableIDs()) {
      TimeZone zone = TimeZone.getTimeZone(s);
      long rawOffsetDiff = regular.getTimeZone().getRawOffset() - zone.getRawOffset();
      // must not be the same timezone (not 0 h and not 24 h difference
      // as for Pacific/Auckland and Etc/GMT+12)
      if (rawOffsetDiff != 0 && rawOffsetDiff != 1000 * 60 * 60 * 24) {
        if (regular.getTimeZone().getOffset(testTime) != zone.getOffset(testTime)) {
          other = Calendar.getInstance(zone);
          break;
        }
      }
    }

    trace(
        "regular offset = "
            + regular.getTimeZone().getRawOffset()
            + " other = "
            + other.getTimeZone().getRawOffset());

    prep.setInt(1, 0);
    prep.setDate(2, null, regular);
    prep.setTime(3, null, regular);
    prep.setTimestamp(4, null, regular);
    prep.execute();

    prep.setInt(1, 1);
    prep.setDate(2, null, other);
    prep.setTime(3, null, other);
    prep.setTimestamp(4, null, other);
    prep.execute();

    prep.setInt(1, 2);
    prep.setDate(2, java.sql.Date.valueOf("2001-02-03"), regular);
    prep.setTime(3, java.sql.Time.valueOf("04:05:06"), regular);
    prep.setTimestamp(4, java.sql.Timestamp.valueOf("2007-08-09 10:11:12.131415"), regular);
    prep.execute();

    prep.setInt(1, 3);
    prep.setDate(2, java.sql.Date.valueOf("2101-02-03"), other);
    prep.setTime(3, java.sql.Time.valueOf("14:05:06"), other);
    prep.setTimestamp(4, java.sql.Timestamp.valueOf("2107-08-09 10:11:12.131415"), other);
    prep.execute();

    prep.setInt(1, 4);
    prep.setDate(2, java.sql.Date.valueOf("2101-02-03"));
    prep.setTime(3, java.sql.Time.valueOf("14:05:06"));
    prep.setTimestamp(4, java.sql.Timestamp.valueOf("2107-08-09 10:11:12.131415"));
    prep.execute();

    rs = stat.executeQuery("SELECT * FROM TEST ORDER BY ID");
    assertResultSetMeta(
        rs,
        4,
        new String[] {"ID", "D", "T", "TS"},
        new int[] {Types.INTEGER, Types.DATE, Types.TIME, Types.TIMESTAMP},
        new int[] {10, 8, 6, 23},
        new int[] {0, 0, 0, 10});

    rs.next();
    assertEquals(0, rs.getInt(1));
    assertTrue(rs.getDate(2, regular) == null && rs.wasNull());
    assertTrue(rs.getTime(3, regular) == null && rs.wasNull());
    assertTrue(rs.getTimestamp(3, regular) == null && rs.wasNull());

    rs.next();
    assertEquals(1, rs.getInt(1));
    assertTrue(rs.getDate(2, other) == null && rs.wasNull());
    assertTrue(rs.getTime(3, other) == null && rs.wasNull());
    assertTrue(rs.getTimestamp(3, other) == null && rs.wasNull());

    rs.next();
    assertEquals(2, rs.getInt(1));
    assertEquals("2001-02-03", rs.getDate(2, regular).toString());
    assertEquals("04:05:06", rs.getTime(3, regular).toString());
    assertFalse(rs.getTime(3, other).toString().equals("04:05:06"));
    assertEquals("2007-08-09 10:11:12.131415", rs.getTimestamp(4, regular).toString());
    assertFalse(rs.getTimestamp(4, other).toString().equals("2007-08-09 10:11:12.131415"));

    rs.next();
    assertEquals(3, rs.getInt("ID"));
    assertFalse(rs.getTimestamp("TS", regular).toString().equals("2107-08-09 10:11:12.131415"));
    assertEquals("2107-08-09 10:11:12.131415", rs.getTimestamp("TS", other).toString());
    assertFalse(rs.getTime("T", regular).toString().equals("14:05:06"));
    assertEquals("14:05:06", rs.getTime("T", other).toString());
    // checkFalse(rs.getDate(2, regular).toString(), "2101-02-03");
    // check(rs.getDate("D", other).toString(), "2101-02-03");

    rs.next();
    assertEquals(4, rs.getInt("ID"));
    assertEquals("2107-08-09 10:11:12.131415", rs.getTimestamp("TS").toString());
    assertEquals("14:05:06", rs.getTime("T").toString());
    assertEquals("2101-02-03", rs.getDate("D").toString());

    assertFalse(rs.next());
    stat.execute("DROP TABLE TEST");
  }
示例#30
0
    @Override
    public void actionPerformed(ActionEvent arg0) {
      SimpleDateFormat dateFormat =
          (SimpleDateFormat) DateUtils.getDateTimeFormat(DateFormat.SHORT, DateFormat.MEDIUM);

      panel = new JPanel(new BorderLayout());
      panel.add(
          new JLabel(
              tr(
                  "<html>Take a photo of your GPS receiver while it displays the time.<br>"
                      + "Display that photo here.<br>"
                      + "And then, simply capture the time you read on the photo and select a timezone<hr></html>")),
          BorderLayout.NORTH);

      imgDisp = new ImageDisplay();
      imgDisp.setPreferredSize(new Dimension(300, 225));
      panel.add(imgDisp, BorderLayout.CENTER);

      JPanel panelTf = new JPanel(new GridBagLayout());

      GridBagConstraints gc = new GridBagConstraints();
      gc.gridx = gc.gridy = 0;
      gc.gridwidth = gc.gridheight = 1;
      gc.weightx = gc.weighty = 0.0;
      gc.fill = GridBagConstraints.NONE;
      gc.anchor = GridBagConstraints.WEST;
      panelTf.add(new JLabel(tr("Photo time (from exif):")), gc);

      lbExifTime = new JLabel();
      gc.gridx = 1;
      gc.weightx = 1.0;
      gc.fill = GridBagConstraints.HORIZONTAL;
      gc.gridwidth = 2;
      panelTf.add(lbExifTime, gc);

      gc.gridx = 0;
      gc.gridy = 1;
      gc.gridwidth = gc.gridheight = 1;
      gc.weightx = gc.weighty = 0.0;
      gc.fill = GridBagConstraints.NONE;
      gc.anchor = GridBagConstraints.WEST;
      panelTf.add(new JLabel(tr("Gps time (read from the above photo): ")), gc);

      tfGpsTime = new JosmTextField(12);
      tfGpsTime.setEnabled(false);
      tfGpsTime.setMinimumSize(new Dimension(155, tfGpsTime.getMinimumSize().height));
      gc.gridx = 1;
      gc.weightx = 1.0;
      gc.fill = GridBagConstraints.HORIZONTAL;
      panelTf.add(tfGpsTime, gc);

      gc.gridx = 2;
      gc.weightx = 0.2;
      panelTf.add(new JLabel(" [" + dateFormat.toLocalizedPattern() + ']'), gc);

      gc.gridx = 0;
      gc.gridy = 2;
      gc.gridwidth = gc.gridheight = 1;
      gc.weightx = gc.weighty = 0.0;
      gc.fill = GridBagConstraints.NONE;
      gc.anchor = GridBagConstraints.WEST;
      panelTf.add(new JLabel(tr("I am in the timezone of: ")), gc);

      String[] tmp = TimeZone.getAvailableIDs();
      List<String> vtTimezones = new ArrayList<>(tmp.length);

      for (String tzStr : tmp) {
        TimeZone tz = TimeZone.getTimeZone(tzStr);

        String tzDesc =
            new StringBuilder(tzStr)
                .append(" (")
                .append(formatTimezone(tz.getRawOffset() / 3600000.0))
                .append(')')
                .toString();
        vtTimezones.add(tzDesc);
      }

      Collections.sort(vtTimezones);

      cbTimezones = new JosmComboBox<>(vtTimezones.toArray(new String[0]));

      String tzId = Main.pref.get("geoimage.timezoneid", "");
      TimeZone defaultTz;
      if (tzId.isEmpty()) {
        defaultTz = TimeZone.getDefault();
      } else {
        defaultTz = TimeZone.getTimeZone(tzId);
      }

      cbTimezones.setSelectedItem(
          new StringBuilder(defaultTz.getID())
              .append(" (")
              .append(formatTimezone(defaultTz.getRawOffset() / 3600000.0))
              .append(')')
              .toString());

      gc.gridx = 1;
      gc.weightx = 1.0;
      gc.gridwidth = 2;
      gc.fill = GridBagConstraints.HORIZONTAL;
      panelTf.add(cbTimezones, gc);

      panel.add(panelTf, BorderLayout.SOUTH);

      JPanel panelLst = new JPanel(new BorderLayout());

      imgList =
          new JList<>(
              new AbstractListModel<String>() {
                @Override
                public String getElementAt(int i) {
                  return yLayer.data.get(i).getFile().getName();
                }

                @Override
                public int getSize() {
                  return yLayer.data != null ? yLayer.data.size() : 0;
                }
              });
      imgList.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
      imgList
          .getSelectionModel()
          .addListSelectionListener(
              new ListSelectionListener() {

                @Override
                public void valueChanged(ListSelectionEvent arg0) {
                  int index = imgList.getSelectedIndex();
                  Integer orientation = null;
                  try {
                    orientation = ExifReader.readOrientation(yLayer.data.get(index).getFile());
                  } catch (Exception e) {
                    Main.warn(e);
                  }
                  imgDisp.setImage(yLayer.data.get(index).getFile(), orientation);
                  Date date = yLayer.data.get(index).getExifTime();
                  if (date != null) {
                    DateFormat df =
                        DateUtils.getDateTimeFormat(DateFormat.SHORT, DateFormat.MEDIUM);
                    lbExifTime.setText(df.format(date));
                    tfGpsTime.setText(df.format(date));
                    tfGpsTime.setCaretPosition(tfGpsTime.getText().length());
                    tfGpsTime.setEnabled(true);
                    tfGpsTime.requestFocus();
                  } else {
                    lbExifTime.setText(tr("No date"));
                    tfGpsTime.setText("");
                    tfGpsTime.setEnabled(false);
                  }
                }
              });
      panelLst.add(new JScrollPane(imgList), BorderLayout.CENTER);

      JButton openButton = new JButton(tr("Open another photo"));
      openButton.addActionListener(
          new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent ae) {
              AbstractFileChooser fc =
                  DiskAccessAction.createAndOpenFileChooser(
                      true,
                      false,
                      null,
                      JpgImporter.FILE_FILTER_WITH_FOLDERS,
                      JFileChooser.FILES_ONLY,
                      "geoimage.lastdirectory");
              if (fc == null) return;
              File sel = fc.getSelectedFile();

              Integer orientation = null;
              try {
                orientation = ExifReader.readOrientation(sel);
              } catch (Exception e) {
                Main.warn(e);
              }
              imgDisp.setImage(sel, orientation);

              Date date = null;
              try {
                date = ExifReader.readTime(sel);
              } catch (Exception e) {
                Main.warn(e);
              }
              if (date != null) {
                lbExifTime.setText(
                    DateUtils.getDateTimeFormat(DateFormat.SHORT, DateFormat.MEDIUM).format(date));
                tfGpsTime.setText(DateUtils.getDateFormat(DateFormat.SHORT).format(date) + ' ');
                tfGpsTime.setEnabled(true);
              } else {
                lbExifTime.setText(tr("No date"));
                tfGpsTime.setText("");
                tfGpsTime.setEnabled(false);
              }
            }
          });
      panelLst.add(openButton, BorderLayout.PAGE_END);

      panel.add(panelLst, BorderLayout.LINE_START);

      boolean isOk = false;
      while (!isOk) {
        int answer =
            JOptionPane.showConfirmDialog(
                Main.parent,
                panel,
                tr("Synchronize time from a photo of the GPS receiver"),
                JOptionPane.OK_CANCEL_OPTION,
                JOptionPane.QUESTION_MESSAGE);
        if (answer == JOptionPane.CANCEL_OPTION) return;

        long delta;

        try {
          delta =
              dateFormat.parse(lbExifTime.getText()).getTime()
                  - dateFormat.parse(tfGpsTime.getText()).getTime();
        } catch (ParseException e) {
          JOptionPane.showMessageDialog(
              Main.parent,
              tr("Error while parsing the date.\n" + "Please use the requested format"),
              tr("Invalid date"),
              JOptionPane.ERROR_MESSAGE);
          continue;
        }

        String selectedTz = (String) cbTimezones.getSelectedItem();
        int pos = selectedTz.lastIndexOf('(');
        tzId = selectedTz.substring(0, pos - 1);
        String tzValue = selectedTz.substring(pos + 1, selectedTz.length() - 1);

        Main.pref.put("geoimage.timezoneid", tzId);
        tfOffset.setText(Long.toString(delta / 1000));
        tfTimezone.setText(tzValue);

        isOk = true;
      }
      statusBarUpdater.updateStatusBar();
      yLayer.updateBufferAndRepaint();
    }