Example usage for org.joda.time DateTimeZone forID

List of usage examples for org.joda.time DateTimeZone forID

Introduction

In this page you can find the example usage for org.joda.time DateTimeZone forID.

Prototype

@FromString
public static DateTimeZone forID(String id) 

Source Link

Document

Gets a time zone instance for the specified time zone id.

Usage

From source file:jp.furplag.util.Localizer.java

License:Apache License

private static DateTimeZone getDateTimeZone(final String zone) {
    if (zone == null)
        return DateTimeZone.getDefault();
    if (StringUtils.isSimilarToBlank(zone))
        return DateTimeZone.UTC;
    if (DateTimeZone.getAvailableIDs().contains(zone))
        return DateTimeZone.forID(zone.toString());
    if (LazyInitializer.ZONE_DUPRECATED.containsKey(zone))
        return DateTimeZone.forTimeZone(TimeZone.getTimeZone(LazyInitializer.ZONE_DUPRECATED.get(zone)));
    if (LazyInitializer.AVAILABLE_ZONE_IDS.contains(zone))
        return DateTimeZone.forTimeZone(TimeZone.getTimeZone(zone));
    Matcher base = OFFSET.matcher(StringUtils.normalize(zone, true));
    if (base.find()) {
        String offsetString = base.group();

        int[] offsetTime = JSONifier.parseLazy(
                JSONifier.stringifyLazy(StringUtils.truncateFirst(offsetString, "[\\+\\-]").split("[:\\.]")),
                int[].class);
        if (offsetTime.length < 1)
            return DateTimeZone.UTC;
        LocalTime offset = new LocalTime(offsetTime.length > 0 ? offsetTime[0] : 0,
                offsetTime.length > 1 ? offsetTime[1] : 0, offsetTime.length > 2 ? offsetTime[2] : 0,
                offsetTime.length > 3 ? offsetTime[3] : 0);

        return DateTimeZone.forID((offsetString.startsWith("-") ? "-" : "+") + offset.toString(OFFSET_FORMAT));
    }//from  w  w w .ja  v a 2  s .c  om

    return DateTimeZone.UTC;
}

From source file:jp.furplag.util.Localizer.java

License:Apache License

private static DateTimeZone getDateTimeZone(final TimeZone zone) {
    if (zone == null)
        return DateTimeZone.getDefault();
    String zoneID = ((TimeZone) zone).getID();
    if (DateTimeZone.getAvailableIDs().contains(zoneID))
        return DateTimeZone.forID(zoneID);
    if (LazyInitializer.ZONE_DUPRECATED.containsKey(zoneID))
        return DateTimeZone.forTimeZone(TimeZone.getTimeZone(LazyInitializer.ZONE_DUPRECATED.get(zoneID)));

    return DateTimeZone.forTimeZone((TimeZone) zone);
}

From source file:jp.furplag.util.Localizer.java

License:Apache License

private static DateTimeZone getDateTimeZone(final Long millis) {
    if (millis == null)
        return DateTimeZone.getDefault();
    if (millis % 86400000L == 0)
        return DateTimeZone.UTC;
    LocalTime offset = LocalTime.fromMillisOfDay((millis % 86400000L) * (millis < 0 ? -1 : 1));

    return DateTimeZone.forID((millis < 0 ? "-" : "+") + offset.toString(OFFSET_FORMAT));
}

From source file:jp.scaleout.elasticsearch.plugins.queryparser.SoQueryParser.java

License:Apache License

