Example usage for java.time LocalDate format

List of usage examples for java.time LocalDate format

Introduction

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

Prototype

@Override 
public String format(DateTimeFormatter formatter) 

Source Link

Document

Formats this date using the specified formatter.

Usage

From source file:de.lgblaumeiser.ptm.rest.BookingRestController.java

@RequestMapping(method = RequestMethod.POST, value = "/{dayString}")
public ResponseEntity<?> addBooking(@PathVariable String dayString, @RequestBody BookingBody newData) {
    LocalDate day = LocalDate.parse(dayString);
    Activity activity = services.activityStore().retrieveById(valueOf(newData.activityId))
            .orElseThrow(IllegalStateException::new);
    Booking newBooking = services.bookingService().addBooking(day, newData.user, activity,
            parse(newData.starttime), newData.comment);
    if (newData.endtime != null) {
        newBooking = services.bookingService().endBooking(newBooking, parse(newData.endtime));
    }// w  w w . j av  a  2 s  .  c  o  m
    URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{day}/{id}")
            .buildAndExpand(day.format(ISO_LOCAL_DATE), newBooking.getId()).toUri();
    return ResponseEntity.created(location).build();
}

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

/**
 * Creates and returns the website's booking page for a specified date.
 * /*  w w w .  j  av a  2  s . c  om*/
 * <p>This is not private only so that it can be unit-tested.
 * 
 * @param date the date in YYYY-MM-DD format.
 * @param validDates the dates for which bookings can be made, in YYYY-MM-DD format.
 * @param reservationFormGetUrl the Url from which to get a reservation form
 * @param cancellationFormGetUrl the Url from which to get a cancellation form.
 * @param s3WebsiteUrl the base Url of the bookings website bucket.
 * @param bookings the bookings for the specified date.
 * @param pageGuid the guid to embed within the page - used by AATs.
 * @param revvingSuffix the suffix to use for the linked css file, used for cache rev-ing.
 * @throws Exception 
 */
