Example usage for org.joda.time LocalDateTime parse

List of usage examples for org.joda.time LocalDateTime parse

Introduction

In this page you can find the example usage for org.joda.time LocalDateTime parse.

Prototype

public static LocalDateTime parse(String str, DateTimeFormatter formatter) 

Source Link

Document

Parses a LocalDateTime from the specified string using a formatter.

Usage

From source file:org.fuin.objects4j.common.LocalDateTimeAdapter.java

License:Open Source License

@Override
public final LocalDateTime convertToEntityAttribute(final String str) {
    if (str == null) {
        return null;
    }/*from  w  ww .  jav a  2 s.c  om*/
    return LocalDateTime.parse(str, ISODateTimeFormat.dateTimeParser());
}

From source file:org.mifosplatform.infrastructure.reportmailingjob.domain.ReportMailingJob.java

License:Mozilla Public License

/** 
 * create a new instance of the ReportmailingJob for a new entry 
 * //from  w w  w.ja  v a  2s  . co m
 * @return ReportMailingJob object
 **/
public static ReportMailingJob instance(JsonCommand jsonCommand, final Report stretchyReport,
        final LocalDate createdOnDate, final AppUser createdByUser, final AppUser runAsUser) {
    final String name = jsonCommand.stringValueOfParameterNamed(ReportMailingJobConstants.NAME_PARAM_NAME);
    final String description = jsonCommand
            .stringValueOfParameterNamed(ReportMailingJobConstants.DESCRIPTION_PARAM_NAME);
    final String recurrence = jsonCommand
            .stringValueOfParameterNamed(ReportMailingJobConstants.RECURRENCE_PARAM_NAME);
    final boolean isActive = jsonCommand
            .booleanPrimitiveValueOfParameterNamed(ReportMailingJobConstants.IS_ACTIVE_PARAM_NAME);
    final String emailRecipients = jsonCommand
            .stringValueOfParameterNamed(ReportMailingJobConstants.EMAIL_RECIPIENTS_PARAM_NAME);
    final String emailSubject = jsonCommand
            .stringValueOfParameterNamed(ReportMailingJobConstants.EMAIL_SUBJECT_PARAM_NAME);
    final String emailMessage = jsonCommand
            .stringValueOfParameterNamed(ReportMailingJobConstants.EMAIL_MESSAGE_PARAM_NAME);
    final String stretchyReportParamMap = jsonCommand
            .stringValueOfParameterNamed(ReportMailingJobConstants.STRETCHY_REPORT_PARAM_MAP_PARAM_NAME);
    final Integer emailAttachmentFileFormatId = jsonCommand
            .integerValueOfParameterNamed(ReportMailingJobConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME);
    final ReportMailingJobEmailAttachmentFileFormat emailAttachmentFileFormat = ReportMailingJobEmailAttachmentFileFormat
            .instance(emailAttachmentFileFormatId);
    LocalDateTime startDateTime = new LocalDateTime();

    if (jsonCommand.hasParameter(ReportMailingJobConstants.START_DATE_TIME_PARAM_NAME)) {
        final String startDateTimeString = jsonCommand
                .stringValueOfParameterNamed(ReportMailingJobConstants.START_DATE_TIME_PARAM_NAME);

        if (startDateTimeString != null) {
            final DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(jsonCommand.dateFormat())
                    .withLocale(jsonCommand.extractLocale());
            startDateTime = LocalDateTime.parse(startDateTimeString, dateTimeFormatter);
        }
    }

    return new ReportMailingJob(name, description, startDateTime, recurrence, createdOnDate, createdByUser,
            emailRecipients, emailSubject, emailMessage, emailAttachmentFileFormat, stretchyReport,
            stretchyReportParamMap, null, startDateTime, null, null, null, isActive, false, runAsUser);
}

From source file:org.mifosplatform.infrastructure.reportmailingjob.domain.ReportMailingJob.java

License:Mozilla Public License

/** 
 * Update the ReportMailingJob entity //from   w w w  .j a  v  a2  s .  c  om
 * 
 * @param jsonCommand JsonCommand object
 * @return map of string to object
 **/
