public static BatchPoints create(String db, ZeitreihenDTO... zeitreihenDTOs)
      throws ParseException {
    BatchPoints batchPoints = BatchPoints.database(db).retentionPolicy("default").build();

    for (ZeitreihenDTO zeitreihenDTO : zeitreihenDTOs) {
      for (Long timestamp : timestamps(zeitreihenDTO)) {
        GregorianCalendar calendar = new GregorianCalendar();
        calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
        calendar.setTimeInMillis(timestamp);
        int monat = calendar.get(Calendar.MONTH) + 1;
        int jahr = calendar.get(Calendar.YEAR);

        batchPoints.point(
            Point.measurement("lastgang")
                .tag("zaehlpunktbezeichnung", zeitreihenDTO.zaehlpunktbezeichnung)
                .tag("commodity", zeitreihenDTO.commodity)
                .tag("zaehlverfahren", zeitreihenDTO.zaehlverfahren)
                .tag("monat", String.valueOf(monat))
                .tag("jahr", String.valueOf(jahr))
                .time(timestamp, TimeUnit.MILLISECONDS)
                .field("value", randomValue())
                .build());
      }
    }
    return batchPoints;
  }
  /**
   * Generates an achor xml file based on the provided proxy configuration properties and writes it
   * to the provided output stream.
   *
   * @param conf configuration proxy properties instance
   * @param instanceIdentifier instance identifier of the resulting anchor
   * @param out the output stream for writing the generated xml
   * @throws Exception if xml generation fails
   */
  private void generateAnchorXml(
      final ConfProxyProperties conf, final String instanceIdentifier, final OutputStream out)
      throws Exception {
    JAXBContext jaxbCtx = JAXBContext.newInstance(ObjectFactory.class);
    Marshaller marshaller = jaxbCtx.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

    ObjectFactory factory = new ObjectFactory();
    ConfigurationSourceType sourceType = factory.createConfigurationSourceType();
    sourceType.setDownloadURL(
        conf.getConfigurationProxyURL() + "/" + OutputBuilder.SIGNED_DIRECTORY_NAME);
    for (byte[] cert : conf.getVerificationCerts()) {
      sourceType.getVerificationCert().add(cert);
    }
    ConfigurationAnchorType anchorType = factory.createConfigurationAnchorType();
    anchorType.setInstanceIdentifier(instanceIdentifier);
    GregorianCalendar gcal = new GregorianCalendar();
    gcal.setTimeZone(TimeZone.getTimeZone("UTC"));
    XMLGregorianCalendar xgcal = DatatypeFactory.newInstance().newXMLGregorianCalendar(gcal);
    anchorType.setGeneratedAt(xgcal);
    anchorType.getSource().add(sourceType);
    JAXBElement<ConfigurationAnchorType> root = factory.createConfigurationAnchor(anchorType);

    marshaller.marshal(root, out);
  }
  public static Collection<BatchPoints> create(
      int chunksize, String db, ZeitreihenDTO... zeitreihenDTOs) throws ParseException {
    List<Point> points = new ArrayList<>();
    for (ZeitreihenDTO zeitreihenDTO : zeitreihenDTOs) {
      for (Long timestamp : timestamps(zeitreihenDTO)) {
        GregorianCalendar calendar = new GregorianCalendar();
        calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
        calendar.setTimeInMillis(timestamp);
        int monat = calendar.get(Calendar.MONTH) + 1;
        int jahr = calendar.get(Calendar.YEAR);

        points.add(
            Point.measurement("lastgang")
                .tag("zaehlpunktbezeichnung", zeitreihenDTO.zaehlpunktbezeichnung)
                .tag("commodity", zeitreihenDTO.commodity)
                .tag("zaehlverfahren", zeitreihenDTO.zaehlverfahren)
                .tag("monat", String.valueOf(monat))
                .tag("jahr", String.valueOf(jahr))
                .time(timestamp, TimeUnit.MILLISECONDS)
                .field("value", randomValue())
                .build());
      }
    }

    Collection<BatchPoints> batchPoints = new ArrayList<>();
    Lists.partition(points, chunksize)
        .forEach(
            chunk -> {
              BatchPoints bp = BatchPoints.database(db).retentionPolicy("default").build();

              chunk.forEach(bp::point);
              batchPoints.add(bp);
            });
    return batchPoints;
  }
Пример #4
0
 /**
  * From initial TNEF to iCalendar Spec. The DTSTART property can be hard-coded to 16010101T000000.
  * This is a value that works well across many calendar client apps. Note: Some examples seen are
  * similar to this but include the hour of the transition. Suspect that is useful - so including
  * it. Zimbra replaces our timezones with closest matchin known ones, so not worth trying to
  * improve this to see if can choose an accurate start date/time in 1601.
  *
  * @param hr
  * @param min
  * @return
  */
 private DtStart getDtStart(int hr, int min) {
   TimeZone utcZone = TimeZone.getTimeZone("UTC");
   GregorianCalendar gc = new GregorianCalendar(1601, 0 /* zero based */, 1, hr, min);
   gc.setTimeZone(utcZone);
   Date startDate = gc.getTime();
   DateTime startDateTime = new DateTime(startDate);
   return new DtStart(startDateTime);
 }
Пример #5
0
  /**
   * Converts a {@link GregorianCalendar} into a {@link XMLGregorianCalendar}
   *
   * @param calendar
   * @return
   */
  public static XMLGregorianCalendar convertToXmlDate(final GregorianCalendar calendar) {
    final GregorianCalendar zuluDate = new GregorianCalendar();
    zuluDate.setTimeZone(TimeZone.getTimeZone("UTC"));
    zuluDate.setTimeInMillis(calendar.getTimeInMillis());

    final XMLGregorianCalendar xmlDate = XML_DATATYPE_FACTORY.newXMLGregorianCalendar(zuluDate);
    return xmlDate;
  }
Пример #6
0
  /**
   * Tests the parsing of an ISO8601 formatted date
   *
   * @throws Exception Forwards all exceptions to JUnit.
   */
  @Ignore("todo: Import the latest changes to enable the below test case.")
  public void itestParse() throws Exception {
    GregorianCalendar cal = new GregorianCalendar(2006, 05, 30, 23, 59, 54);
    cal.set(Calendar.MILLISECOND, 321);
    cal.setTimeZone(TimeZone.getTimeZone("UTC"));
    XMPDateTime dt = XMPDateTimeFactory.createFromCalendar(cal);
    XMPDateTime parsed = ISO8601Converter.parse("2006-06-30T23:59:54.321Z");
    assertEquals(0, dt.compareTo(parsed));

    cal.set(Calendar.MILLISECOND, 0);
    dt = XMPDateTimeFactory.createFromCalendar(cal);
    assertEquals(0, dt.compareTo(ISO8601Converter.parse("2006-06-30T23:59:54Z")));

    cal.set(Calendar.SECOND, 0);
    dt = XMPDateTimeFactory.createFromCalendar(cal);
    assertEquals(0, dt.compareTo(ISO8601Converter.parse("2006-06-30T23:59Z")));

    cal.set(Calendar.HOUR_OF_DAY, 0);
    dt = XMPDateTimeFactory.createFromCalendar(cal);
    assertEquals(0, dt.compareTo(ISO8601Converter.parse("2006-06-30T00:59Z")));

    cal.set(Calendar.MINUTE, 0);
    dt = XMPDateTimeFactory.createFromCalendar(cal);
    assertEquals(0, dt.compareTo(ISO8601Converter.parse("2006-06-30T00:00Z")));

    // Issue reported by S7, dates w/o timezone have to be accepted
    // toDo: Import latest version to run the following test
    // dt = ISO8601Converter.parse("2006-10-13T17:45:26.16");
    // assertEquals("2006-10-13T17:45:26.16", dt.toString());

    dt = ISO8601Converter.parse("2006-10-13T17:45:26.16Z");
    assertEquals("2006-10-13T17:45:26.16Z", dt.toString());

    dt = ISO8601Converter.parse("2006-10-13T17:45:26");
    assertEquals("2006-10-13T17:45:26", dt.toString());

    dt = ISO8601Converter.parse("2006-10-13T17:45:26+5:30");
    assertEquals("2006-10-13T17:45:26+05:30", dt.toString());

    dt = ISO8601Converter.parse("2006-10-13T17:45");
    assertEquals("2006-10-13T17:45", dt.toString());

    dt = ISO8601Converter.parse("2006-10-13T17:45-06");
    assertEquals("2006-10-13T17:45-06:00", dt.toString());

    dt = ISO8601Converter.parse("2006-10-13T17");
    assertEquals("2006-10-13T17:00", dt.toString());

    dt = ISO8601Converter.parse("2006-10-13T17Z");
    assertEquals("2006-10-13T17:00Z", dt.toString());

    dt = ISO8601Converter.parse("2006-10-13T17-03:00");
    assertEquals("2006-10-13T17:00-03:00", dt.toString());

    dt = ISO8601Converter.parse("2006-10-13");
    assertEquals("2006-10-13", dt.toString());
  }
