Example usage for java.time.temporal ChronoUnit DAYS

List of usage examples for java.time.temporal ChronoUnit DAYS

Introduction

In this page you can find the example usage for java.time.temporal ChronoUnit DAYS.

Prototype

ChronoUnit DAYS

To view the source code for java.time.temporal ChronoUnit DAYS.

Click Source Link

Document

Unit that represents the concept of a day.

Usage

From source file:org.nuxeo.ecm.core.TestSQLRepositoryQuery.java

@Test
public void testQueryACLReturnedValue() throws Exception {
    createDocs();/* ww  w  .j a v  a2  s  .  c  o  m*/
    DocumentModel folder1 = session.getDocument(new PathRef("/testfolder1"));
    ACP acp = new ACPImpl();
    ACL acl = new ACLImpl();
    acl.add(new ACE("Administrator", "Everything", true));
    acl.add(new ACE("bob", "Browse", true));
    acl.add(new ACE("steve", "Read", true));
    Date now = new Date();
    Calendar begin = new GregorianCalendar();
    begin.setTimeInMillis(now.toInstant().minus(5, ChronoUnit.DAYS).toEpochMilli());
    // avoid DB rounding for timestamp on seconds / milliseconds
    begin.set(Calendar.SECOND, 0);
    begin.set(Calendar.MILLISECOND, 0);
    Calendar end = new GregorianCalendar();
    end.setTimeInMillis(now.toInstant().plus(5, ChronoUnit.DAYS).toEpochMilli());
    end.set(Calendar.SECOND, 0);
    end.set(Calendar.MILLISECOND, 0);
    acl.add(ACE.builder("leela", "Write").creator("Administrator").begin(begin).end(end).build());
    acl.add(ACE.BLOCK);
    acp.addACL(acl);
    folder1.setACP(acp, true);
    session.save();

    // update the begin and end dates from the one being stored in the DB to correctly match them after
    ACP updatedACP = session.getACP(folder1.getRef());
    ACL updatedACL = updatedACP.getACL(ACL.LOCAL_ACL);
    for (ACE ace : updatedACL) {
        if ("leela".equals(ace.getUsername())) {
            begin = ace.getBegin();
            end = ace.getEnd();
            break;
        }
    }

    IterableQueryResult res;
    // simple query
    res = session.queryAndFetch(
            "SELECT ecm:uuid, ecm:acl/*1/name, ecm:acl/*1/principal, ecm:acl/*1/permission FROM Document WHERE ecm:isProxy = 0 AND "
                    + "ecm:acl/*1/permission in ('Read', 'Browse') AND ecm:acl/*1/grant = 1",
            "NXQL");
    assertEquals(2, res.size());
    Set<String> set = new HashSet<>();
    for (Map<String, Serializable> map : res) {
        set.add(map.get("ecm:acl/*1/name") + ":" + map.get("ecm:acl/*1/principal") + ":"
                + map.get("ecm:acl/*1/permission"));
    }
    res.close();
    assertEquals(new HashSet<>(Arrays.asList("local:bob:Browse", "local:steve:Read")), set);

    // read full ACL
    // ecm:pos in VCS-specific so not checked
    res = session.queryAndFetch(
            "SELECT ecm:uuid, ecm:acl/*1/name, ecm:acl/*1/principal, ecm:acl/*1/permission, ecm:acl/*1/grant"
                    + ", ecm:acl/*1/creator, ecm:acl/*1/begin, ecm:acl/*1/end FROM Document"
                    + " WHERE ecm:isProxy = 0 AND " + "ecm:acl/*/principal = 'bob'",
            "NXQL");
    assertEquals(5, res.size());
    set = new HashSet<>();
    for (Map<String, Serializable> map : res) {
        String ace = map.get("ecm:acl/*1/name") + ":" + map.get("ecm:acl/*1/principal") + ":"
                + map.get("ecm:acl/*1/permission") + ":" + map.get("ecm:acl/*1/grant") + ":"
                + map.get("ecm:acl/*1/creator");
        Calendar cal = (Calendar) map.get("ecm:acl/*1/begin");
        ace += ":" + (cal != null ? cal.getTimeInMillis() : null);
        cal = (Calendar) map.get("ecm:acl/*1/end");
        ace += ":" + (cal != null ? cal.getTimeInMillis() : null);
        set.add(ace);
    }
    res.close();
    assertEquals(
            new HashSet<>(
                    Arrays.asList("local:Administrator:Everything:true:null:null:null",
                            "local:bob:Browse:true:null:null:null", "local:steve:Read:true:null:null:null",
                            "local:leela:Write:true:Administrator:" + begin.getTimeInMillis() + ":"
                                    + end.getTimeInMillis(),
                            "local:Everyone:Everything:false:null:null:null")),
            set);
}