public Map<String, Object> update(final JsonCommand jsonCommand) {
    final Map<String, Object> actualChanges = new LinkedHashMap<>();

    if (jsonCommand.isChangeInStringParameterNamed(ReportMailingJobConstants.NAME_PARAM_NAME, this.name)) {
        final String name = jsonCommand.stringValueOfParameterNamed(ReportMailingJobConstants.NAME_PARAM_NAME);
        actualChanges.put(ReportMailingJobConstants.NAME_PARAM_NAME, name);

        this.name = name;
    }

    if (jsonCommand.isChangeInStringParameterNamed(ReportMailingJobConstants.DESCRIPTION_PARAM_NAME,
            this.description)) {
        final String description = jsonCommand
                .stringValueOfParameterNamed(ReportMailingJobConstants.DESCRIPTION_PARAM_NAME);
        actualChanges.put(ReportMailingJobConstants.DESCRIPTION_PARAM_NAME, description);

        this.description = description;
    }

    if (jsonCommand.isChangeInStringParameterNamed(ReportMailingJobConstants.RECURRENCE_PARAM_NAME,
            this.recurrence)) {
        final String recurrence = jsonCommand
                .stringValueOfParameterNamed(ReportMailingJobConstants.RECURRENCE_PARAM_NAME);
        actualChanges.put(ReportMailingJobConstants.RECURRENCE_PARAM_NAME, recurrence);

        this.recurrence = recurrence;
    }

    if (jsonCommand.isChangeInBooleanParameterNamed(ReportMailingJobConstants.IS_ACTIVE_PARAM_NAME,
            this.isActive)) {
        final boolean isActive = jsonCommand
                .booleanPrimitiveValueOfParameterNamed(ReportMailingJobConstants.IS_ACTIVE_PARAM_NAME);
        actualChanges.put(ReportMailingJobConstants.IS_ACTIVE_PARAM_NAME, isActive);

        this.isActive = isActive;
    }

    if (jsonCommand.isChangeInStringParameterNamed(ReportMailingJobConstants.EMAIL_RECIPIENTS_PARAM_NAME,
            this.emailRecipients)) {
        final String emailRecipients = jsonCommand
                .stringValueOfParameterNamed(ReportMailingJobConstants.EMAIL_RECIPIENTS_PARAM_NAME);
        actualChanges.put(ReportMailingJobConstants.EMAIL_RECIPIENTS_PARAM_NAME, emailRecipients);

        this.emailRecipients = emailRecipients;
    }

    if (jsonCommand.isChangeInStringParameterNamed(ReportMailingJobConstants.EMAIL_SUBJECT_PARAM_NAME,
            this.emailSubject)) {
        final String emailSubject = jsonCommand
                .stringValueOfParameterNamed(ReportMailingJobConstants.EMAIL_SUBJECT_PARAM_NAME);
        actualChanges.put(ReportMailingJobConstants.EMAIL_SUBJECT_PARAM_NAME, emailSubject);

        this.emailSubject = emailSubject;
    }

    if (jsonCommand.isChangeInStringParameterNamed(ReportMailingJobConstants.EMAIL_MESSAGE_PARAM_NAME,
            this.emailMessage)) {
        final String emailMessage = jsonCommand
                .stringValueOfParameterNamed(ReportMailingJobConstants.EMAIL_MESSAGE_PARAM_NAME);
        actualChanges.put(ReportMailingJobConstants.EMAIL_MESSAGE_PARAM_NAME, emailMessage);

        this.emailMessage = emailMessage;
    }

    if (jsonCommand.isChangeInStringParameterNamed(
            ReportMailingJobConstants.STRETCHY_REPORT_PARAM_MAP_PARAM_NAME, this.stretchyReportParamMap)) {
        final String stretchyReportParamMap = jsonCommand
                .stringValueOfParameterNamed(ReportMailingJobConstants.STRETCHY_REPORT_PARAM_MAP_PARAM_NAME);
        actualChanges.put(ReportMailingJobConstants.STRETCHY_REPORT_PARAM_MAP_PARAM_NAME,
                stretchyReportParamMap);

        this.stretchyReportParamMap = stretchyReportParamMap;
    }

    final ReportMailingJobEmailAttachmentFileFormat emailAttachmentFileFormat = ReportMailingJobEmailAttachmentFileFormat
            .instance(this.emailAttachmentFileFormat);

    if (jsonCommand.isChangeInIntegerParameterNamed(
            ReportMailingJobConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME,
            emailAttachmentFileFormat.getId())) {
        final Integer emailAttachmentFileFormatId = jsonCommand.integerValueOfParameterNamed(
                ReportMailingJobConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME);
        actualChanges.put(ReportMailingJobConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME,
                emailAttachmentFileFormatId);

        final ReportMailingJobEmailAttachmentFileFormat newEmailAttachmentFileFormat = ReportMailingJobEmailAttachmentFileFormat
                .instance(emailAttachmentFileFormatId);
        this.emailAttachmentFileFormat = newEmailAttachmentFileFormat.getValue();
    }

    final String newStartDateTimeString = jsonCommand
            .stringValueOfParameterNamed(ReportMailingJobConstants.START_DATE_TIME_PARAM_NAME);

    if (!StringUtils.isEmpty(newStartDateTimeString)) {
        final DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(jsonCommand.dateFormat())
                .withLocale(jsonCommand.extractLocale());
        final LocalDateTime newStartDateTime = LocalDateTime.parse(newStartDateTimeString, dateTimeFormatter);
        final LocalDateTime oldStartDateTime = (this.startDateTime != null)
                ? new LocalDateTime(this.startDateTime)
                : null;

        if ((oldStartDateTime != null) && !newStartDateTime.equals(oldStartDateTime)) {
            actualChanges.put(ReportMailingJobConstants.START_DATE_TIME_PARAM_NAME, newStartDateTimeString);

            this.startDateTime = newStartDateTime.toDate();
        }
    }

    Long currentStretchyReportId = null;

    if (this.stretchyReport != null) {
        currentStretchyReportId = this.stretchyReport.getId();
    }

    if (jsonCommand.isChangeInLongParameterNamed(ReportMailingJobConstants.STRETCHY_REPORT_ID_PARAM_NAME,
            currentStretchyReportId)) {
        final Long updatedStretchyReportId = jsonCommand
                .longValueOfParameterNamed(ReportMailingJobConstants.STRETCHY_REPORT_ID_PARAM_NAME);
        actualChanges.put(ReportMailingJobConstants.STRETCHY_REPORT_ID_PARAM_NAME, updatedStretchyReportId);
    }

    return actualChanges;
}

