Example usage for java.util GregorianCalendar getTime

List of usage examples for java.util GregorianCalendar getTime

Introduction

In this page you can find the example usage for java.util GregorianCalendar getTime.

Prototype

public final Date getTime() 

Source Link

Document

Returns a Date object representing this Calendar's time value (millisecond offset from the Epoch").

Usage

From source file:org.etudes.jforum.repository.ForumRepository.java

/**
 * Check if forum is accessible.//from   w  ww .  j  a v a  2 s.c  om
 * 
 * @param    forum   forum
 * @return    true   if access to the forum is allowed. 
 */
public static boolean isForumAccessibleToUser(Forum forum) {
    if (forum == null)
        throw new IllegalArgumentException();

    if (JForumUserUtil.isJForumFacilitator(UserDirectoryService.getCurrentUser().getId())
            || SecurityService.isSuperUser()) {
        return true;
    }

    if (JForumUserUtil.isJForumParticipant(UserDirectoryService.getCurrentUser().getId())) {
        // ignore forums with invalid dates
        if ((forum.getStartDate() != null) && (forum.getEndDate() != null)) {
            if (forum.getStartDate().after(forum.getEndDate())) {
                return false;
            }
        }

        if ((forum.getStartDate() != null) && (forum.getAllowUntilDate() != null)) {
            if (forum.getStartDate().after(forum.getAllowUntilDate())) {
                return false;
            }
        }

        if ((forum.getEndDate() != null) && (forum.getAllowUntilDate() != null)) {
            if (forum.getEndDate().after(forum.getAllowUntilDate())) {
                return false;
            }
        }

        UserSession currentUser = SessionFacade.getUserSession();

        JForumService jforumService = (JForumService) ComponentManager
                .get("org.etudes.api.app.jforum.JForumService");
        if (forum.getGradeType() == Forum.GRADE_BY_FORUM && jforumService != null) {
            Boolean checkAccess = jforumService.checkItemAccess(ToolManager.getCurrentPlacement().getContext(),
                    ConfigKeys.CM_ID_FORUM + "-" + String.valueOf(forum.getId()), currentUser.getSakaiUserId());

            if (!checkAccess) {
                forum.setBlocked(true);
                forum.setBlockedByTitle(
                        jforumService.getItemAccessMessage(ToolManager.getCurrentPlacement().getContext(),
                                ConfigKeys.CM_ID_FORUM + "-" + String.valueOf(forum.getId()),
                                currentUser.getSakaiUserId()));
                forum.setBlockedByDetails(
                        jforumService.getItemAccessDetails(ToolManager.getCurrentPlacement().getContext(),
                                ConfigKeys.CM_ID_FORUM + "-" + String.valueOf(forum.getId()),
                                currentUser.getSakaiUserId()));
            }
        }

        try {
            Site site = SiteService.getSite(ToolManager.getCurrentPlacement().getContext());

            // get site groups - gets org.sakaiproject.site.api.Group(org.sakaiproject.site.impl.BaseGroup);
            Collection sakaiSiteGroups = site
                    .getGroupsWithMember(UserDirectoryService.getCurrentUser().getId());

            GregorianCalendar gc = new GregorianCalendar();
            Date nowDate = gc.getTime();

            if (forum.getAccessType() == Forum.ACCESS_GROUPS) {
                for (Iterator usrGrpIter = sakaiSiteGroups.iterator(); usrGrpIter.hasNext();) {
                    org.sakaiproject.site.api.Group grp = (org.sakaiproject.site.api.Group) usrGrpIter.next();
                    if (forum.getGroups() != null) {
                        if (forum.getGroups().contains(grp.getId())) {
                            // check for forum group special access
                            List<SpecialAccess> specialAccessList = forum.getSpecialAccessList();

                            boolean specialAccessUser = false, specialAccessUserAccess = false;
                            for (SpecialAccess sa : specialAccessList) {
                                if ((sa.getUserIds().contains(currentUser.getUserId()))) {
                                    specialAccessUser = true;

                                    if (!sa.isOverrideStartDate()) {
                                        sa.setStartDate(forum.getStartDate());
                                    }
                                    if (!sa.isOverrideEndDate()) {
                                        sa.setEndDate(forum.getEndDate());
                                    }
                                    if (!sa.isOverrideLockEndDate()) {
                                        sa.setLockOnEndDate(forum.isLockForum());
                                    }

                                    if (!sa.isOverrideAllowUntilDate()) {
                                        sa.setAllowUntilDate(forum.getAllowUntilDate());
                                    }

                                    if (sa.getStartDate() == null) {
                                        specialAccessUserAccess = true;
                                    } else if (nowDate.getTime() > sa.getStartDate().getTime()) {
                                        specialAccessUserAccess = true;
                                    }

                                    break;
                                }

                            }

                            if (specialAccessUser) {
                                return specialAccessUserAccess;
                            } else {
                                if (forum.getStartDate() != null) {
                                    if (nowDate.getTime() < forum.getStartDate().getTime()) {
                                        return false;
                                    }
                                }
                            }

                            return true;
                        }
                    } else {
                        return false;
                    }
                }
            } else if (forum.getAccessType() == Forum.ACCESS_DENY) {
                return false;
            } else {

                // check forum special access
                List<SpecialAccess> forumSpecialAccessList = forum.getSpecialAccessList();
                boolean specialAccessUser = false, specialAccessUserAccess = false;

                if (forumSpecialAccessList != null) {
                    for (SpecialAccess specialAccess : forumSpecialAccessList) {
                        if (specialAccess.getUserIds().contains(currentUser.getUserId())) {
                            specialAccessUser = true;

                            if (!specialAccess.isOverrideStartDate()) {
                                specialAccess.setStartDate(forum.getStartDate());
                            }
                            if (!specialAccess.isOverrideEndDate()) {
                                specialAccess.setEndDate(forum.getEndDate());
                            }
                            if (!specialAccess.isOverrideLockEndDate()) {
                                specialAccess.setLockOnEndDate(forum.isLockForum());
                            }

                            if (!specialAccess.isOverrideAllowUntilDate()) {
                                specialAccess.setAllowUntilDate(forum.getAllowUntilDate());
                            }

                            if ((specialAccess.getStartDate() != null)
                                    && (nowDate.getTime() < specialAccess.getStartDate().getTime())) {
                                specialAccessUserAccess = false;
                            } else {
                                specialAccessUserAccess = true;
                            }
                            break;
                        }
                    }
                }

                if (specialAccessUser) {
                    return specialAccessUserAccess;
                } else {
                    if (forum.getStartDate() != null) {

                        if (nowDate.getTime() < forum.getStartDate().getTime()) {
                            return false;
                        }
                    }
                }

                return true;
            }
        } catch (IdUnusedException e) {
            return false;
        }
    }
    return false;
}

