Example usage for java.time ZoneId of

List of usage examples for java.time ZoneId of

Introduction

In this page you can find the example usage for java.time ZoneId of.

Prototype

public static ZoneId of(String zoneId) 

Source Link

Document

Obtains an instance of ZoneId from an ID ensuring that the ID is valid and available for use.

Usage

From source file:org.silverpeas.web.socialnetwork.myprofil.servlets.MyProfilRequestRouter.java

private void updateUserSettings(HttpServletRequest request, MyProfilSessionController sc) {
    UserPreferences preferences = sc.getPreferences();
    preferences.setLanguage(request.getParameter("SelectedUserLanguage"));
    preferences.setZoneId(ZoneId.of(request.getParameter("SelectedUserZoneId")));
    preferences.setLook(request.getParameter("SelectedLook"));
    preferences.enableThesaurus(Boolean.valueOf(request.getParameter("opt_thesaurusStatus")));
    preferences.enableDragAndDrop(Boolean.valueOf(request.getParameter("opt_dragDropStatus")));
    preferences.enableWebdavEdition(Boolean.valueOf(request.getParameter("opt_webdavEditingStatus")));
    LookHelper lookHelper = getLookHelper(request);
    if (lookHelper != null && lookHelper.isMenuPersonalisationEnabled()
            && StringUtil.isDefined(request.getParameter("MenuDisplay"))) {
        preferences.setDisplay(UserMenuDisplay.valueOf(request.getParameter("MenuDisplay")));
        lookHelper.setDisplayUserMenu(preferences.getDisplay());
    }/*  w w w .ja va  2 s.  c  o  m*/
    String selectedWorkSpace = request.getParameter("SelectedWorkSpace");
    if (!StringUtil.isDefined(selectedWorkSpace)) {
        preferences.setPersonalWorkSpaceId("");
    } else {
        preferences.setPersonalWorkSpaceId(selectedWorkSpace);
    }
    sc.savePreferences(preferences);
}

From source file:org.silverpeas.core.calendar.notification.CalendarContributionReminderUserNotificationTest.java

@Test
public void durationReminderWithAnotherUserZoneIdOnSimpleEventOf2HoursShouldWork() throws Exception {
    receiver.getUserPreferences().setZoneId(ZoneId.of("Asia/Muscat"));
    final DurationReminder durationReminder = initReminderBuilder(
            setupSimpleEventOn2Hours(ZoneId.systemDefault())).triggerBefore(0, TimeUnit.MINUTE, "");
    triggerDateTime(durationReminder);/*from   ww w. j a v a 2 s. c om*/
    final Map<String, String> titles = computeNotificationTitles(durationReminder);
    assertThat(titles.get(DE), is("Reminder about the event super test - 21.02.2018 21:00 - 23:00 (UTC)"));
    assertThat(titles.get(EN), is("Reminder about the event super test - 02/21/2018 21:00 - 23:00 (UTC)"));
    assertThat(titles.get(FR), is("Rappel sur l'vnement super test - 21/02/2018 21:00 - 23:00 (UTC)"));
    final Map<String, String> contents = computeNotificationContents(durationReminder);
    assertThat(contents.get(DE),
            is("REMINDER: The event <b>super test</b> will be on 21.02.2018 from 21:00 to 23:00 (UTC)."));
    assertThat(contents.get(EN),
            is("REMINDER: The event <b>super test</b> will be on 02/21/2018 from 21:00 to 23:00 (UTC)."));
    assertThat(contents.get(FR),
            is("RAPPEL : L'vnement <b>super test</b> aura lieu le 21/02/2018 de 21:00  23:00 (UTC)."));
}

From source file:org.apache.james.mailbox.elasticsearch.json.MessageToElasticSearchJsonTest.java

@Test
public void convertToJsonWithoutAttachmentShouldConvertEmailBoby() throws IOException {
    // Given//w  ww  . j a va  2s .  co m
    MailboxMessage message = new SimpleMailboxMessage(MESSAGE_ID, null, SIZE, BODY_START_OCTET,
            new SharedByteArrayInputStream(IOUtils.toByteArray(
                    ClassLoader.getSystemResourceAsStream("eml/emailWithNonIndexableAttachment.eml"))),
            new FlagsBuilder().add(Flags.Flag.DELETED, Flags.Flag.SEEN).add("debian", "security").build(),
            propertyBuilder, MAILBOX_ID);
    message.setModSeq(MOD_SEQ);
    message.setUid(UID);

    // When
    MessageToElasticSearchJson messageToElasticSearchJson = new MessageToElasticSearchJson(
            new DefaultTextExtractor(), ZoneId.of("Europe/Paris"), IndexAttachments.NO);
    String convertToJsonWithoutAttachment = messageToElasticSearchJson.convertToJsonWithoutAttachment(message,
            ImmutableList.of(new MockMailboxSession("username").getUser()));

    // Then
    assertThatJson(convertToJsonWithoutAttachment).when(IGNORING_ARRAY_ORDER).when(IGNORING_VALUES)
            .isEqualTo(IOUtils.toString(ClassLoader
                    .getSystemResource("eml/emailWithNonIndexableAttachmentWithoutAttachment.json")));
}

From source file:org.silverpeas.core.calendar.notification.CalendarContributionReminderUserNotificationTest.java

