Example usage for java.time LocalDate parse

List of usage examples for java.time LocalDate parse

Introduction

In this page you can find the example usage for java.time LocalDate parse.

Prototype

public static LocalDate parse(CharSequence text, DateTimeFormatter formatter) 

Source Link

Document

Obtains an instance of LocalDate from a text string using a specific formatter.

Usage

From source file:squash.booking.lambdas.core.RuleManagerTest.java

@Test
public void testCreateRuleThrowsWhenTheOptimisticPersisterThrows() throws Exception {
    // N.B. This applies except when the optimistic persister throws a
    // conditional check failed exclusion, which is covered by other tests.

    // ARRANGE/*from   w ww.j a  va2 s  .  c  o m*/
    thrown.expect(Exception.class);
    String message = "Test OptimisticPersister exception";
    thrown.expectMessage(message);

    // Set up a rule to create that does not clash with existing rules
    BookingRule nonClashingRule = new BookingRule(existingThursdayNonRecurringRule);
    // Change day-of-week so it no longer clashes
    String existingDate = nonClashingRule.getBooking().getDate();
    String newDate = LocalDate.parse(existingDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")).minusDays(1)
            .format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    nonClashingRule.getBooking().setDate(newDate); // Wednesday
    mockery.checking(new Expectations() {
        {
            oneOf(mockOptimisticPersister).put(with(equal(ruleItemName)), with(anything()), with(anything()));
            will(throwException(new Exception(message)));
        }
    });

    // ACT
    doTestCreateRuleClashesOrNotWithExistingRule(nonClashingRule, true);
}

From source file:squash.booking.lambdas.core.RuleManagerTest.java

@Test
public void testCreateRuleThrowsIfTheOptimisticPersisterThrowsAConditionalCheckFailedExceptionThreeTimesRunning()
        throws Exception {
    // The optimistic persister can throw a conditional check failed exclusion
    // if two database writes happen to get interleaved. Almost always, a retry
    // should fix this, and we allow up to three tries. This tests that if all
    // three tries fail then the rule manager will give up and throw.

    // ARRANGE/*ww w.  ja va 2 s  . co  m*/
    thrown.expect(Exception.class);
    String message = "Database put failed - conditional check failed";
    thrown.expectMessage(message);
    int versionToUse = 1; // Arbitrary
    expectOptimisticPersisterToReturnVersionedAttributes(versionToUse, 3);

    initialiseRuleManager();

    // Set up a rule to create that does not clash with existing rules
    BookingRule nonClashingRule = new BookingRule(existingThursdayNonRecurringRule);
    // Change day-of-week so it no longer clashes
    String existingDate = nonClashingRule.getBooking().getDate();
    String newDate = LocalDate.parse(existingDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")).minusDays(1)
            .format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    nonClashingRule.getBooking().setDate(newDate); // Wednesday
    mockery.checking(new Expectations() {
        {
            // All three tries throw
            exactly(3).of(mockOptimisticPersister).put(with(equal(ruleItemName)), with(anything()),
                    with(anything()));
            will(throwException(new Exception(message)));
        }
    });

    // ACT
    // This should throw - albeit after three tries internally.
    // N.B. The second parameter is arbitrary here.
    ruleManager.createRule(nonClashingRule, true);
}

From source file:org.talend.dataprep.transformation.actions.date.ComputeTimeSinceTest.java

/**
 * Compute time since .//from w  w  w.  j a v a  2 s  .  co  m
 *
 * @param date      the date to compute from.
 * @param pattern   the pattern to use.
 * @param unit      the unit for the result.
 * @param sinceWhen the date to calculate since when
 * @return time since now in the wanted unit.
 */
String computeTimeSince(String date, String pattern, ChronoUnit unit, String sinceWhen) {

    DateTimeFormatter format = DateTimeFormatter.ofPattern(pattern);
    Temporal since;
    if (sinceWhen == null) {
        since = LocalDateTime.now();
    } else {
        since = LocalDateTime.parse(sinceWhen, format);
    }

    LocalDateTime start;
    try {
        start = LocalDateTime.parse(date, format);
    } catch (Exception e) {
        start = null;
    }

    if (start == null) {
        LocalDate temp = LocalDate.parse(date, format);
        start = temp.atStartOfDay();
    }

    Temporal result = LocalDateTime.from(start);
    return String.valueOf(unit.between(result, since));
}

From source file:squash.booking.lambdas.core.RuleManagerTest.java

@Test
public void testCreateRuleDoesNotThrowIfTheOptimisticPersisterThrowsAConditionalCheckFailedExceptionOnlyTwice()
        throws Exception {
    // The optimistic persister can throw a conditional check failed exclusion
    // if two database writes happen to get interleaved. Almost always, a retry
    // should fix this, and we allow up to three tries. This tests that if we
    // throw twice but the third try succeeds, then the rule manager does not
    // throw.//from  ww w  .  jav a  2 s.  com

    // ARRANGE
    int versionToUse = 1; // Arbitrary
    expectOptimisticPersisterToReturnVersionedAttributes(versionToUse, 3);
    initialiseRuleManager();

    // Set up a rule to create that does not clash with existing rules
    BookingRule nonClashingRule = new BookingRule(existingThursdayNonRecurringRule);
    // Change day-of-week so it no longer clashes
    String existingDate = nonClashingRule.getBooking().getDate();
    String newDate = LocalDate.parse(existingDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")).minusDays(1)
            .format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    nonClashingRule.getBooking().setDate(newDate); // Wednesday

    final Sequence retrySequence = mockery.sequence("retry");
    mockery.checking(new Expectations() {
        {
            // Two failures...
            exactly(2).of(mockOptimisticPersister).put(with(equal(ruleItemName)), with(anything()),
                    with(anything()));
            will(throwException(new Exception("Database put failed - conditional check failed")));
            inSequence(retrySequence);
            // ... but third attempt succeeds
            oneOf(mockOptimisticPersister).put(with(equal(ruleItemName)), with(anything()), with(anything()));
            will(returnValue(2));
            inSequence(retrySequence);
        }
    });

    // ACT
    // This should _not_ throw - we are allowed three tries
    // N.B. The second parameter is arbitrary here.
    ruleManager.createRule(nonClashingRule, true);
}

From source file:ro.cs.products.Executor.java

private static int execute(CommandLine commandLine) throws Exception {
    int retCode = ReturnCode.OK;
    CommandLineParser parser = new DefaultParser();
    String logFile = props.getProperty("master.log.file");
    String folder;//from   w  w w. ja  v  a 2 s. c  o  m
    boolean debugMode = commandLine.hasOption(Constants.PARAM_VERBOSE);
    Logger.CustomLogger logger;
    SensorType sensorType = commandLine.hasOption(Constants.SENSOR)
            ? Enum.valueOf(SensorType.class, commandLine.getOptionValue(Constants.SENSOR))
            : SensorType.S2;
    if (commandLine.hasOption(Constants.PARAM_INPUT_FOLDER)) {
        folder = commandLine.getOptionValue(Constants.PARAM_INPUT_FOLDER);
        Utilities.ensureExists(Paths.get(folder));
        Logger.initialize(Paths.get(folder, logFile).toAbsolutePath().toString(), debugMode);
        logger = Logger.getRootLogger();
        if (commandLine.hasOption(Constants.PARAM_VERBOSE)) {
            printCommandLine(commandLine);
        }
        if (sensorType == SensorType.L8) {
            logger.warn("Argument --input will be ignored for Landsat8");
        } else {
            String rootFolder = commandLine.getOptionValue(Constants.PARAM_INPUT_FOLDER);
            FillAnglesMethod fillAnglesMethod = Enum.valueOf(FillAnglesMethod.class,
                    commandLine.hasOption(Constants.PARAM_FILL_ANGLES)
                            ? commandLine.getOptionValue(Constants.PARAM_FILL_ANGLES).toUpperCase()
                            : FillAnglesMethod.NONE.name());
            if (!FillAnglesMethod.NONE.equals(fillAnglesMethod)) {
                try {
                    Set<String> products = null;
                    if (commandLine.hasOption(Constants.PARAM_PRODUCT_LIST)) {
                        products = new HashSet<>();
                        for (String product : commandLine.getOptionValues(Constants.PARAM_PRODUCT_LIST)) {
                            if (!product.endsWith(".SAFE")) {
                                products.add(product + ".SAFE");
                            } else {
                                products.add(product);
                            }
                        }
                    }
                    ProductInspector inspector = new ProductInspector(rootFolder, fillAnglesMethod, products);
                    inspector.traverse();
                } catch (IOException e) {
                    logger.error(e.getMessage());
                    retCode = ReturnCode.DOWNLOAD_ERROR;
                }
            }
        }
    } else {
        folder = commandLine.getOptionValue(Constants.PARAM_OUT_FOLDER);
        Utilities.ensureExists(Paths.get(folder));
        Logger.initialize(Paths.get(folder, logFile).toAbsolutePath().toString(), debugMode);
        logger = Logger.getRootLogger();
        printCommandLine(commandLine);

        String proxyType = commandLine.hasOption(Constants.PARAM_PROXY_TYPE)
                ? commandLine.getOptionValue(Constants.PARAM_PROXY_TYPE)
                : nullIfEmpty(props.getProperty("proxy.type", null));
        String proxyHost = commandLine.hasOption(Constants.PARAM_PROXY_HOST)
                ? commandLine.getOptionValue(Constants.PARAM_PROXY_HOST)
                : nullIfEmpty(props.getProperty("proxy.host", null));
        String proxyPort = commandLine.hasOption(Constants.PARAM_PROXY_PORT)
                ? commandLine.getOptionValue(Constants.PARAM_PROXY_PORT)
                : nullIfEmpty(props.getProperty("proxy.port", null));
        String proxyUser = commandLine.hasOption(Constants.PARAM_PROXY_USER)
                ? commandLine.getOptionValue(Constants.PARAM_PROXY_USER)
                : nullIfEmpty(props.getProperty("proxy.user", null));
        String proxyPwd = commandLine.hasOption(Constants.PARAM_PROXY_PASSWORD)
                ? commandLine.getOptionValue(Constants.PARAM_PROXY_PASSWORD)
                : nullIfEmpty(props.getProperty("proxy.pwd", null));
        NetUtils.setProxy(proxyType, proxyHost, proxyPort == null ? 0 : Integer.parseInt(proxyPort), proxyUser,
                proxyPwd);

        List<ProductDescriptor> products = new ArrayList<>();
        Set<String> tiles = new HashSet<>();
        Polygon2D areaOfInterest = new Polygon2D();

        ProductStore source = Enum.valueOf(ProductStore.class,
                commandLine.getOptionValue(Constants.PARAM_DOWNLOAD_STORE, ProductStore.SCIHUB.toString()));

        if (sensorType == SensorType.S2 && !commandLine.hasOption(Constants.PARAM_FLAG_SEARCH_AWS)
                && !commandLine.hasOption(Constants.PARAM_USER)) {
            throw new MissingOptionException("Missing SciHub credentials");
        }

        String user = commandLine.getOptionValue(Constants.PARAM_USER);
        String pwd = commandLine.getOptionValue(Constants.PARAM_PASSWORD);
        if (user != null && pwd != null && !user.isEmpty() && !pwd.isEmpty()) {
            String authToken = "Basic " + new String(Base64.getEncoder().encode((user + ":" + pwd).getBytes()));
            NetUtils.setAuthToken(authToken);
        }

        ProductDownloader downloader = sensorType.equals(SensorType.S2)
                ? new SentinelProductDownloader(source, commandLine.getOptionValue(Constants.PARAM_OUT_FOLDER),
                        props)
                : new LandsatProductDownloader(commandLine.getOptionValue(Constants.PARAM_OUT_FOLDER), props);

        TileMap tileMap = sensorType == SensorType.S2 ? SentinelTilesMap.getInstance()
                : LandsatTilesMap.getInstance();

        if (commandLine.hasOption(Constants.PARAM_AREA)) {
            String[] points = commandLine.getOptionValues(Constants.PARAM_AREA);
            for (String point : points) {
                areaOfInterest.append(Double.parseDouble(point.substring(0, point.indexOf(","))),
                        Double.parseDouble(point.substring(point.indexOf(",") + 1)));
            }
        } else if (commandLine.hasOption(Constants.PARAM_AREA_FILE)) {
            areaOfInterest = Polygon2D.fromWKT(new String(
                    Files.readAllBytes(Paths.get(commandLine.getOptionValue(Constants.PARAM_AREA_FILE))),
                    StandardCharsets.UTF_8));
        } else if (commandLine.hasOption(Constants.PARAM_TILE_SHAPE_FILE)) {
            String tileShapeFile = commandLine.getOptionValue(Constants.PARAM_TILE_SHAPE_FILE);
            if (Files.exists(Paths.get(tileShapeFile))) {
                logger.info(String.format("Reading %s tiles extents", sensorType));
                tileMap.fromKmlFile(tileShapeFile);
                logger.info(String.valueOf(tileMap.getCount() + " tiles found"));
            }
        } else {
            if (tileMap.getCount() == 0) {
                logger.info(String.format("Loading %s tiles extents", sensorType));
                tileMap.read(Executor.class.getResourceAsStream(sensorType + "tilemap.dat"));
                logger.info(String.valueOf(tileMap.getCount() + " tile extents loaded"));
            }
        }

        if (commandLine.hasOption(Constants.PARAM_TILE_LIST)) {
            Collections.addAll(tiles, commandLine.getOptionValues(Constants.PARAM_TILE_LIST));
        } else if (commandLine.hasOption(Constants.PARAM_TILE_LIST_FILE)) {
            tiles.addAll(
                    Files.readAllLines(Paths.get(commandLine.getOptionValue(Constants.PARAM_TILE_LIST_FILE))));
        }

        if (commandLine.hasOption(Constants.PARAM_PRODUCT_LIST)) {
            String[] uuids = commandLine.getOptionValues(Constants.PARAM_PRODUCT_UUID_LIST);
            String[] productNames = commandLine.getOptionValues(Constants.PARAM_PRODUCT_LIST);
            if (sensorType == SensorType.S2
                    && (!commandLine.hasOption(Constants.PARAM_DOWNLOAD_STORE) || ProductStore.SCIHUB.toString()
                            .equals(commandLine.getOptionValue(Constants.PARAM_DOWNLOAD_STORE)))
                    && (uuids == null || uuids.length != productNames.length)) {
                logger.error("For the list of product names a corresponding list of UUIDs has to be given!");
                return -1;
            }
            for (int i = 0; i < productNames.length; i++) {
                ProductDescriptor productDescriptor = sensorType == SensorType.S2
                        ? new SentinelProductDescriptor(productNames[i])
                        : new LandsatProductDescriptor(productNames[i]);
                if (uuids != null) {
                    productDescriptor.setId(uuids[i]);
                }
                products.add(productDescriptor);
            }
        } else if (commandLine.hasOption(Constants.PARAM_PRODUCT_LIST_FILE)) {
            for (String line : Files
                    .readAllLines(Paths.get(commandLine.getOptionValue(Constants.PARAM_PRODUCT_LIST_FILE)))) {
                products.add(sensorType == SensorType.S2 ? new SentinelProductDescriptor(line)
                        : new LandsatProductDescriptor(line));
            }
        }

        double clouds;
        if (commandLine.hasOption(Constants.PARAM_CLOUD_PERCENTAGE)) {
            clouds = Double.parseDouble(commandLine.getOptionValue(Constants.PARAM_CLOUD_PERCENTAGE));
        } else {
            clouds = Constants.DEFAULT_CLOUD_PERCENTAGE;
        }
        String sensingStart;
        if (commandLine.hasOption(Constants.PARAM_START_DATE)) {
            String dateString = commandLine.getOptionValue(Constants.PARAM_START_DATE);
            LocalDate startDate = LocalDate.parse(dateString, DateTimeFormatter.ISO_DATE);
            long days = ChronoUnit.DAYS.between(startDate, LocalDate.now());
            sensingStart = String.format(Constants.PATTERN_START_DATE, days);
        } else {
            sensingStart = Constants.DEFAULT_START_DATE;
        }

        String sensingEnd;
        if (commandLine.hasOption(Constants.PARAM_END_DATE)) {
            String dateString = commandLine.getOptionValue(Constants.PARAM_END_DATE);
            LocalDate endDate = LocalDate.parse(dateString, DateTimeFormatter.ISO_DATE);
            long days = ChronoUnit.DAYS.between(endDate, LocalDate.now());
            sensingEnd = String.format(Constants.PATTERN_START_DATE, days);
        } else {
            sensingEnd = Constants.DEFAULT_END_DATE;
        }

        int limit;
        if (commandLine.hasOption(Constants.PARAM_RESULTS_LIMIT)) {
            limit = Integer.parseInt(commandLine.getOptionValue(Constants.PARAM_RESULTS_LIMIT));
        } else {
            limit = Constants.DEFAULT_RESULTS_LIMIT;
        }

        if (commandLine.hasOption(Constants.PARAM_DOWNLOAD_STORE)) {
            String value = commandLine.getOptionValue(Constants.PARAM_DOWNLOAD_STORE);
            if (downloader instanceof SentinelProductDownloader) {
                ((SentinelProductDownloader) downloader)
                        .setDownloadStore(Enum.valueOf(ProductStore.class, value));
                logger.info("Products will be downloaded from %s", value);
            } else {
                logger.warn("Argument --store will be ignored for Landsat8");
            }
        }

        downloader.shouldCompress(commandLine.hasOption(Constants.PARAM_FLAG_COMPRESS));
        downloader.shouldDeleteAfterCompression(commandLine.hasOption(Constants.PARAM_FLAG_DELETE));
        if (commandLine.hasOption(Constants.PARAM_FILL_ANGLES)) {
            if (downloader instanceof SentinelProductDownloader) {
                ((SentinelProductDownloader) downloader)
                        .setFillMissingAnglesMethod(Enum.valueOf(FillAnglesMethod.class,
                                commandLine.hasOption(Constants.PARAM_FILL_ANGLES)
                                        ? commandLine.getOptionValue(Constants.PARAM_FILL_ANGLES).toUpperCase()
                                        : FillAnglesMethod.NONE.name()));
            } else {
                logger.warn("Argument --ma will be ignored for Landsat8");
            }
        }

        int numPoints = areaOfInterest.getNumPoints();
        tiles = tiles.stream().map(t -> t.startsWith("T") ? t.substring(1) : t).collect(Collectors.toSet());
        if (products.size() == 0 && numPoints == 0 && tileMap.getCount() > 0) {
            Rectangle2D rectangle2D = tileMap.boundingBox(tiles);
            areaOfInterest.append(rectangle2D.getX(), rectangle2D.getY());
            areaOfInterest.append(rectangle2D.getMaxX(), rectangle2D.getY());
            areaOfInterest.append(rectangle2D.getMaxX(), rectangle2D.getMaxY());
            areaOfInterest.append(rectangle2D.getX(), rectangle2D.getMaxY());
            areaOfInterest.append(rectangle2D.getX(), rectangle2D.getY());
        }

        numPoints = areaOfInterest.getNumPoints();
        if (products.size() == 0 && numPoints > 0) {
            String searchUrl;
            AbstractSearch searchProvider;
            logger.debug("No product provided, searching on the AOI");
            if (sensorType == SensorType.L8) {
                logger.debug("Search will be done for Landsat");
                searchUrl = props.getProperty(Constants.PROPERTY_NAME_LANDSAT_SEARCH_URL,
                        Constants.PROPERTY_NAME_DEFAULT_LANDSAT_SEARCH_URL);
                if (!NetUtils.isAvailable(searchUrl)) {
                    logger.warn(searchUrl + " is not available!");
                }
                searchProvider = new LandsatSearch(searchUrl);
                if (commandLine.hasOption(Constants.PARAM_START_DATE)) {
                    searchProvider.setSensingStart(commandLine.getOptionValue(Constants.PARAM_START_DATE));
                }
                if (commandLine.hasOption(Constants.PARAM_END_DATE)) {
                    searchProvider.setSensingEnd(commandLine.getOptionValue(Constants.PARAM_END_DATE));
                }
                if (commandLine.hasOption(Constants.PARAM_TILE_LIST)) {
                    searchProvider.setTiles(tiles);
                }
                ((LandsatSearch) searchProvider).limit(limit);
            } else if (!commandLine.hasOption(Constants.PARAM_FLAG_SEARCH_AWS)) {
                logger.debug("Search will be done on SciHub");
                searchUrl = props.getProperty(Constants.PROPERTY_NAME_SEARCH_URL,
                        Constants.PROPERTY_DEFAULT_SEARCH_URL);
                if (!NetUtils.isAvailable(searchUrl)) {
                    logger.warn(searchUrl + " is not available!");
                    searchUrl = props.getProperty(Constants.PROPERTY_NAME_SEARCH_URL_SECONDARY,
                            Constants.PROPERTY_DEFAULT_SEARCH_URL_SECONDARY);
                }
                searchProvider = new SciHubSearch(searchUrl);
                SciHubSearch search = (SciHubSearch) searchProvider;
                if (user != null && !user.isEmpty() && pwd != null && !pwd.isEmpty()) {
                    search = search.auth(user, pwd);
                }
                String interval = "[" + sensingStart + " TO " + sensingEnd + "]";
                search.filter(Constants.SEARCH_PARAM_INTERVAL, interval).limit(limit);
                if (commandLine.hasOption(Constants.PARAM_RELATIVE_ORBIT)) {
                    search.filter(Constants.SEARCH_PARAM_RELATIVE_ORBIT_NUMBER,
                            commandLine.getOptionValue(Constants.PARAM_RELATIVE_ORBIT));
                }
            } else {
                logger.debug("Search will be done on AWS");
                searchUrl = props.getProperty(Constants.PROPERTY_NAME_AWS_SEARCH_URL,
                        Constants.PROPERTY_DEFAULT_AWS_SEARCH_URL);
                searchProvider = new AmazonSearch(searchUrl);
                searchProvider.setTiles(tiles);
                Calendar calendar = Calendar.getInstance();
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                calendar.add(Calendar.DAY_OF_MONTH,
                        Integer.parseInt(sensingStart.replace("NOW", "").replace("DAY", "")));
                searchProvider.setSensingStart(dateFormat.format(calendar.getTime()));
                calendar = Calendar.getInstance();
                String endOffset = sensingEnd.replace("NOW", "").replace("DAY", "");
                int offset = endOffset.isEmpty() ? 0 : Integer.parseInt(endOffset);
                calendar.add(Calendar.DAY_OF_MONTH, offset);
                searchProvider.setSensingEnd(dateFormat.format(calendar.getTime()));
                if (commandLine.hasOption(Constants.PARAM_RELATIVE_ORBIT)) {
                    searchProvider.setOrbit(
                            Integer.parseInt(commandLine.getOptionValue(Constants.PARAM_RELATIVE_ORBIT)));
                }
            }
            if (searchProvider.getTiles() == null || searchProvider.getTiles().size() == 0) {
                searchProvider.setAreaOfInterest(areaOfInterest);
            }
            searchProvider.setClouds(clouds);
            products = searchProvider.execute();
        } else {
            logger.debug("Product name(s) present, no additional search will be performed.");
        }
        if (downloader instanceof SentinelProductDownloader) {
            ((SentinelProductDownloader) downloader).setFilteredTiles(tiles,
                    commandLine.hasOption(Constants.PARAM_FLAG_UNPACKED));
        }
        downloader.setProgressListener(batchProgressListener);
        downloader.setFileProgressListener(fileProgressListener);
        retCode = downloader.downloadProducts(products);
    }
    return retCode;
}

From source file:squash.booking.lambdas.core.RuleManagerTest.java

@Test
public void testCreateNonrecurringRuleHappyPathCallsTheOptimisticPersisterCorrectly() throws Exception {
    // Happy path where createRule goes right through and creates the
    // non-recurring rule.

    // ARRANGE//from ww w. j a  v  a  2 s  .c o m

    // Set up a rule to create that does not clash with existing rules
    BookingRule nonClashingRule = new BookingRule(existingThursdayNonRecurringRule);
    // Change day-of-week so it no longer clashes
    String existingDate = nonClashingRule.getBooking().getDate();
    String newDate = LocalDate.parse(existingDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")).minusDays(1)
            .format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    nonClashingRule.getBooking().setDate(newDate); // Wednesday

    doTestCreateRuleClashesOrNotWithExistingRule(nonClashingRule, false);
}

From source file:squash.booking.lambdas.core.RuleManagerTest.java

@Test
public void testCreateRecurringRuleHappyPathCallsTheOptimisticPersisterCorrectly() throws Exception {
    // Happy path where createRule goes right through and creates the recurring
    // rule./*  w  w w.j ava  2  s. c o  m*/

    // ARRANGE

    // Set up a rule to create that does not clash with existing rules
    BookingRule nonClashingRule = new BookingRule(existingFridayRecurringRuleWithoutExclusions);
    // Change day-of-week so it no longer clashes
    String existingDate = nonClashingRule.getBooking().getDate();
    String newDate = LocalDate.parse(existingDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")).plusDays(2)
            .format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    nonClashingRule.getBooking().setDate(newDate); // Sunday

    doTestCreateRuleClashesOrNotWithExistingRule(nonClashingRule, false);
}

From source file:squash.booking.lambdas.core.RuleManagerTest.java

@Test
public void testCreateNonrecurringRuleHappyPathReturnsCorrectBookingRules() throws Exception {

    // ARRANGE/*w  ww.j a  v  a2  s  . c  o m*/

    // Set up a rule to create that does not clash with existing rules
    BookingRule nonClashingRule = new BookingRule(existingThursdayNonRecurringRule);
    // Change day-of-week so it no longer clashes
    String existingDate = nonClashingRule.getBooking().getDate();
    String newDate = LocalDate.parse(existingDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")).minusDays(1)
            .format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    nonClashingRule.getBooking().setDate(newDate); // Wednesday

    Set<BookingRule> returnedBookingRules = doTestCreateRuleClashesOrNotWithExistingRule(nonClashingRule,
            false);
    Set<BookingRule> expectedBookingRules = new HashSet<>();
    expectedBookingRules.addAll(existingBookingRules);
    expectedBookingRules.add(nonClashingRule);

    assertEquals("Unexpected booking rules returned by createRule", returnedBookingRules, expectedBookingRules);
}

From source file:investiagenofx2.view.InvestiaGenOFXController.java

private void getAccountsInvestmentsFromWeb() {
    @SuppressWarnings(("unchecked"))
    List<HtmlTable> tables = (List<HtmlTable>) htmlPage
            .getByXPath("//table[contains(@class, 'table-striped')]");
    @SuppressWarnings(("unchecked"))
    List<HtmlDivision> divBalancesAs = (List<HtmlDivision>) htmlPage
            .getByXPath("//div[contains(text(),'Soldes au')]");
    LocalDate balancesAs = LocalDate.parse(divBalancesAs.get(0).asText().replace("Soldes au ", ""),
            DateTimeFormatter.ofPattern("dd MMMM yyyy", Locale.CANADA_FRENCH));
    int i = 0;//from   ww  w .  j  a  va  2s  .c  om
    for (HtmlTable table : tables) {
        if (!table.asText().contains("Numro de \r\n compte")) {
            continue;
        }
        if (accounts.get(i).getAccountID() == null) {
            accounts.get(i).setAccountID(table.getCellAt(1, 3).getTextContent());
        }
        Float total = 0f;
        for (int j = 1; j < table.getRowCount(); j++) {
            String symbol = table.getCellAt(j, 1).getTextContent();
            String name = table.getCellAt(j, 0).getTextContent();
            String quantity = table.getCellAt(j, 5).getTextContent().replaceAll("[^0-9,]", "").replace(",",
                    ".");
            String lastPrice = table.getCellAt(j, 6).getTextContent().replaceAll("[^0-9,]", "").replace(",",
                    ".");
            String marketValue = table.getCellAt(j, 7).getTextContent().replaceAll("[^0-9,]", "").replace(",",
                    ".");
            Investment investment = new Investment(symbol, name, quantity, lastPrice, marketValue);
            accounts.get(i).add(investment);
            total += Float.valueOf(marketValue);
        }
        String totalString = String.format("%.02f", total);
        Investment investment = new Investment("", "Total", totalString, "1.00", totalString);
        accounts.get(i).add(investment);
        if (!balancesAs.equals(dataAsDate))
            accounts.get(i).setBalanceDate(balancesAs);
        i++;
    }
    if (!balancesAs.equals(dataAsDate))
        dataAsDate = balancesAs;
}

From source file:org.tightblog.ui.restapi.WeblogEntryController.java

private Instant calculatePubTime(WeblogEntry entry) {
    Instant pubtime = null;/*from  www. ja  v a  2  s .c o  m*/

    String dateString = entry.getDateString();
    if (!StringUtils.isEmpty(dateString)) {
        try {
            LocalDate newDate = LocalDate.parse(dateString, pubDateFormat);

            // Now handle the time from the hour, minute and second combos
            pubtime = newDate.atTime(entry.getHours(), entry.getMinutes()).atZone(entry.getWeblog().getZoneId())
                    .toInstant();
        } catch (Exception e) {
            log.error("Error calculating pubtime", e);
        }
    }
    return pubtime;
}