Example usage for org.joda.time DateTime parse

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

Introduction

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

Prototype

@FromString
public static DateTime parse(String str) 

Source Link

Document

Parses a DateTime from the specified string.

Usage

From source file:com.sheepdog.mashmesh.resources.SendNotificationResource.java

License:Apache License

@POST
@Produces({ MediaType.TEXT_PLAIN })//from w w  w.  j  av  a 2  s  . co  m
public String scheduleNotification(@FormParam("patientEmail") String patientEmail,
        @FormParam("appointmentAddress") String appointmentAddress,
        @FormParam("appointmentTime") String appointmentTimeRfc339) {
    if (patientEmail == null || patientEmail.isEmpty() || appointmentAddress == null
            || appointmentAddress.isEmpty() || appointmentTimeRfc339 == null
            || appointmentTimeRfc339.isEmpty()) {
        // TODO: Actually report errors with bean validation.
        throw new WebApplicationException(400);
    }

    verifyPatientEmail(patientEmail);

    DateTime appointmentTime = DateTime.parse(appointmentTimeRfc339);
    RideRequest request = SendNotificationTask.createRequest(patientEmail, appointmentAddress, appointmentTime);
    SendNotificationTask.scheduleRequest(request);

    return "OK";
}

From source file:com.smict.person.data.DoctorData.java

/**
 * Add doctor's workday depend on month pattern.
 * @author anubissmile//from   www .ja v a2 s .co  m
 * @param DoctorModel docModel
 * @param DoctTimeModel docTimeModel
 * @return int rec | Count of record that get affected.
 */