From source file:org.movsim.consumption.offline.InputDataParser.java

License:Open Source License

private double convertToSeconds(String time) throws NumberFormatException, IllegalArgumentException {
    if (timeInputPattern.isEmpty()) {
        return Double.parseDouble(time);
    }/*from   w  w  w. j  a  v  a 2 s  .c  o  m*/
    LOG.debug("timeInputPattern={}, time={}", timeInputPattern, time);
    DateTime dateTime = LocalDateTime.parse(time, DateTimeFormat.forPattern(timeInputPattern))
            .toDateTime(DateTimeZone.UTC);
    LOG.debug("{} --> {}", time, dateTime);
    return dateTime.getSecondOfDay();
}

From source file:org.movsim.extended.SimulatorExtended.java

License:Open Source License

public void initialize() throws JAXBException, SAXException {
    LOG.info("Copyright '\u00A9' by Arne Kesting, Martin Treiber, Ralph Germ and Martin Budden (2011-2013)");

    projectName = projectMetaData.getProjectName();
    // TODO temporary handling of Variable Message Sign until added to XML
    roadNetwork.setHasVariableMessageSign(projectName.startsWith("routing"));

    inputData = MovsimInputLoader.getInputData(projectMetaData.getInputFile());

    timeOffsetMillis = 0;/*from  www .j a  va  2  s  .c o  m*/
    if (inputData.getScenario().getSimulation().isSetTimeOffset()) {
        DateTime dateTime = LocalDateTime.parse(inputData.getScenario().getSimulation().getTimeOffset(),
                DateTimeFormat.forPattern("YYYY-MM-dd'T'HH:mm:ssZ")).toDateTime(DateTimeZone.UTC);
        timeOffsetMillis = dateTime.getMillis();
        LOG.info("global time offset set={} --> {} milliseconds.", dateTime, timeOffsetMillis);
        ProjectMetaData.getInstance().setTimeOffsetMillis(timeOffsetMillis);
    }
    projectMetaData.setXodrNetworkFilename(inputData.getScenario().getNetworkFilename()); // TODO

    Simulation simulationInput = inputData.getScenario().getSimulation();

    final boolean loadedRoadNetwork = parseOpenDriveXml(roadNetwork, projectMetaData);
    routing = new Routing(inputData.getScenario().getRoutes(), roadNetwork);

    vehicleFactory = new VehicleFactory(simulationInput.getTimestep(), inputData.getVehiclePrototypes(),
            inputData.getConsumption(), routing);

    roadNetwork.setWithCrashExit(simulationInput.isCrashExit());

    simulationRunnable.setTimeStep(simulationInput.getTimestep());
    setTimeStep(simulationInput.getTimestep());

    // TODO better handling of case "duration = INFINITY"
    double duration = simulationInput.isSetDuration() ? simulationInput.getDuration() : -1;

    simulationRunnable.setDuration(duration < 0 ? Double.MAX_VALUE : duration);

    if (simulationInput.isWithSeed()) {
        MyRandom.initializeWithSeed(simulationInput.getSeed());
    }

    createTrafficCompositionGenerator(simulationInput);

    // For each road in the MovSim XML input data, find the corresponding roadSegment and
    // set its input data accordingly
    // final Map<String, RoadInput> roadInputMap = simulationInput.get.getRoadInput();
    if (loadedRoadNetwork == false && simulationInput.getRoad().size() == 1) {
        defaultTestingRoadMapping(simulationInput.getRoad().get(0));
    } else {
        matchRoadSegmentsAndRoadInput(simulationInput.getRoad());
    }

    createTrafficLights();

    this.timeSteps.add(trafficLights);
    this.timeSteps.add(roadNetwork);

    reset();
}