protected String createBookingPage(String date, List<String> validDates, String reservationFormGetUrl,
        String cancellationFormGetUrl, String s3WebsiteUrl, List<Booking> bookings, String pageGuid,
        String revvingSuffix) throws Exception {

    ImmutablePair<LifecycleState, Optional<String>> lifecycleState = lifecycleManager.getLifecycleState();

    // N.B. we assume that the date is known to be a valid date
    logger.log("About to create booking page");
    logger.log("Lifecycle state is: " + lifecycleState.left.name());
    if (lifecycleState.left.equals(LifecycleState.RETIRED)) {
        logger.log("Lifecycle state forwarding url is: " + lifecycleState.right.get());
    }

    Integer numCourts = 5;

    // Get dates in longhand format for display on the dropdown
    DateTimeFormatter longFormatter = DateTimeFormatter.ofPattern("EE, d MMM, yyyy");
    DateTimeFormatter shortFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    List<String> validDatesLong = new ArrayList<>();
    validDates.stream().forEach((validDate) -> {
        LocalDate localDate = java.time.LocalDate.parse(validDate, shortFormatter);
        validDatesLong.add(localDate.format(longFormatter));
    });

    // In order to merge the day's bookings with our velocity template, we need
    // to create an object with bookings on a grid corresponding to the html
    // table. For each grid cell, we need to know whether the cell is booked,
    // and if it is, the name of the booking, and, if it's a block booking, the
    // span of the block and whether this cell is interior to the block.
    logger.log("About to set up velocity context");
    List<ArrayList<Boolean>> bookedState = new ArrayList<>();
    List<ArrayList<Integer>> rowSpan = new ArrayList<>();
    List<ArrayList<Integer>> colSpan = new ArrayList<>();
    List<ArrayList<Boolean>> isBlockInterior = new ArrayList<>();
    List<ArrayList<String>> names = new ArrayList<>();
    // First set up default arrays for case of no bookings
    for (int slot = 1; slot <= 16; slot++) {
        bookedState.add(new ArrayList<>());
        rowSpan.add(new ArrayList<>());
        colSpan.add(new ArrayList<>());
        isBlockInterior.add(new ArrayList<>());
        names.add(new ArrayList<>());
        for (int court = 1; court <= numCourts; court++) {
            bookedState.get(slot - 1).add(false);
            rowSpan.get(slot - 1).add(1);
            colSpan.get(slot - 1).add(1);
            isBlockInterior.get(slot - 1).add(true);
            names.get(slot - 1).add("");
        }
    }
    // Mutate cells which are in fact booked
    for (Booking booking : bookings) {
        for (int court = booking.getCourt(); court < booking.getCourt() + booking.getCourtSpan(); court++) {
            for (int slot = booking.getSlot(); slot < booking.getSlot() + booking.getSlotSpan(); slot++) {
                bookedState.get(slot - 1).set(court - 1, true);
                rowSpan.get(slot - 1).set(court - 1, booking.getSlotSpan());
                colSpan.get(slot - 1).set(court - 1, booking.getCourtSpan());
                isBlockInterior.get(slot - 1).set(court - 1,
                        ((court == booking.getCourt()) && (slot == booking.getSlot())) ? false : true);
                names.get(slot - 1).set(court - 1, booking.getName());
            }
        }
    }

    // Create the page by merging the data with the page template
    VelocityEngine engine = new VelocityEngine();
    // Use the classpath loader so Velocity finds our template
    Properties properties = new Properties();
    properties.setProperty("resource.loader", "class");
    properties.setProperty("class.resource.loader.class",
            "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
    engine.init(properties);

    VelocityContext context = new VelocityContext();
    context.put("pageGuid", pageGuid);
    context.put("s3WebsiteUrl", s3WebsiteUrl);
    context.put("reservationFormGetUrl", reservationFormGetUrl);
    context.put("cancellationFormGetUrl", cancellationFormGetUrl);
    context.put("pagesDate", date);
    context.put("validDates", validDates);
    context.put("validDatesLong", validDatesLong);
    context.put("numCourts", numCourts);
    context.put("timeSlots", getTimeSlotLabels());
    context.put("bookedState", bookedState);
    context.put("rowSpan", rowSpan);
    context.put("colSpan", colSpan);
    context.put("isBlockInterior", isBlockInterior);
    context.put("names", names);
    context.put("revvingSuffix", revvingSuffix);
    context.put("lifecycleState", lifecycleState.left.name());
    context.put("forwardingUrl", lifecycleState.right.isPresent() ? lifecycleState.right.get() : "");
    logger.log("Set up velocity context");

    // TODO assert some sensible invariants on data sizes?

    // Render the page
    logger.log("About to render booking page");
    StringWriter writer = new StringWriter();
    Template template = engine.getTemplate("squash/booking/lambdas/BookingPage.vm", "utf-8");
    template.merge(context, writer);
    logger.log("Rendered booking page: " + writer);
    return writer.toString();
}

From source file:currency.converter.openexchangerate.OpenExchangeCurrencyConverter.java

/**
 * Retrieves latest exchange rates from <a href="https://openexchangerates.org">OpenExchangeRates</a> by using
 * REST template. Retrieved rates are stored as search history for the specific user.
 * /*w  w w.  j a v a2 s  . com*/
 * @param baseCurrency Base currency for exchange rates
 * @param amount Amount
 * @param dateOfRate Date for getting the historical exchange rate
 * 
 * @return {@link CurrencyRateModel}
 * 
 * @throws InvalidParameterException for invalid date
 */
public CurrencyRateModel getHistoricalCurrencyRates(String baseCurrency, double amount, LocalDate dateOfRate)
        throws InvalidParameterException {

    if (dateOfRate == null) {
        throw new InvalidParameterException("Date of rate is mandatory for historical currency rates!");
    }

    if (StringUtils.isNullOrEmpty(baseCurrency)) {
        baseCurrency = SupportedCurrencies.USD.name();
    }

    if (amount <= ZERO) {
        amount = MINIMUM_AMOUNT;
    }

    String apiKey = configuration.getOpenExchangeApiKey();
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    StringBuilder builder = new StringBuilder();
    builder.append("https://openexchangerates.org/api/historical/").append(dateOfRate.format(formatter))
            .append(".json?app_id=").append(apiKey).append("&base=").append(baseCurrency);

    boolean isCommercialApi = configuration.isOpenExchangeCommercialLicense();
    if (isCommercialApi) {
        builder.append(getTargetCurrencies(baseCurrency));
    }

    logger.info("Historical rate API URL : " + builder.toString());

    RestTemplate restTemplate = new RestTemplate();
    CurrencyRateModel rates = restTemplate.getForObject(builder.toString(), CurrencyRateModel.class);

    multiplyAmount(rates, amount, baseCurrency);
    logger.info(rates.toString());

    // save currency history
    String userName = userService.getLoggedInUserName();
    saveExchangeRate(rates, baseCurrency, amount, dateOfRate, userName);

    return rates;
}

From source file:net.resheim.eclipse.timekeeper.ui.views.ExportToClipboard.java

public void copyWeekAsHTML(LocalDate firstDayOfWeek) {

    provider = new AbstractContentProvider() {

        @Override/*  w  w w . jav  a 2  s.  co m*/
        public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
            this.setFirstDayOfWeek(firstDayOfWeek);
            filter();
        }

        @Override
        public void dispose() {
            // ignore
        }
    };

    provider.inputChanged(null, null, null);
    StringBuilder sb = new StringBuilder();

    sb.append("<table width=\"100%\" style=\"border: 1px solid #aaa; border-collapse: collapse; \">");
    sb.append(System.lineSeparator());
    sb.append("<tr style=\"background: #dedede; border-bottom: 1px solid #aaa\">");
    sb.append("<th>");
    sb.append("Week ");
    sb.append(firstDayOfWeek.format(weekFormat));
    sb.append("</th>");
    String[] headings = Activator.getDefault().getHeadings(firstDayOfWeek);
    for (String heading : headings) {
        sb.append("<th width=\"50em\" style=\"text-align: center; border-left: 1px solid #aaa\">");
        sb.append(heading);
        sb.append("</th>");
    }
    sb.append("</th>");
    sb.append(System.lineSeparator());

    Object[] elements = provider.getElements(null);
    for (Object object : elements) {
        append(firstDayOfWeek, sb, object);
    }

    sb.append("</table>");
    HTMLTransfer textTransfer = HTMLTransfer.getInstance();
    TextTransfer tt = TextTransfer.getInstance();
    Clipboard clipboard = new Clipboard(Display.getCurrent());
    clipboard.setContents(new String[] { sb.toString(), sb.toString() }, new Transfer[] { textTransfer, tt });
    clipboard.dispose();
}