public int addDoctorWorkdayPattern(DoctorModel docModel, DoctTimeModel docTimeModel) {
    DateUtil dt = new DateUtil();
    int key = 0;
    String[] workMonth;
    List<String> insertVal = new ArrayList<String>();
    DateTime firstOfMonth, endOfMonth, nowDate;
    DateTimeFormatter dayName = DateTimeFormat.forPattern("E");
    DateTimeFormatter fullDateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
    DateTimeFormatter fullDate = DateTimeFormat.forPattern("yyyy-MM-dd");
    String day, fullDay;
    String startDateTime, endDateTime;
    int workMinutes;

    /**
     * Loop month.
     */
    for (String month : docTimeModel.getWork_month()) {
        /**
         * Convert BE. to AD.
         */
        workMonth = month.split("-");
        workMonth[1] = String.valueOf(Integer.parseInt(workMonth[1]) - 543);

        /**
         * Make first date of month.
         */
        nowDate = firstOfMonth = DateTime.parse(workMonth[1] + "-" + workMonth[0] + "-" + "01");
        System.out.println(firstOfMonth);

        /**
         * Find Maximum date of month.   
         */
        endOfMonth = firstOfMonth.dayOfMonth().withMaximumValue();
        System.out.println(endOfMonth);

        /**
         * Loop day
         */
        while (Days.daysBetween(nowDate, endOfMonth).getDays() >= 0) {
            /**
             * Get day name.
             */
            day = dayName.print(nowDate);
            fullDay = fullDate.print(nowDate);
            System.out.print(day.concat(" | "));
            System.out.print(fullDay.concat(" | "));
            System.out.println(nowDate);

            /**
             * Fetch time range by day
             */
            //Mon
            // ('1', '2017-06-01 05:23:24', '2017-06-01 15:23:24', '25', '431', '0', '0000-00-00 00:00:01', '0000-00-00 00:00:01')
            if ((day.equals("Mon") || day.equals("."))
                    && (!docTimeModel.getTime_in_mon().get(key).equals("00:00")
                            || !docTimeModel.getTime_out_mon().get(key).equals("00:00"))) {
                workMinutes = Minutes.minutesBetween(LocalTime.parse(docTimeModel.getTime_in_mon().get(key)),
                        LocalTime.parse(docTimeModel.getTime_out_mon().get(key))).getMinutes();
                startDateTime = fullDate.print(nowDate).toString().concat(" ")
                        .concat(docTimeModel.getTime_in_mon().get(key)).concat(":00");
                endDateTime = fullDate.print(nowDate).toString().concat(" ")
                        .concat(docTimeModel.getTime_out_mon().get(key)).concat(":00");
                insertVal.add(" ('" + docModel.getDoctorID() + "', '" + startDateTime + "', '" + endDateTime
                        + "', '" + workMinutes + "', '" + docModel.getBranch_id()
                        + "', '0', '1', '0000-00-00 00:00:01', '0000-00-00 00:00:01') ");
                nowDate = nowDate.plusDays(1);
                continue;
            }

            //Tue
            if ((day.equals("Tue") || day.equals("."))
                    && (!docTimeModel.getTime_in_tue().get(key).equals("00:00")
                            || !docTimeModel.getTime_out_tue().get(key).equals("00:00"))) {
                workMinutes = Minutes.minutesBetween(LocalTime.parse(docTimeModel.getTime_in_tue().get(key)),
                        LocalTime.parse(docTimeModel.getTime_out_tue().get(key))).getMinutes();
                startDateTime = fullDate.print(nowDate).toString().concat(" ")
                        .concat(docTimeModel.getTime_in_tue().get(key)).concat(":00");
                endDateTime = fullDate.print(nowDate).toString().concat(" ")
                        .concat(docTimeModel.getTime_out_tue().get(key)).concat(":00");
                insertVal.add(" ('" + docModel.getDoctorID() + "', '" + startDateTime + "', '" + endDateTime
                        + "', '" + workMinutes + "', '" + docModel.getBranch_id()
                        + "', '0', '1', '0000-00-00 00:00:01', '0000-00-00 00:00:01') ");
                nowDate = nowDate.plusDays(1);
                continue;
            }

            //Wed
            if ((day.equals("Wed") || day.equals("."))
                    && (!docTimeModel.getTime_in_wed().get(key).equals("00:00")
                            || !docTimeModel.getTime_out_wed().get(key).equals("00:00"))) {
                workMinutes = Minutes.minutesBetween(LocalTime.parse(docTimeModel.getTime_in_wed().get(key)),
                        LocalTime.parse(docTimeModel.getTime_out_wed().get(key))).getMinutes();
                startDateTime = fullDate.print(nowDate).toString().concat(" ")
                        .concat(docTimeModel.getTime_in_wed().get(key)).concat(":00");
                endDateTime = fullDate.print(nowDate).toString().concat(" ")
                        .concat(docTimeModel.getTime_out_wed().get(key)).concat(":00");
                insertVal.add(" ('" + docModel.getDoctorID() + "', '" + startDateTime + "', '" + endDateTime
                        + "', '" + workMinutes + "', '" + docModel.getBranch_id()
                        + "', '0', '1', '0000-00-00 00:00:01', '0000-00-00 00:00:01') ");
                nowDate = nowDate.plusDays(1);
                continue;
            }

            //Thu
            if ((day.equals("Thu") || day.equals("."))
                    && (!docTimeModel.getTime_in_thu().get(key).equals("00:00")
                            || !docTimeModel.getTime_out_thu().get(key).equals("00:00"))) {
                workMinutes = Minutes.minutesBetween(LocalTime.parse(docTimeModel.getTime_in_thu().get(key)),
                        LocalTime.parse(docTimeModel.getTime_out_thu().get(key))).getMinutes();
                startDateTime = fullDate.print(nowDate).toString().concat(" ")
                        .concat(docTimeModel.getTime_in_thu().get(key)).concat(":00");
                endDateTime = fullDate.print(nowDate).toString().concat(" ")
                        .concat(docTimeModel.getTime_out_thu().get(key)).concat(":00");
                insertVal.add(" ('" + docModel.getDoctorID() + "', '" + startDateTime + "', '" + endDateTime
                        + "', '" + workMinutes + "', '" + docModel.getBranch_id()
                        + "', '0', '1', '0000-00-00 00:00:01', '0000-00-00 00:00:01') ");
                nowDate = nowDate.plusDays(1);
                continue;
            }

            //Fri
            if ((day.equals("Fri") || day.equals("."))
                    && (!docTimeModel.getTime_in_fri().get(key).equals("00:00")
                            || !docTimeModel.getTime_out_fri().get(key).equals("00:00"))) {
                workMinutes = Minutes.minutesBetween(LocalTime.parse(docTimeModel.getTime_in_fri().get(key)),
                        LocalTime.parse(docTimeModel.getTime_out_fri().get(key))).getMinutes();
                startDateTime = fullDate.print(nowDate).toString().concat(" ")
                        .concat(docTimeModel.getTime_in_fri().get(key)).concat(":00");
                endDateTime = fullDate.print(nowDate).toString().concat(" ")
                        .concat(docTimeModel.getTime_out_fri().get(key)).concat(":00");
                insertVal.add(" ('" + docModel.getDoctorID() + "', '" + startDateTime + "', '" + endDateTime
                        + "', '" + workMinutes + "', '" + docModel.getBranch_id()
                        + "', '0', '1', '0000-00-00 00:00:01', '0000-00-00 00:00:01') ");
                nowDate = nowDate.plusDays(1);
                continue;
            }

            //Sat
            if ((day.equals("Sat") || day.equals("."))
                    && (!docTimeModel.getTime_in_sat().get(key).equals("00:00")
                            || !docTimeModel.getTime_out_sat().get(key).equals("00:00"))) {
                workMinutes = Minutes.minutesBetween(LocalTime.parse(docTimeModel.getTime_in_sat().get(key)),
                        LocalTime.parse(docTimeModel.getTime_out_sat().get(key))).getMinutes();
                startDateTime = fullDate.print(nowDate).toString().concat(" ")
                        .concat(docTimeModel.getTime_in_sat().get(key)).concat(":00");
                endDateTime = fullDate.print(nowDate).toString().concat(" ")
                        .concat(docTimeModel.getTime_out_sat().get(key)).concat(":00");
                insertVal.add(" ('" + docModel.getDoctorID() + "', '" + startDateTime + "', '" + endDateTime
                        + "', '" + workMinutes + "', '" + docModel.getBranch_id()
                        + "', '0', '1', '0000-00-00 00:00:01', '0000-00-00 00:00:01') ");
                nowDate = nowDate.plusDays(1);
                continue;
            }

            //Sun
            if ((day.equals("Sun") || day.equals("."))
                    && (!docTimeModel.getTime_in_sun().get(key).equals("00:00")
                            || !docTimeModel.getTime_out_sun().get(key).equals("00:00"))) {
                workMinutes = Minutes.minutesBetween(LocalTime.parse(docTimeModel.getTime_in_sun().get(key)),
                        LocalTime.parse(docTimeModel.getTime_out_sun().get(key))).getMinutes();
                startDateTime = fullDate.print(nowDate).toString().concat(" ")
                        .concat(docTimeModel.getTime_in_sun().get(key)).concat(":00");
                endDateTime = fullDate.print(nowDate).toString().concat(" ")
                        .concat(docTimeModel.getTime_out_sun().get(key)).concat(":00");
                insertVal.add(" ('" + docModel.getDoctorID() + "', '" + startDateTime + "', '" + endDateTime
                        + "', '" + workMinutes + "', '" + docModel.getBranch_id()
                        + "', '0', '1', '0000-00-00 00:00:01', '0000-00-00 00:00:01') ");
                nowDate = nowDate.plusDays(1);
                continue;
            }

            /**
             * Plus one day.
             */
            nowDate = nowDate.plusDays(1);
        }

        ++key;
    }

    String SQL = StringUtils.join(insertVal, ", ");
    SQL = "INSERT INTO `doctor_workday` " + "(`doctor_id`, `start_datetime`, " + "`end_datetime`, `work_hour`, "
            + "`branch_id`, `branch_room_id`, " + "`checkin_status`, `checkin_datetime`, `checkout_datetime`) "
            + "VALUES ".concat(SQL);

    agent.connectMySQL();
    agent.begin();
    int rec = agent.exeUpdate(SQL);
    agent.commit();
    agent.disconnectMySQL();

    return rec;
}