From source file:org.movsim.simulator.Simulator.java

License:Open Source License

public void initialize() throws JAXBException, SAXException {
    LOG.info("Copyright '\u00A9' by Arne Kesting, Martin Treiber, Ralph Germ and Martin Budden (2011-2013)");

    projectName = projectMetaData.getProjectName();
    // TODO temporary handling of Variable Message Sign until added to XML
    roadNetwork.setHasVariableMessageSign(projectName.startsWith("routing"));

    inputData = MovsimInputLoader.getInputData(projectMetaData.getInputFile());

    timeOffsetMillis = 0;/*from   www  .jav a 2  s. co  m*/
    if (inputData.getScenario().getSimulation().isSetTimeOffset()) {
        DateTime dateTime = LocalDateTime.parse(inputData.getScenario().getSimulation().getTimeOffset(),
                DateTimeFormat.forPattern("YYYY-MM-dd'T'HH:mm:ssZ")).toDateTime(DateTimeZone.UTC);
        timeOffsetMillis = dateTime.getMillis();
        LOG.info("global time offset set={} --> {} milliseconds.", dateTime, timeOffsetMillis);
        ProjectMetaData.getInstance().setTimeOffsetMillis(timeOffsetMillis);
    }
    projectMetaData.setXodrNetworkFilename(inputData.getScenario().getNetworkFilename()); // TODO

    Simulation simulationInput = inputData.getScenario().getSimulation();

    final boolean loadedRoadNetwork = parseOpenDriveXml(roadNetwork, projectMetaData);
    routing = new Routing(inputData.getScenario().getRoutes(), roadNetwork);

    vehicleFactory = new VehicleFactory(simulationInput.getTimestep(), inputData.getVehiclePrototypes(),
            inputData.getConsumption(), routing);

    roadNetwork.setWithCrashExit(simulationInput.isCrashExit());

    simulationRunnable.setTimeStep(simulationInput.getTimestep());

    // TODO better handling of case "duration = INFINITY"
    double duration = simulationInput.isSetDuration() ? simulationInput.getDuration() : -1;

    simulationRunnable.setDuration(duration < 0 ? Double.MAX_VALUE : duration);

    if (simulationInput.isWithSeed()) {
        MyRandom.initializeWithSeed(simulationInput.getSeed());
    }

    defaultTrafficComposition = new TrafficCompositionGenerator(simulationInput.getTrafficComposition(),
            vehicleFactory);

    // For each road in the MovSim XML input data, find the corresponding roadSegment and
    // set its input data accordingly
    // final Map<String, RoadInput> roadInputMap = simulationInput.get.getRoadInput();
    if (loadedRoadNetwork == false && simulationInput.getRoad().size() == 1) {
        defaultTestingRoadMapping(simulationInput.getRoad().get(0));
    } else {
        matchRoadSegmentsAndRoadInput(simulationInput.getRoad());
    }

    trafficLights = new TrafficLights(inputData.getScenario().getTrafficLights(), roadNetwork);

    reset();
}