@Test
public void durationReminderWithAnotherBeforeCalendarZoneIdOnSimpleEventOf2HoursShouldWork() throws Exception {
    final CalendarEvent calendarEvent = setupSimpleEventOn2Hours(ZoneId.of("America/Cancun"));
    final DurationReminder durationReminder = initReminderBuilder(calendarEvent).triggerBefore(0,
            TimeUnit.MINUTE, "");
    triggerDateTime(durationReminder);// w  w w  .  j av  a2s.  c o m
    final Map<String, String> titles = computeNotificationTitles(durationReminder);
    assertThat(titles.get(DE),
            is("Reminder about the event super test - 21.02.2018 21:00 - 23:00 (America/Cancun)"));
    assertThat(titles.get(EN),
            is("Reminder about the event super test - 02/21/2018 21:00 - 23:00 (America/Cancun)"));
    assertThat(titles.get(FR),
            is("Rappel sur l'vnement super test - 21/02/2018 21:00 - 23:00 (America/Cancun)"));
    final Map<String, String> contents = computeNotificationContents(durationReminder);
    assertThat(contents.get(DE), is(
            "REMINDER: The event <b>super test</b> will be on 21.02.2018 from 21:00 to 23:00 (America/Cancun)."));
    assertThat(contents.get(EN), is(
            "REMINDER: The event <b>super test</b> will be on 02/21/2018 from 21:00 to 23:00 (America/Cancun)."));
    assertThat(contents.get(FR), is(
            "RAPPEL : L'vnement <b>super test</b> aura lieu le 21/02/2018 de 21:00  23:00 (America/Cancun)."));
}

From source file:org.apache.tinkerpop.gremlin.structure.io.Model.java