Пример #7
0
 private GregorianCalendar getCreationDate() {
   final GregorianCalendar creationDate = new GregorianCalendar();
   creationDate.setTimeZone(TimeZone.getTimeZone("UTC"));
   creationDate.set(Calendar.YEAR, 2013);
   creationDate.set(Calendar.MONTH, 11);
   creationDate.set(Calendar.DAY_OF_MONTH, 15);
   creationDate.set(Calendar.HOUR_OF_DAY, 14);
   creationDate.set(Calendar.MINUTE, 20);
   creationDate.set(Calendar.SECOND, 02);
   return creationDate;
 }
  public void testWheelchairAccessible() throws Exception {
    Vertex near_a = graph.getVertex("near_1_agency_entrance_a");
    Vertex near_b = graph.getVertex("near_1_agency_entrance_b");
    Vertex near_c = graph.getVertex("near_1_agency_C");
    Vertex near_e = graph.getVertex("near_1_agency_E");

    Vertex stop_d = graph.getVertex("agency:D");
    Vertex split_d = null;
    for (StreetTransitLink e : Iterables.filter(stop_d.getOutgoing(), StreetTransitLink.class)) {
      split_d = e.getToVertex();
    }

    RoutingRequest options = new RoutingRequest();
    options.wheelchairAccessible = true;
    options.dateTime = TestUtils.dateInSeconds("America/New_York", 2009, 8, 18, 0, 0, 0);

    ShortestPathTree spt;
    GraphPath path;

    // stop B is accessible, so there should be a path.
    options.setRoutingContext(graph, near_a, near_b);
    spt = aStar.getShortestPathTree(options);

    path = spt.getPath(near_b, false);
    assertNotNull(path);

    // stop C is not accessible, so there should be no path.
    options.setRoutingContext(graph, near_a, near_c);
    spt = aStar.getShortestPathTree(options);

    path = spt.getPath(near_c, false);
    assertNull(path);

    // stop E has no accessibility information, but we should still be able to route to it.
    options.setRoutingContext(graph, near_a, near_e);
    spt = aStar.getShortestPathTree(options);

    path = spt.getPath(near_e, false);
    assertNotNull(path);

    // from stop A to stop D would normally be trip 1.1 to trip 2.1, arriving at 00:30. But trip
    // 2 is not accessible, so we'll do 1.1 to 3.1, arriving at 01:00
    GregorianCalendar time = new GregorianCalendar(2009, 8, 18, 0, 0, 0);
    time.setTimeZone(TimeZone.getTimeZone("America/New_York"));
    options.dateTime = TestUtils.toSeconds(time);
    options.setRoutingContext(graph, near_a, split_d);
    spt = aStar.getShortestPathTree(options);

    time.add(Calendar.HOUR, 1);
    time.add(Calendar.SECOND, 1); // for the StreetTransitLink
    path = spt.getPath(split_d, false);
    assertNotNull(path);
    assertEquals(TestUtils.toSeconds(time), path.getEndTime());
  }
  private void init() throws IOException {
    members = new StructureMembers("stationObs");

    // used to convert from adde format
    calendar = new GregorianCalendar();
    calendar.setTimeZone(TimeZone.getTimeZone("GMT"));

    // time unit
    timeUnit = DateUnit.getUnixDateUnit();

    try {
      AddePointDataReader reader = callAdde(addeURL);

      String[] params = reader.getParams();
      String[] units = reader.getUnits();
      int[] scales = reader.getScales();
      scaleFactor = new double[params.length];

      if (debugHead) System.out.println(" Param  Unit Scale");
      for (int paramNo = 0; paramNo < params.length; paramNo++) {
        // memberNames.add( params[i]);

        if (debugHead)
          System.out.println(" " + params[paramNo] + " " + units[paramNo] + " " + scales[paramNo]);
        if (scales[paramNo] != 0)
          scaleFactor[paramNo] = 1.0 / Math.pow(10.0, (double) scales[paramNo]);

        DataType dt = null;
        if ("CHAR".equals(units[paramNo])) dt = DataType.STRING;
        else if (scaleFactor[paramNo] == 0) dt = DataType.INT;
        else dt = DataType.DOUBLE;

        String unitString = null;
        if ((units[paramNo] != null) && (units[paramNo].length() > 0))
          unitString = visad.jmet.MetUnits.makeSymbol(units[paramNo]);

        AddeTypedDataVariable tdv = new AddeTypedDataVariable(params[paramNo], unitString, dt);
        dataVariables.add(tdv);
        StructureMembers.Member m =
            members.addMember(
                tdv.getShortName(),
                tdv.getDescription(),
                tdv.getUnitsString(),
                tdv.getDataType(),
                tdv.getShape());
        m.setDataParam(paramNo);
        members.addMember(m);
      }

    } catch (AddeException e) {
      e.printStackTrace();
      throw new IOException(e.getMessage());
    }
  }
Пример #10
0
 private GregorianCalendar completionDate() {
   final GregorianCalendar completionDate = new GregorianCalendar();
   completionDate.setTimeZone(TimeZone.getTimeZone("UTC"));
   completionDate.set(Calendar.YEAR, 2013);
   completionDate.set(Calendar.MONTH, 11);
   completionDate.set(Calendar.DAY_OF_MONTH, 15);
   completionDate.set(Calendar.HOUR_OF_DAY, 16);
   completionDate.set(Calendar.MINUTE, 05);
   completionDate.set(Calendar.SECOND, 16);
   return completionDate;
 }
Пример #11
0
 /**
  * Generate a GregorianCalendar from a date string that represents a date/time in GMT
  *
  * @param DateTime date string in format 20090211T180303Z (rfc2445, iCalendar).
  * @return the GregorianCalendar
  */
 public static GregorianCalendar parseDateTimeToCalendar(String date) {
   GregorianCalendar cal =
       new GregorianCalendar(
           Integer.parseInt(date.substring(0, 4)),
           Integer.parseInt(date.substring(4, 6)) - 1,
           Integer.parseInt(date.substring(6, 8)),
           Integer.parseInt(date.substring(9, 11)),
           Integer.parseInt(date.substring(11, 13)),
           Integer.parseInt(date.substring(13, 15)));
   cal.setTimeZone(TimeZone.getTimeZone("GMT"));
   return cal;
 }