From source file:com.solidfire.core.serialization.DateTimeAdapter.java

License:Open Source License

/**
 * Reads a DateTime object.//www  .j  av a 2  s  .  c o m
 *
 * @param reader the JSON reader to read from.
 * @return The DateTime object that was read.
 * @throws IOException if the DateTime object cannot be parsed
 */
@Override
public DateTime read(JsonReader reader) throws IOException {
    return DateTime.parse(reader.nextString());
}

From source file:com.spotify.reaper.resources.RepairScheduleResource.java

License:Apache License

/**
 * Endpoint used to create a repair schedule. Does not allow triggering the run.
 * Repair schedule will create new repair runs based on the schedule.
 *
 * Notice that query parameter "tables" can be a single String, or a
 * comma-separated list of table names. If the "tables" parameter is omitted, and only the
 * keyspace is defined, then created repair runs will target all the tables in the keyspace.
 *
 * @return created repair schedule data as JSON.
 *///w  w w.j  av  a  2s . c  o  m
@POST
public Response addRepairSchedule(@Context UriInfo uriInfo,
        @QueryParam("clusterName") Optional<String> clusterName,
        @QueryParam("keyspace") Optional<String> keyspace,
        @QueryParam("tables") Optional<String> tableNamesParam, @QueryParam("owner") Optional<String> owner,
        @QueryParam("segmentCount") Optional<Integer> segmentCount,
        @QueryParam("repairParallelism") Optional<String> repairParallelism,
        @QueryParam("intensity") Optional<String> intensityStr,
        @QueryParam("scheduleDaysBetween") Optional<Integer> scheduleDaysBetween,
        @QueryParam("scheduleTriggerTime") Optional<String> scheduleTriggerTime) {
    LOG.info(
            "add repair schedule called with: clusterName = {}, keyspace = {}, tables = {}, "
                    + "owner = {}, segmentCount = {}, repairParallelism = {}, "
                    + "intensity = {}, scheduleDaysBetween = {}, scheduleTriggerTime = {}",
            clusterName, keyspace, tableNamesParam, owner, segmentCount, repairParallelism, intensityStr,
            scheduleDaysBetween, scheduleTriggerTime);
    try {
        Response possibleFailResponse = RepairRunResource.checkRequestForAddRepair(context, clusterName,
                keyspace, owner, segmentCount, repairParallelism, intensityStr);
        if (null != possibleFailResponse) {
            return possibleFailResponse;
        }

        DateTime nextActivation;
        if (scheduleTriggerTime.isPresent()) {
            try {
                nextActivation = DateTime.parse(scheduleTriggerTime.get());
            } catch (IllegalArgumentException ex) {
                LOG.info("cannot parse data string: " + scheduleTriggerTime.get());
                return Response.status(Response.Status.BAD_REQUEST).entity("invalid schedule_trigger_time")
                        .build();
            }
            LOG.info("first schedule activation will be: " + CommonTools.dateTimeToISO8601(nextActivation));
        } else {
            nextActivation = DateTime.now().plusDays(1).withTimeAtStartOfDay();
            LOG.info("no schedule_trigger_time given, so setting first scheduling next night: "
                    + CommonTools.dateTimeToISO8601(nextActivation));
        }
        if (nextActivation.isBeforeNow()) {
            return Response.status(Response.Status.BAD_REQUEST)
                    .entity("given schedule_trigger_time is in the past: "
                            + CommonTools.dateTimeToISO8601(nextActivation))
                    .build();
        }

        Double intensity;
        if (intensityStr.isPresent()) {
            intensity = Double.parseDouble(intensityStr.get());
        } else {
            intensity = context.config.getRepairIntensity();
            LOG.debug("no intensity given, so using default value: " + intensity);
        }

        int segments = context.config.getSegmentCount();
        if (segmentCount.isPresent()) {
            LOG.debug("using given segment count {} instead of configured value {}", segmentCount.get(),
                    context.config.getSegmentCount());
            segments = segmentCount.get();
        }

        int daysBetween = context.config.getScheduleDaysBetween();
        if (scheduleDaysBetween.isPresent()) {
            LOG.debug("using given schedule days between {} instead of configured value {}",
                    scheduleDaysBetween.get(), context.config.getScheduleDaysBetween());
            daysBetween = scheduleDaysBetween.get();
        }

        Cluster cluster = context.storage.getCluster(Cluster.toSymbolicName(clusterName.get())).get();
        Set<String> tableNames;
        try {
            tableNames = CommonTools.getTableNamesBasedOnParam(context, cluster, keyspace.get(),
                    tableNamesParam);
        } catch (IllegalArgumentException ex) {
            return Response.status(Response.Status.NOT_FOUND).entity(ex.getMessage()).build();
        }

        RepairUnit theRepairUnit = CommonTools.getNewOrExistingRepairUnit(context, cluster, keyspace.get(),
                tableNames);

        RepairParallelism parallelism = context.config.getRepairParallelism();
        if (repairParallelism.isPresent()) {
            LOG.debug("using given repair parallelism {} instead of configured value {}",
                    repairParallelism.get(), context.config.getRepairParallelism());
            parallelism = RepairParallelism.valueOf(repairParallelism.get().toUpperCase());
        }

        RepairSchedule newRepairSchedule = CommonTools.storeNewRepairSchedule(context, cluster, theRepairUnit,
                daysBetween, nextActivation, owner.get(), segments, parallelism, intensity);

        return Response.created(buildRepairScheduleURI(uriInfo, newRepairSchedule))
                .entity(new RepairScheduleStatus(newRepairSchedule, theRepairUnit)).build();

    } catch (ReaperException e) {
        LOG.error(e.getMessage());
        e.printStackTrace();
        return Response.status(500).entity(e.getMessage()).build();
    }
}