From source file:lumbermill.internal.elasticsearch.ElasticSearchOkHttpClientImpl.java

private String indexRowWithDateAndType(JsonEvent event) {

    Optional<String> formattedType = type.format(event);
    if (!formattedType.isPresent()) {
        throw new IllegalStateException(
                "Issue with type, could not extract field from event " + type.original());
    }/*from   www.  j  a va  2  s  . co  m*/

    Optional<String> formattedIndex = index.format(event);
    if (!formattedIndex.isPresent()) {
        throw new IllegalStateException(
                "Issue with index, could not extract field from event: " + index.original());
    }

    Optional<String> formattedDocumentId = Optional.empty();
    if (documentId.isPresent()) {
        formattedDocumentId = documentId.get().format(event);
        if (!formattedDocumentId.isPresent()) {
            throw new IllegalStateException(
                    "Issue with index, could not extract field from event: " + index.original());
        }
    }

    ObjectNode objectNode = OBJECT_MAPPER.createObjectNode();
    ObjectNode data = OBJECT_MAPPER.createObjectNode();

    // Prepare for adding day to index for each event
    if (indexIsPrefix) {
        LocalDate indexDate;
        // TODO: Not sure how to handle this... what should be the behaviour if the specified timestamp field
        //       does not exist
        if (event.has(this.timestampField)) {
            indexDate = LocalDate.parse(event.valueAsString(this.timestampField).substring(0, 10),
                    DateTimeFormatter.ISO_DATE);
        } else {
            indexDate = LocalDate.now();
        }
        data.put("_index", formattedIndex.get() + indexDate.format(DateTimeFormatter.ofPattern("yyyy.MM.dd")));
    } else {
        data.put("_index", formattedIndex.get());
    }
    data.put("_type", formattedType.get());

    if (formattedDocumentId.isPresent()) {
        data.put("_id", formattedDocumentId.get());
    }
    objectNode.set("index", data);

    return objectNode.toString();
}

From source file:org.wallride.service.PostService.java

/**
 *
 * @param blogLanguage//w ww.ja  va 2s .  com
 * @param type
 * @param maxRank
 * @see PostService#getPopularPosts(String, PopularPost.Type)
 */
@CacheEvict(value = WallRideCacheConfiguration.POPULAR_POST_CACHE, key = "'list.type.' + #blogLanguage.language + '.' + #type")
public void updatePopularPosts(BlogLanguage blogLanguage, PopularPost.Type type, int maxRank) {
    logger.info("Start update of the popular posts");

    GoogleAnalytics googleAnalytics = blogLanguage.getBlog().getGoogleAnalytics();
    if (googleAnalytics == null) {
        logger.info("Configuration of Google Analytics can not be found");
        return;
    }

    Analytics analytics = GoogleAnalyticsUtils.buildClient(googleAnalytics);

    WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext,
            "org.springframework.web.servlet.FrameworkServlet.CONTEXT.guestServlet");
    if (context == null) {
        logger.info("GuestServlet is not ready yet");
        return;
    }

    final RequestMappingHandlerMapping mapping = context.getBean(RequestMappingHandlerMapping.class);

    Map<Post, Long> posts = new LinkedHashMap<>();

    int startIndex = 1;
    int currentRetry = 0;
    int totalResults = 0;

    do {
        try {
            LocalDate now = LocalDate.now();
            LocalDate startDate;
            switch (type) {
            case DAILY:
                startDate = now.minusDays(1);
                break;
            case WEEKLY:
                startDate = now.minusWeeks(1);
                break;
            case MONTHLY:
                startDate = now.minusMonths(1);
                break;
            default:
                throw new ServiceException();
            }

            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            Analytics.Data.Ga.Get get = analytics.data().ga()
                    .get(googleAnalytics.getProfileId(), startDate.format(dateTimeFormatter),
                            now.format(dateTimeFormatter), "ga:sessions")
                    .setDimensions(String.format("ga:pagePath", googleAnalytics.getCustomDimensionIndex()))
                    .setSort(String.format("-ga:sessions", googleAnalytics.getCustomDimensionIndex()))
                    .setStartIndex(startIndex).setMaxResults(GoogleAnalyticsUtils.MAX_RESULTS);
            if (blogLanguage.getBlog().isMultiLanguage()) {
                get.setFilters("ga:pagePath=~/" + blogLanguage.getLanguage() + "/");
            }

            logger.info(get.toString());
            final GaData gaData = get.execute();
            if (CollectionUtils.isEmpty(gaData.getRows())) {
                break;
            }

            for (List row : gaData.getRows()) {
                UriComponents uriComponents = UriComponentsBuilder.fromUriString((String) row.get(0)).build();

                MockHttpServletRequest request = new MockHttpServletRequest(servletContext);
                request.setRequestURI(uriComponents.getPath());
                request.setQueryString(uriComponents.getQuery());
                MockHttpServletResponse response = new MockHttpServletResponse();

                BlogLanguageRewriteRule rewriteRule = new BlogLanguageRewriteRule(blogService);
                BlogLanguageRewriteMatch rewriteMatch = (BlogLanguageRewriteMatch) rewriteRule.matches(request,
                        response);
                try {
                    rewriteMatch.execute(request, response);
                } catch (ServletException e) {
                    throw new ServiceException(e);
                } catch (IOException e) {
                    throw new ServiceException(e);
                }

                request.setRequestURI(rewriteMatch.getMatchingUrl());

                HandlerExecutionChain handler;
                try {
                    handler = mapping.getHandler(request);
                } catch (Exception e) {
                    throw new ServiceException(e);
                }

                if (!(handler.getHandler() instanceof HandlerMethod)) {
                    continue;
                }

                HandlerMethod method = (HandlerMethod) handler.getHandler();
                if (!method.getBeanType().equals(ArticleDescribeController.class)
                        && !method.getBeanType().equals(PageDescribeController.class)) {
                    continue;
                }

                // Last path mean code of post
                String code = uriComponents.getPathSegments().get(uriComponents.getPathSegments().size() - 1);
                Post post = postRepository.findOneByCodeAndLanguage(code,
                        rewriteMatch.getBlogLanguage().getLanguage());
                if (post == null) {
                    logger.debug("Post not found [{}]", code);
                    continue;
                }

                if (!posts.containsKey(post)) {
                    posts.put(post, Long.parseLong((String) row.get(1)));
                }
                if (posts.size() >= maxRank) {
                    break;
                }
            }

            if (posts.size() >= maxRank) {
                break;
            }

            startIndex += GoogleAnalyticsUtils.MAX_RESULTS;
            totalResults = gaData.getTotalResults();
        } catch (IOException e) {
            logger.warn("Failed to synchronize with Google Analytics", e);
            if (currentRetry >= GoogleAnalyticsUtils.MAX_RETRY) {
                throw new GoogleAnalyticsException(e);
            }

            currentRetry++;
            logger.info("{} ms to sleep...", GoogleAnalyticsUtils.RETRY_INTERVAL);
            try {
                Thread.sleep(GoogleAnalyticsUtils.RETRY_INTERVAL);
            } catch (InterruptedException ie) {
                throw new GoogleAnalyticsException(e);
            }
            logger.info("Retry for the {} time", currentRetry);
        }
    } while (startIndex <= totalResults);

    popularPostRepository.deleteByType(blogLanguage.getLanguage(), type);

    int rank = 1;
    for (Map.Entry<Post, Long> entry : posts.entrySet()) {
        PopularPost popularPost = new PopularPost();
        popularPost.setLanguage(blogLanguage.getLanguage());
        popularPost.setType(type);
        popularPost.setRank(rank);
        popularPost.setViews(entry.getValue());
        popularPost.setPost(entry.getKey());
        popularPostRepository.saveAndFlush(popularPost);
        rank++;
    }

    logger.info("Complete the update of popular posts");
}