Пример #12
0
 /**
  * Generate a time in milliseconds from an email date string that represents a date/time in GMT
  *
  * @param Email style DateTime string in format 2010-02-23T16:00:00.000Z (ISO 8601, rfc3339)
  * @return the time in milliseconds (since Jan 1, 1970)
  */
 public static long parseEmailDateTimeToMillis(String date) {
   GregorianCalendar cal =
       new GregorianCalendar(
           Integer.parseInt(date.substring(0, 4)),
           Integer.parseInt(date.substring(5, 7)) - 1,
           Integer.parseInt(date.substring(8, 10)),
           Integer.parseInt(date.substring(11, 13)),
           Integer.parseInt(date.substring(14, 16)),
           Integer.parseInt(date.substring(17, 19)));
   cal.setTimeZone(TimeZone.getTimeZone("GMT"));
   return cal.getTimeInMillis();
 }
Пример #13
0
  public static XMLGregorianCalendar convertDateToUTCtime(Date date) {
    try {
      GregorianCalendar gc = (GregorianCalendar) GregorianCalendar.getInstance();
      gc.setTime(date);
      gc.setTimeZone(TimeZone.getTimeZone("UTC"));
      return DatatypeFactory.newInstance().newXMLGregorianCalendar(gc);

    } catch (Exception e) {
      logger.error("Exception captured at convertDateToUTCtime", e);
      return null;
    }
  }
Пример #14
0
  @Override
  public boolean match(Date now) {
    GregorianCalendar calendar = new GregorianCalendar();
    calendar.setTimeInMillis(now.getTime());
    calendar.setTimeZone(this.zone);

    int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
    if (this.weekdayList.contains(dayOfWeek)) {
      return super.match(now);
    } else {
      return false;
    }
  }
Пример #15
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);
  }
 public void testParseDateTimeToMillis(String date) {
   // Format for calendar date strings is 20100223T160000000Z
   String dateString = "20100223T151617000Z";
   long dateTime = Utility.parseDateTimeToMillis(dateString);
   GregorianCalendar cal = new GregorianCalendar();
   cal.setTimeInMillis(dateTime);
   cal.setTimeZone(TimeZone.getTimeZone("GMT"));
   assertEquals(cal.get(Calendar.YEAR), 2010);
   assertEquals(cal.get(Calendar.MONTH), 1); // 0 based
   assertEquals(cal.get(Calendar.DAY_OF_MONTH), 23);
   assertEquals(cal.get(Calendar.HOUR_OF_DAY), 16);
   assertEquals(cal.get(Calendar.MINUTE), 16);
   assertEquals(cal.get(Calendar.SECOND), 17);
 }
Пример #17
0
  /** @tests java.util.Date#parse(java.lang.String) */
  public void test_parseLjava_lang_String() {
    // Test for method long java.util.Date.parse(java.lang.String)
    Date d = new Date(Date.parse("13 October 1998"));
    GregorianCalendar cal = new GregorianCalendar();
    cal.setTime(d);
    assertEquals("Parsed incorrect month", 9, cal.get(Calendar.MONTH));
    assertEquals("Parsed incorrect year", 1998, cal.get(Calendar.YEAR));
    assertEquals("Parsed incorrect date", 13, cal.get(Calendar.DATE));

    d = new Date(Date.parse("Jan-12 1999"));
    assertTrue("Wrong parsed date 1", d.equals(new GregorianCalendar(1999, 0, 12).getTime()));
    d = new Date(Date.parse("Jan12-1999"));
    assertTrue("Wrong parsed date 2", d.equals(new GregorianCalendar(1999, 0, 12).getTime()));
    d = new Date(Date.parse("Jan12 69-1"));
    cal.setTimeZone(TimeZone.getTimeZone("GMT"));
    cal.clear();
    cal.set(1969, Calendar.JANUARY, 12, 1, 0);
    assertTrue("Wrong parsed date 3", d.equals(cal.getTime()));
    d = new Date(Date.parse("6:45:13 3/2/1200 MST"));
    cal.setTimeZone(TimeZone.getTimeZone("MST"));
    cal.clear();
    cal.set(1200, 2, 2, 6, 45, 13);
    assertTrue("Wrong parsed date 4", d.equals(cal.getTime()));
    d = new Date(Date.parse("Mon, 22 Nov 1999 12:52:06 GMT"));
    cal.setTimeZone(TimeZone.getTimeZone("GMT"));
    cal.clear();
    cal.set(1999, Calendar.NOVEMBER, 22, 12, 52, 06);
    assertTrue("Wrong parsed date 5", d.equals(cal.getTime()));

    try {
      // Regression for HARMONY-259
      Date.parse(null);
      fail("Date.parse(null) should throw IllegalArgumentException");
    } catch (IllegalArgumentException e) {
      // expected
    }
  }
  /*
   * (non-Javadoc)
   * @see org.datanucleus.store.mapping.JavaTypeMapping#getObject(org.datanucleus.ExecutionContext, java.lang.Object, int[])
   */
  public Object getObject(ExecutionContext ec, ResultSet resultSet, int[] exprIndex) {
    try {
      // Check for null entries
      if (getDatastoreMapping(0).getObject(resultSet, exprIndex[0]) == null) {
        return null;
      }
    } catch (Exception e) {
      // Do nothing
    }

    if (singleColumn) {
      Timestamp ts = (Timestamp) getDatastoreMapping(0).getObject(resultSet, exprIndex[0]);
      GregorianCalendar cal = new GregorianCalendar();
      cal.setTimeInMillis(ts.getTime());

      String timezoneID =
          ec.getNucleusContext()
              .getPersistenceConfiguration()
              .getStringProperty("datanucleus.ServerTimeZoneID");
      if (timezoneID != null) {
        // Apply server timezone ID since we dont know what it was upon persistence
        cal.setTimeZone(TimeZone.getTimeZone(timezoneID));
      }
      return cal;
    } else {
      // (Timestamp millisecs, Timezone) implementation
      long millisecs = getDatastoreMapping(0).getLong(resultSet, exprIndex[0]);

      GregorianCalendar cal = new GregorianCalendar();
      cal.setTime(new Date(millisecs));
      String timezoneId = getDatastoreMapping(1).getString(resultSet, exprIndex[1]);
      if (timezoneId != null) {
        cal.setTimeZone(TimeZone.getTimeZone(timezoneId));
      }
      return cal;
    }
  }
Пример #19
0
  /** Some checks for the getLastMillisecond(TimeZone) method. */
  public void testGetLastMillisecondWithCalendar() {
    Second s = new Second(50, 45, 21, 21, 4, 2001);
    GregorianCalendar calendar = new GregorianCalendar(Locale.GERMANY);
    calendar.setTimeZone(TimeZone.getTimeZone("Europe/Frankfurt"));
    assertEquals(987889550999L, s.getLastMillisecond(calendar));

    // try null calendar
    boolean pass = false;
    try {
      s.getLastMillisecond((Calendar) null);
    } catch (NullPointerException e) {
      pass = true;
    }
    assertTrue(pass);
  }
Пример #20
0
  /** Some checks for the getFirstMillisecond(TimeZone) method. */
  @Test
  public void testGetFirstMillisecondWithCalendar() {
    Millisecond m = new Millisecond(500, 55, 40, 2, 15, 4, 2000);
    GregorianCalendar calendar = new GregorianCalendar(Locale.GERMANY);
    calendar.setTimeZone(TimeZone.getTimeZone("Europe/Frankfurt"));
    assertEquals(955766455500L, m.getFirstMillisecond(calendar));

    // try null calendar
    boolean pass = false;
    try {
      m.getFirstMillisecond((Calendar) null);
    } catch (NullPointerException e) {
      pass = true;
    }
    assertTrue(pass);
  }