From source file:com.talvish.tales.parts.translators.StringToDateTimeTranslator.java

License:Apache License

@Override
public Object translate(Object anObject) {
    Object returnValue;/*from   ww w .ja  v a 2  s  .  c  o m*/
    if (anObject == null) {
        returnValue = this.nullValue;
    } else {
        try {
            String stringValue = (String) anObject;

            if (this.trim) {
                stringValue = stringValue.trim();
            }
            if (stringValue.equals("")) {
                returnValue = this.emptyValue;
            } else {
                returnValue = DateTime.parse(stringValue);
            }
        } catch (IllegalArgumentException e) {
            throw new TranslationException(String.format("Unable to translate '%s' into a datetime.", anObject),
                    e);
        } catch (ClassCastException e) {
            throw new TranslationException(e);
        }
    }
    return returnValue;
}

From source file:com.thinkbiganalytics.metadata.modeshape.template.JcrChangeComment.java

License:Apache License

@Override
public DateTime getCreateDateTime() {
    if (JcrPropertyUtil.hasProperty(getNode(), CREATE_DATE_TIME))
        return DateTime.parse(JcrPropertyUtil.getProperty(getNode(), CREATE_DATE_TIME));

    return JcrPropertyUtil.getProperty(getNode(), CREATED_TIME);
}

