Example usage for org.joda.time.format DateTimeFormat forPattern

List of usage examples for org.joda.time.format DateTimeFormat forPattern

Introduction

In this page you can find the example usage for org.joda.time.format DateTimeFormat forPattern.

Prototype

public static DateTimeFormatter forPattern(String pattern) 

Source Link

Document

Factory to create a formatter from a pattern string.

Usage

From source file:com.arya.belajar.view.controller.ItemController.java

@RequestMapping(value = "save", method = RequestMethod.POST)
public String saveItem(Item item, @RequestParam("expiredDateParam") String expiredDateParam) {
    DateTime expiredDate = DateTimeFormat.forPattern("yyyy-MM-dd").parseDateTime(expiredDateParam);
    item.setExpiredDate(expiredDate);//from w  w  w  . ja  v a 2 s .co m
    itemService.saveItem(item);
    return "redirect:/item/form";
}

From source file:com.avid.central.obsplugin.inewslibrary.ExportRundown.java

public String GenerateFileName() {
    String fileName = Rundown.ChannelID;
    fileName += "_";
    fileName += Rundown.GetFileDate().toString(DateTimeFormat.forPattern("yyyyMMdd"));
    fileName += "_";
    fileName += Rundown.GetFileStartTime();
    fileName += "_";
    fileName += Rundown.GetFileEndTime();
    fileName += ".xml";

    return fileName;
}

From source file:com.avid.central.obsplugin.inewslibrary.ExportStories.java