Пример #21
0
 private Literal decodeLiteral(final Object generic) {
   if (generic instanceof GenericRecord) {
     final GenericRecord record = (GenericRecord) generic;
     final Schema schema = record.getSchema();
     if (schema.equals(Schemas.STRING_LANG)) {
       final String label = record.get(0).toString(); // Utf8 class used
       final Object language = record.get(1);
       return this.factory.createLiteral(label, language.toString());
     } else if (schema.equals(Schemas.SHORT)) {
       return this.factory.createLiteral(((Integer) record.get(0)).shortValue());
     } else if (schema.equals(Schemas.BYTE)) {
       return this.factory.createLiteral(((Integer) record.get(0)).byteValue());
     } else if (schema.equals(Schemas.BIGINTEGER)) {
       return this.factory.createLiteral(record.get(0).toString(), XMLSchema.INTEGER);
     } else if (schema.equals(Schemas.BIGDECIMAL)) {
       return this.factory.createLiteral(record.get(0).toString(), XMLSchema.DECIMAL);
     } else if (schema.equals(Schemas.CALENDAR)) {
       final int tz = (Integer) record.get(0);
       final GregorianCalendar calendar = new GregorianCalendar();
       calendar.setTimeInMillis((Long) record.get(1));
       calendar.setTimeZone(
           TimeZone.getTimeZone(
               String.format(
                   "GMT%s%02d:%02d", tz >= 0 ? "+" : "-", Math.abs(tz) / 60, Math.abs(tz) % 60)));
       return this.factory.createLiteral(this.datatypeFactory.newXMLGregorianCalendar(calendar));
     }
   } else if (generic instanceof CharSequence) {
     return this.factory.createLiteral(generic.toString()); // Utf8 class used
   } else if (generic instanceof Boolean) {
     return this.factory.createLiteral((Boolean) generic);
   } else if (generic instanceof Long) {
     return this.factory.createLiteral((Long) generic);
   } else if (generic instanceof Integer) {
     return this.factory.createLiteral((Integer) generic);
   } else if (generic instanceof Double) {
     return this.factory.createLiteral((Double) generic);
   } else if (generic instanceof Float) {
     return this.factory.createLiteral((Float) generic);
   }
   Preconditions.checkNotNull(generic);
   throw new IllegalArgumentException("Unsupported generic data: " + generic);
 }
  @Override
  public void convert(String ttl, String startTime) {
    try {
      long start_l, stop_l;
      long ttl_l = Long.parseLong(ttl);
      stop_l = System.currentTimeMillis();
      if (startTime != null) stop_l = Long.parseLong(startTime);
      start_l = stop_l - ttl_l;

      GregorianCalendar cal = (GregorianCalendar) GregorianCalendar.getInstance();
      cal.setTimeZone(getTimeZone());
      cal.setTimeInMillis(start_l);
      DatatypeFactory factory = DatatypeFactory.newInstance();
      start = vf.createLiteral(factory.newXMLGregorianCalendar(cal));

      cal.setTimeInMillis(stop_l);
      stop = vf.createLiteral(factory.newXMLGregorianCalendar(cal));
    } catch (DatatypeConfigurationException e) {
      throw new RuntimeException("Exception occurred creating DataTypeFactory", e);
    }
  }
    public Object getPropertyValue() {
      GregorianCalendar result = new GregorianCalendar();

      result.setTimeZone(timezone);

      result.set(Calendar.YEAR, year.getNumber().intValue());
      int mi = 0;
      String ms = month.getValue().toString();
      for (int i = 0; i < MONTH_STRINGS.length; i++) {
        if (MONTH_STRINGS[i].equals(ms)) {
          mi = i;
          break;
        }
      }
      result.set(Calendar.MONTH, mi);
      result.set(Calendar.DATE, day.getNumber().intValue());
      result.set(Calendar.HOUR_OF_DAY, hour.getNumber().intValue());
      result.set(Calendar.MINUTE, min.getNumber().intValue());
      result.set(Calendar.SECOND, sec.getNumber().intValue());

      return result;
    }