From source file:com.axelor.apps.account.service.MoveLineExportService.java

/**
 * Mthode ralisant l'export SI - Agresso des en-ttes pour les journaux de type trsorerie
 * @param mlr/*  w w w  .  jav a 2 s  .c  om*/
 * @param replay
 * @throws AxelorException
 * @throws IOException
 */
@SuppressWarnings("unchecked")
@Transactional(rollbackOn = { AxelorException.class, Exception.class })
public void exportMoveLineTypeSelect1008FILE1(MoveLineReport moveLineReport, boolean replay)
        throws AxelorException, IOException {

    log.info("In export service 1008 FILE 1:");

    Company company = moveLineReport.getCompany();

    String dateQueryStr = String.format(" WHERE self.company = %s", company.getId());
    JournalType journalType = moveLineReportService.getJournalType(moveLineReport);
    if (moveLineReport.getJournal() != null) {
        dateQueryStr += String.format(" AND self.journal = %s", moveLineReport.getJournal().getId());
    } else {
        dateQueryStr += String.format(" AND self.journal.type = %s", journalType.getId());
    }
    if (moveLineReport.getPeriod() != null) {
        dateQueryStr += String.format(" AND self.period = %s", moveLineReport.getPeriod().getId());
    }
    if (replay) {
        dateQueryStr += String.format(" AND self.accountingOk = true AND self.moveLineReport = %s",
                moveLineReport.getId());
    } else {
        dateQueryStr += " AND self.accountingOk = false ";
    }
    dateQueryStr += " AND self.ignoreInAccountingOk = false AND self.journal.notExportOk = false ";
    dateQueryStr += String.format(" AND self.statusSelect = %s ", MoveRepository.STATUS_VALIDATED);
    Query dateQuery = JPA.em().createQuery(
            "SELECT self.date from Move self" + dateQueryStr + "group by self.date order by self.date");

    List<LocalDate> allDates = new ArrayList<LocalDate>();
    allDates = dateQuery.getResultList();

    log.debug("allDates : {}", allDates);

    List<String[]> allMoveData = new ArrayList<String[]>();
    String companyCode = "";

    String reference = "";
    String moveQueryStr = "";
    String moveLineQueryStr = "";
    if (moveLineReport.getRef() != null) {
        reference = moveLineReport.getRef();
    }
    if (company != null) {
        companyCode = moveLineReport.getCompany().getCode();
        moveQueryStr += String.format(" AND self.company = %s", company.getId());
    }
    if (moveLineReport.getPeriod() != null) {
        moveQueryStr += String.format(" AND self.period = %s", moveLineReport.getPeriod().getId());
    }
    if (moveLineReport.getDateFrom() != null) {
        moveLineQueryStr += String.format(" AND self.date >= '%s'", moveLineReport.getDateFrom().toString());
    }
    if (moveLineReport.getDateTo() != null) {
        moveLineQueryStr += String.format(" AND self.date <= '%s'", moveLineReport.getDateTo().toString());
    }
    if (moveLineReport.getDate() != null) {
        moveLineQueryStr += String.format(" AND self.date <= '%s'", moveLineReport.getDate().toString());
    }
    if (replay) {
        moveQueryStr += String.format(" AND self.accountingOk = true AND self.moveLineReport = %s",
                moveLineReport.getId());
    } else {
        moveQueryStr += " AND self.accountingOk = false ";
    }
    moveQueryStr += String.format(" AND self.statusSelect = %s ", MoveRepository.STATUS_VALIDATED);

    LocalDate interfaceDate = moveLineReport.getDate();

    for (LocalDate dt : allDates) {

        List<Journal> journalList = journalRepo.all()
                .filter("self.type = ?1 AND self.notExportOk = false", journalType).fetch();

        if (moveLineReport.getJournal() != null) {
            journalList = new ArrayList<Journal>();
            journalList.add(moveLineReport.getJournal());
        }

        for (Journal journal : journalList) {

            List<Move> moveList = moveRepo.all().filter(
                    "self.date = ?1 AND self.ignoreInAccountingOk = false AND self.journal.notExportOk = false AND self.journal = ?2"
                            + moveQueryStr,
                    dt, journal).fetch();

            String journalCode = journal.getExportCode();

            if (moveList.size() > 0) {

                long moveLineListSize = moveLineRepo.all()
                        .filter("self.move in ?1 AND (self.debit > 0 OR self.credit > 0) " + moveLineQueryStr,
                                moveList)
                        .count();

                if (moveLineListSize > 0) {

                    String exportNumber = this.getTreasuryExportNumber(company);

                    Move firstMove = moveList.get(0);
                    String periodCode = firstMove.getPeriod().getFromDate().format(MONTH_FORMAT);

                    this.updateMoveList(moveList, moveLineReport, interfaceDate, exportNumber);

                    String items[] = new String[8];
                    items[0] = companyCode;
                    items[1] = journalCode;
                    items[2] = exportNumber;
                    items[3] = interfaceDate.format(DATE_FORMAT);
                    items[4] = "0";
                    items[5] = reference;
                    items[6] = dt.format(DATE_FORMAT);
                    items[7] = periodCode;
                    allMoveData.add(items);
                }
            }
        }
    }

    String fileName = "entete" + todayTime.format(DATE_TIME_FORMAT) + "tresorerie.dat";
    String filePath = accountConfigService.getExportPath(accountConfigService.getAccountConfig(company));
    new File(filePath).mkdirs();

    log.debug("Full path to export : {}{}", filePath, fileName);
    CsvTool.csvWriter(filePath, fileName, '|', null, allMoveData);
    // Utilis pour le debuggage
    //         CsvTool.csvWriter(filePath, fileName, '|', this.createHeaderForHeaderFile(mlr.getTypeSelect()), allMoveData);
}