From source file:org.kuali.continuity.admin.main.server.SimpleServiceImpl.java

/**
 * Special functions for Critical Function Examples
 *//*from  w  ww.  ja v  a  2 s.  c o  m*/
public String[][] getStringArray(String rootName, Integer institutionId) {

    GregorianCalendar now = new GregorianCalendar();
    System.out.println("get String Array Start. " + now.getTime() + ": " + rootName);

    List sourceList = new ArrayList();
    try {
        if (rootName.equals("plan")) {
            institutionId = (Integer) this.getContextAttribute("systemDomainId");
            logger.debug("get String Array: Getting plans:");
            sourceList = continuityPlanService.getSimpleContinuityPlanList(institutionId);
            logger.debug("get String Array: got plans: " + sourceList.size());

        } else if (rootName.equals("deptplan")) {
            institutionId = (Integer) this.getContextAttribute("systemDomainId");
            logger.debug("get String Array: Getting plans:");
            sourceList = deptPlanService.getSimpleContinuityPlanList(institutionId);

            logger.debug("get String Array: got plans: " + sourceList.size());

            String[][] ret = new String[sourceList.size()][3];
            for (int i = 0; i < sourceList.size(); i++) {
                Object[] cp = (Object[]) sourceList.get(i);
                // Object[] cp = (Object[]) ddata;
                ret[i][0] = cp[0].toString();
                ret[i][1] = cp[1].toString();
                ret[i][2] = cp[2].toString();
                // ret[i][0] = cp[0].toString();
                // ret[i][1] = cp[1].toString();
                // ret[i][2] =
            }

            return ret;

        } else if (rootName.equals("function")) {
            int planId = institutionId; // In this case the UI sends a plan Id
            // instead.

            logger.debug("Getting functions for Plan " + planId);
            sourceList = criticalFunctionService.getCriticalFunctionList(planId);
            logger.debug("Got response from service " + sourceList.size());
        }
    } catch (Exception e) {
        logger.warn("Error occurred getting Array for: " + rootName, e);
        System.out.println("Error occurred getting Array for: " + rootName + ": " + e);
        e.printStackTrace();
    }
    String[][] ret;
    ArrayList<String[]> lret = new ArrayList();
    int retsize = 1;
    if (sourceList.size() > 1)
        retsize = sourceList.size();
    ret = new String[retsize][2];
    int iret = 0;
    for (int i = 0; i < sourceList.size(); i++) {

        Object ddata = sourceList.get(i);
        if (ddata instanceof BaseDomainObject) {
            BaseDomainObject bd = (BaseDomainObject) ddata;
            ret[i][0] = bd.getId().toString();
            ret[i][1] = bd.getName();
            iret++;

            // These can be eliminated.
        } else if (ddata instanceof Object[]) {
            Object[] cp = (Object[]) ddata;
            ret[i][0] = cp[0].toString();
            ret[i][1] = cp[1].toString();
            iret++;
        } else if (ddata instanceof ContinuityPlan) {
            ContinuityPlan cp = (ContinuityPlan) ddata;
            ret[i][0] = cp.getId().toString();
            ret[i][1] = cp.getName();
            iret++;
        } else if (ddata instanceof CriticalFunction) {
            CriticalFunction cf = (CriticalFunction) ddata;
            ret[i][0] = cf.getId().toString();
            ret[i][1] = cf.getName();
            iret++;
        }

    }
    GregorianCalendar now2 = new GregorianCalendar();
    System.out.println("get String Array End. " + now2.getTime());
    return ret;
}