From source file:org.openhab.binding.darksky.internal.handler.DarkSkyWeatherAndForecastHandler.java

/**
 * Applies the given configuration to the given timestamp.
 *
 * @param dateTime timestamp represented as {@link ZonedDateTime}
 * @param config {@link DarkSkyChannelConfiguration} instance
 * @return the modified timestamp/*from   w  w w.  jav a  2  s  .c o  m*/
 */
private ZonedDateTime applyChannelConfig(ZonedDateTime dateTime, @Nullable DarkSkyChannelConfiguration config) {
    ZonedDateTime modifiedDateTime = dateTime;
    if (config != null) {
        if (config.getOffset() != 0) {
            if (logger.isTraceEnabled()) {
                logger.trace("Apply offset of {} min to timestamp '{}'.", config.getOffset(),
                        modifiedDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
            }
            modifiedDateTime = modifiedDateTime.plusMinutes(config.getOffset());
        }
        long earliestInMinutes = config.getEarliestInMinutes();
        if (earliestInMinutes > 0) {
            ZonedDateTime earliestDateTime = modifiedDateTime.truncatedTo(ChronoUnit.DAYS)
                    .plusMinutes(earliestInMinutes);
            if (modifiedDateTime.isBefore(earliestDateTime)) {
                if (logger.isTraceEnabled()) {
                    logger.trace("Use earliest timestamp '{}' instead of '{}'.",
                            earliestDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME),
                            modifiedDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
                }
                return earliestDateTime;
            }
        }
        long latestInMinutes = config.getLatestInMinutes();
        if (latestInMinutes > 0) {
            ZonedDateTime latestDateTime = modifiedDateTime.truncatedTo(ChronoUnit.DAYS)
                    .plusMinutes(latestInMinutes);
            if (modifiedDateTime.isAfter(latestDateTime)) {
                if (logger.isTraceEnabled()) {
                    logger.trace("Use latest timestamp '{}' instead of '{}'.",
                            latestDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME),
                            modifiedDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
                }
                return latestDateTime;
            }
        }
    }
    return modifiedDateTime;
}

From source file:org.sakaiproject.sitestats.tool.wicket.pages.UserActivityPage.java

@Override
protected void onInitialize() {
    super.onInitialize();

    Form form = new Form("form");
    add(form);/*from  ww w.ja va  2s  .  c o  m*/
    add(new Menus("menu", siteId));

    lastJobRunContainer = new WebMarkupContainer("lastJobRunContainer");
    lastJobRunContainer.setOutputMarkupId(true);
    add(lastJobRunContainer);
    lastJobRunContainer.add(new LastJobRun("lastJobRun", siteId));

    IChoiceRenderer<DisplayUser> userChoiceRenderer = new ChoiceRenderer<DisplayUser>() {
        @Override
        public Object getDisplayValue(DisplayUser user) {
            // Short circuit if user is blank
            if (StringUtils.isBlank(user.userId)) {
                return new ResourceModel("user_unknown").getObject();
            }

            // String representation of 'select user' option
            if (ReportManager.WHO_NONE.equals(user.userId)) {
                return new ResourceModel("de_select_user").getObject();
            }

            return user.display;
        }

        @Override
        public String getIdValue(DisplayUser user, int index) {
            return user.userId;
        }
    };

    DropDownChoice<DisplayUser> userFilter = new DropDownChoice<>("userFilter",
            new PropertyModel<>(this, "displayUser"), new LoadableDisplayUserListModel(siteId),
            userChoiceRenderer);
    userFilter.add(new AjaxFormComponentUpdatingBehavior("onchange") {
        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            if (ReportManager.WHO_NONE.equals(displayUser.userId)) {
                searchButton.setEnabled(false);
                target.add(searchButton);
            } else {
                searchButton.setEnabled(true);
                target.add(searchButton);
            }
        }
    });
    userFilter.setLabel(new ResourceModel("de_userFilter"));
    form.add(new SimpleFormComponentLabel("userFilterLabel", userFilter));
    form.add(userFilter);

    IChoiceRenderer<String> toolChoiceRenderer = new ChoiceRenderer<String>() {
        @Override
        public Object getDisplayValue(String toolId) {
            return Locator.getFacade().getEventRegistryService().getToolName(toolId);
        }

        @Override
        public String getIdValue(String toolId, int index) {
            return toolId;
        }
    };
    DropDownChoice<String> eventFilterByTool = new DropDownChoice<>("eventFilter",
            new PropertyModel<>(this, "tool"), new LoadableToolIdListModel(siteId), toolChoiceRenderer);
    eventFilterByTool.setLabel(new ResourceModel("de_eventFilter"));
    form.add(new SimpleFormComponentLabel("eventFilterLabel", eventFilterByTool));
    form.add(eventFilterByTool);

    ZoneId tz = Locator.getFacade().getUserTimeService().getLocalTimeZone().toZoneId();
    startDate = ZonedDateTime.now(tz).truncatedTo(ChronoUnit.DAYS);
    SakaiDateTimeField startDateField = new SakaiDateTimeField("startDate",
            new PropertyModel<>(this, "startDate"), tz);
    startDateField.setLabel(new ResourceModel("de_dateRangeFrom"));
    form.add(new SimpleFormComponentLabel("startDateLabel", startDateField));
    form.add(startDateField);

    endDate = startDate.plusDays(1);
    SakaiDateTimeField endDateField = new SakaiDateTimeField("endDate", new PropertyModel<>(this, "endDate"),
            tz);
    endDateField.setLabel(new ResourceModel("de_dateRangeTo"));
    form.add(new SimpleFormComponentLabel("endDateLabel", endDateField));
    form.add(endDateField);

    String zoneName = startDate.getZone().getDisplayName(TextStyle.FULL, getSession().getLocale());
    StringResourceModel legendModel = new StringResourceModel("de_dateRange", getPage(), null,
            new Object[] { zoneName });
    form.add(new Label("dateRangeLegend", legendModel));

    final UserTrackingResultsPanel resultsPanel = new UserTrackingResultsPanel("results",
            TrackingParams.EMPTY_PARAMS);
    resultsPanel.setOutputMarkupPlaceholderTag(true);
    resultsPanel.setVisible(false);
    add(resultsPanel);

    searchButton = new SakaiAjaxButton("search", form) {
        @Override
        public void onSubmit(AjaxRequestTarget target, Form form) {
            // run search
            PrefsData pd = Locator.getFacade().getStatsManager().getPreferences(siteId, false);
            TrackingParams params = new TrackingParams(siteId,
                    Tools.getEventsForToolFilter(tool, siteId, pd, true),
                    Collections.singletonList(displayUser.userId), startDate.toInstant(), endDate.toInstant());
            resultsPanel.setTrackingParams(params);
            resultsPanel.setVisible(true);
            target.add(resultsPanel);
            lastJobRunContainer.replace(new LastJobRun("lastJobRun", siteId));
            target.add(lastJobRunContainer);
            Locator.getFacade().getStatsManager().logEvent(new UserId(user), StatsManager.LOG_ACTION_TRACK,
                    siteId, false);
        }
    };
    searchButton.setEnabled(false);
    form.add(searchButton);
}