@Override
public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException {
    XContentParser parser = parseContext.parser();

    String queryName = null;/*  w  w  w .j a  v a 2  s  . c o m*/
    QueryParserSettings qpSettings = new QueryParserSettings();
    qpSettings.defaultField(parseContext.defaultField());
    qpSettings.lenient(parseContext.queryStringLenient());
    qpSettings.analyzeWildcard(defaultAnalyzeWildcard);
    qpSettings.allowLeadingWildcard(defaultAllowLeadingWildcard);
    qpSettings.locale(Locale.ROOT);

    String currentFieldName = null;
    XContentParser.Token token;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            currentFieldName = parser.currentName();
        } else if (token == XContentParser.Token.START_ARRAY) {
            if ("fields".equals(currentFieldName)) {
                while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
                    String fField = null;
                    float fBoost = -1;
                    char[] text = parser.textCharacters();
                    int end = parser.textOffset() + parser.textLength();
                    for (int i = parser.textOffset(); i < end; i++) {
                        if (text[i] == '^') {
                            int relativeLocation = i - parser.textOffset();
                            fField = new String(text, parser.textOffset(), relativeLocation);
                            fBoost = Float.parseFloat(
                                    new String(text, i + 1, parser.textLength() - relativeLocation - 1));
                            break;
                        }
                    }
                    if (fField == null) {
                        fField = parser.text();
                    }
                    if (qpSettings.fields() == null) {
                        qpSettings.fields(Lists.<String>newArrayList());
                    }

                    if (Regex.isSimpleMatchPattern(fField)) {
                        for (String field : parseContext.mapperService().simpleMatchToIndexNames(fField)) {
                            qpSettings.fields().add(field);
                            if (fBoost != -1) {
                                if (qpSettings.boosts() == null) {
                                    qpSettings.boosts(new ObjectFloatHashMap<String>());
                                }
                                qpSettings.boosts().put(field, fBoost);
                            }
                        }
                    } else {
                        qpSettings.fields().add(fField);
                        if (fBoost != -1) {
                            if (qpSettings.boosts() == null) {
                                qpSettings.boosts(new ObjectFloatHashMap<String>());
                            }
                            qpSettings.boosts().put(fField, fBoost);
                        }
                    }
                }
            } else {
                throw new QueryParsingException(parseContext,
                        "[query_string] query does not support [" + currentFieldName + "]");
            }
        } else if (token.isValue()) {
            if ("query".equals(currentFieldName)) {
                qpSettings.queryString(parser.text());
            } else if ("default_field".equals(currentFieldName) || "defaultField".equals(currentFieldName)) {
                qpSettings.defaultField(parser.text());
            } else if ("default_operator".equals(currentFieldName)
                    || "defaultOperator".equals(currentFieldName)) {
                String op = parser.text();
                if ("or".equalsIgnoreCase(op)) {
                    qpSettings.defaultOperator(org.apache.lucene.queryparser.classic.QueryParser.Operator.OR);
                } else if ("and".equalsIgnoreCase(op)) {
                    qpSettings.defaultOperator(org.apache.lucene.queryparser.classic.QueryParser.Operator.AND);
                } else {
                    throw new QueryParsingException(parseContext,
                            "Query default operator [" + op + "] is not allowed");
                }
            } else if ("analyzer".equals(currentFieldName)) {
                NamedAnalyzer analyzer = parseContext.analysisService().analyzer(parser.text());
                if (analyzer == null) {
                    throw new QueryParsingException(parseContext,
                            "[query_string] analyzer [" + parser.text() + "] not found");
                }
                qpSettings.forcedAnalyzer(analyzer);
            } else if ("quote_analyzer".equals(currentFieldName) || "quoteAnalyzer".equals(currentFieldName)) {
                NamedAnalyzer analyzer = parseContext.analysisService().analyzer(parser.text());
                if (analyzer == null) {
                    throw new QueryParsingException(parseContext,
                            "[query_string] quote_analyzer [" + parser.text() + "] not found");
                }
                qpSettings.forcedQuoteAnalyzer(analyzer);
            } else if ("allow_leading_wildcard".equals(currentFieldName)
                    || "allowLeadingWildcard".equals(currentFieldName)) {
                qpSettings.allowLeadingWildcard(parser.booleanValue());
            } else if ("auto_generate_phrase_queries".equals(currentFieldName)
                    || "autoGeneratePhraseQueries".equals(currentFieldName)) {
                qpSettings.autoGeneratePhraseQueries(parser.booleanValue());
            } else if ("max_determinized_states".equals(currentFieldName)
                    || "maxDeterminizedStates".equals(currentFieldName)) {
                qpSettings.maxDeterminizedStates(parser.intValue());
            } else if ("lowercase_expanded_terms".equals(currentFieldName)
                    || "lowercaseExpandedTerms".equals(currentFieldName)) {
                qpSettings.lowercaseExpandedTerms(parser.booleanValue());
            } else if ("enable_position_increments".equals(currentFieldName)
                    || "enablePositionIncrements".equals(currentFieldName)) {
                qpSettings.enablePositionIncrements(parser.booleanValue());
            } else if ("escape".equals(currentFieldName)) {
                qpSettings.escape(parser.booleanValue());
            } else if ("use_dis_max".equals(currentFieldName) || "useDisMax".equals(currentFieldName)) {
                qpSettings.useDisMax(parser.booleanValue());
            } else if ("fuzzy_prefix_length".equals(currentFieldName)
                    || "fuzzyPrefixLength".equals(currentFieldName)) {
                qpSettings.fuzzyPrefixLength(parser.intValue());
            } else if ("fuzzy_max_expansions".equals(currentFieldName)
                    || "fuzzyMaxExpansions".equals(currentFieldName)) {
                qpSettings.fuzzyMaxExpansions(parser.intValue());
            } else if ("fuzzy_rewrite".equals(currentFieldName) || "fuzzyRewrite".equals(currentFieldName)) {
                qpSettings.fuzzyRewriteMethod(
                        QueryParsers.parseRewriteMethod(parseContext.parseFieldMatcher(), parser.textOrNull()));
            } else if ("phrase_slop".equals(currentFieldName) || "phraseSlop".equals(currentFieldName)) {
                qpSettings.phraseSlop(parser.intValue());
            } else if (parseContext.parseFieldMatcher().match(currentFieldName, FUZZINESS)) {
                qpSettings.setFuzziness(Fuzziness.parse(parser));
            } else if ("boost".equals(currentFieldName)) {
                qpSettings.boost(parser.floatValue());
            } else if ("tie_breaker".equals(currentFieldName) || "tieBreaker".equals(currentFieldName)) {
                qpSettings.tieBreaker(parser.floatValue());
            } else if ("analyze_wildcard".equals(currentFieldName)
                    || "analyzeWildcard".equals(currentFieldName)) {
                qpSettings.analyzeWildcard(parser.booleanValue());
            } else if ("rewrite".equals(currentFieldName)) {
                qpSettings.rewriteMethod(
                        QueryParsers.parseRewriteMethod(parseContext.parseFieldMatcher(), parser.textOrNull()));
            } else if ("minimum_should_match".equals(currentFieldName)
                    || "minimumShouldMatch".equals(currentFieldName)) {
                qpSettings.minimumShouldMatch(parser.textOrNull());
            } else if ("quote_field_suffix".equals(currentFieldName)
                    || "quoteFieldSuffix".equals(currentFieldName)) {
                qpSettings.quoteFieldSuffix(parser.textOrNull());
            } else if ("lenient".equalsIgnoreCase(currentFieldName)) {
                qpSettings.lenient(parser.booleanValue());
            } else if ("locale".equals(currentFieldName)) {
                String localeStr = parser.text();
                qpSettings.locale(LocaleUtils.parse(localeStr));
            } else if ("time_zone".equals(currentFieldName)) {
                try {
                    qpSettings.timeZone(DateTimeZone.forID(parser.text()));
                } catch (IllegalArgumentException e) {
                    throw new QueryParsingException(parseContext,
                            "[query_string] time_zone [" + parser.text() + "] is unknown");
                }
            } else if ("_name".equals(currentFieldName)) {
                queryName = parser.text();
            } else {
                throw new QueryParsingException(parseContext,
                        "[query_string] query does not support [" + currentFieldName + "]");
            }
        }
    }
    if (qpSettings.queryString() == null) {
        throw new QueryParsingException(parseContext, "query_string must be provided with a [query]");
    }
    qpSettings.defaultAnalyzer(parseContext.mapperService().searchAnalyzer());
    qpSettings.defaultQuoteAnalyzer(parseContext.mapperService().searchQuoteAnalyzer());

    if (qpSettings.escape()) {
        qpSettings.queryString(
                org.apache.lucene.queryparser.classic.QueryParser.escape(qpSettings.queryString()));
    }

    //qpSettings.queryTypes(parseContext.queryTypes());

    MapperQueryParser queryParser = parseContext.queryParser(qpSettings);

    try {
        Query query = queryParser.parse(qpSettings.queryString());
        if (query == null) {
            return null;
        }
        if (qpSettings.boost() != QueryParserSettings.DEFAULT_BOOST) {
            query.setBoost(query.getBoost() * qpSettings.boost());
        }
        query = fixNegativeQueryIfNeeded(query);
        if (query instanceof BooleanQuery) {
            Queries.applyMinimumShouldMatch((BooleanQuery) query, qpSettings.minimumShouldMatch());
        }
        if (queryName != null) {
            parseContext.addNamedQuery(queryName, query);
        }
        logger.debug("query: " + query.toString());
        return query;
    } catch (org.apache.lucene.queryparser.classic.ParseException e) {
        throw new QueryParsingException(parseContext,
                "Failed to parse query [" + qpSettings.queryString() + "]", e);
    }
}