Пример #24
0
  private void updateCalendarTimeZone(Object timezoneId) {
    TimeZone tz = null;
    if (!DEFAULT_ITEMID.equals(timezoneId)) {
      tz = TimeZone.getTimeZone((String) timezoneId);
    }

    // remember the week that was showing, so we can re-set it later
    Date startDate = calendarComponent.getStartDate();
    calendar.setTime(startDate);
    int weekNumber = calendar.get(java.util.Calendar.WEEK_OF_YEAR);
    calendarComponent.setTimeZone(tz);
    calendar.setTimeZone(calendarComponent.getTimeZone());

    if (viewMode == Mode.WEEK) {
      calendar.set(java.util.Calendar.WEEK_OF_YEAR, weekNumber);
      calendar.set(java.util.Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());

      calendarComponent.setStartDate(calendar.getTime());
      calendar.add(java.util.Calendar.DATE, 6);
      calendarComponent.setEndDate(calendar.getTime());
    }
  }
  public void testRunForTrain() {
    /**
     * This is the notorious Byrd bug: we're going from Q to T at 8:30. There's a trip from S to T
     * at 8:50 and a second one at 9:50. To get to S by 8:50, we need to take trip 12.1 from Q to R,
     * and 13.1 from R to S. If we take the direct-but-slower 11.1, we'll miss the 8:50 and have to
     * catch the 9:50.
     */
    Vertex destination = graph.getVertex("agency:T");
    RoutingRequest options = new RoutingRequest();
    // test is designed such that transfers must be instantaneous
    options.transferSlack = (0);
    GregorianCalendar startTime = new GregorianCalendar(2009, 11, 2, 8, 30, 0);
    startTime.setTimeZone(TimeZone.getTimeZone("America/New_York"));
    options.dateTime = TestUtils.toSeconds(startTime);
    options.setRoutingContext(graph, "agency:Q", destination.getLabel());
    ShortestPathTree spt = aStar.getShortestPathTree(options);
    GraphPath path = spt.getPath(destination, false);

    long endTime = path.getEndTime();
    Calendar c = new GregorianCalendar();
    c.setTimeInMillis(endTime * 1000L);
    assertTrue(endTime - TestUtils.toSeconds(startTime) < 7200);
  }
  public void testJPEGIPTC() throws Exception {
    Metadata metadata = new Metadata();
    metadata.set(Metadata.CONTENT_TYPE, "image/jpeg");
    InputStream stream = getClass().getResourceAsStream("/test-documents/testJPEG_IPTC_EXT.jpg");
    parser.parse(stream, new DefaultHandler(), metadata, new ParseContext());

    assertEquals("Washington", metadata.get(IPTC.CITY));
    assertEquals("United States", metadata.get(IPTC.COUNTRY));
    assertEquals("US", metadata.get(IPTC.COUNTRY_CODE));

    assertEquals(
        "A stream bank in Rock Creek Park Washington DC during a photo bike tour with ASPP DC/South chapter.",
        metadata.get(IPTC.DESCRIPTION));
    assertEquals(
        "A stream bank in Rock Creek Park Washington DC during a photo bike tour with ASPP DC/South chapter.",
        metadata.get(Metadata.DESCRIPTION));

    assertEquals("Rock Creek Park", metadata.get(IPTC.HEADLINE));
    assertEquals("Downstream", metadata.get(Metadata.TITLE));

    assertEquals("intellectual genre", metadata.get(IPTC.INTELLECTUAL_GENRE));

    List<String> iptcKeywords = Arrays.asList(metadata.getValues(IPTC.KEYWORDS));
    assertTrue(iptcKeywords.contains("stream"));
    assertTrue(iptcKeywords.contains("park"));
    assertTrue(iptcKeywords.contains("bank"));
    List<String> tikaKeywords = Arrays.asList(metadata.getValues(Metadata.KEYWORDS));
    assertTrue(Arrays.toString(tikaKeywords.toArray()).contains("stream"));
    assertTrue(Arrays.toString(tikaKeywords.toArray()).contains("park"));
    assertTrue(Arrays.toString(tikaKeywords.toArray()).contains("bank"));

    assertEquals("DC", metadata.get(IPTC.PROVINCE_OR_STATE));

    List<String> iptcSceneCode = Arrays.asList(metadata.getValues(IPTC.SCENE_CODE));
    assertEquals(2, iptcSceneCode.size());
    assertTrue(Arrays.toString(iptcSceneCode.toArray()).contains("iptc scene 1"));
    assertTrue(Arrays.toString(iptcSceneCode.toArray()).contains("iptc scene 2"));

    List<String> iptcSubjectCode = Arrays.asList(metadata.getValues(IPTC.SUBJECT_CODE));
    assertEquals(2, iptcSubjectCode.size());
    assertTrue(Arrays.toString(iptcSubjectCode.toArray()).contains("iptc subject code 1"));
    assertTrue(Arrays.toString(iptcSubjectCode.toArray()).contains("iptc subject code 2"));

    assertEquals("Rock Creek Park", metadata.get(IPTC.SUBLOCATION));

    GregorianCalendar calendar = new GregorianCalendar();
    calendar.set(Calendar.YEAR, 2011);
    calendar.set(Calendar.MONTH, 7);
    calendar.set(Calendar.DATE, 31);
    calendar.set(Calendar.HOUR_OF_DAY, 12);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
    assertEquals(calendar.getTime(), metadata.getDate(IPTC.DATE_CREATED));

    assertEquals("Ray Gauss II", metadata.get(IPTC.DESCRIPTION_WRITER));
    assertEquals("instructions", metadata.get(IPTC.INSTRUCTIONS));
    assertEquals("job identifier", metadata.get(IPTC.JOB_ID));
    assertEquals("Downstream", metadata.get(IPTC.TITLE));
    assertTrue(metadata.get(IPTC.COPYRIGHT_NOTICE).contains("Ray Gauss II"));

    List<String> creators = Arrays.asList(metadata.getValues(IPTC.CREATOR));
    assertTrue(Arrays.toString(creators.toArray()).contains("Ray Gauss II"));

    assertEquals("DAM Architect", metadata.get(IPTC.CREATORS_JOB_TITLE));
    assertEquals("provider", metadata.get(IPTC.CREDIT_LINE));
    assertEquals("rights usage terms", metadata.get(IPTC.RIGHTS_USAGE_TERMS));
    assertEquals("source", metadata.get(IPTC.SOURCE));
    assertEquals("1234 Some Road", metadata.get(IPTC.CONTACT_INFO_ADDRESS));
    assertEquals("Atlanta", metadata.get(IPTC.CONTACT_INFO_CITY));
    assertEquals("US", metadata.get(IPTC.CONTACT_INFO_COUNTRY));

    List<String> ciWorkEmails = Arrays.asList(metadata.getValues(IPTC.CONTACT_INFO_EMAIL));
    // Photoshop does not support true multi-value here
    assertTrue(Arrays.toString(ciWorkEmails.toArray()).contains("*****@*****.**"));
    assertTrue(Arrays.toString(ciWorkEmails.toArray()).contains("*****@*****.**"));

    List<String> ciWorkTels = Arrays.asList(metadata.getValues(IPTC.CONTACT_INFO_PHONE));
    // Photoshop does not support true multi-value here
    assertTrue(Arrays.toString(ciWorkTels.toArray()).contains("555-1234"));
    assertTrue(Arrays.toString(ciWorkTels.toArray()).contains("555-4321"));

    assertEquals("30339", metadata.get(IPTC.CONTACT_INFO_POSTAL_CODE));
    assertEquals("GA", metadata.get(IPTC.CONTACT_INFO_STATE_PROVINCE));

    List<String> ciWorkUrls = Arrays.asList(metadata.getValues(IPTC.CONTACT_INFO_WEB_URL));
    // Photoshop does not support true multi-value here
    assertTrue(Arrays.toString(ciWorkUrls.toArray()).contains("http://alfresco.com"));
    assertTrue(Arrays.toString(ciWorkUrls.toArray()).contains("http://example.com"));

    assertEquals("rocky 1 and rocky 2 are big", metadata.get(IPTC.ADDITIONAL_MODEL_INFO));

    List<String> orgCodes = Arrays.asList(metadata.getValues(IPTC.ORGANISATION_CODE));
    assertEquals(2, orgCodes.size());
    assertEquals("ASPP", orgCodes.get(0));
    assertEquals("OTHER_ORG", orgCodes.get(1));

    // List<String> cvTerms = Arrays.asList(metadata.getValues(IPTC.CONTROLLED_VOCABULARY_TERM));

    List<String> modelAges = Arrays.asList(metadata.getValues(IPTC.MODEL_AGE));
    assertEquals(2, modelAges.size());
    assertEquals("1000", modelAges.get(0));
    assertEquals("1001", modelAges.get(1));

    List<String> orgNames = Arrays.asList(metadata.getValues(IPTC.ORGANISATION_NAME));
    assertEquals(2, orgNames.size());
    assertEquals("ASPP", orgNames.get(0));
    assertEquals("Other Org", orgNames.get(1));

    List<String> peopleShown = Arrays.asList(metadata.getValues(IPTC.PERSON));
    assertEquals(2, peopleShown.size());
    assertEquals("rocky 1", peopleShown.get(0));
    assertEquals("rocky 2", peopleShown.get(1));

    assertEquals(
        "http://cv.iptc.org/newscodes/digitalsourcetype/digitalCapture",
        metadata.get(IPTC.DIGITAL_SOURCE_TYPE));
    assertEquals("Photo Bike Tour", metadata.get(IPTC.EVENT));

    assertEquals("RGAUSS", metadata.get(IPTC.IMAGE_SUPPLIER_ID));
    assertEquals("Ray Gauss II", metadata.get(IPTC.IMAGE_SUPPLIER_NAME));
    assertEquals("supplier image ID", metadata.get(IPTC.IMAGE_SUPPLIER_IMAGE_ID));
    assertEquals("3456", metadata.get(IPTC.MAX_AVAIL_HEIGHT));
    assertEquals("5184", metadata.get(IPTC.MAX_AVAIL_WIDTH));
    assertEquals("1.2.0", metadata.get(IPTC.PLUS_VERSION));

    List<String> copyrightOwnerIds = Arrays.asList(metadata.getValues(IPTC.COPYRIGHT_OWNER_ID));
    assertEquals(1, copyrightOwnerIds.size());
    assertEquals("RGAUSS", copyrightOwnerIds.get(0));
    // assertEquals("", copyrightOwnerIds.get(1)); // TODO: Get ExifTool to preserve empty values

    List<String> copyrightOwnerNames = Arrays.asList(metadata.getValues(IPTC.COPYRIGHT_OWNER_NAME));
    assertEquals(2, copyrightOwnerNames.size());
    assertEquals("Ray Gauss II", copyrightOwnerNames.get(0));
    assertEquals("GG", copyrightOwnerNames.get(1));

    List<String> imageCreatorIds = Arrays.asList(metadata.getValues(IPTC.IMAGE_CREATOR_ID));
    assertEquals(1, imageCreatorIds.size());
    assertEquals("RGAUSS", imageCreatorIds.get(0));
    // assertEquals("", imageCreatorIds.get(1)); // TODO: Get ExifTool to preserve empty values

    assertTrue(metadata.isMultiValued(IPTC.IMAGE_CREATOR_NAME));
    List<String> imageCreatorNames = Arrays.asList(metadata.getValues(IPTC.IMAGE_CREATOR_NAME));
    assertEquals(2, imageCreatorNames.size());
    assertEquals("Ray Gauss II", imageCreatorNames.get(0));
    assertEquals("GG", imageCreatorNames.get(1));

    List<String> licensorIds = Arrays.asList(metadata.getValues(IPTC.LICENSOR_ID));
    assertEquals("RGAUSS", licensorIds.get(0));

    assertTrue(metadata.isMultiValued(IPTC.LICENSOR_NAME));
    List<String> licensorNames = Arrays.asList(metadata.getValues(IPTC.LICENSOR_NAME));
    assertEquals(2, licensorNames.size());
    assertEquals("Ray Gauss II", licensorNames.get(0));
    assertEquals("GG", licensorNames.get(1));

    // Photoshop does not support licensor addresses, cities, or countries

    List<String> licensorEmails = Arrays.asList(metadata.getValues(IPTC.LICENSOR_EMAIL));
    assertEquals("*****@*****.**", licensorEmails.get(0));
    // assertEquals("", licensorEmails.get(1)); // TODO: Get ExifTool to preserve empty values
    List<String> licensorTel1 = Arrays.asList(metadata.getValues(IPTC.LICENSOR_TELEPHONE_1));
    assertEquals("555-5555", licensorTel1.get(0));
    // assertEquals("", licensorTel1.get(1)); // TODO: Get ExifTool to preserve empty values
    List<String> licensorTel2 = Arrays.asList(metadata.getValues(IPTC.LICENSOR_TELEPHONE_2));
    assertEquals("555-4444", licensorTel2.get(0));
    // assertEquals("", licensorTel2.get(1)); // TODO: Get ExifTool to preserve empty values
    List<String> licensorUrls = Arrays.asList(metadata.getValues(IPTC.LICENSOR_URL));
    assertEquals("http://rgauss.com", licensorUrls.get(0));
    // assertEquals("", licensorUrls.get(1)); // TODO: Get ExifTool to preserve empty values

    assertEquals("Age Unknown", metadata.get(IPTC.MINOR_MODEL_AGE_DISCLOSURE));
    List<String> modelReleaseIds = Arrays.asList(metadata.getValues(IPTC.MODEL_RELEASE_ID));
    assertEquals("model release id 1", modelReleaseIds.get(0));
    assertEquals("model release id 2", modelReleaseIds.get(1));
    assertEquals("Not Applicable", metadata.get(IPTC.MODEL_RELEASE_STATUS));

    List<String> propertyReleaseIds = Arrays.asList(metadata.getValues(IPTC.PROPERTY_RELEASE_ID));
    assertEquals("prop release id 1", propertyReleaseIds.get(0));
    assertEquals("prop release id 2", propertyReleaseIds.get(1));
    assertEquals("Not Applicable", metadata.get(IPTC.PROPERTY_RELEASE_STATUS));

    List<String> aoCopyright =
        Arrays.asList(metadata.getValues(IPTC.ARTWORK_OR_OBJECT_DETAIL_COPYRIGHT_NOTICE));
    assertEquals("Ray Gauss II", aoCopyright.get(0));
    // assertEquals("", aoCopyright.get(1)); // TODO: Get ExifTool to preserve empty values
    // assertEquals("", aoCopyright.get(2)); // TODO: Get ExifTool to preserve empty values
    List<String> aoCreator =
        Arrays.asList(metadata.getValues(IPTC.ARTWORK_OR_OBJECT_DETAIL_CREATOR));
    assertEquals("Mother Nature", aoCreator.get(0));
    assertEquals("Man", aoCreator.get(1));
    assertEquals("Mother Nature", aoCreator.get(2));
    List<String> aoDateCreated =
        Arrays.asList(metadata.getValues(IPTC.ARTWORK_OR_OBJECT_DETAIL_DATE_CREATED));
    assertEquals("1890:01:01", aoDateCreated.get(0));
    // assertEquals("", aoDateCreated.get(1)); // TODO: Get ExifTool to preserve empty values
    assertEquals("1901:02:01", aoDateCreated.get(1));
    // assertEquals("", aoDateCreated.get(2)); // TODO: Get ExifTool to preserve empty values
    List<String> aoSource = Arrays.asList(metadata.getValues(IPTC.ARTWORK_OR_OBJECT_DETAIL_SOURCE));
    assertEquals("National Park Service", aoSource.get(0));
    // assertEquals("", aoSource.get(1)); // TODO: Get ExifTool to preserve empty values
    // assertEquals("", aoSource.get(2)); // TODO: Get ExifTool to preserve empty values
    List<String> aoSourceInventoryNum =
        Arrays.asList(metadata.getValues(IPTC.ARTWORK_OR_OBJECT_DETAIL_SOURCE_INVENTORY_NUMBER));
    assertEquals("123456", aoSourceInventoryNum.get(0));
    // assertEquals("", aoSourceInventoryNum.get(1)); // TODO: Get ExifTool to preserve empty values
    assertEquals(
        "654321",
        aoSourceInventoryNum.get(
            1)); // This should be index 2, TODO: Get ExifTool to preserve empty values
    List<String> aoSourceTitles =
        Arrays.asList(metadata.getValues(IPTC.ARTWORK_OR_OBJECT_DETAIL_TITLE));
    assertEquals("Rock Creek Stream Bank", aoSourceTitles.get(0));
    assertEquals("Pollution", aoSourceTitles.get(1));
    assertEquals("Some Tree", aoSourceTitles.get(2));

    List<String> locationShownCity = Arrays.asList(metadata.getValues(IPTC.LOCATION_SHOWN_CITY));
    assertEquals("Washington", locationShownCity.get(0));
    // assertEquals("", locationShownCity.get(1)); // TODO: Get ExifTool to preserve empty values
    List<String> locationShownCountryCode =
        Arrays.asList(metadata.getValues(IPTC.LOCATION_SHOWN_COUNTRY_CODE));
    assertEquals("US", locationShownCountryCode.get(0));
    // assertEquals("", locationShownCountryCode.get(1)); // TODO: Get ExifTool to preserve empty
    // values
    List<String> locationShownCountryName =
        Arrays.asList(metadata.getValues(IPTC.LOCATION_SHOWN_COUNTRY_NAME));
    assertEquals("United States", locationShownCountryName.get(0));
    // assertEquals("", locationShownCountryName.get(1)); // TODO: Get ExifTool to preserve empty
    // values
    List<String> locationShownState =
        Arrays.asList(metadata.getValues(IPTC.LOCATION_SHOWN_PROVINCE_OR_STATE));
    assertEquals("D.C.", locationShownState.get(0));
    // assertEquals("", locationShownState.get(1)); // TODO: Get ExifTool to preserve empty values
    List<String> locationShownSublocation =
        Arrays.asList(metadata.getValues(IPTC.LOCATION_SHOWN_SUBLOCATION));
    assertEquals("Rock Creek Park Sub", locationShownSublocation.get(0));
    assertEquals("Stream Section", locationShownSublocation.get(1));
    List<String> locationShownWorldRegion =
        Arrays.asList(metadata.getValues(IPTC.LOCATION_SHOWN_WORLD_REGION));
    assertEquals("North America", locationShownWorldRegion.get(0));
    // assertEquals("", locationShownWorldRegion.get(1)); // TODO: Get ExifTool to preserve empty
    // values

    assertEquals("Washington", metadata.get(IPTC.LOCATION_CREATED_CITY));
    assertEquals("US", metadata.get(IPTC.LOCATION_CREATED_COUNTRY_CODE));
    assertEquals("United States", metadata.get(IPTC.LOCATION_CREATED_COUNTRY_NAME));
    assertEquals("D.C.", metadata.get(IPTC.LOCATION_CREATED_PROVINCE_OR_STATE));
    assertEquals("Rock Creek Park", metadata.get(IPTC.LOCATION_CREATED_SUBLOCATION));
    assertEquals("North America", metadata.get(IPTC.LOCATION_CREATED_WORLD_REGION));

    assertTrue(IPTC.REGISTRY_ENTRY_CREATED_ORGANISATION_ID.isMultiValuePermitted());
    assertTrue(metadata.isMultiValued(IPTC.REGISTRY_ENTRY_CREATED_ORGANISATION_ID));
    List<String> registryEntryOrgIds =
        Arrays.asList(metadata.getValues(IPTC.REGISTRY_ENTRY_CREATED_ORGANISATION_ID));
    assertEquals(2, registryEntryOrgIds.size());
    assertEquals("PLUS", registryEntryOrgIds.get(0));
    // assertEquals("", registryEntryOrgIds.get(1)); // TODO: Get ExifTool to preserve empty values
    assertEquals(
        "ORG 2",
        registryEntryOrgIds.get(
            1)); // This should be index 2, TODO: Get ExifTool to preserve empty values

    assertTrue(IPTC.REGISTRY_ENTRY_CREATED_ORGANISATION_ID.isMultiValuePermitted());
    assertTrue(metadata.isMultiValued(IPTC.REGISTRY_ENTRY_CREATED_ITEM_ID));
    List<String> registryEntryItemIds =
        Arrays.asList(metadata.getValues(IPTC.REGISTRY_ENTRY_CREATED_ITEM_ID));
    assertEquals(registryEntryItemIds.size(), 3);
    assertEquals("100-ABC-ABC-555", registryEntryItemIds.get(0));
    assertEquals("11223344", registryEntryItemIds.get(1));
    assertEquals("55667788", registryEntryItemIds.get(2));
  }
 @Override
 public void setTimeZone(TimeZone zone) {
   super.setTimeZone(zone);
   calculatePersianDate();
 }