From source file:edu.jhuapl.openessence.web.util.Filters.java

public List<Filter> getFilters(final Map<String, String[]> parameterValues, final OeDataSource ds,
        final String prePullArg, final int prePullInc, final String resolution, int calWeekStartDay,
        final boolean adjustDate) throws ErrorMessageException {

    final List<Filter> filters = new ArrayList<Filter>();
    for (final FilterDimension fd : ds.getFilterDimensions()) {
        final FieldType type = fd.getSqlType();

        for (final String sfx : parmSfx.keySet()) {
            final String key = fd.getId() + sfx;

            if (!reservedParameters.contains(key)) {
                final String[] values = parameterValues.get(key);

                // No values for a filter dimension is ok
                if (!ArrayUtils.isEmpty(values)) {
                    if (values.length == 1) {
                        Object argument = ControllerUtils.formatData(key, values[0], type, false).get(key);

                        final Relation rel = type == FieldType.TEXT ? Relation.LIKE : parmSfx.get(sfx);

                        try {
                            if (fd.getId().equals(prePullArg) && (rel == Relation.GTEQ)) {
                                argument = muckDate((Date) argument, prePullInc, resolution, calWeekStartDay);
                            }/*from  ww  w  .  j  a v  a  2 s .  c  om*/
                            // if end date, account for hours 00:00:00 to 23:59:59
                            if ((type == FieldType.DATE_TIME || type == FieldType.DATE)
                                    && (rel == Relation.LTEQ)) {
                                GregorianCalendar x = new GregorianCalendar();
                                x.setTime((Date) argument);

                                // Only perform this operation if it hasn't already been handled in a previous call.
                                // When generating a Chart, it will go to the end of the day and adjust the filter
                                // to be 23:59:59.999 (5/1/13 becomes 5/1/13-23:59:59.999).  But, when the user
                                // would click-through on a bar/slice, it would accidently perform this action again.
                                // This resulted in adding another day to the query; now becoming 5/2/13 23:59:59.998.
                                if (adjustDate) {
                                    x.add(Calendar.DATE, 1);
                                    x.add(Calendar.MILLISECOND, -1);
                                    argument = x.getTime();
                                }
                            }
                            filters.add(fd.makeFilter(rel, argument));
                        } catch (OeDataSourceException e) {
                            throw new ErrorMessageException("Could not create filter", e);
                        }
                    } else {
                        final Object[] arguments = new Object[values.length];
                        for (int i = 0; i < values.length; i++) {
                            arguments[i] = ControllerUtils.formatData(key, values[i], type, false).get(key);
                        }

                        try {
                            filters.add(fd.makeFilter(Relation.IN, arguments));
                        } catch (OeDataSourceException e) {
                            throw new ErrorMessageException("Could not create filter", e);
                        }
                    }
                }
            }
        }
    }

    return filters;
}

From source file:carsharing.starter.automotive.iot.ibm.com.mobilestarterapp.AnalyzeMyDriving.java