From source file:com.axelor.apps.account.service.MoveLineExportService.java

/**
 * Mthode ralisant l'export SI - Agresso des en-ttes pour les journaux de type avoir
 * @param mlr/*from  www. j a  va 2  s  . c  o  m*/
 * @param replay
 * @throws AxelorException
 * @throws IOException
 */
@SuppressWarnings("unchecked")
@Transactional(rollbackOn = { AxelorException.class, Exception.class })
public void exportMoveLineTypeSelect1007FILE1(MoveLineReport moveLineReport, boolean replay)
        throws AxelorException, IOException {

    log.info("In export service 1007 FILE 1:");

    Company company = moveLineReport.getCompany();

    String dateQueryStr = String.format(" WHERE self.company = %s", company.getId());
    JournalType journalType = moveLineReportService.getJournalType(moveLineReport);
    if (moveLineReport.getJournal() != null) {
        dateQueryStr += String.format(" AND self.journal = %s", moveLineReport.getJournal().getId());
    } else {
        dateQueryStr += String.format(" AND self.journal.type = %s", journalType.getId());
    }
    if (moveLineReport.getPeriod() != null) {
        dateQueryStr += String.format(" AND self.period = %s", moveLineReport.getPeriod().getId());
    }
    if (replay) {
        dateQueryStr += String.format(" AND self.accountingOk = true AND self.moveLineReport = %s",
                moveLineReport.getId());
    } else {
        dateQueryStr += " AND self.accountingOk = false ";
    }
    dateQueryStr += " AND self.ignoreInAccountingOk = false AND self.journal.notExportOk = false ";
    dateQueryStr += String.format(" AND self.statusSelect = %s ", MoveRepository.STATUS_VALIDATED);
    Query dateQuery = JPA.em().createQuery(
            "SELECT self.date from Move self" + dateQueryStr + "group by self.date order by self.date");

    List<LocalDate> allDates = new ArrayList<LocalDate>();
    allDates = dateQuery.getResultList();

    log.debug("allDates : {}", allDates);

    List<String[]> allMoveData = new ArrayList<String[]>();
    String companyCode = "";

    String reference = "";
    String moveQueryStr = "";
    String moveLineQueryStr = "";
    if (moveLineReport.getRef() != null) {
        reference = moveLineReport.getRef();
    }
    if (moveLineReport.getCompany() != null) {
        companyCode = moveLineReport.getCompany().getCode();
        moveQueryStr += String.format(" AND self.company = %s", moveLineReport.getCompany().getId());
    }
    if (moveLineReport.getPeriod() != null) {
        moveQueryStr += String.format(" AND self.period = %s", moveLineReport.getPeriod().getId());
    }
    if (moveLineReport.getDateFrom() != null) {
        moveLineQueryStr += String.format(" AND self.date >= '%s'", moveLineReport.getDateFrom().toString());
    }
    if (moveLineReport.getDateTo() != null) {
        moveLineQueryStr += String.format(" AND self.date <= '%s'", moveLineReport.getDateTo().toString());
    }
    if (moveLineReport.getDate() != null) {
        moveLineQueryStr += String.format(" AND self.date <= '%s'", moveLineReport.getDate().toString());
    }
    if (replay) {
        moveQueryStr += String.format(" AND self.accountingOk = true AND self.moveLineReport = %s",
                moveLineReport.getId());
    } else {
        moveQueryStr += " AND self.accountingOk = false ";
    }
    moveQueryStr += String.format(" AND self.statusSelect = %s ", MoveRepository.STATUS_VALIDATED);

    LocalDate interfaceDate = moveLineReport.getDate();

    for (LocalDate dt : allDates) {

        List<Journal> journalList = journalRepo.all()
                .filter("self.type = ?1 AND self.notExportOk = false", journalType).fetch();

        if (moveLineReport.getJournal() != null) {
            journalList = new ArrayList<Journal>();
            journalList.add(moveLineReport.getJournal());
        }

        for (Journal journal : journalList) {

            List<Move> moveList = moveRepo.all().filter(
                    "self.date = ?1 AND self.ignoreInAccountingOk = false AND self.journal.notExportOk = false AND self.journal = ?2"
                            + moveQueryStr,
                    dt, journal).fetch();

            String journalCode = journal.getExportCode();

            if (moveList.size() > 0) {

                BigDecimal sumCredit = this.getSumCredit(
                        "self.account.reconcileOk = true AND self.credit != 0.00 AND self.move in ?1 "
                                + moveLineQueryStr,
                        moveList);

                if (sumCredit.compareTo(BigDecimal.ZERO) == 1) {

                    String exportNumber = this.getSaleExportNumber(company);

                    Move firstMove = moveList.get(0);
                    String periodCode = firstMove.getPeriod().getFromDate().format(MONTH_FORMAT);

                    this.updateMoveList(moveList, moveLineReport, interfaceDate, exportNumber);

                    String items[] = new String[8];
                    items[0] = companyCode;
                    items[1] = journalCode;
                    items[2] = exportNumber;
                    items[3] = interfaceDate.format(DATE_FORMAT);
                    items[4] = sumCredit.toString();
                    items[5] = reference;
                    items[6] = dt.format(DATE_FORMAT);
                    items[7] = periodCode;
                    allMoveData.add(items);
                }
            }
        }
    }

    String fileName = "entete" + todayTime.format(DATE_TIME_FORMAT) + "avoirs.dat";
    String filePath = accountConfigService.getExportPath(accountConfigService.getAccountConfig(company));
    new File(filePath).mkdirs();

    log.debug("Full path to export : {}{}", filePath, fileName);
    CsvTool.csvWriter(filePath, fileName, '|', null, allMoveData);
    // Utilis pour le debuggage
    //         CsvTool.csvWriter(filePath, fileName, '|', this.createHeaderForHeaderFile(mlr.getTypeSelect()), allMoveData);
}