From source file:org.supercsv.cellprocessor.joda.ParseLocalDateTime.java

License:Apache License

/**
 * {@inheritDoc}/* ww w .jav a  2 s .c  o m*/
 */
@Override
protected LocalDateTime parse(final String string, final DateTimeFormatter formatter) {
    return LocalDateTime.parse(string, formatter);
}

From source file:org.wso2.carbon.apimgt.usage.client.impl.APIUsageStatisticsRestClientImpl.java

License:Open Source License

/**
 * This method gets the app usage data for invoking APIs
 *
 * @param tableName name of the required table in the database
 * @param idList    Id list of applications
 * @return a collection containing the data related to App usage
 * @throws APIMgtUsageQueryServiceClientException if an error occurs while querying the database
 *//*from  w ww.  j a  v a  2 s  .  c om*/
private List<AppUsageDTO> getTopAppUsageData(String tableName, List<String> idList, String fromDate,
        String toDate, int limit) throws APIMgtUsageQueryServiceClientException {
    List<AppUsageDTO> topAppUsageDataList = new ArrayList<AppUsageDTO>();
    try {
        if (!idList.isEmpty()) {
            String startDate = fromDate + ":00";
            String endDate = toDate + ":00";
            String granularity = APIUsageStatisticsClientConstants.HOURS_GRANULARITY;//default granularity

            Map<String, Integer> durationBreakdown = this.getDurationBreakdown(startDate, endDate);
            LocalDateTime currentDate = LocalDateTime.now(DateTimeZone.UTC);
            DateTimeFormatter formatter = DateTimeFormat
                    .forPattern(APIUsageStatisticsClientConstants.TIMESTAMP_PATTERN);
            LocalDateTime fromLocalDateTime = LocalDateTime.parse(startDate, formatter);//GMT time

            if (fromLocalDateTime.isBefore(currentDate.minusYears(1))) {
                granularity = APIUsageStatisticsClientConstants.MONTHS_GRANULARITY;
            } else if ((durationBreakdown.get(APIUsageStatisticsClientConstants.DURATION_MONTHS) > 0)
                    || (durationBreakdown.get(APIUsageStatisticsClientConstants.DURATION_DAYS) > 0)) {
                granularity = APIUsageStatisticsClientConstants.DAYS_GRANULARITY;
            }
            StringBuilder idListQuery = new StringBuilder();
            for (int i = 0; i < idList.size(); i++) {
                if (i > 0) {
                    idListQuery.append(" or ");
                }
                idListQuery.append(APIUsageStatisticsClientConstants.APPLICATION_ID + "==");
                idListQuery.append("'" + idList.get(i) + "'");
            }
            StringBuilder query = new StringBuilder("from " + tableName + " on " + idListQuery.toString()
                    + " within " + getTimestamp(startDate) + "L, " + getTimestamp(endDate) + "L per '"
                    + granularity + "' select " + APIUsageStatisticsClientConstants.APPLICATION_ID + ", "
                    + APIUsageStatisticsClientConstants.USERNAME + ", sum("
                    + APIUsageStatisticsClientConstants.TOTAL_REQUEST_COUNT
                    + ") as net_total_requests group by " + APIUsageStatisticsClientConstants.APPLICATION_ID
                    + ", " + APIUsageStatisticsClientConstants.USERNAME + " order by net_total_requests DESC");
            // limit enforced
            if (limit >= 0) {
                query.append(" limit" + limit);
            }
            query.append(";");
            JSONObject jsonObj = APIUtil.executeQueryOnStreamProcessor(
                    APIUsageStatisticsClientConstants.APIM_ACCESS_SUMMARY_SIDDHI_APP, query.toString());
            String applicationId;
            String username;
            long requestCount;
            AppUsageDTO appUsageDTO;
            if (jsonObj != null) {
                JSONArray jArray = (JSONArray) jsonObj.get(APIUsageStatisticsClientConstants.RECORDS_DELIMITER);
                for (Object record : jArray) {
                    JSONArray recordArray = (JSONArray) record;
                    if (recordArray.size() == 3) {
                        applicationId = (String) recordArray.get(0);
                        username = (String) recordArray.get(1);
                        requestCount = (Long) recordArray.get(2);
                        String appName = subscriberAppsMap.get(applicationId);
                        boolean found = false;
                        for (AppUsageDTO dto : topAppUsageDataList) {
                            if (dto.getAppName().equals(appName)) {
                                dto.addToUserCountArray(username, requestCount);
                                found = true;
                                break;
                            }
                        }
                        if (!found) {
                            appUsageDTO = new AppUsageDTO();
                            appUsageDTO.setAppName(appName);
                            appUsageDTO.addToUserCountArray(username, requestCount);
                            topAppUsageDataList.add(appUsageDTO);
                        }
                    }
                }
            }
        }
    } catch (APIManagementException e) {
        handleException("Error occurred while querying top app usage data from Stream Processor ", e);
    }
    return topAppUsageDataList;
}