public void sendLocation(final Location location) {
    if (connectDeviceClient()) {
        final GregorianCalendar cal = new GregorianCalendar();
        final TimeZone gmt = TimeZone.getTimeZone("GMT");
        cal.setTimeZone(gmt);//from w  ww  . j  ava2s .  c  om
        final SimpleDateFormat formattedCal = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        formattedCal.setCalendar(cal);
        final String timestamp = formattedCal.format(cal.getTime());

        final double speed = Math.max(0.0, location.getSpeed() * 60 * 60 / 1000);
        final double longitude = location.getLongitude();
        final double latitude = location.getLatitude();
        final String mobileAppDeviceId = FirstPage.mobileAppDeviceId;
        final String status = tripID != null ? "Unlocked" : "Locked";

        if (tripID == null) {
            // this trip should be completed, so lock device now
            userUnlocked = false;
        }

        final JsonObject event = new JsonObject();
        final JsonObject data = new JsonObject();
        event.add("d", data);
        data.addProperty("trip_id", tripID);
        data.addProperty("speed", speed);
        data.addProperty("lng", longitude);
        data.addProperty("lat", latitude);
        data.addProperty("ts", timestamp);
        data.addProperty("id", mobileAppDeviceId);
        data.addProperty("status", status);

        final ActionBar supportActionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
        if (deviceClient.publishEvent("sensorData", event, 0)) {
            Log.d("MQTT", "publish event " + event.toString());
            supportActionBar.setTitle(speedMessage + " - Data sent (" + (++transmissionCount) + ")");
        } else {
            Log.d("MQTT", "ERROR in publishing event " + event.toString());
            supportActionBar.setTitle("Data Transmission Error.");
        }
    }
}

From source file:org.extensiblecatalog.ncip.v2.koha.KohaLookupUserService.java