From source file:com.tomtom.speedtools.time.UTCTime.java

License:Apache License

/**
 * Parses a {@code DateTime} from the specified string.
 *
 * This uses {@link org.joda.time.format.ISODateTimeFormat#dateTimeParser()}.
 *
 * @param str the string to parse, not null.
 * @return UTC time./*  w  w w  . ja  v a 2 s  .  c  o m*/
 */
@Nonnull
public static DateTime parse(@Nonnull final String str) {
    assert str != null;
    return DateTime.parse(str).withZone(DateTimeZone.UTC);
}

From source file:com.tremolosecurity.provisioning.service.GenerateReport.java

License:Apache License

private void generateReportData(HttpServletRequest req, HttpServletResponse resp, Gson gson,
        ReportType reportToRun, Connection db) throws SQLException, IOException {
    PreparedStatement ps;/*  w  ww .j  a v  a2  s  .  c om*/
    ResultSet rs;
    if (logger.isDebugEnabled()) {
        logger.debug("Report SQL : '" + reportToRun.getSql() + "'");
    }
    ps = db.prepareStatement(reportToRun.getSql());
    int i = 1;
    for (String paramType : reportToRun.getParamater()) {
        switch (paramType) {
        case "currentUser":
            if (logger.isDebugEnabled()) {
                logger.debug("Current User : '" + req.getParameter("currentUser") + "'");
            }
            ps.setString(i, req.getParameter("currentUser"));
            break;
        case "userKey":
            if (logger.isDebugEnabled()) {
                logger.debug("User Key : '" + req.getParameter("userKey") + "'");
            }
            ps.setString(i, req.getParameter("userKey"));
            break;
        case "beginDate":
            String beginDate = req.getParameter("beginDate");
            if (logger.isDebugEnabled()) {
                logger.debug("Begin Date : '" + beginDate + "'");
            }
            Date d = new Date(DateTime.parse(beginDate).getMillis());
            ps.setDate(i, d);
            break;

        case "endDate":

            String endDate = req.getParameter("endDate");
            if (logger.isDebugEnabled()) {
                logger.debug("End Date : '" + endDate + "'");
            }
            Date de = new Date(DateTime.parse(endDate).getMillis());
            ps.setDate(i, de);
            break;
        }

        i++;
    }

    rs = ps.executeQuery();

    String groupingVal = null;
    ReportResults res = new ReportResults();
    res.setName(reportToRun.getName());
    res.setDescription(reportToRun.getDescription());
    res.setDataFields(reportToRun.getDataFields());
    res.setHeaderFields(reportToRun.getHeaderFields());
    res.setGrouping(new ArrayList<ReportGrouping>());

    ReportGrouping grouping = null;

    if (!reportToRun.isGroupings()) {
        grouping = new ReportGrouping();
        grouping.setData(new ArrayList<Map<String, String>>());
        grouping.setHeader(new HashMap<String, String>());
        res.getGrouping().add(grouping);
    }

    logger.debug("Running report");

    while (rs.next()) {
        if (logger.isDebugEnabled()) {
            logger.debug("New row");
        }

        HashMap<String, String> row = new HashMap<String, String>();

        for (String dataField : reportToRun.getDataFields()) {
            if (logger.isDebugEnabled()) {
                logger.debug("Field - " + dataField + "='" + rs.getString(dataField) + "'");
            }
            row.put(dataField, rs.getString(dataField));
        }

        if (reportToRun.isGroupings()) {
            String rowID = rs.getString(reportToRun.getGroupBy());
            if (logger.isDebugEnabled()) {
                logger.debug("Grouping Val : '" + groupingVal + "'");
                logger.debug("Group By : '" + reportToRun.getGroupBy() + "'");
                logger.debug("Value of Group By in row : '" + rowID + "'");

            }

            if (groupingVal == null || !groupingVal.equals(rowID)) {
                grouping = new ReportGrouping();
                grouping.setData(new ArrayList<Map<String, String>>());
                grouping.setHeader(new HashMap<String, String>());
                res.getGrouping().add(grouping);

                for (String headerField : reportToRun.getHeaderFields()) {
                    grouping.getHeader().put(headerField, rs.getString(headerField));
                }

                groupingVal = rowID;
            }
        }

        grouping.getData().add(row);
    }

    ProvisioningResult pres = new ProvisioningResult();
    pres.setSuccess(true);
    pres.setReportResults(res);

    String json = gson.toJson(pres);

    if (logger.isDebugEnabled()) {
        logger.debug("JSON : " + json);
    }

    resp.getOutputStream().print(json);
}