Пример #28
0
  public void actionPerformed(ActionEvent aE) {
    if (aE.getSource() == plotButton) {
      if (sourceTable.sourceListModel.isSelectionEmpty() == false
          && sourceTable.getValueAt(sourceTable.getSelectedRow(), 0) != null) {
        // Build dates
        final GregorianCalendar startDate = new GregorianCalendar();
        final GregorianCalendar endDate = new GregorianCalendar();
        startDate.setTimeZone(TimeZone.getTimeZone("GMT+10"));
        endDate.setTimeZone(TimeZone.getTimeZone("GMT+10"));
        try {
          Calendar now = GregorianCalendar.getInstance();
          now.setTimeZone(TimeZone.getTimeZone("GMT+10"));
          now.set(Calendar.HOUR_OF_DAY, 0);
          now.set(Calendar.MINUTE, 0);
          now.set(Calendar.SECOND, 0);
          now.set(Calendar.MILLISECOND, 0);
          if (week.isSelected()) {
            startDate.setTimeInMillis(now.getTimeInMillis() - ((long) 7 * 24 * 60 * 60 * 1000));
            endDate.setTimeInMillis(now.getTimeInMillis());
          } else if (month.isSelected()) {
            startDate.setTimeInMillis(now.getTimeInMillis() - ((long) 28 * 24 * 60 * 60 * 1000));
            endDate.setTimeInMillis(now.getTimeInMillis());
          } else if (thisMonth.isSelected()) {
            Calendar monthStart = new GregorianCalendar();
            monthStart.setTimeZone(TimeZone.getTimeZone("GMT+10"));
            monthStart.setTimeInMillis(now.getTimeInMillis());
            if (monthStart.get(Calendar.DAY_OF_MONTH) == 1) {
              monthStart.set(Calendar.MONTH, monthStart.get(Calendar.MONTH) - 1);
            }
            monthStart.set(Calendar.DAY_OF_MONTH, 1);
            startDate.setTimeInMillis(monthStart.getTimeInMillis());
            endDate.setTimeInMillis(now.getTimeInMillis());
          } else {
            startDate.setTime(dateParser.parse(startDateS.getSelectedItem().toString() + " 00:00"));
            endDate.setTime(dateParser.parse(endDateS.getSelectedItem().toString() + " 00:00"));
            endDate.add(Calendar.DATE, 1); // for "inclusive"
          }
          // SimpleDateFormat sqlDateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
          // sqlDateFormatter.setTimeZone(TimeZone.getTimeZone("GMT+10"));
          // System.out.println(sqlDateFormatter.format(startDate.getTimeInMillis())+"
          // "+sqlDateFormatter.format(endDate.getTimeInMillis()));

          if (startDate.before(endDate)) {
            loadingLayerUI.start();

            final Thread fetchMissingData =
                new Thread( // Thread to fetch missing Data in
                    new Runnable() {
                      public void run() {
                        missingPlotter.setData(
                            dbConn,
                            siteTable.getValueAt(siteTable.getSelectedRow(), 0).toString(),
                            getSelectedSources(sourceTable.getSelectedRows()),
                            startDate.getTimeInMillis(),
                            endDate.getTimeInMillis(),
                            1440);
                      }
                    });

            fetchMissingData.start(); // Fetch Missing Data

            new Thread(
                    new Runnable() { // new Thread to wait for missing data to complete and then
                                     // ungrey window
                      public void run() {
                        try {
                          fetchMissingData.join();
                        } catch (InterruptedException e) {
                          e.printStackTrace();
                        }
                        loadingLayerUI.stop();
                      }
                    })
                .start();

          } else {
            JOptionPane.showMessageDialog(null, "Error: Start date must be before End Date.");
          }
        } catch (ParseException e) {
          e.printStackTrace();
          JOptionPane.showMessageDialog(
              null, "Error: could not build valid dates from the selection made.");
        }
      } else {
        JOptionPane.showMessageDialog(
            null,
            "Error Code 002\r\nPlease select a file to Analyse.",
            "Error",
            JOptionPane.ERROR_MESSAGE);
      }
    }
  }