From source file:lib.Global.java

License:Open Source License

@Override
public void onStart(Application app) {
    log.info("Graylog web interface version {} starting up.", Version.VERSION);

    final String appSecret = app.configuration().getString("application.secret");
    if (appSecret == null || appSecret.isEmpty()) {
        log.error("Please configure application.secret in your conf/graylog-web-interface.conf");
        throw new IllegalStateException("No application.secret configured.");
    }/*from  w w w .  jav a 2s .c o  m*/
    if (appSecret.length() < 16) {
        log.error(
                "Please configure application.secret in your conf/graylog-web-interface.conf to be longer than 16 characters. Suggested is using pwgen -N 1 -s 96 or similar");
        throw new IllegalStateException(
                "application.secret is too short, use at least 16 characters! Suggested is to use pwgen -N 1 -s 96 or similar");
    }

    final String graylog2ServerUris = app.configuration().getString("graylog2-server.uris", "");
    if (graylog2ServerUris.isEmpty()) {
        log.error("graylog2-server.uris is not set!");
        throw new IllegalStateException("graylog2-server.uris is empty");
    }
    final String[] uris = graylog2ServerUris.split(",");
    if (uris.length == 0) {
        log.error("graylog2-server.uris is empty!");
        throw new IllegalStateException("graylog2-server.uris is empty");
    }
    final URI[] initialNodes = new URI[uris.length];
    int i = 0;
    for (String uri : uris) {
        try {
            initialNodes[i++] = new URI(uri);
        } catch (URISyntaxException e) {
            log.error("Invalid URI in 'graylog2-server.uris': " + uri, e);
        }
    }
    final String timezone = app.configuration().getString("timezone", "");
    if (!timezone.isEmpty()) {
        try {
            DateTools.setApplicationTimeZone(DateTimeZone.forID(timezone));
        } catch (IllegalArgumentException e) {
            log.error("Invalid timezone {} specified!", timezone);
            throw new IllegalStateException(e);
        }
    }
    log.info("Using application default timezone {}", DateTools.getApplicationTimeZone());

    // Dirty hack to disable the play2-graylog2 AccessLog if the plugin isn't there
    gelfAccessLog = app.configuration().getBoolean("graylog2.appender.send-access-log", false);

    final ObjectMapper objectMapper = buildObjectMapper();
    Json.setObjectMapper(objectMapper);

    final List<Module> modules = Lists.newArrayList();
    modules.add(new AbstractModule() {
        @Override
        protected void configure() {
            bind(URI[].class).annotatedWith(Names.named("Initial Nodes")).toInstance(initialNodes);
            bind(Long.class).annotatedWith(Names.named("Default Timeout"))
                    .toInstance(org.graylog2.restclient.lib.Configuration.apiTimeout("DEFAULT"));
            bind(ObjectMapper.class).toInstance(objectMapper);
        }
    });
    modules.add(new ModelFactoryModule());
    injector = Guice.createInjector(modules);

    // start the services that need starting
    final ApiClient api = injector.getInstance(ApiClient.class);
    api.start();
    injector.getInstance(ServerNodesRefreshService.class).start();
    // TODO replace with custom AuthenticatedAction filter
    RedirectAuthenticator.userService = injector.getInstance(UserService.class);
    RedirectAuthenticator.sessionService = injector.getInstance(SessionService.class);

    // temporarily disabled for preview to prevent confusion.
    //        LocalAdminUserRealm localAdminRealm = new LocalAdminUserRealm("local-accounts");
    //        localAdminRealm.setCredentialsMatcher(new HashedCredentialsMatcher("SHA2"));
    //        setupLocalUser(api, localAdminRealm, app);

    Realm serverRestInterfaceRealm = injector.getInstance(ServerRestInterfaceRealm.class);
    final DefaultSecurityManager securityManager = new DefaultSecurityManager(
            Lists.newArrayList(serverRestInterfaceRealm));
    // disable storing sessions (TODO we might want to write a session store bridge to play's session cookie)
    final DefaultSessionStorageEvaluator sessionStorageEvaluator = new DefaultSessionStorageEvaluator();
    sessionStorageEvaluator.setSessionStorageEnabled(false);
    final DefaultSubjectDAO subjectDAO = new DefaultSubjectDAO();
    subjectDAO.setSessionStorageEvaluator(sessionStorageEvaluator);
    securityManager.setSubjectDAO(subjectDAO);

    final Authenticator authenticator = securityManager.getAuthenticator();
    if (authenticator instanceof ModularRealmAuthenticator) {
        ModularRealmAuthenticator a = (ModularRealmAuthenticator) authenticator;
        a.setAuthenticationStrategy(new RethrowingFirstSuccessfulStrategy());
        a.setAuthenticationListeners(
                Lists.<AuthenticationListener>newArrayList(new PlayAuthenticationListener()));
    }
    SecurityUtils.setSecurityManager(securityManager);

}