From source file:org.silverpeas.core.calendar.ical4j.ICal4JImporter.java

private CalendarEventOccurrence occurrenceFromICalEvent(final Mutable<ZoneId> zoneId, final CalendarEvent event,
        final VEvent vEvent) {
    // The original start date
    Temporal originalStartDate = iCal4JDateCodec.decode(vEvent.getRecurrenceId().getDate(), zoneId.get());
    // The occurrence
    CalendarEventOccurrence occurrence = CalendarEventOccurrenceBuilder.forEvent(event)
            .startingAt(originalStartDate).endingAt(originalStartDate.plus(1, ChronoUnit.DAYS)).build();
    // The period
    occurrence.setPeriod(extractPeriod(zoneId, vEvent));
    // Component data
    copyICalEventToComponent(vEvent, occurrence.asCalendarComponent());
    return occurrence;
}

From source file:org.silverpeas.core.calendar.Recurrence.java

private Temporal computeDateForMonthlyFrequencyFrom(final Temporal source, DayOfWeekOccurrence dayOfWeek) {
    Temporal current = source;//from ww  w.  j a  v  a2 s. co m
    if (dayOfWeek.nth() > 1) {
        current = current.with(ChronoField.ALIGNED_WEEK_OF_MONTH, dayOfWeek.nth());
    } else if (dayOfWeek.nth() < 0) {
        current = current.with(ChronoField.DAY_OF_MONTH, 1).plus(1, ChronoUnit.MONTHS).minus(1, ChronoUnit.DAYS)
                .plus(dayOfWeek.nth(), ChronoUnit.WEEKS).with(dayOfWeek.dayOfWeek());
    }
    return current;
}

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