private void updateResponseData(ILSDIvOneOneLookupUserInitiationData initData,
        ILSDIvOneOneLookupUserResponseData responseData, JSONObject kohaUser, KohaRemoteServiceManager svcMgr)
        throws ParseException, KohaException {

    ResponseHeader responseHeader = KohaUtil.reverseInitiationHeader(initData);

    if (responseHeader != null)
        responseData.setResponseHeader(responseHeader);

    UserId userId = KohaUtil.createUserId(initData.getUserId().getUserIdentifierValue(),
            LocalConfig.getDefaultAgency());
    responseData.setUserId(userId);/*  ww w  .  jav  a  2 s . c  o m*/

    UserOptionalFields userOptionalFields = new UserOptionalFields();

    if (LocalConfig.useRestApiInsteadOfSvc()) {

        if (initData.getNameInformationDesired()) {
            String firstname = (String) kohaUser.get("firstname");
            String surname = (String) kohaUser.get("surname");
            String title = (String) kohaUser.get("title");
            String othernames = (String) kohaUser.get("othernames");

            StructuredPersonalUserName structuredPersonalUserName = new StructuredPersonalUserName();
            structuredPersonalUserName.setGivenName(firstname);
            structuredPersonalUserName.setPrefix(title);
            structuredPersonalUserName.setSurname(surname);
            structuredPersonalUserName.setSuffix(othernames);

            PersonalNameInformation personalNameInformation = new PersonalNameInformation();
            personalNameInformation.setStructuredPersonalUserName(structuredPersonalUserName);

            NameInformation nameInformation = new NameInformation();
            nameInformation.setPersonalNameInformation(personalNameInformation);
            userOptionalFields.setNameInformation(nameInformation);
        }

        if (initData.getUserAddressInformationDesired())
            userOptionalFields.setUserAddressInformations(KohaUtil.parseUserAddressInformations(kohaUser));

        if (initData.getUserPrivilegeDesired()) {

            String branchcode = (String) kohaUser.get("branchcode");
            String agencyUserPrivilegeType = (String) kohaUser.get("categorycode");

            if (branchcode != null && agencyUserPrivilegeType != null) {

                List<UserPrivilege> userPrivileges = new ArrayList<UserPrivilege>();
                UserPrivilege userPrivilege = new UserPrivilege();

                userPrivilege.setAgencyId(new AgencyId(branchcode));

                userPrivilege.setAgencyUserPrivilegeType(new AgencyUserPrivilegeType(
                        "http://www.niso.org/ncip/v1_0/imp1/schemes/agencyuserprivilegetype/agencyuserprivilegetype.scm",
                        agencyUserPrivilegeType));

                userPrivilege.setValidFromDate(
                        KohaUtil.parseGregorianCalendarFromKohaDate((String) kohaUser.get("dateenrolled")));
                userPrivilege.setValidToDate(
                        KohaUtil.parseGregorianCalendarFromKohaDate((String) kohaUser.get("dateexpiry")));

                userPrivileges.add(userPrivilege);
                userOptionalFields.setUserPrivileges(userPrivileges);
            }
        }

        if (initData.getDateOfBirthDesired()) {
            String dateOfBirth = (String) kohaUser.get("dateofbirth");
            userOptionalFields.setDateOfBirth(KohaUtil.parseGregorianCalendarFromKohaDate(dateOfBirth));
        }

        if (initData.getLoanedItemsDesired()) {
            JSONArray checkouts = (JSONArray) kohaUser.get("checkouts");

            if (checkouts != null && checkouts.size() != 0) {
                List<LoanedItem> loanedItems = new ArrayList<LoanedItem>();
                for (int i = 0; i < checkouts.size(); ++i) {
                    JSONObject checkout = (JSONObject) checkouts.get(i);
                    loanedItems.add(KohaUtil.parseLoanedItem(checkout));
                }
                responseData.setLoanedItems(loanedItems);
            }

        }

        if (initData.getRequestedItemsDesired()) {
            JSONArray holds = (JSONArray) kohaUser.get("holds");

            if (holds != null && holds.size() != 0) {
                List<RequestedItem> requestedItems = new ArrayList<RequestedItem>();
                for (int i = 0; i < holds.size(); ++i) {
                    JSONObject hold = (JSONObject) holds.get(i);
                    RequestedItem requestedItem = KohaUtil.parseRequestedItem(hold);
                    if (requestedItem != null)
                        requestedItems.add(requestedItem);
                }
                responseData.setRequestedItems(requestedItems);
            }
        }

        if (initData.getBlockOrTrapDesired()) {

            List<BlockOrTrap> blocks = new ArrayList<BlockOrTrap>(4);

            // Parse expiration
            GregorianCalendar expiryDate = KohaUtil
                    .parseGregorianCalendarFromKohaDate((String) kohaUser.get("dateexpiry"));

            GregorianCalendar warningForExpiryDateGregCal = ((GregorianCalendar) expiryDate.clone());
            warningForExpiryDateGregCal.add(GregorianCalendar.DAY_OF_YEAR, -14);

            Date now = new Date();
            if (now.after(expiryDate.getTime())) {

                BlockOrTrap expired = KohaUtil.createBlockOrTrap("Expired");

                blocks.add(expired);

            } else if (now.after(warningForExpiryDateGregCal.getTime())) {

                Days days = Days.daysBetween(new DateTime(now), new DateTime(expiryDate));

                BlockOrTrap expiresSoon = KohaUtil
                        .createBlockOrTrap("Expires in " + (days.getDays() + 1) + " days");

                blocks.add(expiresSoon);
            }

            // Parse debarred status
            String debarredStatus = (String) kohaUser.get("debarred");

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

                String debarredComment = (String) kohaUser.get("debarredcomment");

                BlockOrTrap debarred = KohaUtil.createBlockOrTrap(
                        "Debarred" + (debarredComment != null ? ": " + debarredComment : ""));

                blocks.add(debarred);
            }

            if (blocks.size() > 0)
                userOptionalFields.setBlockOrTraps(blocks);

        }

        if (initData.getUserFiscalAccountDesired()) {

            JSONArray accountLines = (JSONArray) kohaUser.get("accountLines");

            if (accountLines != null && accountLines.size() != 0) {
                List<UserFiscalAccount> userFiscalAccounts = new ArrayList<UserFiscalAccount>(1);
                UserFiscalAccount userFiscalAccount = new UserFiscalAccount();
                List<AccountDetails> accountDetails = new ArrayList<AccountDetails>();

                for (int i = 0; i < accountLines.size(); ++i) {
                    JSONObject accountLine = (JSONObject) accountLines.get(i);
                    accountDetails.add(KohaUtil.parseAccountDetails(accountLine));
                }

                BigDecimal amount = null; // Sum all transactions ..
                for (AccountDetails details : accountDetails) {
                    if (amount == null)
                        amount = details.getFiscalTransactionInformation().getAmount().getMonetaryValue();
                    else
                        amount = amount
                                .add(details.getFiscalTransactionInformation().getAmount().getMonetaryValue());
                }
                userFiscalAccount.setAccountBalance(KohaUtil.createAccountBalance(amount));

                userFiscalAccount.setAccountDetails(accountDetails);
                userFiscalAccounts.add(userFiscalAccount); // Suppose user has
                // only one account
                // ..
                responseData.setUserFiscalAccounts(userFiscalAccounts);
            }
        }

        if (initData.getHistoryDesired() != null) {
            LoanedItemsHistory loanedItemsHistory = KohaUtil.parseLoanedItemsHistory(kohaUser, initData);
            responseData.setLoanedItemsHistory(loanedItemsHistory);
        }

    } else {
        JSONObject userInfo = (JSONObject) kohaUser.get("userInfo");
        if (userInfo != null) {
            if (initData.getNameInformationDesired()) {
                String firstname = (String) userInfo.get("firstname");
                String surname = (String) userInfo.get("surname");
                String title = (String) userInfo.get("title");
                String othernames = (String) userInfo.get("othernames");

                StructuredPersonalUserName structuredPersonalUserName = new StructuredPersonalUserName();
                structuredPersonalUserName.setGivenName(firstname);
                structuredPersonalUserName.setPrefix(title);
                structuredPersonalUserName.setSurname(surname);
                structuredPersonalUserName.setSuffix(othernames);

                PersonalNameInformation personalNameInformation = new PersonalNameInformation();
                personalNameInformation.setStructuredPersonalUserName(structuredPersonalUserName);

                NameInformation nameInformation = new NameInformation();
                nameInformation.setPersonalNameInformation(personalNameInformation);
                userOptionalFields.setNameInformation(nameInformation);
            }

            if (initData.getUserAddressInformationDesired())
                userOptionalFields.setUserAddressInformations(KohaUtil.parseUserAddressInformations(userInfo));

            if (initData.getUserPrivilegeDesired()) {

                String branchcode = (String) userInfo.get("branchcode");
                String agencyUserPrivilegeType = (String) userInfo.get("categorycode");

                if (branchcode != null && agencyUserPrivilegeType != null) {

                    List<UserPrivilege> userPrivileges = new ArrayList<UserPrivilege>();
                    UserPrivilege userPrivilege = new UserPrivilege();

                    userPrivilege.setAgencyId(new AgencyId(branchcode));

                    userPrivilege.setAgencyUserPrivilegeType(new AgencyUserPrivilegeType(
                            "http://www.niso.org/ncip/v1_0/imp1/schemes/agencyuserprivilegetype/agencyuserprivilegetype.scm",
                            agencyUserPrivilegeType));

                    userPrivilege.setValidFromDate(
                            KohaUtil.parseGregorianCalendarFromKohaDate((String) userInfo.get("dateenrolled")));
                    userPrivilege.setValidToDate(
                            KohaUtil.parseGregorianCalendarFromKohaDate((String) userInfo.get("dateexpiry")));

                    userPrivileges.add(userPrivilege);
                    userOptionalFields.setUserPrivileges(userPrivileges);
                }
            }

            if (initData.getBlockOrTrapDesired()) {
                List<BlockOrTrap> blockOrTraps = KohaUtil.parseBlockOrTraps((JSONArray) userInfo.get("blocks"));
                userOptionalFields.setBlockOrTraps(blockOrTraps);
            }

            if (initData.getDateOfBirthDesired()) {
                String dateOfBirth = (String) userInfo.get("dateofbirth");
                userOptionalFields.setDateOfBirth(KohaUtil.parseGregorianCalendarFromKohaDate(dateOfBirth));
            }
        }

        JSONArray requestedItemsParsed = (JSONArray) kohaUser.get("requestedItems");
        if (requestedItemsParsed != null && requestedItemsParsed.size() != 0) {
            List<RequestedItem> requestedItems = new ArrayList<RequestedItem>();
            for (int i = 0; i < requestedItemsParsed.size(); ++i) {
                JSONObject requestedItemParsed = (JSONObject) requestedItemsParsed.get(i);
                RequestedItem requestedItem = KohaUtil.parseRequestedItem(requestedItemParsed);
                if (requestedItem != null)
                    requestedItems.add(requestedItem);
            }
            responseData.setRequestedItems(requestedItems);
        }

        JSONArray loanedItemsParsed = (JSONArray) kohaUser.get("loanedItems");
        if (loanedItemsParsed != null && loanedItemsParsed.size() != 0) {
            List<LoanedItem> loanedItems = new ArrayList<LoanedItem>();
            for (int i = 0; i < loanedItemsParsed.size(); ++i) {
                JSONObject loanedItem = (JSONObject) loanedItemsParsed.get(i);
                loanedItems.add(KohaUtil.parseLoanedItem(loanedItem));
            }
            responseData.setLoanedItems(loanedItems);
        }

        JSONArray userFiscalAccountParsed = (JSONArray) kohaUser.get("userFiscalAccount");
        if (userFiscalAccountParsed != null && userFiscalAccountParsed.size() != 0) {
            List<UserFiscalAccount> userFiscalAccounts = new ArrayList<UserFiscalAccount>();
            UserFiscalAccount userFiscalAccount = new UserFiscalAccount();
            List<AccountDetails> accountDetails = new ArrayList<AccountDetails>();

            for (int i = 0; i < userFiscalAccountParsed.size(); ++i) {
                JSONObject accountDetail = (JSONObject) userFiscalAccountParsed.get(i);
                accountDetails.add(KohaUtil.parseAccountDetails(accountDetail));
            }

            BigDecimal amount = null; // Sum all transactions ..
            for (AccountDetails details : accountDetails) {
                if (amount == null)
                    amount = details.getFiscalTransactionInformation().getAmount().getMonetaryValue();
                else
                    amount.add(details.getFiscalTransactionInformation().getAmount().getMonetaryValue());
            }
            userFiscalAccount.setAccountBalance(KohaUtil.createAccountBalance(amount));

            userFiscalAccount.setAccountDetails(accountDetails);
            userFiscalAccounts.add(userFiscalAccount); // Suppose user has
            // only one account
            // ..
            responseData.setUserFiscalAccounts(userFiscalAccounts);
        }

    }
    responseData.setUserOptionalFields(userOptionalFields);

}