From source file:com.vmware.photon.controller.housekeeper.dcp.ImageDeleteService.java

License:Open Source License

/**
 * Retrieve the created time for the image.
 *
 * @param current/*w w w.  j  a  va 2  s .c o m*/
 */
private void getImageCreatedTime(final State current) {
    AsyncMethodCallback callback = new AsyncMethodCallback() {
        @Override
        public void onComplete(Object o) {
            try {
                ImageInfoResponse r = ((Host.AsyncClient.get_image_info_call) o).getResult();
                ServiceUtils.logInfo(ImageDeleteService.this, "DeleteImageResponse %s", r);

                switch (r.getResult()) {
                case OK:
                    State patch = buildPatch(current.taskInfo.stage, null);
                    patch.imageCreatedTime = DateTime.parse(r.getImage_info().getCreated_time()).getMillis();
                    sendSelfPatch(patch);
                    break;
                case IMAGE_NOT_FOUND:
                    sendStageProgressPatch(current, TaskState.TaskStage.FINISHED);
                    break;
                case DATASTORE_NOT_FOUND:
                    throw new DatastoreNotFoundException(r.getError());
                case SYSTEM_ERROR:
                    throw new SystemErrorException(r.getError());
                case INVALID_REF_COUNT_FILE:
                    throw new InvalidRefCountException(r.getError());
                default:
                    throw new UnknownError(String.format("Unknown result code %s", r.getResult()));
                }
            } catch (Exception e) {
                onError(e);
            }
        }

        @Override
        public void onError(Exception e) {
            failTask(e);
        }
    };

    try {
        getHostClient(current).getImageInfo(current.image, current.dataStore, callback);
    } catch (IOException | RpcException e) {
        failTask(e);
    }
}