From source file:org.wso2.carbon.apimgt.usage.client.impl.APIUsageStatisticsRestClientImpl.java

License:Open Source License

/**
 * This method gets the top user usage data for invoking APIs
 *
 * @param tableName name of the required table in the database
 * @param apiName   API name/*from w  ww  .ja  va 2s  . co  m*/
 * @param version   version of the required API
 * @param fromDate  Start date of the time span
 * @param toDate    End date of time span
 * @return a collection containing the data related to Api usage
 * @throws APIMgtUsageQueryServiceClientException if an error occurs while querying the database
 */
private List<ApiTopUsersDTO> getTopApiUsers(String tableName, String apiName, String tenantDomain,
        String version, String fromDate, String toDate) throws APIMgtUsageQueryServiceClientException {
    List<ApiTopUsersDTO> apiTopUsersDataList = new ArrayList<ApiTopUsersDTO>();
    try {
        StringBuilder topApiUserQuery;
        long totalRequestCount = getTotalRequestCountOfAPIVersion(tableName, apiName, tenantDomain, version,
                fromDate, toDate);

        String granularity = APIUsageStatisticsClientConstants.HOURS_GRANULARITY;//default granularity

        Map<String, Integer> durationBreakdown = this.getDurationBreakdown(fromDate, toDate);

        LocalDateTime currentDate = LocalDateTime.now(DateTimeZone.UTC);
        DateTimeFormatter formatter = DateTimeFormat
                .forPattern(APIUsageStatisticsClientConstants.TIMESTAMP_PATTERN);
        LocalDateTime fromLocalDateTime = LocalDateTime.parse(fromDate, formatter);//GMT time

        if (fromLocalDateTime.isBefore(currentDate.minusYears(1))) {
            granularity = APIUsageStatisticsClientConstants.MONTHS_GRANULARITY;
        } else if ((durationBreakdown.get(APIUsageStatisticsClientConstants.DURATION_MONTHS) > 0)
                || (durationBreakdown.get(APIUsageStatisticsClientConstants.DURATION_DAYS) > 0)) {
            granularity = APIUsageStatisticsClientConstants.DAYS_GRANULARITY;
        }

        topApiUserQuery = new StringBuilder("from " + APIUsageStatisticsClientConstants.API_USER_PER_APP_AGG
                + " on(" + APIUsageStatisticsClientConstants.API_CREATOR_TENANT_DOMAIN + "=='" + tenantDomain
                + "' AND " + APIUsageStatisticsClientConstants.API_NAME + "=='" + apiName);

        if (!APIUsageStatisticsClientConstants.FOR_ALL_API_VERSIONS.equals(version)) {
            topApiUserQuery.append("' AND " + APIUsageStatisticsClientConstants.API_VERSION + "=='" + version);
        }
        topApiUserQuery.append("') within " + getTimestamp(fromDate) + "L, " + getTimestamp(toDate) + "L per '"
                + granularity + "' select " + APIUsageStatisticsClientConstants.USERNAME + ", "
                + APIUsageStatisticsClientConstants.API_CREATOR + ", sum("
                + APIUsageStatisticsClientConstants.TOTAL_REQUEST_COUNT + ") as net_total_requests group by "
                + APIUsageStatisticsClientConstants.USERNAME + ", "
                + APIUsageStatisticsClientConstants.API_CREATOR + " order by net_total_requests DESC;");

        JSONObject jsonObj = APIUtil.executeQueryOnStreamProcessor(
                APIUsageStatisticsClientConstants.APIM_ACCESS_SUMMARY_SIDDHI_APP, topApiUserQuery.toString());

        String username;
        Long requestCount;
        if (jsonObj != null) {
            JSONArray jArray = (JSONArray) jsonObj.get(APIUsageStatisticsClientConstants.RECORDS_DELIMITER);
            for (Object record : jArray) {
                JSONArray recordArray = (JSONArray) record;
                if (recordArray.size() == 3) {
                    String creator = (String) recordArray.get(1);
                    if (creator != null && MultitenantUtils.getTenantDomain(creator).equals(tenantDomain)) {
                        username = (String) recordArray.get(0);
                        requestCount = (Long) recordArray.get(2);
                        ApiTopUsersDTO apiTopUsersDTO = new ApiTopUsersDTO();
                        apiTopUsersDTO.setApiName(apiName);
                        apiTopUsersDTO.setFromDate(fromDate);
                        apiTopUsersDTO.setToDate(toDate);
                        apiTopUsersDTO.setVersion(version);
                        apiTopUsersDTO.setProvider(creator);

                        //remove @carbon.super from super tenant users
                        if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME
                                .equals(MultitenantUtils.getTenantDomain(username))) {
                            username = MultitenantUtils.getTenantAwareUsername(username);
                        }
                        apiTopUsersDTO.setUser(username);
                        apiTopUsersDTO.setRequestCount(requestCount);
                        apiTopUsersDTO.setTotalRequestCount(totalRequestCount);
                        apiTopUsersDataList.add(apiTopUsersDTO);
                    }
                }
            }
        }
    } catch (APIManagementException e) {
        handleException("Error occurred while querying top api users data from Stream Processor ", e);
    }
    return apiTopUsersDataList;
}