From source file:cs.stats.gui.StatsCharts.java

public StatsCharts(double tresholdTRT) {
    super(new BorderLayout());

    this.tresholdTRT = tresholdTRT;

    datasets = new TimeSeriesCollection[SUBPLOT_COUNT];

    // set the initial date according to the one specified in SystemClock object
    GregorianCalendar calendar = new GregorianCalendar();
    calendar.set(GregorianCalendar.HOUR, 8);
    calendar.set(GregorianCalendar.DAY_OF_MONTH, 1);
    calendar.set(GregorianCalendar.MONTH, 2);
    calendar.set(GregorianCalendar.YEAR, 2010);

    //setup the initial date range
    GregorianCalendar calendarForInitialDateRange = new GregorianCalendar();
    calendarForInitialDateRange.set(GregorianCalendar.HOUR, 8);
    calendarForInitialDateRange.set(GregorianCalendar.DAY_OF_MONTH, 1);
    calendarForInitialDateRange.set(GregorianCalendar.MONTH, 2);
    calendarForInitialDateRange.set(GregorianCalendar.YEAR, 2010);

    initialDateRange = new DateRange(calendarForInitialDateRange.getTime(), calendar.getTime());
    initialDateRange1 = new DateRange(calendarForInitialDateRange.getTime(), calendar.getTime());
    initialDateRange2 = new DateRange(calendarForInitialDateRange.getTime(), calendar.getTime());
    initialDateRange3 = new DateRange(calendarForInitialDateRange.getTime(), calendar.getTime());
    initialDateRange4 = new DateRange(calendarForInitialDateRange.getTime(), calendar.getTime());
    initialDateRange5 = new DateRange(calendarForInitialDateRange.getTime(), calendar.getTime());

    JPanel tabbedPanel = createChartTab();
    add(tabbedPanel, "North");
}