@Override
public List<Parameter> getParameters() {
    List<Parameter> parameters = super.getParameters();

    parameters.add(SelectParameter.Builder.builder() //
            .name(TIME_UNIT_PARAMETER) //
            .item(ChronoUnit.YEARS.name(), "years") //
            .item(ChronoUnit.MONTHS.name(), "months") //
            .item(ChronoUnit.DAYS.name(), "days") //
            .item(ChronoUnit.HOURS.name(), "hours") //
            .defaultValue(ChronoUnit.HOURS.name()) //
            .build());//from www  .  ja v  a  2 s  . c  o m

    parameters.add(SelectParameter.Builder.builder() //
            .name(SINCE_WHEN_PARAMETER) //
            .canBeBlank(false) //
            .item(NOW_SERVER_SIDE_MODE, NOW_SERVER_SIDE_MODE) //
            .item(SPECIFIC_DATE_MODE, SPECIFIC_DATE_MODE, new Parameter(SPECIFIC_DATE_PARAMETER, //
                    ParameterType.DATE, //
                    StringUtils.EMPTY, //
                    false, //
                    false)) //
            .item(OTHER_COLUMN_MODE, OTHER_COLUMN_MODE, new Parameter(SELECTED_COLUMN_PARAMETER, //
                    ParameterType.COLUMN, //
                    StringUtils.EMPTY, //
                    false, //
                    false)) //
            .defaultValue(NOW_SERVER_SIDE_MODE) //
            .build());

    return ActionsBundle.attachToAction(parameters, this);
}

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

@Test
public void should_compute_days() throws IOException {
    //given/*from  w w w.  ja v a 2  s.  c  o m*/
    final String date = "06/15/2015";
    final String result = computeTimeSince(date, "MM/dd/yyyy", ChronoUnit.DAYS);

    final DataSetRow row = getDefaultRow("statistics_MM_dd_yyyy.json");
    row.set("0001", date);

    final Map<String, String> expectedValues = new HashMap<>();
    expectedValues.put("0000", "lorem bacon");
    expectedValues.put("0001", date);
    expectedValues.put("0003", result);
    expectedValues.put("0002", "Bacon");

    parameters.put(TIME_UNIT_PARAMETER, DAYS.name());

    //when
    ActionTestWorkbench.test(row, actionRegistry, factory.create(action, parameters));

    //then
    assertEquals(expectedValues, row.values());
}

From source file:org.tightblog.service.WeblogEntryManager.java

/**
 * Determine whether further comments for a particular blog entry are allowed.
 * @return true if additional comments may be made, false otherwise.
 *///  w  w w. ja  v  a  2  s  . c  o m
public boolean canSubmitNewComments(WeblogEntry entry) {
    if (!entry.isPublished()) {
        return false;
    }
    if (WebloggerProperties.CommentPolicy.NONE
            .equals(webloggerPropertiesRepository.findOrNull().getCommentPolicy())) {
        return false;
    }
    if (WebloggerProperties.CommentPolicy.NONE.equals(entry.getWeblog().getAllowComments())) {
        return false;
    }
    if (entry.getCommentDays() == 0) {
        return false;
    }
    if (entry.getCommentDays() < 0) {
        return true;
    }
    boolean ret = false;

    Instant inPubTime = entry.getPubTime();
    if (inPubTime != null) {
        Instant lastCommentDay = inPubTime.plus(entry.getCommentDays(), ChronoUnit.DAYS);
        if (Instant.now().isBefore(lastCommentDay)) {
            ret = true;
        }
    }
    return ret;
}

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;/*w ww .j  a va2  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;
}