From source file:com.widowcrawler.exo.parse.Parser.java

License:Apache License

public Sitemap parse(InputStream inputStream) throws XMLStreamException, SitemapParseException {

    final XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(inputStream, "utf-8");

    final Sitemap retval = new Sitemap(new HashSet<>());

    final Set<SitemapURL> sitemapURLs = new HashSet<>();
    SitemapURL.Builder urlBuilder = null;
    String urlContent;//from  ww  w.  j a v a2s .  c o  m

    reader.getEventType();

    while (reader.hasNext()) {
        switch (state) {
        case START:
            reader.nextTag();

            if (StringUtils.equalsIgnoreCase(reader.getLocalName(), URLSET_TAG_NAME)) {
                state = State.URLSET;
            } else if (StringUtils.equalsIgnoreCase(reader.getLocalName(), SITEMAPINDEX_TAG_NAME)) {
                state = State.SITEMAPINDEX;
            } else {
                String message = "Invalid root element. Must be either urlset or sitemapindex";
                logger.error(message);
                throw new SitemapParseException(message);
            }

            break;

        case END:
            // consume all end tags
            if (reader.getEventType() != XMLStreamConstants.END_ELEMENT) {
                String message = decorate("There should be only one root element in each sitemap.xml",
                        reader.getLocation());
                logger.error(message);
                throw new SitemapParseException(message);
            }

            reader.next();
            break;

        /////////////////////
        // URLSET Hierarchy
        /////////////////////
        case URLSET:
            // If we're done with the URLs, we're done overall
            if (reader.nextTag() == XMLStreamConstants.END_ELEMENT) {
                state = State.END;
                break;
            }

            // Check that we're entering into a <url> element
            if (!StringUtils.equalsIgnoreCase(reader.getLocalName(), URL_TAG_NAME)) {
                String message = "A <urlset> element can only contain <url> elements. Found: "
                        + reader.getLocalName();
                logger.error(message);
                throw new SitemapParseException(message);
            }

            urlBuilder = new SitemapURL.Builder();
            state = State.URL;
            break;

        case URL:
            reader.nextTag();

            if (reader.getEventType() == XMLStreamConstants.START_ELEMENT) {
                //logger.info("reader.getLocalName(): " + reader.getLocalName());
                switch (StringUtils.lowerCase(reader.getLocalName())) {
                case LOC_TAG_NAME:
                    state = State.URL_PROP_LOC;
                    break;
                case LASTMOD_TAG_NAME:
                    state = State.URL_PROP_LASTMOD;
                    break;
                case CHANGEFREQ_TAG_NAME:
                    state = State.URL_PROP_CHANGEFREQ;
                    break;
                case PRIORITY_TAG_NAME:
                    state = State.URL_PROP_PRIORITY;
                    break;
                case MOBILE_TAG_NAME:
                    state = State.URL_PROP_MOBILE;
                    break;
                default:
                    String message = "Unexpected tag in url: " + reader.getLocalName();
                    logger.error(message);
                    throw new SitemapParseException(message);
                }
            } else if (reader.getEventType() == XMLStreamConstants.END_ELEMENT) {
                // we're done collecting the data for this URL
                assert urlBuilder != null;
                sitemapURLs.add(urlBuilder.build());
                urlBuilder = new SitemapURL.Builder();
                state = State.URLSET;
            }
            break;

        case URL_PROP_LOC:
            urlContent = reader.getElementText();

            try {
                assert urlBuilder != null;
                urlBuilder.withLocation(new URL(StringUtils.trimToNull(urlContent)));

            } catch (MalformedURLException ex) {
                String message = String.format("Malformed URL found: %s", urlContent);
                logger.error(message);
                throw new SitemapParseException(message);
            }
            state = State.URL;
            break;

        case URL_PROP_LASTMOD:
            assert urlBuilder != null;
            urlBuilder.withLastModified(DateTime.parse(reader.getElementText()));
            state = State.URL;
            break;

        case URL_PROP_CHANGEFREQ:
            assert urlBuilder != null;
            urlBuilder.withChangeFrequency(ChangeFreq.valueOf(StringUtils.upperCase(reader.getElementText())));
            state = State.URL;
            break;

        case URL_PROP_PRIORITY:
            assert urlBuilder != null;
            urlBuilder.withPriority(Double.valueOf(reader.getElementText()));
            state = State.URL;
            break;

        case URL_PROP_MOBILE:
            assert urlBuilder != null;
            urlBuilder.withIsMobileContent(true);
            // consume until "end tag" of self-closing tag
            // Also works if someone puts content in
            reader.getElementText();
            state = State.URL;
            break;

        ///////////////////////////
        // SITEMAPINDEX Hierarchy
        ///////////////////////////
        case SITEMAPINDEX:
            // If we're done with all the Sitemaps, we're done overall
            if (reader.nextTag() == XMLStreamConstants.END_ELEMENT) {
                state = State.END;
                break;
            }

            state = State.SITEMAP;
            break;

        case SITEMAP:
            if (!StringUtils.equalsIgnoreCase(reader.getLocalName(), SITEMAP_TAG_NAME)) {
                throw new SitemapParseException("A <sitemapindex> element can only contain <sitemap> elements");
            }

            reader.nextTag();

            if (reader.getEventType() == XMLStreamConstants.START_ELEMENT) {
                switch (StringUtils.lowerCase(reader.getLocalName())) {
                case LOC_TAG_NAME:
                    state = State.URL_PROP_LOC;
                    break;
                case LASTMOD_TAG_NAME:
                    state = State.URL_PROP_LASTMOD;
                    break;
                default:
                    throw new SitemapParseException("Unexpected tag in sitemap: " + reader.getLocalName());
                }
            } else if (reader.getEventType() == XMLStreamConstants.END_ELEMENT) {
                // we're done collecting the data for this URL
                assert urlBuilder != null;
                sitemapURLs.add(urlBuilder.build());
                urlBuilder = new SitemapURL.Builder();
                state = State.URLSET;
            }

        case SITEMAP_PROP_LOC:
            urlContent = reader.getElementText();

            try {
                URL sitemapURL = new URL(StringUtils.trimToNull(urlContent));

                Sitemap temp = Retry.retry(() -> {
                    try {
                        return Exo.parse(sitemapURL.toString());
                    } catch (Exception ex) {
                        throw new RuntimeException(ex);
                    }
                });

                retval.merge(temp);

            } catch (MalformedURLException ex) {
                String message = String.format("Malformed URL found: %s", urlContent);
                logger.error(message);
                throw new SitemapParseException(message);

            } catch (InterruptedException e) {
                logger.warn("Thread interrupted while (re)trying");
                Thread.currentThread().interrupt();

            } catch (RetryFailedException e) {
                String message = String.format("Failed to retrieve sitemap of sitemap index at %s", urlContent);
                logger.error(message);
                throw new SitemapParseException(message);
            }

            state = State.URL;
            break;

        case SITEMAP_PROP_LASTMOD:
            // Do nothing with this data for now
            reader.getElementText();
            break;
        }

        //System.out.println(state);
    }

    return retval.merge(new Sitemap(sitemapURLs));
}