Пример #29
0
  public static void main(String[] args) throws Throwable {

    int N = 10000;
    long t1970 = new java.util.Date(70, 0, 01).getTime();
    Random r = new Random();
    for (int i = 0; i < N; i++) {
      int days = r.nextInt(50) * 365 + r.nextInt(365);
      long secs = t1970 + days * 86400 + r.nextInt(86400);
      int nanos = r.nextInt(NANOS_PER_SECOND);
      int nanos_ms = nanos / 1000000 * 1000000; // millis precision
      long millis = secs * 1000 + r.nextInt(1000);
      LocalDateTime ldt = LocalDateTime.ofEpochSecond(secs, nanos, ZoneOffset.UTC);
      LocalDateTime ldt_ms = LocalDateTime.ofEpochSecond(secs, nanos_ms, ZoneOffset.UTC);
      Instant inst = Instant.ofEpochSecond(secs, nanos);
      Instant inst_ms = Instant.ofEpochSecond(secs, nanos_ms);
      ///////////// java.util.Date /////////////////////////
      Date jud = new java.util.Date(millis);
      Instant inst0 = jud.toInstant();
      if (jud.getTime() != inst0.toEpochMilli() || !jud.equals(Date.from(inst0))) {
        System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
        throw new RuntimeException("FAILED: j.u.d -> instant -> j.u.d");
      }
      // roundtrip only with millis precision
      Date jud0 = Date.from(inst_ms);
      if (jud0.getTime() != inst_ms.toEpochMilli() || !inst_ms.equals(jud0.toInstant())) {
        System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
        throw new RuntimeException("FAILED: instant -> j.u.d -> instant");
      }
      //////////// java.util.GregorianCalendar /////////////
      GregorianCalendar cal = new GregorianCalendar();
      // non-roundtrip of tz name between j.u.tz and j.t.zid
      cal.setTimeZone(TimeZone.getTimeZone(ZoneId.systemDefault()));
      cal.setGregorianChange(new java.util.Date(Long.MIN_VALUE));
      cal.setFirstDayOfWeek(Calendar.MONDAY);
      cal.setMinimalDaysInFirstWeek(4);
      cal.setTimeInMillis(millis);
      ZonedDateTime zdt0 = cal.toZonedDateTime();
      if (cal.getTimeInMillis() != zdt0.toInstant().toEpochMilli()
          || !cal.equals(GregorianCalendar.from(zdt0))) {
        System.out.println("cal:" + cal);
        System.out.println("zdt:" + zdt0);
        System.out.println("calNew:" + GregorianCalendar.from(zdt0));
        System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
        throw new RuntimeException("FAILED: gcal -> zdt -> gcal");
      }
      inst0 = cal.toInstant();
      if (cal.getTimeInMillis() != inst0.toEpochMilli()) {
        System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
        throw new RuntimeException("FAILED: gcal -> zdt");
      }
      ZonedDateTime zdt = ZonedDateTime.of(ldt_ms, ZoneId.systemDefault());
      GregorianCalendar cal0 = GregorianCalendar.from(zdt);
      if (zdt.toInstant().toEpochMilli() != cal0.getTimeInMillis()
          || !zdt.equals(GregorianCalendar.from(zdt).toZonedDateTime())) {
        System.out.printf("ms: %16d  ns: %10d  ldt:[%s]%n", millis, nanos, ldt);
        throw new RuntimeException("FAILED: zdt -> gcal -> zdt");
      }
    }

    ///////////// java.util.TimeZone /////////////////////////
    for (String zidStr : TimeZone.getAvailableIDs()) {
      // TBD: tzdt intergration
      if (zidStr.startsWith("SystemV")
          || zidStr.contains("Riyadh8")
          || zidStr.equals("US/Pacific-New")
          || zidStr.equals("EST")
          || zidStr.equals("HST")
          || zidStr.equals("MST")) {
        continue;
      }
      ZoneId zid = ZoneId.of(zidStr, ZoneId.SHORT_IDS);
      if (!zid.equals(TimeZone.getTimeZone(zid).toZoneId())) {
        throw new RuntimeException("FAILED: zid -> tz -> zid :" + zidStr);
      }
      TimeZone tz = TimeZone.getTimeZone(zidStr);
      // no round-trip for alias and "GMT"
      if (!tz.equals(TimeZone.getTimeZone(tz.toZoneId()))
          && !ZoneId.SHORT_IDS.containsKey(zidStr)
          && !zidStr.startsWith("GMT")) {
        throw new RuntimeException("FAILED: tz -> zid -> tz :" + zidStr);
      }
    }
    System.out.println("Passed!");
  }
  /** Creates new form frmAsignarTransporte */
  public frmAsignarTransporte() {
    initComponents();
    gestorH.actualizarUsuario(labelusuario);
    txtFecha.setEditable(false);
    txtFecha.setEnabled(false);
    txtHora.setEditable(false);
    txtHora.setEnabled(false);
    // setear el campo de fecha con la del sistema
    GregorianCalendar gc = new GregorianCalendar();
    GregorianCalendar.getInstance();
    gc.setTimeZone(TimeZone.getTimeZone("GMT-3"));
    gc.get(Calendar.DAY_OF_WEEK);
    gc.get(Calendar.MONTH);
    gc.get(Calendar.YEAR);
    SimpleDateFormat formateador = new SimpleDateFormat("dd-MM-yyyy");
    txtFecha.setText(formateador.format(gc.getTime()));
    // setear el campo de hora con la del sistema
    GregorianCalendar calendario = new GregorianCalendar();
    GregorianCalendar.getInstance();
    gc.setTimeZone(TimeZone.getTimeZone("GMT-3"));
    calendario.get(Calendar.HOUR);
    calendario.get(Calendar.MINUTE);
    SimpleDateFormat formateadorHora = new SimpleDateFormat("HH:mm");
    txtHora.setText(formateadorHora.format(calendario.getTime()));

    // Las siguientes lineas son para dar a la pantalla el tamaño requerido y luego centrarla en la
    // pantalla.
    Toolkit kit = Toolkit.getDefaultToolkit();
    Dimension tamanioPantalla = kit.getScreenSize();
    int ancho = 820;
    int alto = 570;
    //        int posX = (int) ((tamanioPantalla.width - ancho) / 2);
    //        int posY = (int) ((tamanioPantalla.height - alto) / 2);
    this.setSize(ancho, alto);
    this.setLocation(260, 30);

    // redimensionar columnas tabla
    tblViaje.getColumnModel().getColumn(0).setPreferredWidth(50);
    tblViaje.getColumnModel().getColumn(1).setPreferredWidth(50);
    tblViaje.getColumnModel().getColumn(2).setPreferredWidth(100);
    tblVehiculo.getColumnModel().getColumn(0).setPreferredWidth(100);
    tblVehiculo.getColumnModel().getColumn(1).setPreferredWidth(100);
    // centrar cabecera jtable
    DefaultTableCellRenderer renderer =
        (DefaultTableCellRenderer) tblVehiculo.getTableHeader().getDefaultRenderer();
    renderer.setHorizontalAlignment(0);
    DefaultTableCellRenderer renderer2 =
        (DefaultTableCellRenderer) tblViaje.getTableHeader().getDefaultRenderer();
    renderer2.setHorizontalAlignment(0);

    Iterator ite = gestorH.listarClase(Viaje.class).iterator();
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy");
    SimpleDateFormat sdfguion = new SimpleDateFormat("dd-MM-yyyy");
    while (ite.hasNext()) {
      Viaje viaje = (Viaje) ite.next();
      Date fecha1 = sdf.parse(viaje.getFecha(), new ParsePosition(0));
      Date fecha3 = sdfguion.parse(txtFecha.getText(), new ParsePosition(0));
      if (viaje.getEstado().equalsIgnoreCase("En Proceso")
          && (viaje.getTipoViaje().getNombreTipoViaje().equalsIgnoreCase("Traslado a Puerto")
              || viaje
                  .getTipoViaje()
                  .getNombreTipoViaje()
                  .equalsIgnoreCase("Traslado a Establecimiento"))) {
        if (fecha1.before(fecha3)) {
          viaje.setEstado("Finalizado");
          viaje.getVehiculo().setEstado("Disponible");
        }
      }
    }

    gestorA.RellenarTablaViajes(tblViaje);
  }