Example usage for org.joda.time ReadableInterval contains

List of usage examples for org.joda.time ReadableInterval contains

Introduction

In this page you can find the example usage for org.joda.time ReadableInterval contains.

Prototype

boolean contains(ReadableInterval interval);

Source Link

Document

Does this time interval contain the specified time interval.

Usage

From source file:com.helger.datetime.holiday.mgr.AbstractHolidayManager.java

License:Apache License

@Nonnull
@ReturnsMutableCopy/*w  ww . j  a  v a  2s .co  m*/
public HolidayMap getHolidays(@Nonnull final ReadableInterval aInterval, @Nullable final String... aArgs) {
    if (aInterval == null)
        throw new NullPointerException("Interval is NULL.");

    final HolidayMap aHolidayMap = new HolidayMap();
    for (int nYear = aInterval.getStart().getYear(); nYear <= aInterval.getEnd().getYear(); nYear++) {
        final HolidayMap yearHolidays = getHolidays(nYear, aArgs);
        for (final Map.Entry<LocalDate, ISingleHoliday> aEntry : yearHolidays.getMap().entrySet())
            if (aInterval.contains(aEntry.getKey().toDateTimeAtStartOfDay()))
                aHolidayMap.add(aEntry.getKey(), aEntry.getValue());
    }
    return aHolidayMap;
}

From source file:com.jjlharrison.jollyday.impl.DefaultHolidayManager.java

License:Apache License

/**
 * {@inheritDoc}// w ww . j a va2  s. c o  m
 *
 * Calls <code>getHolidays(year, args)</code> for each year within the
 * interval and returns a list of holidays which are then contained in the
 * interval.
 */
@Override
public Set<Holiday> getHolidays(ReadableInterval interval, final String... args) {
    if (interval == null) {
        throw new IllegalArgumentException("Interval is NULL.");
    }
    Set<Holiday> holidays = new HashSet<Holiday>();
    for (int year = interval.getStart().getYear(); year <= interval.getEnd().getYear(); year++) {
        Set<Holiday> yearHolidays = getHolidays(year, args);
        for (Holiday h : yearHolidays) {
            if (interval.contains(h.getDate().toDateTimeAtStartOfDay())) {
                holidays.add(h);
            }
        }
    }
    return holidays;
}

From source file:org.sonar.replay.Main.java

License:LGPL