From source file:org.bimserver.plugins.MavenPluginLocation.java

public SPluginBundleVersion getPluginBundleVersion(String version) {
    try {//from w w  w  .j  a v a 2s.  com
        Path pomFile = getVersionPom(version);

        MavenXpp3Reader mavenreader = new MavenXpp3Reader();

        Model model = null;
        try (FileReader fileReader = new FileReader(pomFile.toFile())) {
            model = mavenreader.read(fileReader);
        }
        SPluginBundleVersion sPluginBundleVersion = new SPluginBundleVersion();
        sPluginBundleVersion.setOrganization(model.getOrganization().getName());
        sPluginBundleVersion.setName(model.getName());
        sPluginBundleVersion.setType(SPluginBundleType.MAVEN);
        sPluginBundleVersion.setGroupId(groupId);
        sPluginBundleVersion.setArtifactId(artifactId);
        sPluginBundleVersion.setVersion(version);
        sPluginBundleVersion.setDescription(model.getDescription());
        sPluginBundleVersion.setRepository(defaultrepository);
        sPluginBundleVersion.setMismatch(false);

        try {
            sPluginBundleVersion.setIcon(getVersionIcon(version));
        } catch (ArtifactResolutionException e) {
            // Not a problem
        }
        try {
            GregorianCalendar date = getVersionDate(version);
            //            byte[] bytes = Files.readAllBytes(date);
            //            Properties properties = new Properties();
            //            properties.load(new ByteArrayInputStream(bytes));
            //            String buildDateString = properties.getProperty("build.date");
            //            
            //            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
            if (date != null) {
                sPluginBundleVersion.setDate(date.getTime());
            }
        } catch (ArtifactResolutionException e) {
            // Not a problem
        } catch (Exception e) {
            LOGGER.error("", e);
        }

        return sPluginBundleVersion;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (XmlPullParserException e) {
        e.printStackTrace();
    } catch (ArtifactResolutionException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.egov.egf.web.actions.budget.BaseBudgetDetailAction.java

public Date getPreviousYearFor(final Date date) {
    final GregorianCalendar previousYearToDate = new GregorianCalendar();
    previousYearToDate.setTime(date);//from w ww  .  j  av  a  2 s .c  om
    final int prevYear = previousYearToDate.get(Calendar.YEAR) - 1;
    previousYearToDate.set(Calendar.YEAR, prevYear);
    return previousYearToDate.getTime();
}

From source file:org.webical.web.component.event.EventForm.java

/**
 * Create an empty Event and set the start and end times
 * @return Event/* ww  w .j  av  a 2 s.  c  o m*/
 */
private EventWrapper createEmptyEvent() {
    this.formEvent = new Event();
    this.eventWrapper = new EventWrapper(formEvent);

    GregorianCalendar dateCalendar = CalendarUtils.duplicateCalendar(selectedDate);
    GregorianCalendar timeCalendar = CalendarUtils.newTodayCalendar(dateCalendar.getFirstDayOfWeek());
    dateCalendar.set(GregorianCalendar.HOUR_OF_DAY, timeCalendar.get(GregorianCalendar.HOUR_OF_DAY));
    dateCalendar.set(GregorianCalendar.MINUTE, timeCalendar.get(GregorianCalendar.MINUTE) / 5 * 5);

    //Fill the start and end times with proper values
    eventWrapper.setDtStart(dateCalendar.getTime());
    dateCalendar.add(GregorianCalendar.HOUR_OF_DAY, 1);
    eventWrapper.setDtEnd(dateCalendar.getTime());

    return this.eventWrapper;
}

From source file:nodomain.freeyourgadget.gadgetbridge.service.devices.miband2.operations.FetchActivityOperation.java

private GregorianCalendar saveSamples() {
    if (samples.size() > 0) {
        // save all the samples that we got
        try (DBHandler handler = GBApplication.acquireDB()) {
            DaoSession session = handler.getDaoSession();
            SampleProvider<MiBandActivitySample> sampleProvider = new MiBandSampleProvider(getDevice(),
                    session);/*from  www.  j  a  va  2  s.  com*/
            Device device = DBHelper.getDevice(getDevice(), session);
            User user = DBHelper.getUser(session);

            GregorianCalendar timestamp = (GregorianCalendar) startTimestamp.clone();
            for (MiBandActivitySample sample : samples) {
                sample.setDevice(device);
                sample.setUser(user);
                sample.setTimestamp((int) (timestamp.getTimeInMillis() / 1000));
                sample.setProvider(sampleProvider);

                if (LOG.isDebugEnabled()) {
                    //                        LOG.debug("sample: " + sample);
                }

                timestamp.add(Calendar.MINUTE, 1);
            }
            sampleProvider.addGBActivitySamples(samples.toArray(new MiBandActivitySample[0]));

            saveLastSyncTimestamp(timestamp);
            LOG.info("Mi2 activity data: last sample timestamp: "
                    + DateTimeUtils.formatDateTime(timestamp.getTime()));
            return timestamp;

        } catch (Exception ex) {
            GB.toast(getContext(), "Error saving activity samples", Toast.LENGTH_LONG, GB.ERROR);
        } finally {
            samples.clear();
        }
    }
    return null;
}