From source file:com.axelor.apps.account.service.MoveLineExportService.java

/**
 * Mthode ralisant l'export SI - Agresso des en-ttes pour les journaux de type vente
 * @param mlr/*from  w w w  .  j  a v a 2s  .c o  m*/
 * @param replay
 * @throws AxelorException
 * @throws IOException
 */
@SuppressWarnings("unchecked")
@Transactional(rollbackOn = { AxelorException.class, Exception.class })
public void exportMoveLineTypeSelect1006FILE1(MoveLineReport moveLineReport, boolean replay)
        throws AxelorException, IOException {

    log.info("In export service Type 1006 FILE 1 :");

    Company company = moveLineReport.getCompany();

    String dateQueryStr = String.format(" WHERE self.company = %s", company.getId());
    JournalType journalType = moveLineReportService.getJournalType(moveLineReport);
    if (moveLineReport.getJournal() != null) {
        dateQueryStr += String.format(" AND self.journal = %s", moveLineReport.getJournal().getId());
    } else {
        dateQueryStr += String.format(" AND self.journal.type = %s", journalType.getId());
    }
    if (moveLineReport.getPeriod() != null) {
        dateQueryStr += String.format(" AND self.period = %s", moveLineReport.getPeriod().getId());
    }
    if (replay) {
        dateQueryStr += String.format(" AND self.accountingOk = true AND self.moveLineReport = %s",
                moveLineReport.getId());
    } else {
        dateQueryStr += " AND self.accountingOk = false ";
    }
    dateQueryStr += " AND self.ignoreInAccountingOk = false AND self.journal.notExportOk = false ";
    dateQueryStr += String.format(" AND self.statusSelect = %s ", MoveRepository.STATUS_VALIDATED);
    Query dateQuery = JPA.em().createQuery(
            "SELECT self.date from Move self" + dateQueryStr + "group by self.date order by self.date");

    List<LocalDate> allDates = new ArrayList<LocalDate>();
    allDates = dateQuery.getResultList();

    log.debug("allDates : {}", allDates);

    List<String[]> allMoveData = new ArrayList<String[]>();
    String companyCode = "";

    String reference = "";
    String moveQueryStr = "";
    String moveLineQueryStr = "";
    if (moveLineReport.getRef() != null) {
        reference = moveLineReport.getRef();
    }
    if (company != null) {
        companyCode = company.getCode();
        moveQueryStr += String.format(" AND self.company = %s", company.getId());
    }
    if (moveLineReport.getPeriod() != null) {
        moveQueryStr += String.format(" AND self.period = %s", moveLineReport.getPeriod().getId());
    }
    if (moveLineReport.getDateFrom() != null) {
        moveLineQueryStr += String.format(" AND self.date >= '%s'", moveLineReport.getDateFrom().toString());
    }
    if (moveLineReport.getDateTo() != null) {
        moveLineQueryStr += String.format(" AND self.date <= '%s'", moveLineReport.getDateTo().toString());
    }
    if (moveLineReport.getDate() != null) {
        moveLineQueryStr += String.format(" AND self.date <= '%s'", moveLineReport.getDate().toString());
    }
    if (replay) {
        moveQueryStr += String.format(" AND self.accountingOk = true AND self.moveLineReport = %s",
                moveLineReport.getId());
    } else {
        moveQueryStr += " AND self.accountingOk = false ";
    }
    moveQueryStr += String.format(" AND self.statusSelect = %s ", MoveRepository.STATUS_VALIDATED);

    LocalDate interfaceDate = moveLineReport.getDate();

    for (LocalDate dt : allDates) {

        List<Journal> journalList = journalRepo.all()
                .filter("self.type = ?1 AND self.notExportOk = false", journalType).fetch();

        if (moveLineReport.getJournal() != null) {
            journalList = new ArrayList<Journal>();
            journalList.add(moveLineReport.getJournal());
        }

        for (Journal journal : journalList) {

            List<? extends Move> moveList = moveRepo.all().filter(
                    "self.date = ?1 AND self.ignoreInAccountingOk = false AND self.journal.notExportOk = false AND self.journal = ?2"
                            + moveQueryStr,
                    dt, journal).fetch();

            String journalCode = journal.getExportCode();

            if (moveList.size() > 0) {

                BigDecimal sumDebit = this.getSumDebit(
                        "self.account.reconcileOk = true AND self.debit != 0.00 AND self.move in ?1 "
                                + moveLineQueryStr,
                        moveList);

                if (sumDebit.compareTo(BigDecimal.ZERO) == 1) {

                    String exportNumber = this.getSaleExportNumber(company);

                    Move firstMove = moveList.get(0);
                    String periodCode = firstMove.getPeriod().getFromDate().format(MONTH_FORMAT);

                    this.updateMoveList((List<Move>) moveList, moveLineReport, interfaceDate, exportNumber);

                    String items[] = new String[8];
                    items[0] = companyCode;
                    items[1] = journalCode;
                    items[2] = exportNumber;
                    items[3] = interfaceDate.format(DATE_FORMAT);
                    items[4] = sumDebit.toString();
                    items[5] = reference;
                    items[6] = dt.format(DATE_FORMAT);
                    items[7] = periodCode;
                    allMoveData.add(items);
                }
            }
        }
    }

    String fileName = "entete" + todayTime.format(DATE_TIME_FORMAT) + "ventes.dat";
    String filePath = accountConfigService.getExportPath(accountConfigService.getAccountConfig(company));
    new File(filePath).mkdirs();

    log.debug("Full path to export : {}{}", filePath, fileName);
    CsvTool.csvWriter(filePath, fileName, '|', null, allMoveData);
    // Utilis pour le debuggage
    //         CsvTool.csvWriter(filePath, fileName, '|', this.createHeaderForHeaderFile(mlr.getTypeSelect()), allMoveData);
}