public static void main(String[] args) {
    /*/*from   w  ww  .ja v  a2 s .c om*/
       Inputs:
       1) Perforce connection info
       2) Sonar db connection info
       3) Perforce Depot
       4) optional: label filter (regex)
       5) optional: time span window (start/end) ? by label name?
       6) optional: version pattern (how to parse # out of label name)
            
       Logic for version number
       1) If it has a checked in version number in pom.xml use that
       2) Otherwise if version is a ${..} parse
            
       General logic:
       1) Get all labels (regarding filter)
       2) For each label...
       2.1) Find time of label
       2.2) If time is not in option span, break.
       2.3) p4 sync to that label
       2.4) figure out version number
       2.5) exec 'mvn clean sonar:sonar' passing it
       2.5.1) sonar conn info
       2.5.2) sonar project date
       2.5.3) conditional: label version as whatever property was found ${}
    */

    Properties props = new Properties();

    if (!readPropertiesFile(args, props)) {
        System.exit(1);
    }

    System.getProperties().putAll(props);
    System.getProperties().put("maven.home", System.getenv("M2_HOME"));
    if (!System.getProperties().containsKey("mvn.exe")) {
        System.getProperties().put("mvn.exe", "mvn");
    }

    // Mild-validation
    if (!System.getProperties().containsKey("p4.file.specs")) {
        LOGGER.warn(
                "Not specifying 'p4.file.specs' will default to the entire perforce depot which is probably NOT what you want.");
    }

    try {

        File tempDir = new File(System.getProperty("java.io.tmpdir"));
        File syncDir = new File(new File(tempDir, "sonar-replay"), "workspace");
        syncDir.mkdirs();
        LOGGER.debug("Made temp workspace: " + syncDir.getAbsolutePath());

        P4JLog.setLogCallback(new LogCallback(System.out));

        P4JServer server = P4JServerFactory.getServer(System.getProperty("p4.url"), null);
        LOGGER.debug("Connecting to server...");
        server.connect();
        server.setUserName(System.getProperty("p4.user"));
        server.setAuthTicket(null); // turn off use of tickets.
        server.login(System.getProperty("p4.password"));
        LOGGER.info("Logged into perforce server [" + System.getProperty("p4.user") + " @ "
                + System.getProperty("p4.url") + "].");

        server.registerCallback(new P4JCommandCallback() {
            public void issuingServerCommand(int i, String s) {
                LOGGER.debug(i + ": Issuing Server Command : " + s);
            }

            public void completedServerCommand(int i, long l) {
                LOGGER.debug(i + ": Completed Server Command : " + l);
            }

            public void receivedServerInfoLine(int i, String s) {
                LOGGER.debug("-- " + i + ": I* Received Server Info : " + s);
            }

            public void receivedServerErrorLine(int i, String s) {
                LOGGER.debug("-- " + i + ": E* Received Server Error : " + s);
            }

            public void receivedServerMessage(int i, int i1, int i2, String s) {
                LOGGER.debug("-- " + i + ": Received Server Message : " + i1 + " : " + i2 + " : " + s);
            }
        });

        server.registerProgressCallback(new DemoProgressCallback());

        List<P4JFileSpec> fileSpecs = parseFileSpecs(System.getProperty("p4.file.specs", "//..."));

        //            System.out.println("validSpecs: " + fileSpecs);

        P4JClientSpecImpl spec = new P4JClientSpecImpl();
        spec.setRoot(syncDir.getAbsolutePath());
        final P4JClientViewImpl view = new P4JClientViewImpl();
        final List<P4JClientView.P4JClientViewMapping> mappings = new ArrayList<P4JClientView.P4JClientViewMapping>();
        final String clientName = "sonar-replay-" + InetAddress.getLocalHost().getHostName();
        for (P4JFileSpec fileSpec : fileSpecs) {
            LOGGER.debug("Adding file spec: " + fileSpec.getDisplayPath());
            mappings.add(new P4JClientViewImpl.P4JClientViewMappingImpl(0, fileSpec.getDisplayPath(),
                    "//" + clientName + "/..."));
        }
        view.setMapping(mappings);
        spec.setClientView(view);
        spec.setName(clientName);
        spec.setOwnerName(server.getUserName());
        spec.setHostName("");
        P4JClient clientStub = new P4JClientImpl(server, spec, false);

        LOGGER.debug("Creating client...");
        server.newClient(clientStub);

        P4JClient client = server.getClient(clientStub.getName());
        LOGGER.debug("Client created.");

        server.setCurrentClient(client);

        LOGGER.debug("Clearing workspace...");

        List<P4JFileSpec> cleared = client.sync(
                P4JFileSpecBuilder
                        .getValidFileSpecs(P4JFileSpecBuilder.makeFileSpecList(new String[] { "#0" })),
                false, false, false, false);
        LOGGER.debug("Files cleared: " + cleared.size());

        LOGGER.debug("Getting labels.");
        // Get all the labels for the project...
        List<P4JLabel> labels = new ArrayList<P4JLabel>();
        if (System.getProperties().containsKey("p4.label.name.filters")) {
            for (String nameFilter : System.getProperty("p4.label.name.filters").split(",")) {
                labels.addAll(server.getLabelList(ALL_USERS, MAX_LABEL_COUNT, nameFilter, fileSpecs));
            }
        } else {
            labels.addAll(server.getLabelList(ALL_USERS, MAX_LABEL_COUNT, NO_LABEL_FILTER, fileSpecs));
        }

        Collections.sort(labels, new Comparator<P4JLabel>() {
            public int compare(P4JLabel o1, P4JLabel o2) {
                return Long.valueOf(o1.getLastUpdate().getTime()).compareTo(o2.getLastUpdate().getTime());
            }
        });

        LOGGER.info("Labels retrieved: " + labels.size());

        DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd");

        ReadableInterval interval = new Interval(
                fmt.parseMillis(System.getProperty("p4.interval.start", "1900-01-01")),
                fmt.parseMillis(System.getProperty("p4.interval.end", "2100-01-01")));

        Pattern labelFilter = Pattern.compile(System.getProperty("p4.label.filter", ".*"));
        for (P4JLabel label : labels) {
            // If the labels last update time is within the filtering time interval...
            final DateTime lastUpdatedOn = new DateTime(label.getLastUpdate().getTime());
            if (interval.contains(lastUpdatedOn)) {
                final Matcher matcher = labelFilter.matcher(label.getName());
                // If the label matches the regex
                if (matcher.matches()) {
                    LOGGER.info("Processing label: " + label.getName());
                    // Parse out the version
                    String version = matcher.group(1);

                    System.getProperties().put("sonar.projectDate", fmt.print(lastUpdatedOn));
                    if (version != null) {
                        System.getProperties().put("build.number", version);
                    }

                    LOGGER.debug("Syncing label.");
                    List<P4JFileSpec> synced = client.sync(
                            P4JFileSpecBuilder.getValidFileSpecs(P4JFileSpecBuilder
                                    .makeFileSpecList(new String[] { "@" + label.getName() })),
                            false, false, false, false);

                    LOGGER.debug("Files synced: " + synced.size());

                    LOGGER.debug("Starting Maven...");

                    try {
                        ProcessBuilder b = new ProcessBuilder().command(
                                System.getenv("M2_HOME") + "/bin/" + System.getProperty("mvn.exe"),
                                //                                                "-X",
                                "--batch-mode", "-e", "-Dbuild.number=" + version,
                                "-Dsonar.projectDate=" + System.getProperty("sonar.projectDate"),
                                "-Dsonar.exclusions=" + System.getProperty("sonar.exclusions", ""), "-s",
                                System.getProperty("m2.settings",
                                        System.getProperty("user.home") + "/.m2/settings.xml"),
                                "clean", "install", "sonar:sonar").directory(syncDir);
                        Process p = b.start();
                        //                            Process p = Runtime.getRuntime().exec(
                        //                                    new String[]{
                        //                                            System.getenv("M2_HOME") + "/bin/mvn",
                        //                                            "-Dbuild.number=" + version,
                        //                                            "-Dsonar.projectDate=" + System.getProperty("sonar.projectDate"),
                        //                                            "clean",
                        //                                            "validate"
                        //                                    }
                        //                            );

                        new Thread(new StreamRedirector(p.getErrorStream(), true)).start();
                        new Thread(new StreamRedirector(p.getInputStream(), false)).start();
                        p.waitFor();
                    } catch (IOException e) {
                        LOGGER.warn(e.getMessage(), e);
                    } catch (InterruptedException e) {
                        LOGGER.warn(e.getMessage(), e);
                    }

                    //                        try {
                    //                        // Now we are synced, fire up maven
                    //                        Configuration configuration = new DefaultConfiguration()
                    //                            .setUserSettingsFile( MavenEmbedder.DEFAULT_USER_SETTINGS_FILE )
                    //                            .setGlobalSettingsFile( MavenEmbedder.DEFAULT_GLOBAL_SETTINGS_FILE )
                    //                            .setClassLoader( Thread.currentThread().getContextClassLoader() )
                    //                                .setSystemProperties(System.getProperties())
                    //                                .setLocalRepository(new File(new File(System.getProperty("user.home"), ".m2"), "repository"))
                    //                                ;
                    //
                    //                        ConfigurationValidationResult validationResult = MavenEmbedder.validateConfiguration( configuration );
                    //
                    //                        if ( validationResult.isValid() )
                    //                        {
                    //
                    //                            MavenEmbedder embedder = new MavenEmbedder( configuration );
                    //
                    //                            MavenExecutionRequest request = new DefaultMavenExecutionRequest()
                    //                                .setBaseDirectory( syncDir )
                    //                                .setGoals( Arrays.asList( new String[]{"help:effective-settings"} ) )
                    //                                ;
                    //
                    //                            MavenExecutionResult result = embedder.execute( request );
                    //
                    //                            if ( result.hasExceptions() )
                    //                            {
                    //                                for (Exception exception : (List<Exception>) result.getExceptions()) {
                    //                                    exception.printStackTrace();
                    //                                }
                    //                                return;
                    //                            }
                    //                        } else {
                    //                            final Exception settingsException = validationResult.getGlobalSettingsException();
                    //                            if(settingsException != null) settingsException.printStackTrace();
                    //                            final Exception exception = validationResult.getUserSettingsException();
                    //                            if(exception != null) {
                    //                                exception.printStackTrace();
                    //                            }
                    //                            validationResult.display();
                    //                        }
                    //                        } catch (MavenEmbedderException e) {
                    //                            e.printStackTrace();
                    //                        }
                }
            }
        }

        LOGGER.debug("Clearing workspace...");

        List<P4JFileSpec> synced = client.sync(
                P4JFileSpecBuilder
                        .getValidFileSpecs(P4JFileSpecBuilder.makeFileSpecList(new String[] { "#0" })),
                false, false, false, false);
        LOGGER.debug("Files cleared: " + synced.size());

        server.setCurrentClient(null);

        server.deleteClient(client.getName(), false);

    } catch (URISyntaxException e) {
        LOGGER.warn(e.getMessage(), e);
    } catch (P4JConnectionException e) {
        LOGGER.warn(e.getMessage(), e);
    } catch (P4JNoSuchObjectException e) {
        LOGGER.warn(e.getMessage(), e);
    } catch (P4JConfigException e) {
        LOGGER.warn(e.getMessage(), e);
    } catch (P4JResourceException e) {
        LOGGER.warn(e.getMessage(), e);
    } catch (P4JAccessException e) {
        LOGGER.warn(e.getMessage(), e);
    } catch (P4JRequestException e) {
        LOGGER.warn(e.getMessage(), e);
    } catch (UnknownHostException e) {
        LOGGER.warn(e.getMessage(), e);
    }

    //        ReplayConfig config = buildReplayConfig(args);

}