From source file:lt.norma.crossbow.contracts.Exchange.java

License:Open Source License

/**
 * Creates an exchange with time zone set to "America/New_York" and trading hours 09:30 - 16:00.
 * //from   w  w  w .j a v a2s.c o  m
 * @return Nasdaq exchange
 */
public static Exchange createNasdaq() {
    return new Exchange("Nasdaq", DateTimeZone.forID("America/New_York"), new LocalTime(9, 30, 0),
            new LocalTime(16, 0, 0));
}

From source file:lt.norma.crossbow.contracts.Exchange.java

License:Open Source License

/**
 * Creates an exchange with time zone set to "America/New_York" and trading hours 09:30 - 16:00.
 * //from  ww  w  .j a  v a  2s  .  c  o  m
 * @return Nyse exchange
 */
public static Exchange createNyse() {
    return new Exchange("Nyse", DateTimeZone.forID("America/New_York"), new LocalTime(9, 30, 0),
            new LocalTime(16, 0, 0));
}

From source file:monasca.api.infrastructure.persistence.mysql.AlarmMySqlRepoImpl.java

License:Apache License

private List<Alarm> createAlarms(String tenantId, List<Map<String, Object>> rows) {
    Alarm alarm;//from  w  ww .  j a v a2  s .c o m
    String previousAlarmId = null;
    final List<Alarm> alarms = new LinkedList<>();
    List<MetricDefinition> alarmedMetrics = null;
    for (final Map<String, Object> row : rows) {
        final String alarmId = (String) row.get("alarm_id");
        if (!alarmId.equals(previousAlarmId)) {
            alarmedMetrics = new ArrayList<>();
            alarm = new Alarm(alarmId, getString(row, "alarm_definition_id"),
                    getString(row, "alarm_definition_name"), getString(row, "severity"), alarmedMetrics,
                    AlarmState.valueOf(getString(row, "state")), getString(row, "lifecycle_state"),
                    getString(row, "link"),
                    new DateTime(((Timestamp) row.get("state_updated_timestamp")).getTime(),
                            DateTimeZone.forID("UTC")),
                    new DateTime(((Timestamp) row.get("updated_timestamp")).getTime(),
                            DateTimeZone.forID("UTC")),
                    new DateTime(((Timestamp) row.get("created_timestamp")).getTime(),
                            DateTimeZone.forID("UTC")));
            alarms.add(alarm);
        }
        previousAlarmId = alarmId;
        final Map<String, String> dimensionMap = new HashMap<>();

        // Not all Metrics have dimensions (at least theoretically)
        if (row.containsKey("metric_dimensions")) {
            final String dimensions = getString(row, "metric_dimensions");
            if (dimensions != null && !dimensions.isEmpty()) {
                for (String dimension : dimensions.split(",")) {
                    final String[] parsed_dimension = dimension.split("=");
                    if (parsed_dimension.length == 2) {
                        dimensionMap.put(parsed_dimension[0], parsed_dimension[1]);
                    } else {
                        logger.error("Failed to parse dimension. Dimension is malformed: {}", dimension);
                    }
                }
            }
        }

        alarmedMetrics.add(new MetricDefinition(getString(row, "metric_name"), dimensionMap));
    }
    return alarms;
}