private Model() {
    final Configuration conf = new BaseConfiguration();
    conf.setProperty(TinkerGraph.GREMLIN_TINKERGRAPH_DEFAULT_VERTEX_PROPERTY_CARDINALITY,
            VertexProperty.Cardinality.list.name());
    final TinkerGraph graph = TinkerGraph.open(conf);
    TinkerFactory.generateTheCrew(graph);
    final GraphTraversalSource g = graph.traversal();

    final Compatibility[] noTypeGraphSONPlusGryo3_2_3 = Compatibilities.with(GryoCompatibility.class)
            .beforeRelease("3.2.4").join(Compatibilities.UNTYPED_GRAPHSON).matchToArray();
    final Compatibility[] noTypeGraphSONPlusGryo3_3_0 = Compatibilities.with(GryoCompatibility.class)
            .beforeRelease("3.3.0").join(Compatibilities.UNTYPED_GRAPHSON).matchToArray();
    final Compatibility[] noGraphSONBeforeV3 = Compatibilities.with(GraphSONCompatibility.class)
            .configuredAs(".*v2d0-partial|v1d0|v2d0-no-types").join(Compatibilities.GRYO_ONLY).matchToArray();

    // IMPORTANT - the "title" or name of the Entry needs to be unique

    // Serialization of Class in Gryo 1.0 had a bug that prevented proper operation in versions prior to 3.2.4.
    addCoreEntry(File.class, "Class", "", noTypeGraphSONPlusGryo3_2_3);
    addCoreEntry(new Date(1481750076295L), "Date");
    addCoreEntry(100.00d, "Double");
    addCoreEntry(100.00f, "Float", "", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addCoreEntry(100, "Integer");
    addCoreEntry(Arrays.asList(1, "person", true), "List",
            "List is used to distinguish between different collection types as JSON is not explicit enough for all of Gremlin's requirements.",
            noGraphSONBeforeV3);//from   w w  w .  j  a  va  2s .  c  o m
    addCoreEntry(100L, "Long", "", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    final Map<Object, Object> map = new HashMap<>();
    map.put("test", 123);
    map.put(new Date(1481750076295L), "red");
    map.put(Arrays.asList(1, 2, 3), new Date(1481750076295L));
    addCoreEntry(map, "Map",
            "Map is redefined so that to provide the ability to allow for non-String keys, which is not possible in JSON.",
            noGraphSONBeforeV3);
    addCoreEntry(new HashSet<>(Arrays.asList(1, "person", true)), "Set",
            "Allows a JSON collection to behave as a Set.", noGraphSONBeforeV3);
    // Timestamp was added to Gryo 1.0 as of 3.2.4. It was not supported in 3.2.3.
    addCoreEntry(new java.sql.Timestamp(1481750076295L), "Timestamp", "", noTypeGraphSONPlusGryo3_2_3);
    addCoreEntry(UUID.fromString("41d2e28a-20a4-4ab0-b379-d810dede3786"), "UUID");

    addGraphStructureEntry(graph.edges().next(), "Edge", "");
    addGraphStructureEntry(g.V().out().out().path().next(), "Path", "");
    addGraphStructureEntry(graph.edges().next().properties().next(), "Property", "");
    // TODO: missing a stargraph deserializer in graphson v1/v2
    addEntry("Graph Structure", StarGraph.of(graph.vertices().next()), "StarGraph", "",
            Compatibilities.GRYO_ONLY.match());
    addGraphStructureEntry(graph, "TinkerGraph",
            "`TinkerGraph` has a custom serializer that is registered as part of the `TinkerIoRegistry`.");
    // TODO: tree has bugs for graphson
    addEntry("Graph Structure", g.V(1).out().out().tree().next(), "Tree", "",
            Compatibilities.GRYO_ONLY.match());
    addGraphStructureEntry(graph.vertices().next(), "Vertex", "");
    addGraphStructureEntry(graph.vertices().next().properties().next(), "VertexProperty", "");

    addGraphProcessEntry(SackFunctions.Barrier.normSack, "Barrier", "",
            Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addGraphProcessEntry(new Bytecode.Binding("x", 1), "Binding",
            "A \"Binding\" refers to a `Bytecode.Binding`.", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addGraphProcessEntry(g.V().hasLabel("person").out().in().tree().asAdmin().getBytecode(), "Bytecode",
            "The following `Bytecode` example represents the traversal of `g.V().hasLabel('person').out().in().tree()`. Obviously the serialized `Bytecode` woudl be quite different for the endless variations of commands that could be used together in the Gremlin language.",
            Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addGraphProcessEntry(VertexProperty.Cardinality.list, "Cardinality", "",
            Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addGraphProcessEntry(Column.keys, "Column", "", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addGraphProcessEntry(Direction.OUT, "Direction", "", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addGraphProcessEntry(Operator.sum, "Operator", "", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addGraphProcessEntry(Order.incr, "Order", "", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addGraphProcessEntry(TraversalOptionParent.Pick.any, "Pick", "",
            Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addGraphProcessEntry(Pop.all, "Pop", "", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addGraphProcessEntry(org.apache.tinkerpop.gremlin.util.function.Lambda.function("{ it.get() }"), "Lambda",
            "", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    final TraversalMetrics tm = createStaticTraversalMetrics();
    final MutableMetrics metrics = new MutableMetrics(tm.getMetrics("7.0.0()"));
    metrics.addNested(new MutableMetrics(tm.getMetrics("3.0.0()")));
    addGraphProcessEntry(metrics, "Metrics", "", noTypeGraphSONPlusGryo3_3_0);
    addGraphProcessEntry(P.gt(0), "P", "", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addGraphProcessEntry(P.within(1), "P within", "", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addGraphProcessEntry(P.without(1, 2), "P without", "", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    // A bug in the the Gryo serialization of ConjunctiveP prevented its proper serialization in versions prior to 3.3.0 and 3.2.4.
    addGraphProcessEntry(P.gt(0).and(P.lt(10)), "P and", "", noTypeGraphSONPlusGryo3_2_3);
    // A bug in the the Gryo serialization of ConjunctiveP prevented its proper serialization in versions prior to 3.3.0 and 3.2.4.
    addGraphProcessEntry(P.gt(0).or(P.within(-1, -10, -100)), "P or", "", noTypeGraphSONPlusGryo3_2_3);
    addGraphProcessEntry(Scope.local, "Scope", "", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addGraphProcessEntry(T.label, "T", "", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addGraphProcessEntry(createStaticTraversalMetrics(), "TraversalMetrics", "", noTypeGraphSONPlusGryo3_3_0);
    addGraphProcessEntry(g.V().hasLabel("person").asAdmin().nextTraverser(), "Traverser", "",
            Compatibilities.UNTYPED_GRAPHSON.matchToArray());

    final Map<String, Object> requestBindings = new HashMap<>();
    requestBindings.put("x", 1);

    final Map<String, Object> requestAliases = new HashMap<>();
    requestAliases.put("g", "social");

    // RequestMessage is not testable prior to Gryo 3.0 as serialization was handled by an intermediate component
    // (MessageSerializer) that doesn't fit the test model.
    RequestMessage requestMessage;
    requestMessage = RequestMessage.build("authentication")
            .overrideRequestId(UUID.fromString("cb682578-9d92-4499-9ebc-5c6aa73c5397"))
            .add("saslMechanism", "PLAIN", "sasl", "AHN0ZXBocGhlbgBwYXNzd29yZA==").create();
    addRequestMessageEntry(requestMessage, "Authentication Response",
            "The following `RequestMessage` is an example of the response that should be made to a SASL-based authentication challenge.");
    requestMessage = RequestMessage.build("eval").processor("session")
            .overrideRequestId(UUID.fromString("cb682578-9d92-4499-9ebc-5c6aa73c5397"))
            .add("gremlin", "g.V(x)", "bindings", requestBindings, "language", "gremlin-groovy", "session",
                    UUID.fromString("41d2e28a-20a4-4ab0-b379-d810dede3786"))
            .create();
    addRequestMessageEntry(requestMessage, "Session Eval",
            "The following `RequestMessage` is an example of a simple session request for a script evaluation with parameters.");
    requestMessage = RequestMessage.build("eval").processor("session")
            .overrideRequestId(UUID.fromString("cb682578-9d92-4499-9ebc-5c6aa73c5397"))
            .add("gremlin", "social.V(x)", "bindings", requestBindings, "language", "gremlin-groovy", "aliases",
                    requestAliases, "session", UUID.fromString("41d2e28a-20a4-4ab0-b379-d810dede3786"))
            .create();
    addRequestMessageEntry(requestMessage, "Session Eval Aliased",
            "The following `RequestMessage` is an example of a session request for a script evaluation with an alias that binds the `TraversalSource` of \"g\" to \"social\".");
    requestMessage = RequestMessage.build("close").processor("session")
            .overrideRequestId(UUID.fromString("cb682578-9d92-4499-9ebc-5c6aa73c5397"))
            .add("session", UUID.fromString("41d2e28a-20a4-4ab0-b379-d810dede3786")).create();
    addRequestMessageEntry(requestMessage, "Session Close",
            "The following `RequestMessage` is an example of a request to close a session.");
    requestMessage = RequestMessage.build("eval")
            .overrideRequestId(UUID.fromString("cb682578-9d92-4499-9ebc-5c6aa73c5397"))
            .add("gremlin", "g.V(x)", "bindings", requestBindings, "language", "gremlin-groovy").create();
    addRequestMessageEntry(requestMessage, "Sessionless Eval",
            "The following `RequestMessage` is an example of a simple sessionless request for a script evaluation with parameters.");
    requestMessage = RequestMessage.build("eval")
            .overrideRequestId(UUID.fromString("cb682578-9d92-4499-9ebc-5c6aa73c5397"))
            .add("gremlin", "social.V(x)", "bindings", requestBindings, "language", "gremlin-groovy", "aliases",
                    requestAliases)
            .create();
    addRequestMessageEntry(requestMessage, "Sessionless Eval Aliased",
            "The following `RequestMessage` is an example of a sessionless request for a script evaluation with an alias that binds the `TraversalSource` of \"g\" to \"social\".");

    // ResponseMessage is not testable prior to Gryo 3.0 as serialization was handled by an intermediate component
    // (MessageSerializer) that doesn't fit the test model
    ResponseMessage responseMessage = ResponseMessage
            .build(UUID.fromString("41d2e28a-20a4-4ab0-b379-d810dede3786"))
            .code(org.apache.tinkerpop.gremlin.driver.message.ResponseStatusCode.AUTHENTICATE).create();
    addResponseMessageEntry(responseMessage, "Authentication Challenge",
            "When authentication is enabled, an initial request to the server will result in an authentication challenge. The typical response message will appear as follows, but handling it could be different depending on the SASL implementation (e.g. multiple challenges maybe requested in some cases, but not in the default provided by Gremlin Server).");
    responseMessage = ResponseMessage.build(UUID.fromString("41d2e28a-20a4-4ab0-b379-d810dede3786"))
            .code(org.apache.tinkerpop.gremlin.driver.message.ResponseStatusCode.SUCCESS)
            .result(Collections.singletonList(graph.vertices().next())).create();
    addResponseMessageEntry(responseMessage, "Standard Result",
            "The following `ResponseMessage` is a typical example of the typical successful response Gremlin Server will return when returning results from a script.");

    addExtendedEntry(new BigDecimal(new java.math.BigInteger("123456789987654321123456789987654321")),
            "BigDecimal", "", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addExtendedEntry(new BigInteger("123456789987654321123456789987654321"), "BigInteger", "",
            Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addExtendedEntry(new Byte("1"), "Byte", "", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    // ByteBuffer was added to Gryo 1.0 as of 3.2.4. It was not supported in earlier versions.
    addEntry("Extended", () -> java.nio.ByteBuffer.wrap("some bytes for you".getBytes()), "ByteBuffer", "",
            noTypeGraphSONPlusGryo3_2_3);
    addExtendedEntry("x".charAt(0), "Char", "", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addExtendedEntry(Duration.ofDays(5), "Duration", "The following example is a `Duration` of five days.",
            Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    try {
        // InetAddress was added to Gryo 1.0 as of 3.2.4. It was not supported in earlier versions.
        addEntry("Extended", InetAddress.getByName("localhost"), "InetAddress", "",
                noTypeGraphSONPlusGryo3_2_3);
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
    addExtendedEntry(Instant.parse("2016-12-14T16:39:19.349Z"), "Instant", "",
            Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addExtendedEntry(LocalDate.of(2016, 1, 1), "LocalDate", "",
            Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addExtendedEntry(LocalDateTime.of(2016, 1, 1, 12, 30), "LocalDateTime", "",
            Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addExtendedEntry(LocalTime.of(12, 30, 45), "LocalTime", "",
            Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addExtendedEntry(MonthDay.of(1, 1), "MonthDay", "", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addExtendedEntry(OffsetDateTime.parse("2007-12-03T10:15:30+01:00"), "OffsetDateTime", "",
            Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addExtendedEntry(OffsetTime.parse("10:15:30+01:00"), "OffsetTime", "",
            Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addExtendedEntry(Period.of(1, 6, 15), "Period",
            "The following example is a `Period` of one year, six months and fifteen days.",
            Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addExtendedEntry(new Short("100"), "Short", "", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addExtendedEntry(Year.of(2016), "Year", "The following example is of the `Year` \"2016\".",
            Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addExtendedEntry(YearMonth.of(2016, 6), "YearMonth",
            "The following example is a `YearMonth` of \"June 2016\"",
            Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addExtendedEntry(ZonedDateTime.of(2016, 12, 23, 12, 12, 24, 36, ZoneId.of("GMT+2")), "ZonedDateTime", "",
            Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addExtendedEntry(ZoneOffset.ofHoursMinutesSeconds(3, 6, 9), "ZoneOffset",
            "The following example is a `ZoneOffset` of three hours, six minutes, and nine seconds.",
            Compatibilities.UNTYPED_GRAPHSON.matchToArray());
}

From source file:org.silverpeas.core.calendar.notification.CalendarContributionReminderUserNotificationTest.java

@Test
public void durationReminderWithAnotherAfterCalendarZoneIdOnSimpleEventOf2HoursShouldWork() throws Exception {
    final CalendarEvent calendarEvent = setupSimpleEventOn2Hours(ZoneId.of("Asia/Muscat"));
    final DurationReminder durationReminder = initReminderBuilder(calendarEvent).triggerBefore(0,
            TimeUnit.MINUTE, "");
    triggerDateTime(durationReminder);//from  www  .  j av a2 s .  com
    final Map<String, String> titles = computeNotificationTitles(durationReminder);
    assertThat(titles.get(DE),
            is("Reminder about the event super test - 21.02.2018 21:00 - 23:00 (Asia/Muscat)"));
    assertThat(titles.get(EN),
            is("Reminder about the event super test - 02/21/2018 21:00 - 23:00 (Asia/Muscat)"));
    assertThat(titles.get(FR),
            is("Rappel sur l'vnement super test - 21/02/2018 21:00 - 23:00 (Asia/Muscat)"));
    final Map<String, String> contents = computeNotificationContents(durationReminder);
    assertThat(contents.get(DE), is(
            "REMINDER: The event <b>super test</b> will be on 21.02.2018 from 21:00 to 23:00 (Asia/Muscat)."));
    assertThat(contents.get(EN), is(
            "REMINDER: The event <b>super test</b> will be on 02/21/2018 from 21:00 to 23:00 (Asia/Muscat)."));
    assertThat(contents.get(FR), is(
            "RAPPEL : L'vnement <b>super test</b> aura lieu le 21/02/2018 de 21:00  23:00 (Asia/Muscat)."));
}

From source file:com.tascape.reactor.report.MySqlBaseBean.java

public static long getMillis(String time) {
    if (time == null || time.trim().isEmpty()) {
        return System.currentTimeMillis();
    } else {// w ww  .  j a v  a2  s .  c  om
        LocalDateTime ldt = LocalDateTime.parse(time, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
        LOG.trace("ldt {}", ldt);
        ZoneId zone = ZoneId.of("America/Los_Angeles");
        ldt.atZone(zone);
        LOG.trace("ldt {}", ldt);
        return ldt.toInstant(ZoneOffset.ofHours(-8)).toEpochMilli();
    }
}

From source file:org.silverpeas.core.calendar.notification.CalendarContributionReminderUserNotificationTest.java

@Test
public void durationReminderWithAnotherBeforeUserZoneIdOnSeveralDaysEventOf2HoursShouldWork() throws Exception {
    receiver.getUserPreferences().setZoneId(ZoneId.of("America/Cancun"));
    final DurationReminder durationReminder = initReminderBuilder(
            setupSeveralDaysEventOn2Hours(ZoneId.systemDefault())).triggerBefore(0, TimeUnit.MINUTE, "");
    triggerDateTime(durationReminder);// ww  w . j a va2 s  .c  om
    final Map<String, String> titles = computeNotificationTitles(durationReminder);
    assertThat(titles.get(DE),
            is("Reminder about the event super test - 21.02.2018 23:00 - 22.02.2018 01:00 (UTC)"));
    assertThat(titles.get(EN),
            is("Reminder about the event super test - 02/21/2018 23:00 - 02/22/2018 01:00 (UTC)"));
    assertThat(titles.get(FR),
            is("Rappel sur l'vnement super test - 21/02/2018 23:00 - 22/02/2018 01:00 (UTC)"));
    final Map<String, String> contents = computeNotificationContents(durationReminder);
    assertThat(contents.get(DE), is(
            "REMINDER: The event <b>super test</b> will be from 21.02.2018 at 23:00 to 22.02.2018 at 01:00 (UTC)."));
    assertThat(contents.get(EN), is(
            "REMINDER: The event <b>super test</b> will be from 02/21/2018 at 23:00 to 02/22/2018 at 01:00 (UTC)."));
    assertThat(contents.get(FR), is(
            "RAPPEL : L'vnement <b>super test</b> aura lieu du 21/02/2018  23:00 au 22/02/2018  01:00 (UTC)."));
}

From source file:org.silverpeas.core.calendar.notification.CalendarContributionReminderUserNotificationTest.java

@Test
public void durationReminderWithAnotherAfterUserZoneIdOnSeveralDaysEventOf2HoursShouldWork() throws Exception {
    receiver.getUserPreferences().setZoneId(ZoneId.of("Asia/Muscat"));
    final DurationReminder durationReminder = initReminderBuilder(
            setupSeveralDaysEventOn2Hours(ZoneId.systemDefault())).triggerBefore(0, TimeUnit.MINUTE, "");
    triggerDateTime(durationReminder);/*from w w  w  .j a  v  a2s. c o m*/
    final Map<String, String> titles = computeNotificationTitles(durationReminder);
    assertThat(titles.get(DE),
            is("Reminder about the event super test - 21.02.2018 23:00 - 22.02.2018 01:00 (UTC)"));
    assertThat(titles.get(EN),
            is("Reminder about the event super test - 02/21/2018 23:00 - 02/22/2018 01:00 (UTC)"));
    assertThat(titles.get(FR),
            is("Rappel sur l'vnement super test - 21/02/2018 23:00 - 22/02/2018 01:00 (UTC)"));
    final Map<String, String> contents = computeNotificationContents(durationReminder);
    assertThat(contents.get(DE), is(
            "REMINDER: The event <b>super test</b> will be from 21.02.2018 at 23:00 to 22.02.2018 at 01:00 (UTC)."));
    assertThat(contents.get(EN), is(
            "REMINDER: The event <b>super test</b> will be from 02/21/2018 at 23:00 to 02/22/2018 at 01:00 (UTC)."));
    assertThat(contents.get(FR), is(
            "RAPPEL : L'vnement <b>super test</b> aura lieu du 21/02/2018  23:00 au 22/02/2018  01:00 (UTC)."));
}

From source file:gov.noaa.pfel.erddap.dataset.EDDTableFromHttpGet.java

/** 
     * This is used to add insert or delete commands into a data file of this dataset. 
     * This is EDDTableFromHttpGet overwriting the default implementation.
     *//from  ww w.j  ava  2  s.c  o m
     * <p>The key should be author_secret. So keys are specific to specific people/actors.
     * The author will be kept and added to the 'author' column in the dataset.
     *
     * <p>INSERT works like SQL's INSERT and UPDATE.
     * If the info matches existing values of sortColumnSourceNames,
     * the previous data is updated/overwritten. Otherwise, it is inserted.
     *
     * <p>DELETE works like SQL's DELETE
     *
     * @param tDirStructureColumnNames the column names for the parts of the 
     *   dir and file names. All of these names must be in requiredColumnNames.
     * @param keys the valid values of author= (to authenticate the author)
     * @param columnNames the names of all of the dataset's source variables.
     *   This does not include timestamp, author, or command.
     *   The time variable must be named time.
     * @param columnUnits any of them may be null or "".
     *   All timestamp columns (in the general sense) should have UDUNITS 
     *   String time units (e.g., "yyyy-MM-dd'T'HH:mm:ss") 
     *   or numeric time units (e.g., "days since 1985-01-01").
     *   For INSERT and DELETE calls, the time values must be in that format
     *   (you can't revert to ISO 8601 format as with data requests in the rest of ERDDAP).
     * @param columnTypes the Java names for the types (e.g., double).
     *   The missing values are the default missing values for PrimitiveArrays.
     *   All timestamp columns MUST be doubles.
     *   'long' is not supported because .nc3 files don't support longs.
     * @param columnStringLengths -1 if not a string column.
     * @param requiredColumnNames the names which identify a unique row.
     *   RequiredColumnNames MUST all be in columnNames.
     *   Insert requests MUST have all of the requiredColumnNames and usually have all 
     *     columnNames + author. Missing columns will get (standard PrimitiveArray) 
     *     missing values.
     *   Delete requests MUST have all of the requiredColumnNames and, in addition,
     *     usually have just author. Other columns are irrelevant.
     *   This should be as minimal as possible, and always includes time:  
     *   For TimeSeries: stationID, time.
     *   For Trajectory: trajectoryID, time.
     *   For Profile: stationID, time, depth.
     *   For TimeSeriesProfile: stationID, time, depth.
     *   For TrajectoryProfile: trajectoryID, time, depth.
     * @param command INSERT_COMMAND or DELETE_COMMAND
     * @param userDapQuery the param string, still percent-encoded
     * @param dirTable  a copy of the dirTable  (changes may be made to it) or null.
     * @param fileTable a copy of the fileTable (changes may be made to it) or null.
     * @return the response string 
     * @throws Throwable if any kind of trouble
     */
    public static String insertOrDelete(String startDir, StringArray tDirStructureColumnNames,
            IntArray tDirStructureNs, IntArray tDirStructureCalendars, HashSet<String> keys, String columnNames[],
            String columnUnits[], String columnTypes[], int columnStringLengths[], String requiredColumnNames[],
            byte command, String userDapQuery, Table dirTable, Table fileTable) throws Throwable {

        double timestamp = System.currentTimeMillis() / 1000.0;
        if (dirTable == null || fileTable == null) { //ensure both or neither
            dirTable = null;
            fileTable = null;
        }

        //store values parallelling columnNames
        int nColumns = columnNames.length;
        PrimitiveArray columnValues[] = new PrimitiveArray[nColumns];
        Class columnClasses[] = new Class[nColumns];
        DataType columnDataTypes[] = new DataType[nColumns];
        boolean columnIsString[] = new boolean[nColumns];
        int timeColumn = -1;
        DateTimeFormatter timeFormatter = null; //used if time variable is string
        double timeBaseAndFactor[] = null; //used if time variable is numeric
        for (int col = 0; col < nColumns; col++) {
            if (!String2.isSomething(columnUnits[col]))
                columnUnits[col] = "";

            if (columnNames[col].equals(EDV.TIME_NAME)) {
                timeColumn = col;
                if (columnIsString[col]) {
                    if (columnUnits[col].toLowerCase().indexOf("yyyy") < 0) //was "yy"
                        throw new SimpleException(
                                EDStatic.queryError + "Invalid units for the string time variable. "
                                        + "Units MUST specify the format of the time values.");
                    timeFormatter = DateTimeFormat.forPattern(columnUnits[col]).withZone(ZoneId.of("UTC"));
                } else { //numeric time values
                    timeBaseAndFactor = Calendar2.getTimeBaseAndFactor(columnUnits[col]); //throws RuntimeException if trouble
                }
            }

            if (columnTypes[col].equals("String")) {
                columnClasses[col] = String.class;
                columnDataTypes[col] = DataType.STRING;
                columnIsString[col] = true;
                if (columnStringLengths[col] < 1 || columnStringLengths[col] > 64000)
                    throw new SimpleException(EDStatic.queryError + "Invalid string length="
                            + columnStringLengths[col] + " for column=" + columnNames[col] + ".");
            } else {
                columnClasses[col] = PrimitiveArray.elementStringToClass(columnTypes[col]);
                columnDataTypes[col] = NcHelper.getDataType(columnClasses[col]);
            }
        }

        //parse the userDapQuery's parts. Ensure it is valid. 
        String parts[] = String2.split(userDapQuery, '&');
        int nParts = parts.length;
        String author = null; //the part before '_'
        int arraySize = -1; //until an array is found
        BitSet requiredColumnsFound = new BitSet();
        for (int p = 0; p < nParts; p++) {
            parts[p] = SSR.percentDecode(parts[p]);
            int eqPo = parts[p].indexOf('=');
            if (eqPo <= 0 || //no '=' or no name
                    "<>~!".indexOf(parts[p].charAt(eqPo - 1)) >= 0) // <= >= != ~=
                throw new SimpleException(
                        EDStatic.queryError + "The \"" + parts[p] + "\" parameter isn't in the form name=value.");
            String tName = parts[p].substring(0, eqPo);
            String tValue = parts[p].substring(eqPo + 1);
            if (tValue.startsWith("~")) // =~
                throw new SimpleException(
                        EDStatic.queryError + "The \"" + parts[p] + "\" parameter isn't in the form name=value.");

            //catch and verify author=
            if (tName.equals(AUTHOR)) {
                if (author != null)
                    throw new SimpleException(EDStatic.queryError + "There are two parameters with name=author.");
                if (!keys.contains(tValue))
                    throw new SimpleException(EDStatic.queryError + "Invalid author_key.");
                if (p != nParts - 1)
                    throw new SimpleException(EDStatic.queryError + "name=author must be the last parameter.");
                int po = Math.max(0, tValue.indexOf('_'));
                author = tValue.substring(0, po); //may be ""

            } else {
                //is it a requiredColumn?
                int whichRC = String2.indexOf(requiredColumnNames, tName);
                if (whichRC >= 0)
                    requiredColumnsFound.set(whichRC);

                //whichColumn? 
                int whichCol = String2.indexOf(columnNames, tName);
                if (whichCol < 0)
                    throw new SimpleException(EDStatic.queryError + "Unknown columnName=" + tName);
                if (columnValues[whichCol] != null)
                    throw new SimpleException(
                            EDStatic.queryError + "There are two parameters with columnName=" + tName + ".");

                //get the values
                if (tValue.startsWith("[") && tValue.endsWith("]")) {
                    //deal with array of values: name=[valuesCSV]
                    columnValues[whichCol] = PrimitiveArray.csvFactory(columnClasses[whichCol], tValue);
                    if (arraySize < 0)
                        arraySize = columnValues[whichCol].size();
                    else if (arraySize != columnValues[whichCol].size())
                        throw new SimpleException(
                                EDStatic.queryError + "Different parameters with arrays have different sizes: "
                                        + arraySize + "!=" + columnValues[whichCol].size() + ".");

                } else {
                    //deal with single value: name=value
                    columnValues[whichCol] = PrimitiveArray.csvFactory(columnClasses[whichCol], tValue);

                    if (columnClasses[whichCol] == String.class && (tValue.length() < 2 || tValue.charAt(0) != '"'
                            || tValue.charAt(tValue.length() - 1) != '"'))
                        throw new SimpleException(EDStatic.queryError + "The String value for columnName=" + tName
                                + " must start and end with \"'s.");
                    if (columnValues[whichCol].size() != 1)
                        throw new SimpleException(
                                EDStatic.queryError + "One value (not " + columnValues[whichCol].size()
                                        + ") expected for columnName=" + tName + ". (missing [ ] ?)");
                }
            }
        }

        //ensure required parameters were specified 
        if (author == null)
            throw new SimpleException(EDStatic.queryError + "author= was not specified.");
        int notFound = requiredColumnsFound.nextClearBit(0);
        if (notFound < requiredColumnNames.length)
            throw new SimpleException(EDStatic.queryError + "requiredColumnName=" + requiredColumnNames[notFound]
                    + " wasn't specified.");

        //make all columnValues the same size
        //(timestamp, author, command are separate and have just 1 value)
        int maxSize = Math.max(1, arraySize);
        for (int col = 0; col < nColumns; col++) {
            PrimitiveArray pa = columnValues[col];
            if (pa == null) {
                //this var wasn't in the command, so use mv's
                columnValues[col] = PrimitiveArray.factory(columnClasses[col], maxSize, "");
            } else if (pa.size() == 1 && maxSize > 1) {
                columnValues[col] = PrimitiveArray.factory(columnClasses[col], maxSize, pa.getString(0));
            }
        }

        //figure out the fullFileName for each row
        StringArray fullFileNames = new StringArray(maxSize, false);
        for (int row = 0; row < maxSize; row++) {
            //figure out the epochSeconds time value
            double tTime = timeColumn < 0 ? Double.NaN : //no time column
                    timeBaseAndFactor == null
                            ? Calendar2.toEpochSeconds(columnValues[timeColumn].getString(row), timeFormatter)
                            : Calendar2.unitsSinceToEpochSeconds( //numeric time
                                    timeBaseAndFactor[0], timeBaseAndFactor[1],
                                    columnValues[timeColumn].getDouble(row));

            fullFileNames.add(whichFile(startDir, tDirStructureColumnNames, tDirStructureNs, tDirStructureCalendars,
                    columnNames, columnValues, row, tTime));
        }

        //EVERYTHING SHOULD BE VALIDATED BY NOW. NO ERRORS AFTER HERE!
        //append each input row to the appropriate file
        Array oneTimestampArray = Array.factory(new double[] { timestamp });
        //I reported to netcdf-java mailing list: this generated null pointer exception in 4.6.6:
        // String tsar[] = new String[]{author};
        // Array oneAuthorArray    = Array.factory(tsar); //new String[]{author});
        //This works:
        ArrayString.D1 oneAuthorArray = new ArrayString.D1(1);
        oneAuthorArray.set(0, author);

        Array oneCommandArray = Array.factory(new byte[] { command });
        int row = 0;
        while (row < maxSize) {
            //figure out which file
            String fullFileName = fullFileNames.get(row);

            //open the file
            NetcdfFileWriter file = null;
            boolean fileIsNew = false;
            int[] origin = new int[1];
            try {

                Group rootGroup = null;
                Dimension rowDim = null;
                Variable vars[] = new Variable[nColumns];
                Variable timestampVar = null;
                Variable authorVar = null;
                Variable commandVar = null;
                if (File2.isFile(fullFileName)) {
                    file = NetcdfFileWriter.openExisting(fullFileName);
                    rootGroup = file.addGroup(null, "");
                    rowDim = rootGroup.findDimension("row");

                    //find Variables for columnNames.   May be null, but shouldn't be.
                    StringArray columnsNotFound = new StringArray();
                    for (int col = 0; col < nColumns; col++) {
                        vars[col] = rootGroup.findVariable(columnNames[col]);
                        if (vars[col] == null)
                            columnsNotFound.add(columnNames[col]);
                    }
                    timestampVar = rootGroup.findVariable(TIMESTAMP);
                    authorVar = rootGroup.findVariable(AUTHOR);
                    commandVar = rootGroup.findVariable(COMMAND);
                    if (timestampVar == null)
                        columnsNotFound.add(TIMESTAMP);
                    if (authorVar == null)
                        columnsNotFound.add(AUTHOR);
                    if (commandVar == null)
                        columnsNotFound.add(COMMAND);
                    if (columnsNotFound.size() > 0)
                        throw new SimpleException(MustBe.InternalError + ": column(s)=" + columnsNotFound
                                + " not found in " + fullFileName);

                } else {
                    //if file doesn't exist, create it
                    fileIsNew = true; //first
                    file = NetcdfFileWriter.createNew(NetcdfFileWriter.Version.netcdf3, fullFileName);
                    rootGroup = file.addGroup(null, "");
                    rowDim = file.addUnlimitedDimension("row");
                    ArrayList rowDimAL = new ArrayList();
                    rowDimAL.add(rowDim);

                    //define Variables
                    for (int col = 0; col < nColumns; col++) {
                        String cName = columnNames[col];
                        String cType = columnTypes[col];
                        if (columnIsString[col]) {
                            vars[col] = file.addStringVariable(rootGroup, cName, rowDimAL,
                                    columnStringLengths[col]);
                        } else {
                            vars[col] = file.addVariable(rootGroup, cName, columnDataTypes[col], rowDimAL);
                        }
                    }
                    timestampVar = file.addVariable(rootGroup, TIMESTAMP, DataType.DOUBLE, rowDimAL);
                    authorVar = file.addStringVariable(rootGroup, AUTHOR, rowDimAL, AUTHOR_STRLEN);
                    commandVar = file.addVariable(rootGroup, COMMAND, DataType.BYTE, rowDimAL);

                    // create the file
                    file.create();
                }

                //append the series of commands that go to this fullFileName
                int startRow = row++;
                while (row < maxSize && fullFileNames.get(row).equals(fullFileName))
                    row++;
                int stopRow = row; //1 past end

                //which row in the file table?
                int fileTableRow = -1;
                if (fileTable != null) {
                    //already in fileTable?
                    //fileTableRow = ...

                    //add to fileTable
                }

                //write the data to the file
                origin[0] = rowDim.getLength();
                for (int col = 0; col < nColumns; col++) {
                    PrimitiveArray subsetPA = columnValues[col];
                    if (startRow > 0 || stopRow != maxSize)
                        subsetPA = subsetPA.subset(startRow, 1, stopRow - 1); //inclusive
                    file.write(vars[col], origin, Array.factory(subsetPA.toObjectArray()));

                    //adjust min/max in fileTable
                    if (fileTable != null && command == INSERT_COMMAND) {
                        if (columnIsString[col]) {
                            //fileTableRow...   
                        } else {
                            double stats[] = subsetPA.calculateStats();
                            if (stats[PrimitiveArray.STATS_N] > 0) { //has some non MVs
                                //fileTableRow... Math.min(  , stats[PrimitiveArray.STATS_MIN]));
                                //fileTableRow....Math.max(  , stats[PrimitiveArray.STATS_MAX]));
                            }
                            if (stats[PrimitiveArray.STATS_N] < stopRow - startRow) {
                                //fileTableRow... hasMV
                            }
                        }
                    }
                }
                Array timestampArray = oneTimestampArray;
                Array authorArray = oneAuthorArray;
                Array commandArray = oneCommandArray;
                if (stopRow - startRow > 1) {
                    //double timestampAr[] = new double[stopRow - startRow]; 
                    //String authorAr[]    = new String[stopRow - startRow];
                    //byte   commandAr[]   = new byte  [stopRow - startRow];
                    //Arrays.fill(timestampAr, timestamp);
                    //Arrays.fill(authorAr,    author);
                    //Arrays.fill(commandAr,   command);
                    //timestampArray = Array.factory(timestampAr);
                    //authorArray    = Array.factory(authorAr);
                    //commandArray   = Array.factory(commandAr);

                    int thisShape[] = new int[] { stopRow - startRow };
                    timestampArray = Array.factoryConstant(double.class, thisShape, new Double(timestamp));
                    authorArray = Array.factoryConstant(String.class, thisShape, author);
                    commandArray = Array.factoryConstant(byte.class, thisShape, new Byte(command));
                }
                file.write(timestampVar, origin, timestampArray);
                file.writeStringData(authorVar, origin, authorArray);
                file.write(commandVar, origin, commandArray);

                //adjust min/max in fileTable
                if (fileTable != null && command == INSERT_COMMAND) {
                    //fileTableRow... Math.min(   , timestamp));
                    //fileTableRow....Math.max(   , timestamp));

                    //fileTableRow... Math.min(   , author));
                    //fileTableRow....Math.max(   , author));

                    //fileTableRow... Math.min(   , command));
                    //fileTableRow....Math.max(   , command));
                }

                //make it so!
                file.flush(); //force file update

                //close the file
                file.close();
                file = null;

            } catch (Throwable t) {
                if (file != null) {
                    try {
                        file.close();
                    } catch (Throwable t2) {
                    }
                }
                if (fileIsNew)
                    File2.delete(fullFileName);
                String2.log(
                        String2.ERROR + " while " + (fileIsNew ? "creating" : "adding to") + " " + fullFileName);
                throw t;
            }
        }

        //Don't ever change any of this (except adding somthing new to the end). 
        //Clients rely on it.
        return "SUCCESS: Data received. No errors. timestamp=" + Calendar2.epochSecondsToIsoStringT3(timestamp)
                + "Z=" + timestamp + " seconds since 1970-01-01T00:00:00Z.\n";
    }