From source file:org.wso2.carbon.apimgt.usage.client.impl.APIUsageStatisticsRestClientImpl.java

License:Open Source License

/**
 * This method gets the API faulty invocation data
 *
 * @param tableName name of the required table in the database
 * @param idList    Ids List of applications
 * @return a collection containing the data related to API faulty invocations
 * @throws APIMgtUsageQueryServiceClientException if an error occurs while querying the database
 *//* w  w w.  java2s  . c  o  m*/
private List<FaultCountDTO> getFaultAppUsageData(String tableName, List<String> idList, String fromDate,
        String toDate, int limit) throws APIMgtUsageQueryServiceClientException {
    List<FaultCountDTO> falseAppUsageDataList = new ArrayList<FaultCountDTO>();
    try {
        if (!idList.isEmpty()) {
            String startDate = fromDate + ":00";
            String endDate = toDate + ":00";
            String granularity = APIUsageStatisticsClientConstants.MINUTES_GRANULARITY;//default granularity
            Map<String, Integer> durationBreakdown = this.getDurationBreakdown(startDate, endDate);
            LocalDateTime currentDate = LocalDateTime.now(DateTimeZone.UTC);
            DateTimeFormatter formatter = DateTimeFormat
                    .forPattern(APIUsageStatisticsClientConstants.TIMESTAMP_PATTERN);
            LocalDateTime fromLocalDateTime = LocalDateTime.parse(startDate, formatter);//GMT time

            if (fromLocalDateTime.isBefore(currentDate.minusYears(1))) {
                granularity = APIUsageStatisticsClientConstants.MONTHS_GRANULARITY;
            } else if (durationBreakdown.get(APIUsageStatisticsClientConstants.DURATION_MONTHS) > 0
                    || durationBreakdown.get(APIUsageStatisticsClientConstants.DURATION_WEEKS) > 0) {
                granularity = APIUsageStatisticsClientConstants.DAYS_GRANULARITY;
            } else if (durationBreakdown.get(APIUsageStatisticsClientConstants.DURATION_DAYS) > 0) {
                granularity = APIUsageStatisticsClientConstants.HOURS_GRANULARITY;
            }

            StringBuilder idListQuery = new StringBuilder();
            for (int i = 0; i < idList.size(); i++) {
                if (i > 0) {
                    idListQuery.append(" or ");
                }
                idListQuery.append(APIUsageStatisticsClientConstants.APPLICATION_ID + "==");
                idListQuery.append("'" + idList.get(i) + "'");
            }
            String query = "from " + tableName + " on " + idListQuery.toString() + " within "
                    + getTimestamp(startDate) + "L, " + getTimestamp(endDate) + "L per '" + granularity
                    + "' select " + APIUsageStatisticsClientConstants.APPLICATION_ID + ", "
                    + APIUsageStatisticsClientConstants.API_NAME + ", "
                    + APIUsageStatisticsClientConstants.API_CREATOR + ", sum("
                    + APIUsageStatisticsClientConstants.TOTAL_FAULT_COUNT + ") as total_faults group by "
                    + APIUsageStatisticsClientConstants.APPLICATION_ID + ", "
                    + APIUsageStatisticsClientConstants.API_CREATOR + ", "
                    + APIUsageStatisticsClientConstants.API_NAME + ";";
            JSONObject jsonObj = APIUtil.executeQueryOnStreamProcessor(
                    APIUsageStatisticsClientConstants.APIM_FAULT_SUMMARY_SIDDHI_APP, query);
            String applicationId;
            String apiName;
            String apiCreator;
            long faultCount;
            FaultCountDTO faultCountDTO;
            if (jsonObj != null) {
                JSONArray jArray = (JSONArray) jsonObj.get(APIUsageStatisticsClientConstants.RECORDS_DELIMITER);
                for (Object record : jArray) {
                    JSONArray recordArray = (JSONArray) record;
                    if (recordArray.size() == 4) {
                        applicationId = (String) recordArray.get(0);
                        apiName = (String) recordArray.get(1);
                        apiCreator = (String) recordArray.get(2);
                        apiName = apiName + " (" + apiCreator + ")";
                        faultCount = (Long) recordArray.get(3);
                        String appName = subscriberAppsMap.get(applicationId);
                        boolean found = false;
                        for (FaultCountDTO dto : falseAppUsageDataList) {
                            if (dto.getAppName().equals(appName)) {
                                dto.addToApiFaultCountArray(apiName, faultCount);
                                found = true;
                                break;
                            }
                        }
                        if (!found) {
                            faultCountDTO = new FaultCountDTO();
                            faultCountDTO.setAppName(appName);
                            faultCountDTO.addToApiFaultCountArray(apiName, faultCount);
                            falseAppUsageDataList.add(faultCountDTO);
                        }
                    }
                }
            }
        }
    } catch (APIManagementException e) {
        handleException("Error occurred while querying API faulty invocation data from Stream Processor ", e);
    }
    return falseAppUsageDataList;
}