From source file:name.martingeisse.admin.customization.Main.java

License:Open Source License

/**
 * The main method//www  . jav a  2  s  .c  om
 * @param args command-line arguments (ignored)
 * @throws Exception on errors
 */
@SuppressWarnings("unchecked")
public static void main(final String[] args) throws Exception {

    // --- code generation start ---
    /*
    Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/phorum?zeroDateTimeBehavior=convertToNull&useTimezone=false", "root", "");
    MetaDataExporter exporter = new MetaDataExporter();
    exporter.setTargetFolder(new File("generated"));
    exporter.setPackageName("phorum");
    exporter.setSerializerClass(MetaDataSerializer.class);
    exporter.setBeanSerializer(new BeanSerializer(true));
    exporter.export(connection.getMetaData());
    connection.close();
    System.exit(0);
    */
    // --- code generation end ---

    //      DatabaseDescriptor mainDatabase = new DatabaseDescriptor();
    //      mainDatabase.setDisplayName("main database");
    //      mainDatabase.setUrl("jdbc:postgresql://localhost/admintest");
    //      mainDatabase.setUsername("postgres");
    //      mainDatabase.setPassword("postgres");
    //      ApplicationConfiguration.addDatabase(mainDatabase);

    // the database
    //      final AbstractDatabaseDescriptor phpbbDatabase = new MysqlDatabaseDescriptor();
    //      phpbbDatabase.setDisplayName("phpBB database");
    //      phpbbDatabase.setUrl("jdbc:mysql://localhost/phpbb");
    //      phpbbDatabase.setUsername("root");
    //      phpbbDatabase.setPassword("");
    //      ApplicationConfiguration.get().addDatabase(phpbbDatabase);

    //
    // The database. Note about "useTimezone=false": This is needed so we can load local dates and
    // datetimes from the database. JDBC uses an inherently broken model here, which we're trying to
    // circumvent. Speaking in Joda-Time terms, the database stores a local date or datetime value,
    // NOT an instant -- that is, the timezone is implicit, not stored. JDBC, however, always
    // wants to convert this to an instant that is expressed as a java.sql.Date or java.sql.Timestamp,
    // i.e. an instant that is represented in UTC, using an implicit timezone whose origin depends
    // on the JDBC driver. To obtain a local value without too much hassle, we set "useTimezone=false"
    // to make this conversion a NOP, i.e. make JDBC assume that the database value is a local value
    // that is to be interpreted as UTC, so the conversion just takes this value and adds "UTC" to it.
    // We then take the value and create a local value as a Joda object by throwing away the "UTC" again.
    //
    // NOTE: This description is specific to MySQL. For other databases, we basically need to do
    // whatever is necessary to read the local value from the database as a local value expressed
    // as a Joda object, circumventing JDBC's stupidity and implicit rules.
    //
    // NOTE: The server stores a server-wide time zone setting. One *could* use that to interpret
    // database values as instants instead of local values. However, (1) this setting cannot be
    // trusted to be correct since it's not used in many places in DB-side time handling (i.e.
    // we might very well have to deal with an incorrectly configured database and existing
    // applications that know how to work around it), and (2) we'll have to deal with values in the
    // DB that are meant as local values, and might even be part of a (local value, time zone) pair.
    // Applying the server time zone to such values would be incorrect. So we'll only deal with the
    // server time zone as much as needed to get rid of it and obtain the local values that are
    // actually stored in the DB tables.
    //
    // If part of the application wants to store an instant in the database -- a quite common task --
    // we'll rather have the application convert it manually, possibly providing access to
    // automatic type conversion (e.g. an implicitly converting ISqlDateTimeTypeInfo). The
    // admin framework should not do this -- it would be an implicit conversion layer that adds
    // confusion, and it would be unclear to the application developer how the time zone used
    // for that conversion is related to the SQL server time zone setting.
    //
    // NOTE: Actually we don't absolutely *need* that parameter for MySQL since it's the default.
    //
    final MysqlDatabaseDescriptor phorumDatabase = new MysqlDatabaseDescriptor();
    phorumDatabase.setDisplayName("Phorum database");
    phorumDatabase.setUrl("jdbc:mysql://localhost/phorum?zeroDateTimeBehavior=convertToNull&useTimezone=false");
    phorumDatabase.setUsername("root");
    phorumDatabase.setPassword("");
    phorumDatabase.setDefaultTimeZone(DateTimeZone.forID("Europe/Berlin"));
    // phorumDatabase.setDefaultTimeZone(DateTimeZone.forID("Europe/London"));
    phorumDatabase.initialize();
    ApplicationConfiguration.get().addDatabase(phorumDatabase);
    EntityConnectionManager.initializeDatabaseDescriptors(phorumDatabase);

    // plugins / capabilities
    ApplicationConfiguration.get().addPlugin(new DefaultPlugin());
    // ApplicationConfiguration.get().addPlugin(new FixedNameEntityReferenceDetector("extensions", "group_id", "extension_groups"));
    ApplicationConfiguration.get().addPlugin(new CustomizationPlugin());
    ApplicationConfiguration.get()
            .addPlugin(new SingleEntityPropertyFilter(1, null, "modificationTimestamp", false));
    ApplicationConfiguration.get()
            .addPlugin(new SingleEntityPropertyFilter(1, null, "modificationUser_id", false));
    ApplicationConfiguration.get()
            .addPlugin(new SingleEntityPropertyFilter(1, "User", "lastLoginAttemptTimestamp", false));
    //      ApplicationConfiguration.get().addPlugin(new GlobalEntityListPresenter("ids", "IDs only", IdOnlyGlobalEntityListPanel.class));
    //      ApplicationConfiguration.get().addPlugin(new GlobalEntityListPresenter("roleList", "Role List", RoleOrderListPanel.class));
    //      ApplicationConfiguration.get().addPlugin(new GlobalEntityListPresenter("popdata", "Populator / DataView", PopulatorDataViewPanel.class));

    final ExplicitEntityPropertyFilter userPropertyFilter = new ExplicitEntityPropertyFilter(2, "User");
    userPropertyFilter.getVisiblePropertyNames().add("id");
    userPropertyFilter.getVisiblePropertyNames().add("name");
    ApplicationConfiguration.get().addPlugin(userPropertyFilter);

    // general parameters
    //      PagesConfigurationUtil.setPageBorderFactory(new name.martingeisse.admin.customization.PageBorderFactory());

    // entity parameters
    EntityConfiguration generalEntityConfiguration = new EntityConfiguration();
    //      generalEntityConfiguration.setEntityNameMappingStrategy(new PrefixEliminatingEntityNameMappingStrategy("phpbb_"));
    IEntityNameMappingStrategy.PARAMETER_KEY.set(new PrefixEliminatingEntityNameMappingStrategy("phorum_"));
    EntityConfiguration.parameterKey.set(generalEntityConfiguration);

    // entity navigation contributors
    /*
    EntityCapabilities.entityNavigationContributorCapability.add(new IEntityNavigationContributor() {
       @Override
       public void contributeNavigationNodes(EntityDescriptor entity, NavigationNode mainEntityInstanceNode) {
    if (entity.getName().equals("settings")) {
       mainEntityInstanceNode.setHandler(new EntityInstancePanelHandler(SettingPanel.class));
    } else {
       mainEntityInstanceNode.setHandler(new EntityInstancePanelHandler(RawEntityPresentationPanel.class));
    }
    mainEntityInstanceNode.getChildFactory().createEntityInstancePanelChild("edit", "Edit", NavigationMountedEntityAutoformPanel.class);
       }
    });
    */

    // test raw entity presentation column order
    //      EntityConfigurationUtil.getGeneralEntityConfiguration().setEntityListFieldOrder(new IEntityListFieldOrder() {
    //         @Override
    //         public int compare(EntityPropertyDescriptor prop1, EntityPropertyDescriptor prop2) {
    //            return prop1.getName().compareTo(prop2.getName());
    //         }
    //      });

    // test entity search support
    EntityCapabilities.entitySearchContributorCapability.add(new IEntitySearchContributor() {

        @Override
        public IEntitySearchStrategy getSearchStrategy(EntityDescriptor entity) {
            return new IEntitySearchStrategy() {
                @Override
                public Predicate createFilter(EntityDescriptor entity, String searchTerm) {
                    EntityConditions conditions = new EntityConditions(entity);
                    conditions.addFieldComparison("name", Ops.LIKE, "%" + searchTerm.replace("%", "") + "%");
                    return conditions;
                }
            };
        }

        @Override
        public int getScore(EntityDescriptor entity) {
            return (entity.getProperties().get("name") == null ? Integer.MIN_VALUE : 0);
        }

    });

    // entity autoforms
    IEntityAnnotatedClassResolver classResolver = new EntityAutoformAnnotatedClassResolver(
            "name.martingeisse.admin.customization.entity");
    EntityCapabilities.entityAnnotationContributorCapability
            .add(new AnnotatedClassEntityAnnotationContributor(classResolver));

    // initialize specific entity code mapping
    IEntityOrmMapper.PARAMETER_KEY.set(new IEntityOrmMapper() {
        @Override
        public EntityOrmMapping map(EntityDescriptor entityDescriptor) {
            try {
                String baseName = entityDescriptor.getName();
                String suffix = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, baseName);
                String className = "phorum.Phorum" + suffix;
                String qclassName = "phorum.QPhorum" + suffix;
                return new EntityOrmMapping(entityDescriptor, Class.forName(className), GenericTypeUtil
                        .<Class<? extends RelationalPath<?>>>unsafeCast(Class.forName(qclassName)));
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            }
        }
    });

    // run
    WebServerLauncher.launch();

}

From source file:name.martingeisse.admin.customization.tools.CodeGenerator.java

License:Open Source License

/**
 * The main method./*from   w  w  w. j a  va 2s  .  co  m*/
 * @param args ...
 * @throws Exception on errors
 */
public static void main(String[] args) throws Exception {
    BeanSerializer beanSerializer = new BeanSerializer(true);
    Connection connection = DriverManager.getConnection(
            "jdbc:mysql://localhost/phorum?zeroDateTimeBehavior=convertToNull&useTimezone=false", "root", "");
    MetaDataExporter exporter = new MetaDataExporter();
    exporter.setTargetFolder(new File("generated"));
    exporter.setPackageName("phorum");
    exporter.setSerializerClass(MetaDataSerializer.class);
    exporter.setBeanSerializer(beanSerializer);
    // exporter.setConfiguration(new CustomMysqlQuerydslConfiguration(new MySQLTemplates(), null));
    exporter.setConfiguration(
            new CustomMysqlQuerydslConfiguration(new MySQLTemplates(), DateTimeZone.forID("Europe/Moscow")));
    exporter.export(connection.getMetaData());
    connection.close();
}