public ExportStoryData ProcessRundown(List<Story> stories, ExportConfiguration config) {
    ExportStoryData exportData = new ExportStoryData(config);

    // create a new OBS_Export
    ExportRundown _export = new ExportRundown();

    // Represents the starting time of an item, can be calculated from previous item start time or set explicitly by the user
    int currentStartTime = 0;

    // Flags the fact that the previous Story parsed was a break with a defined time
    boolean lastStoryWasBreak = false;

    // Flags the fact that we have now validated the header
    boolean headerValid = false;

    // identifiers used in exporting cue sheets
    String CueSheetLocation = "<p family=\"0\" font=\"\" pitch=\"0\">" + config.cuesheet_id + "</p>";
    String BodyStart = "<body";
    String BodyEnd = "</body>";

    // do everything inside a try {} block
    // if we encounter any of the conditions listed above which preclude exporting the rundown
    // then we throw an exception which includes the reason why
    try {// w w w  .  j  a  v  a 2s. c o  m
        // go through stories and decide what to do with each
        for (Story story : stories) {
            List<mos> vizGrapics = new ArrayList<mos>();

            // is this a break story?
            if (story.Story.getHead().getMeta().isBreak()) {
                // yes it is
                // need to get the content of the info Field
                String info = GetFieldStringValue(story.Story.getFields().getStringOrBooleanOrDate(),
                        config.info_field);
                if (null == info) {
                    RaiseError(String.format("field \"%s\" was not found", config.info_field));
                }

                String subject = GetFieldStringValue(story.Story.getFields().getStringOrBooleanOrDate(),
                        config.subject_field);
                if (null == subject) {
                    RaiseError(String.format("field \"%s\" was not found", config.subject_field));
                }

                // is it one of our "special" fields
                if (info.equalsIgnoreCase(config.obs_channel_id)) {
                    if (subject.length() == 0) {
                        // the channelID is missing so abort the export
                        RaiseError(String.format("the rundown %s was not found", config.obs_channel_id));
                    }

                    // this is the Story that contains the channel ID
                    _export.Rundown.ChannelID = subject;

                    // determine the mode, first test for MDS
                    if (subject.toUpperCase().startsWith(config.mds_prefix.toUpperCase())) {
                        exportData.setMdsMode(true);
                    } else if (!subject.toUpperCase().startsWith(config.onc_prefix.toUpperCase())
                            && config.onc_prefix.length() > 0) {
                        RaiseError(String.format("the %s was not identified as an ONC or MDS rundown",
                                config.obs_channel_id));
                    }

                } else if (info.equalsIgnoreCase(config.title_id)) {
                    if (subject.length() == 0 && exportData.getValidateFields()) {
                        // the rundown name is missing so abort the export
                        RaiseError(String.format("the rundown %s was not found", config.title_id));
                    }

                    // this is the Story that contains the rundown name
                    _export.Rundown.Title = subject;
                } else if (info.equalsIgnoreCase(config.day_id)) {
                    // this is the Story that contains the rundown day
                    if (subject.length() > 0) {
                        _export.Rundown.Day = subject;
                    }

                } else if (info.equalsIgnoreCase(config.date_id)) {
                    // this is the Story that contains the rundown date
                    if (subject.length() > 0) {
                        _export.Rundown.Date = subject;
                    }
                }

                String startTime = GetFieldStringValue(story.Story.getFields().getStringOrBooleanOrDate(),
                        config.start_time_field);
                if (null == startTime && exportData.getValidateFields()) {
                    RaiseError(String.format("field \"%s\" was not found", config.start_time_field));
                }

                // check for start and end time data
                if (subject.equalsIgnoreCase(config.start_id) && startTime.length() > 0) {
                    if (startTime.charAt(0) == '@') {
                        // we have an absolute start time
                        currentStartTime = Integer.parseInt(startTime.substring(1));
                        _export.Rundown.RundownStartTime = currentStartTime;
                    } else {
                        // start time is relative to start of show
                        currentStartTime = Integer.parseInt(startTime.substring(1))
                                + _export.Rundown.RundownStartTime;
                        _export.Rundown.RundownStartTime = currentStartTime;
                    }
                } else if (subject.equalsIgnoreCase(config.end_id) && startTime.length() > 0) {
                    if (startTime.charAt(0) == '@') {
                        // we have an absolute end time
                        _export.Rundown.RundownEndTime = Integer.parseInt(startTime.substring(1));
                    } else {
                        // start time is relative to start of show
                        _export.Rundown.RundownEndTime = Integer.parseInt(startTime.substring(1))
                                + _export.Rundown.RundownStartTime;
                    }

                    lastStoryWasBreak = true;
                }
            } else {
                if (!story.Story.getHead().getMeta().isFloat()) {
                    // this is not a floated Story so we must have passed the "header"
                    // if we haven't validated the "header" at this point then now is the time to do so!
                    if (!headerValid) {
                        if (-1 == _export.Rundown.RundownStartTime && exportData.getValidateFields()) {
                            // the start time has not been set so abort the export
                            RaiseError("the rundown start time is missing");
                        }

                        headerValid = true;
                    }

                    // every time we encounter a non-break, non-floated Story reset the rundown end time to unspecified
                    // it should get set to the correct value by the final break Story
                    _export.Rundown.RundownEndTime = -1;

                    // get the subject
                    String subject = GetFieldStringValue(story.Story.getFields().getStringOrBooleanOrDate(),
                            config.subject_field);
                    if (null == subject) {
                        RaiseError(String.format("field \"%s\" was not found", config.subject_field));
                    }

                    if (subject.length() == 0 && exportData.getValidateFields()) {
                        RaiseError("at least one story is missing its Subject details");
                    }

                    // check for an update and retrieve modification time
                    String updatedTimestamp = null;
                    int update = GetFieldIntegerValue(story.Story.getFields().getStringOrBooleanOrDate(),
                            config.update_field);
                    DateTime modificationTime = GetFieldDateValue(
                            story.Story.getFields().getStringOrBooleanOrDate(), config.modified_field);
                    if (null != modificationTime) {
                        DateTimeFormatter fmt = ISODateTimeFormat.dateHourMinuteSecond();
                        updatedTimestamp = modificationTime.toString(fmt);
                    }

                    // get the start time
                    String startTime = GetFieldStringValue(story.Story.getFields().getStringOrBooleanOrDate(),
                            config.start_time_field);

                    // do we have start time data?
                    if (startTime != null && !startTime.isEmpty()) {
                        // update the running start time
                        if (startTime.charAt(0) == '@') {
                            // we have an absolute start time
                            currentStartTime = Integer.parseInt(startTime.substring(1));
                        } else {
                            // start time is relative to start of show
                            currentStartTime = Integer.parseInt(startTime.substring(1))
                                    + _export.Rundown.RundownStartTime;
                        }
                    } else {
                        // no start time specified so we need to get it from the previous item
                        // if there are not yet any stories in the list then just use the start time we are carrying forward
                        if (_export.Stories.size() > 0 && !lastStoryWasBreak) {
                            // there is at least one Story
                            currentStartTime += _export.Stories.get(_export.Stories.size() - 1).StoryDuration;
                        }
                    }

                    // get the VideoID
                    String videoID = GetFieldStringValue(story.Story.getFields().getStringOrBooleanOrDate(),
                            config.video_id_field);
                    if (exportData.getMdsMode()) {
                        if (null == videoID) {
                            RaiseError(String.format("field \"%s\" was not found", config.video_id_field));
                        }
                        if (videoID.length() == 0 && exportData.getValidateFields()) {
                            RaiseError("at least one story is missing its VideoID details");
                        }
                    } else if (null == videoID || videoID.isEmpty()) {
                        videoID = "";
                    }

                    // get the Type
                    String type = GetFieldStringValue(story.Story.getFields().getStringOrBooleanOrDate(),
                            config.type_field);
                    if (exportData.getMdsMode()) {
                        if (null == type) {
                            RaiseError(String.format("field \"%s\" was not found", config.type_field));
                        }
                        if (type.length() == 0 && exportData.getValidateFields()) {
                            RaiseError("at least one story is missing its type details");
                        }
                    }

                    // get the Upmix
                    String upMix = GetFieldStringValue(story.Story.getFields().getStringOrBooleanOrDate(),
                            config.upmix_field);
                    if (exportData.getMdsMode()) {
                        if (null == upMix) {
                            RaiseError(String.format("field \"%s\" was not found", config.upmix_field));
                        }
                        if (upMix.length() == 0 && exportData.getValidateFields()) {
                            RaiseError("at least one story is missing its upmix details");
                        }
                    }

                    // get the Music
                    String music = GetFieldStringValue(story.Story.getFields().getStringOrBooleanOrDate(),
                            config.music_field);
                    if (exportData.getMdsMode()) {
                        if (null == music || music.length() == 0) {
                            exportData.getResponse()
                                    .setMessage("At least one story is missing its music element");
                        }
                    }

                    if (!exportData.getMdsMode() && exportData.getValidateFields()) {
                        // get the Endorsement details
                        String endorseBy = GetFieldStringValue(
                                story.Story.getFields().getStringOrBooleanOrDate(), config.endorse_field);
                        if (null == endorseBy) {
                            RaiseError(String.format("field \"%s\" was not found", config.endorse_field));
                        }
                        if (endorseBy.length() == 0) {
                            exportData.getResponse().setMessage("At least one story has not been approved");
                            //                                RaiseError("at least one story has not been approved");
                        }

                        // get the Export Approval flags
                        int approved = GetFieldIntegerValue(story.Story.getFields().getStringOrBooleanOrDate(),
                                config.export_field);
                        if (approved == 0) {
                            RaiseError("at least one story is not ready for export");
                        }
                    }

                    // get VIZ production cue
                    // are there any anchored elements?
                    if (exportData.getCheckGrahics()) {
                        if (null != story.Story.getAeset() && story.Story.getAeset().getAe().size() > 0) {
                            // is there one for VIZ?
                            for (Ae ae : story.Story.getAeset().getAe()) {

                                for (Object ap : ae.getMcOrAp()) {
                                    if (ap.getClass() != Nsml.Aeset.Ae.Mc.class) {
                                        continue;
                                    }

                                    Nsml.Aeset.Ae.Mc mc = (Nsml.Aeset.Ae.Mc) ap;
                                    for (Object content : mc.getAp()) {
                                        if (content.getClass() != ApContent.class) {
                                            continue;
                                        }

                                        ApContent apContent = (ApContent) content;
                                        for (Object data : apContent.getContent()) {
                                            if (data.getClass() == String.class) {
                                                String graphic = (String) data;
                                                if (!graphic.contains(config.viz_id)) {
                                                    continue;
                                                }

                                                for (AttachmentType at : story.Story.getAesetAtts()
                                                        .getAttachment()) {
                                                    if (mc.getIdref().equals(at.getId())) {
                                                        // found it!
                                                        String graphicData = at.getValue();
                                                        if (graphicData != null) {
                                                            try {
                                                                AttachmentContent ac = AttachmentContent
                                                                        .Parse(graphicData);
                                                                if (ac != null) {
                                                                    vizGrapics.add(ac.mos);
                                                                }
                                                            } catch (Exception ex) {
                                                            }

                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        if (0 == vizGrapics.size()) {
                            exportData.getResponse()
                                    .setMessage("At least one story is missing its graphic element");
                        }
                    }

                    // Story looks OK so add it to the export
                    OBSStory obsStory = new OBSStory();

                    obsStory.Subject = subject;
                    obsStory.Type = type;
                    obsStory.StoryStartTime = currentStartTime;
                    obsStory.StoryDuration = GetFieldIntegerValue(
                            story.Story.getFields().getStringOrBooleanOrDate(), config.duration_field);
                    obsStory.VideoID = videoID;

                    if (exportData.getMdsMode()) {
                        obsStory.Upmix = upMix.equals("1") || upMix.equals("true");
                        obsStory.Music = music;
                        obsStory.Graphics = vizGrapics;
                    } else {
                        if (null != updatedTimestamp) {
                            obsStory.Modified = updatedTimestamp;
                            obsStory.Update = update == 1;
                        }
                    }

                    // the story body as NSML
                    String formattedBody;

                    // unformatted version of the story body
                    String unformattedBody;

                    // the contents of the script info tag
                    String scriptInfo = null;

                    // the contents of the cue sheet tag
                    String cueSheet = null;

                    int cueSheetLocation = -1;

                    // get the story body free of all formatting
                    unformattedBody = GetStoryBody(story.Story);

                    // look for escape characters in the value and encode them
                    unformattedBody = unformattedBody.replace("&", "&amp;");
                    unformattedBody = unformattedBody.replace("\"", "&quot;");
                    unformattedBody = unformattedBody.replace("<", "&lt;");
                    unformattedBody = unformattedBody.replace(">", "&gt;");
                    unformattedBody = unformattedBody.replace("'", "&apos;");

                    // now look for a cue sheet
                    cueSheetLocation = unformattedBody.indexOf(config.cuesheet_id);

                    if (cueSheetLocation >= 0) {
                        // there is a cue sheet so extract it from the unformatted body if MDS mode
                        if (exportData.getMdsMode() && unformattedBody
                                .length() > (cueSheetLocation + config.cuesheet_id.length())) {
                            cueSheet = unformattedBody
                                    .substring(cueSheetLocation + config.cuesheet_id.length());
                        }

                        // crop the cue sheet from the unformatted body
                        unformattedBody = unformattedBody.substring(0, cueSheetLocation);
                    }

                    // we now have the unformatted body free of cue sheet data together with the cue sheet if it exists

                    // are we exporting the story in its formatted version?
                    if (exportData.getRetainFormatting()) {
                        formattedBody = "";

                        // get the formatted story body
                        // first get offsets to body tags
                        int storyStart = story.StoryAsNSML.indexOf(BodyStart);
                        int storyEnd = story.StoryAsNSML.indexOf(BodyEnd);

                        // check for non-empty body
                        if (-1 != storyEnd) {
                            // make sure we extract the end tag
                            storyEnd += BodyEnd.length();
                            formattedBody = story.StoryAsNSML.substring(storyStart, storyEnd);
                            // now we have the formatted story body

                            // if the story is not empty and has a cue sheet section we need to remove it
                            cueSheetLocation = formattedBody.indexOf(CueSheetLocation);

                            if (cueSheetLocation >= 0 && unformattedBody.length() > 0) {
                                // there is a cue sheet and the story isn't empty so we need to remove the cue sheet from the formatted body
                                String script = formattedBody.substring(0, cueSheetLocation);
                                // add back the body end tag
                                script += BodyEnd;
                                scriptInfo = "<![CDATA[\n" + script + "]]>";

                            } else if (unformattedBody.length() > 0) {
                                scriptInfo = "<![CDATA[\n" + formattedBody + "]]>";
                            }

                        }

                    } else {
                        // simply export the unformatted body
                        scriptInfo = unformattedBody;
                    }

                    obsStory.ScriptInfo = scriptInfo;
                    if (exportData.getMdsMode() && null != cueSheet) {
                        obsStory.CueSheet = cueSheet;
                    }

                    _export.Stories.add(obsStory);

                    lastStoryWasBreak = false;
                }
            }
        }

        // check that we have an end time
        if (-1 == _export.Rundown.RundownEndTime) {
            if (exportData.getValidateFields()) {
                // nope, reject this one
                RaiseError("the rundown end time is missing");
            } else {
                _export.Rundown.RundownEndTime = _export.Rundown.RundownStartTime;
            }
        }

        // check for Channel ID
        if (_export.Rundown.ChannelID.length() == 0 && exportData.getValidateFields()) {
            RaiseError(String.format("the rundown %s is missing", config.obs_channel_id));
        }

        // check for Channel Name
        if (_export.Rundown.Title.length() == 0 && exportData.getValidateFields()) {
            RaiseError(String.format("the rundown %s is missing", config.title_id));
        }

        // check for Date
        if (_export.Rundown.Date.length() == 0) {
            // log a warning here (no date specified)
            // set date to today's date
            DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-mm-dd");
            _export.Rundown.Date = DateTime.now().toString(dtf);
            if (null == exportData.getResponse().getMessage()) {
                exportData.getResponse().setMessage("The date information was missing from the rundown");
            }
        }
        exportData.getResponse().setDate(_export.Rundown.Date);

        // check for Day
        if (_export.Rundown.Day.length() == 0) {
            // log a warning here (no day specified)
            // set date to today's date
            _export.Rundown.Day = String.format("%02d", DateTime.now().dayOfMonth().get());
            if (null == exportData.getResponse().getMessage()) {
                exportData.getResponse().setMessage("The day information was missing from the rundown");
            }
        }
        exportData.getResponse().setDay(_export.Rundown.Day);

        exportData.setRundownAsXml(_export.GenerateXML(exportData.getMdsMode()));

        exportData.getResponse().setChannelID(_export.Rundown.ChannelID);
        exportData.getResponse().setStartTime(_export.Rundown.GetStartTime());
        exportData.getResponse().setEndTime(_export.Rundown.GetEndTime());
        exportData.getResponse().setTitle(_export.Rundown.Title);

        exportData.getResponse().setFileName(_export.GenerateFileName());
        exportData.getResponse().setResult(1);
    } catch (Exception ex) {
        exportData.getResponse().setMessage(ex.getMessage());
    }

    return exportData;
}

From source file:com.avid.central.obsplugin.inewslibrary.OBSRundown.java

public DateTime GetFileDate() {
    try {//w  w w.  ja  v  a 2 s . c o m
        DateTimeParser[] parsers = { DateTimeFormat.forPattern("dd MMMM YYYY").getParser(),
                DateTimeFormat.forPattern("dd-MMMM-YYYY").getParser() };
        DateTimeFormatter dtf = new DateTimeFormatterBuilder().append(null, parsers).toFormatter();
        DateTime dt = DateTime.parse(Date, dtf);
        return dt;
    } catch (Exception ex) {
        String s = ex.getMessage();
    }

    return new DateTime(0);
}

From source file:com.axelor.controller.ConnectionToPrestashop.java

License:Open Source License

@Transactional
@SuppressWarnings("finally")
public String syncCustomer() {
    String message = "";
    try {/*  www  .  j ava 2 s .  c  o m*/
        List<Integer> prestashopIdList = new ArrayList<Integer>();
        List<Integer> erpIdList = new ArrayList<Integer>();
        List<Partner> erpList = Partner.all().fetch();

        for (Partner prestahopCustomer : erpList) {
            erpIdList.add(prestahopCustomer.getPrestashopid());
        }
        System.out.println("API KEY :: " + apiKey);
        URL url = new URL("http://localhost/client-lib/crud/action.php?resource=customers&action=getallid&Akey="
                + apiKey);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();

        InputStream inputStream = connection.getInputStream();
        Scanner scan = new Scanner(inputStream);
        while (scan.hasNext()) {
            String data = scan.nextLine();
            System.out.println(data);
            prestashopIdList.add(Integer.parseInt(data));
        }
        System.out.println("From Prestashop :: " + prestashopIdList.size());
        System.out.println("From ERP :: " + erpIdList.size());
        scan.close();

        // Check new entries in the prestshop
        Iterator<Integer> prestaListIterator = prestashopIdList.iterator();
        while (prestaListIterator.hasNext()) {
            Integer tempId = prestaListIterator.next();
            System.out.println("Current prestaid for operation ::" + tempId);
            if (erpIdList.contains(tempId)) {
                Customer tempCustomer = getCustomer(tempId);
                String dateUpdate = tempCustomer.getDate_upd();
                LocalDateTime dt1 = LocalDateTime.parse(dateUpdate,
                        DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"));
                Partner pCust = Partner.all().filter("prestashopId=?", tempId).fetchOne();
                LocalDateTime dt2 = pCust.getUpdatedOn();
                if (dt2 != null) {
                    int diff = Seconds.secondsBetween(dt2, dt1).getSeconds();
                    if (diff > 1)
                        updateCustomer(tempCustomer, tempId);
                } else {
                    updateCustomer(tempCustomer, tempId);
                }
                erpIdList.remove(tempId);
            } else {
                System.out.println("Current prestaid for insertion operation ::" + tempId);
                // insert new data in ERP Database
                insertCustomer(tempId);
                erpIdList.remove(tempId);
            }
        }
        if (erpIdList.isEmpty()) {
            System.out.println("Synchronization is completed.");
            message = "done";
        } else {
            // delete from ERP
            Iterator<Integer> erpListIterator = erpIdList.iterator();
            while (erpListIterator.hasNext()) {
                Integer tempId = erpListIterator.next();
                if (tempId != 0) {
                    System.out.println("Currently in  Erp ::" + tempId);
                    Partner customerDelete = Partner.all().filter("prestashopid=?", tempId).fetchOne();
                    String firstName = customerDelete.getFirstName();
                    customerDelete.setArchived(Boolean.TRUE);
                    System.out.println("customer deleted ::" + firstName);
                }
            }
            while (prestaListIterator.hasNext()) {
                Integer tempId = prestaListIterator.next();
                System.out.println("Currently in prestashop ::" + tempId);
            }
            System.out.println("Synchronization is completed.");
            message = "done";
        }
    } catch (Exception e) {
        message = "Wrong Authentication Key or Key has been disabled.";
    } finally {
        return message;
    }
}

From source file:com.axelor.controller.ConnectionToPrestashop.java

License:Open Source License

@Transactional
public void updateCustomer(Customer pojoCustomer, int prestashopId) {
    DateTimeFormatter dateTimeFormat = DateTimeFormat.forPattern("yyyy-MM-dd");
    LocalDate dateOfBirth = dateTimeFormat.parseLocalDate(pojoCustomer.getBirthday());
    Partner prestashopCustomer = Partner.filter("prestashopid=?", prestashopId).fetchOne();
    prestashopCustomer.setPrestashopid(prestashopId);
    prestashopCustomer.setFirstName(pojoCustomer.getFirstname());
    prestashopCustomer.setName(pojoCustomer.getLastname());
    prestashopCustomer.setFullName(pojoCustomer.getLastname() + " " + pojoCustomer.getFirstname());
    prestashopCustomer.setEmail(pojoCustomer.getEmail());
    prestashopCustomer.setCompany(pojoCustomer.getCompany());
    prestashopCustomer.setPassword(pojoCustomer.getPasswd());
    prestashopCustomer.setBirthdate(dateOfBirth);
    prestashopCustomer.setActive(BooleanUtils.toBoolean(pojoCustomer.getActive()));
    prestashopCustomer.setArchived(BooleanUtils.toBoolean(pojoCustomer.getDeleted()));
    System.out.println(pojoCustomer.getId_default_group());
    prestashopCustomer.setPrestashopCustomerGroup(
            PrestashopCustomerGroup.all().filter("id_group=?", pojoCustomer.getId_default_group()).fetchOne());
    System.out.println(prestashopCustomer.getPrestashopCustomerGroup().getId_group());
    System.out.println("ASSOCIATIONS : " + pojoCustomer.getAssociations());
    prestashopCustomer.save();//w  w w.ja  va  2  s. c  om
}

From source file:com.axelor.controller.ConnectionToPrestashop.java

License:Open Source License

@SuppressWarnings("null")
@Transactional//from  www.ja v  a  2  s  .  c  o  m
public void insertCustomer(int customerId) {
    com.axelor.pojo.Customer pojoCustomer = getCustomer(customerId);
    Partner prestashopCustomer = new Partner();
    DateTimeFormatter dateTimeFormat = DateTimeFormat.forPattern("yyyy-MM-dd");
    LocalDate dateOfBirth = dateTimeFormat.parseLocalDate(pojoCustomer.getBirthday());
    // add this customer into ERP
    prestashopCustomer.setPrestashopid(customerId);
    prestashopCustomer.setFirstName(pojoCustomer.getFirstname());
    prestashopCustomer.setName(pojoCustomer.getLastname());
    prestashopCustomer.setFullName(pojoCustomer.getLastname() + " " + pojoCustomer.getFirstname());
    prestashopCustomer.setEmail(pojoCustomer.getEmail());
    prestashopCustomer.setCompany(pojoCustomer.getCompany());
    prestashopCustomer.setPassword(pojoCustomer.getPasswd());
    prestashopCustomer.setBirthdate(dateOfBirth);
    prestashopCustomer.setActive(BooleanUtils.toBoolean(pojoCustomer.getActive()));
    prestashopCustomer.setArchived(BooleanUtils.toBoolean(pojoCustomer.getDeleted()));
    System.out.println(pojoCustomer.getId_default_group());
    prestashopCustomer.setPrestashopCustomerGroup(
            PrestashopCustomerGroup.all().filter("id_group=?", pojoCustomer.getId_default_group()).fetchOne());
    System.out.println(prestashopCustomer.getPrestashopCustomerGroup().getId_group());
    System.out.println("ASSOCIATIONS : " + pojoCustomer.getAssociations());
    prestashopCustomer.save();
}

From source file:com.axelor.controller.ConnectionToPrestashop.java

License:Open Source License

@SuppressWarnings("finally")
@Transactional//from ww  w . java2 s. c o  m
public String syncAddress() {
    String message = "";
    try {
        List<Integer> prestashopIdList = new ArrayList<Integer>();
        List<Integer> erpIdList = new ArrayList<Integer>();
        List<Address> erpList = Address.all().fetch();

        for (Address prestahopAddress : erpList) {
            erpIdList.add(prestahopAddress.getPrestashopid());
        }

        URL url = new URL("http://localhost/client-lib/crud/action.php?resource=addresses&action=getallid&Akey="
                + apiKey);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();

        InputStream inputStream = connection.getInputStream();
        Scanner scan = new Scanner(inputStream);
        while (scan.hasNext()) {
            String data = scan.nextLine();
            System.out.println(data);
            prestashopIdList.add(Integer.parseInt(data));
        }
        System.out.println("From Prestashop Addresses :: " + prestashopIdList.size());
        System.out.println("From ERP Addresses :: " + erpIdList.size());
        scan.close();

        // Check new entries in the prestashop
        Iterator<Integer> prestaListIterator = prestashopIdList.iterator();
        while (prestaListIterator.hasNext()) {
            Integer tempId = prestaListIterator.next();
            System.out.println("Current AddressPrestashopId for operation ::" + tempId);
            if (erpIdList.contains(tempId)) {
                com.axelor.pojo.Address tempAddress = getAddress(tempId);
                String dateUpdate = tempAddress.getDate_upd();
                LocalDateTime dt1 = LocalDateTime.parse(dateUpdate,
                        DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"));
                Address pAddress = Address.all().filter("prestashopid=?", tempId).fetchOne();
                LocalDateTime dt2 = pAddress.getUpdatedOn();
                if (dt2 != null) {
                    int diff = Seconds.secondsBetween(dt2, dt1).getSeconds();
                    if (diff > 1)
                        updateAddress(tempAddress, tempId);
                } else {
                    updateAddress(tempAddress, tempId);
                }
                erpIdList.remove(tempId);
            } else {
                System.out.println("Current AddressPrestashopId for insertion operation ::" + tempId);
                // insert new data in ERP Database
                insertAddress(tempId);
                erpIdList.remove(tempId);
            }
        }
        if (erpIdList.isEmpty()) {
            System.out.println("Synchronization is completed.");
            message = "done";
        } else {
            // delete from ERP
            Iterator<Integer> erpListIterator = erpIdList.iterator();
            while (erpListIterator.hasNext()) {
                Integer tempId = erpListIterator.next();
                if (tempId != 0) {
                    Address addressDelete = Address.all().filter("prestashopid=?", tempId).fetchOne();
                    String fullName = addressDelete.getFullName();
                    // addressDelete.remove();
                    addressDelete.setArchived(Boolean.TRUE);
                    System.out.println("Address deleted ::" + fullName);
                }
            }
            while (prestaListIterator.hasNext()) {
                Integer tempId = prestaListIterator.next();
                System.out.println("Currently in prestashop ::" + tempId);
            }
            System.out.println("Synchronization is completed.");
            message = "done";
        }
    } catch (Exception e) {
        message = "Wrong Authentication Key or Key has been disabled.";
    } finally {
        return message;
    }
}

From source file:com.axelor.controller.RetrievePrestrashopOrders.java

License:Open Source License

@Transactional
public void insertOrders(int prestashopOrderId) {
    System.out.println("Setting Default values...");
    com.axelor.pojo.Orders pojoOrder = new com.axelor.pojo.Orders();
    // SET DEFAULT VALUES
    pojoOrder.setPrestashopOrderId(0);//from  ww  w.  j  a va 2 s. co m
    pojoOrder.setId_address_delivery(0);
    pojoOrder.setId_address_invoice(0);
    pojoOrder.setId_cart(0);
    pojoOrder.setId_currency(0);
    pojoOrder.setId_lang(0);
    pojoOrder.setId_customer(0);
    pojoOrder.setId_carrier(0);
    pojoOrder.setCurrent_state(0);
    pojoOrder.setModule("cashondelivery");
    pojoOrder.setInvoice_date("1970-01-01");
    pojoOrder.setPayment("Cash on delivery (COD)");
    pojoOrder.setDate_add("1970-01-01");
    pojoOrder.setTotal_paid(new BigDecimal("00.00"));
    pojoOrder.setTotal_paid_tax_excl(new BigDecimal("00.00"));
    pojoOrder.setReference("REFERENCE");
    pojoOrder.setCompany(0);
    pojoOrder.setAssociations("associations");
    System.out.println("INserting............");
    try {
        URL url = new URL("http://localhost/client-lib/crud/action.php?resource=orders&action=retrieve&id="
                + prestashopOrderId + "&Akey=" + apiKey);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setRequestMethod("POST");
        JAXBContext jaxbContext = JAXBContext.newInstance(com.axelor.pojo.Orders.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        connection.setDoOutput(true);
        connection.setDoInput(true);
        OutputStream outputStream = connection.getOutputStream();
        jaxbMarshaller.marshal(pojoOrder, outputStream);
        connection.connect();

        //InputStream inputStream = connection.getInputStream();
        //Scanner scan = new Scanner(inputStream);
        //String temp="";

        //         while (scan.hasNext()) {
        //            temp += scan.nextLine();            
        //         }
        //         scan.close();
        //   System.out.println(temp);

        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        pojoOrder = (com.axelor.pojo.Orders) jaxbUnmarshaller
                .unmarshal(new UnmarshalInputStream(connection.getInputStream()));

        SalesOrder prestashopSaleOrder = new SalesOrder();

        //Resolve invoiceFirstDAte and creationDate
        DateTimeFormatter dateTimeFormat = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
        LocalDate invoiceFirstDate;
        LocalDate creationDate;
        try {
            invoiceFirstDate = dateTimeFormat.parseLocalDate(pojoOrder.getInvoice_date());
        } catch (IllegalFieldValueException e) {
            invoiceFirstDate = new LocalDate("1970-01-01");
        }
        creationDate = dateTimeFormat.parseLocalDate(pojoOrder.getDate_add());

        //Resolve Address

        Address baseAddress = Address.all().filter("prestashopid=?", pojoOrder.getId_address_delivery())
                .fetchOne();

        //Resolve Currency
        Currency baseCurrency = Currency.all().filter("prestashop_currency_id=?", pojoOrder.getId_currency())
                .fetchOne();

        //Resolve Partner
        Partner basePartner = Partner.all().filter("prestashopid=?", pojoOrder.getId_customer()).fetchOne();

        if (baseAddress == null || basePartner == null)
            return;
        System.out.println("Currency :: " + baseCurrency.getPrestashopCurrencyId());
        //Resolve Total Tax
        BigDecimal totalPaid, totalPaidExcl, totalTax;
        totalPaid = pojoOrder.getTotal_paid();
        totalPaidExcl = pojoOrder.getTotal_paid_tax_excl();
        totalTax = totalPaid.subtract(totalPaidExcl);

        //Resolve Current State / status_select
        int statusSelect;
        int prestashopCurentState = pojoOrder.getCurrent_state();
        switch (prestashopCurentState) {
        case 1:
        case 3:
        case 10:
        case 11:
            statusSelect = 1; //assign draft to statusSelect
            break;
        case 2:
        case 12:
            statusSelect = 2; //assign confirmed to statusSelect
            break;
        case 4:
        case 5:
        case 7:
        case 9:
            statusSelect = 3; //assign validated to statusSelect
            break;
        case 6:
        case 8:
            statusSelect = 4; //assign cancelled to statusSelect
            break;
        default:
            statusSelect = 0; //assign Error to statusSelect
        }

        //Resolve Payment Mode
        int erpPaymentMode = 0;
        String paymentMode = pojoOrder.getModule();
        if (paymentMode.equals("cashondelivery"))
            erpPaymentMode = 4;
        else if (paymentMode.equals("cheque"))
            erpPaymentMode = 6;
        else if (paymentMode.equals("bankwire"))
            erpPaymentMode = 8;
        PaymentMode basePaymentMode = PaymentMode.all().filter("id=?", erpPaymentMode).fetchOne();

        //Resolve Company, currently set to static value(1)
        Company baseCompany = Company.find(1L);

        // add this order into ERP
        prestashopSaleOrder.setPrestashopOrderId(prestashopOrderId);
        prestashopSaleOrder.setDeliveryAddress(baseAddress);
        prestashopSaleOrder.setMainInvoicingAddress(baseAddress);
        prestashopSaleOrder.setPrestashopCartId(pojoOrder.getId_cart());
        prestashopSaleOrder.setCurrency(baseCurrency);
        prestashopSaleOrder.setClientPartner(basePartner);
        prestashopSaleOrder.setPrestashopCarrierId(pojoOrder.getId_carrier());
        prestashopSaleOrder.setStatusSelect(statusSelect);
        prestashopSaleOrder.setPaymentMode(basePaymentMode);
        prestashopSaleOrder.setInvoicedFirstDate(invoiceFirstDate);
        prestashopSaleOrder.setPrestashopPayment(pojoOrder.getPayment());
        prestashopSaleOrder.setCreationDate(creationDate);
        prestashopSaleOrder.setTaxTotal(totalTax);
        prestashopSaleOrder.setInTaxTotal(pojoOrder.getTotal_paid());
        prestashopSaleOrder.setExTaxTotal(pojoOrder.getTotal_paid_tax_excl());
        prestashopSaleOrder.setExternalReference(pojoOrder.getReference());
        prestashopSaleOrder.setCompany(baseCompany);
        prestashopSaleOrder.save();
        String salesOrders = pojoOrder.getAssociations();
        System.out.println("POJO ASDS ::" + salesOrders);

        String association = "";
        int count = 0;
        Pattern associationsPattern = Pattern.compile("^count:(.*?);(.*?)/associations");
        Matcher associationsMatcher = associationsPattern.matcher(salesOrders);
        while (associationsMatcher.find()) {
            count = Integer.parseInt(associationsMatcher.group(1));
            association = associationsMatcher.group(2);
        }

        System.out.println("COUNT :: " + count);
        System.out.println("ASSO :: " + association);
        String[] salesOrderLineArray = new String[count];
        String[] salesOrderLine = new String[8];
        salesOrderLineArray = association.split(":::");
        for (int i = 0; i < salesOrderLineArray.length; i++) {
            System.out.println("ARRAY :: " + salesOrderLineArray[i]);
            salesOrderLine = salesOrderLineArray[i].split(";;;");

            BigDecimal price = new BigDecimal(salesOrderLine[5]);
            BigDecimal qty = new BigDecimal(salesOrderLine[3]);
            BigDecimal exTaxTotal = price.multiply(qty);

            SalesOrderLine orderLines = new SalesOrderLine();
            orderLines.setCompanyExTaxTotal(exTaxTotal);
            orderLines.setExTaxTotal(exTaxTotal);
            orderLines.setPrice(price);
            orderLines.setProductName(salesOrderLine[4]);
            orderLines.setQty(qty);
            orderLines.setSaleSupplySelect(1);
            orderLines.setSequence(i + 1);
            orderLines.setPrestashopSalesOrderLineId(Integer.parseInt(salesOrderLine[0]));
            orderLines.setTaxLine(TaxLine.find(1L));
            orderLines.setUnit(Unit.find(1L));

            orderLines.setSalesOrder(SalesOrder.find(prestashopSaleOrder.getId()));

            Product productOfSalesOrderLine = Product.all()
                    .filter("prestashopProductId=?", Integer.parseInt(salesOrderLine[1])).fetchOne();
            if (productOfSalesOrderLine != null) {
                System.out.println("Saving");
                orderLines.setProduct(productOfSalesOrderLine);
                orderLines.save();
            } else {
                System.out.println("Product is removed from prestashop.");
            }
            System.out.println("PRODUCT2 :: " + salesOrderLine[2]);
            System.out.println("PRODUCT3 :: " + salesOrderLine[3]);
            System.out.println("PRODUCT4 :: " + salesOrderLine[4]);
        }

    } catch (Exception e) {
        System.out.println(e);
    }
}

From source file:com.axelor.data.adapter.JodaAdapter.java

License:Open Source License

@Override
public Object adapt(Object value, Map<String, Object> context) {

    if (value == null || !(value instanceof String)) {
        return value;
    }// ww w . ja v  a2  s  .  com

    String format = this.get("format", DEFAULT_FORMAT);

    DateTimeFormatter fmt = DateTimeFormat.forPattern(format);
    DateTime dt;
    try {
        dt = fmt.parseDateTime((String) value);
    } catch (Exception e) {
        throw new IllegalArgumentException("Invalid value: " + value, e);
    }

    String type = this.get("type", null);

    if ("LocalDate".equals(type)) {
        return dt.toLocalDate();
    }
    if ("LocalTime".equals(type)) {
        return dt.toLocalTime();
    }
    if ("LocalDateTime".equals(type)) {
        return dt.toLocalDateTime();
    }
    return dt;
}