From source file:com.axelor.apps.account.service.MoveLineExportService.java

/**
 * Mthode ralisant l'export SI - Agresso des fichiers dtails
 * @param mlr//  w w w  .  j a  v  a 2  s  .  c  o  m
 * @param fileName
 * @throws AxelorException
 * @throws IOException
 */
@SuppressWarnings("unchecked")
public void exportMoveLineAllTypeSelectFILE2(MoveLineReport moveLineReport, String fileName)
        throws AxelorException, IOException {

    log.info("In export service FILE 2 :");

    Company company = moveLineReport.getCompany();

    String companyCode = "";
    String moveLineQueryStr = "";

    int typeSelect = moveLineReport.getTypeSelect();

    if (company != null) {
        companyCode = company.getCode();
        moveLineQueryStr += String.format(" AND self.move.company = %s", company.getId());
    }
    if (moveLineReport.getJournal() != null) {
        moveLineQueryStr += String.format(" AND self.move.journal = %s", moveLineReport.getJournal().getId());
    } else {
        moveLineQueryStr += String.format(" AND self.move.journal.type = %s",
                moveLineReportService.getJournalType(moveLineReport).getId());
    }

    if (moveLineReport.getPeriod() != null) {
        moveLineQueryStr += String.format(" AND self.move.period = %s", moveLineReport.getPeriod().getId());
    }
    if (moveLineReport.getDateFrom() != null) {
        moveLineQueryStr += String.format(" AND self.date >= '%s'", moveLineReport.getDateFrom().toString());
    }

    if (moveLineReport.getDateTo() != null) {
        moveLineQueryStr += String.format(" AND self.date <= '%s'", moveLineReport.getDateTo().toString());
    }
    if (moveLineReport.getDate() != null) {
        moveLineQueryStr += String.format(" AND self.date <= '%s'", moveLineReport.getDate().toString());
    }
    if (typeSelect != 8) {
        moveLineQueryStr += String.format(" AND self.account.reconcileOk = false ");
    }
    moveLineQueryStr += String.format(
            "AND self.move.accountingOk = true AND self.move.ignoreInAccountingOk = false AND self.move.moveLineReport = %s",
            moveLineReport.getId());
    moveLineQueryStr += String.format(" AND self.move.statusSelect = %s ", MoveRepository.STATUS_VALIDATED);

    Query queryDate = JPA.em().createQuery(
            "SELECT self.date from MoveLine self where self.account != null AND (self.debit > 0 OR self.credit > 0) "
                    + moveLineQueryStr + " group by self.date ORDER BY self.date");

    List<LocalDate> dates = new ArrayList<LocalDate>();
    dates = queryDate.getResultList();

    log.debug("dates : {}", dates);

    List<String[]> allMoveLineData = new ArrayList<String[]>();

    for (LocalDate localDate : dates) {

        Query queryExportAgressoRef = JPA.em().createQuery(
                "SELECT DISTINCT self.move.exportNumber from MoveLine self where self.account != null "
                        + "AND (self.debit > 0 OR self.credit > 0) AND self.date = '" + localDate.toString()
                        + "'" + moveLineQueryStr);
        List<String> exportAgressoRefs = new ArrayList<String>();
        exportAgressoRefs = queryExportAgressoRef.getResultList();
        for (String exportAgressoRef : exportAgressoRefs) {

            if (exportAgressoRef != null && !exportAgressoRef.isEmpty()) {

                int sequence = 1;

                Query query = JPA.em().createQuery(
                        "SELECT self.account.id from MoveLine self where self.account != null AND (self.debit > 0 OR self.credit > 0) "
                                + "AND self.date = '" + localDate.toString()
                                + "' AND self.move.exportNumber = '" + exportAgressoRef + "'" + moveLineQueryStr
                                + " group by self.account.id");

                List<Long> accountIds = new ArrayList<Long>();
                accountIds = query.getResultList();

                log.debug("accountIds : {}", accountIds);

                for (Long accountId : accountIds) {
                    if (accountId != null) {
                        String accountCode = accountRepo.find(accountId).getCode();
                        List<MoveLine> moveLines = moveLineRepo.all().filter(
                                "self.account.id = ?1 AND (self.debit > 0 OR self.credit > 0) AND self.date = '"
                                        + localDate.toString() + "' AND self.move.exportNumber = '"
                                        + exportAgressoRef + "'" + moveLineQueryStr,
                                accountId).fetch();

                        log.debug("movelines  : {} ", moveLines);

                        if (moveLines.size() > 0) {

                            List<MoveLine> moveLineList = moveLineService.consolidateMoveLines(moveLines);

                            List<MoveLine> sortMoveLineList = this.sortMoveLineByDebitCredit(moveLineList);

                            for (MoveLine moveLine3 : sortMoveLineList) {

                                Journal journal = moveLine3.getMove().getJournal();
                                LocalDate date = moveLine3.getDate();
                                String items[] = null;

                                if (typeSelect == 9) {
                                    items = new String[13];
                                } else {
                                    items = new String[12];
                                }

                                items[0] = companyCode;
                                items[1] = journal.getExportCode();
                                items[2] = moveLine3.getMove().getExportNumber();
                                items[3] = String.format("%s", sequence);
                                sequence++;
                                items[4] = accountCode;

                                BigDecimal totAmt = moveLine3.getCredit().subtract(moveLine3.getDebit());
                                String moveLineSign = "C";
                                if (totAmt.compareTo(BigDecimal.ZERO) == -1) {
                                    moveLineSign = "D";
                                    totAmt = totAmt.negate();
                                }
                                items[5] = moveLineSign;
                                items[6] = totAmt.toString();

                                String analyticAccounts = "";
                                for (AnalyticMoveLine analyticDistributionLine : moveLine3
                                        .getAnalyticMoveLineList()) {
                                    analyticAccounts = analyticAccounts
                                            + analyticDistributionLine.getAnalyticAccount().getCode() + "/";
                                }

                                if (typeSelect == 9) {
                                    items[7] = "";
                                    items[8] = analyticAccounts;
                                    items[9] = String.format("%s DU %s", journal.getCode(),
                                            date.format(DATE_FORMAT));
                                } else {
                                    items[7] = analyticAccounts;
                                    items[8] = String.format("%s DU %s", journal.getCode(),
                                            date.format(DATE_FORMAT));
                                }

                                allMoveLineData.add(items);

                            }
                        }
                    }
                }
            }
        }
    }

    String filePath = accountConfigService.getExportPath(accountConfigService.getAccountConfig(company));
    new File(filePath).mkdirs();

    log.debug("Full path to export : {}{}", filePath, fileName);
    CsvTool.csvWriter(filePath, fileName, '|', null, allMoveLineData);
    // Utilis pour le debuggage
    //         CsvTool.csvWriter(filePath, fileName, '|',  this.createHeaderForDetailFile(typeSelect), allMoveLineData);
}