Example usage for java.text DateFormat parse

List of usage examples for java.text DateFormat parse

Introduction

In this page you can find the example usage for java.text DateFormat parse.

Prototype

public Date parse(String source) throws ParseException 

Source Link

Document

Parses text from the beginning of the given string to produce a date.

Usage

From source file:com.aurel.track.exchange.msProject.exchange.MsProjectExchangeBL.java

/**
 * Parse the date according to dateFormat
 *//*from   w  w  w .  j av a2  s . co  m*/
public static Date parseDateTime(String dateStr) {
    DateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    if (dateStr != null) {
        try {
            return dateTimeFormat.parse(dateStr);
        } catch (Exception e) {
            LOGGER.debug(e.getMessage());
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
    }
    return null;
}

From source file:io.seldon.importer.articles.ItemAttributesImporter.java

public static Map<String, String> getAttributes(String url, String existingCategory) {
    ItemProcessResult itemProcessResult = new ItemProcessResult();
    itemProcessResult.client_item_id = url;
    itemProcessResult.extraction_status = "EXTRACTION_FAILED";

    logger.info("Trying to get attributes for " + url);
    Map<String, String> attributes = null;
    String title = "";
    String category = "";
    String subCategory = "";
    String img_url = "";
    String description = "";
    String tags = "";
    String leadtext = "";
    String link = "";
    String publishDate = "";
    String domain = "";
    try {//from  www .ja  va  2  s. c o m
        long now = System.currentTimeMillis();
        long timeSinceLastRequest = now - lastUrlFetchTime;
        if (timeSinceLastRequest < minFetchGapMsecs) {
            long timeToSleep = minFetchGapMsecs - timeSinceLastRequest;
            logger.info(
                    "Sleeping " + timeToSleep + "msecs as time since last fetch is " + timeSinceLastRequest);
            Thread.sleep(timeToSleep);
        }
        Document articleDoc = Jsoup.connect(url).userAgent("SeldonBot/1.0").timeout(httpGetTimeout).get();
        lastUrlFetchTime = System.currentTimeMillis();
        //get IMAGE URL
        if (StringUtils.isNotBlank(imageCssSelector)) {
            Element imageElement = articleDoc.select(imageCssSelector).first();
            if (imageElement != null && imageElement.attr("content") != null) {
                img_url = imageElement.attr("content");
            }
            if (imageElement != null && StringUtils.isBlank(img_url)) {
                img_url = imageElement.attr("src");
            }
            if (imageElement != null && StringUtils.isBlank(img_url)) {
                img_url = imageElement.attr("href");
            }

        }

        if (StringUtils.isBlank(img_url) && StringUtils.isNotBlank(defImageUrl)) {
            logger.info("Setting image to default: " + defImageUrl);
            img_url = defImageUrl;
        }
        img_url = StringUtils.strip(img_url);

        //get TITLE
        if (StringUtils.isNotBlank(titleCssSelector)) {
            Element titleElement = articleDoc.select(titleCssSelector).first();
            if ((titleElement != null) && (titleElement.attr("content") != null)) {
                title = titleElement.attr("content");
            }

            // if still blank get from text instead
            if (StringUtils.isBlank(title) && (titleElement != null)) {
                title = titleElement.text();
            }
        }

        //get LEAD TEXT
        if (StringUtils.isNotBlank(leadTextCssSelector)) {
            Element leadElement = articleDoc.select(leadTextCssSelector).first();
            if (leadElement != null && leadElement.attr("content") != null) {
                leadtext = leadElement.attr("content");
            }
        }

        //get publish date
        if (StringUtils.isNotBlank(publishDateCssSelector)) {
            //2013-01-21T10:40:55Z
            Element pubElement = articleDoc.select(publishDateCssSelector).first();
            if (pubElement != null && pubElement.attr("content") != null) {
                String pubtext = pubElement.attr("content");
                SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH);
                Date result = null;
                try {
                    result = df.parse(pubtext);
                } catch (ParseException e) {
                    logger.info("Failed to parse date withUTC format " + pubtext);
                }
                //try a simpler format
                df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
                try {
                    result = df.parse(pubtext);
                } catch (ParseException e) {
                    logger.info("Failed to parse date " + pubtext);
                }

                if (result != null)
                    publishDate = dateFormatter.format(result);
                else
                    logger.error("Failed to parse date " + pubtext);
            }
        }

        //get Link
        if (StringUtils.isNotBlank(linkCssSelector)) {
            Element linkElement = articleDoc.select(linkCssSelector).first();
            if (linkElement != null && linkElement.attr("content") != null) {
                link = linkElement.attr("content");
            }
        }

        //get CONTENT
        if (StringUtils.isNotBlank(textCssSelector)) {
            Element descriptionElement = articleDoc.select(textCssSelector).first();
            if (descriptionElement != null)
                description = Jsoup.parse(descriptionElement.html()).text();
        }

        //get TAGS
        Set<String> tagSet = AttributesImporterUtils.getTags(articleDoc, tagsCssSelector, title);

        if (tagSet.size() > 0)
            tags = CollectionTools.join(tagSet, ",");

        //get CATEGORY - client specific
        if (StringUtils.isNotBlank(categoryCssSelector)) {
            Element categoryElement = articleDoc.select(categoryCssSelector).first();
            if (categoryElement != null && categoryElement.attr("content") != null) {
                category = categoryElement.attr("content");
                if (StringUtils.isNotBlank(category))
                    category = category.toUpperCase();
            }
        } else if (StringUtils.isNotBlank(categoryClassPrefix)) {
            String className = "io.seldon.importer.articles.category." + categoryClassPrefix
                    + "CategoryExtractor";
            Class<?> clazz = Class.forName(className);
            Constructor<?> ctor = clazz.getConstructor();
            CategoryExtractor extractor = (CategoryExtractor) ctor.newInstance();
            category = extractor.getCategory(url, articleDoc);
        }

        //get Sub CATEGORY - client specific
        if (StringUtils.isNotBlank(subCategoryCssSelector)) {
            Element subCategoryElement = articleDoc.select(subCategoryCssSelector).first();
            if (subCategoryElement != null && subCategoryElement.attr("content") != null) {
                subCategory = subCategoryElement.attr("content");
                if (StringUtils.isNotBlank(subCategory))
                    subCategory = category.toUpperCase();
            }
        } else if (StringUtils.isNotBlank(subCategoryClassPrefix)) {
            String className = "io.seldon.importer.articles.category." + subCategoryClassPrefix
                    + "SubCategoryExtractor";
            Class<?> clazz = Class.forName(className);
            Constructor<?> ctor = clazz.getConstructor();
            CategoryExtractor extractor = (CategoryExtractor) ctor.newInstance();
            subCategory = extractor.getCategory(url, articleDoc);
        }

        // Get domain
        if (domainIsNeeded) {
            domain = getDomain(url);
        }

        if ((StringUtils.isNotBlank(title) && (imageNotNeeded || StringUtils.isNotBlank(img_url))
                && (categoryNotNeeded || StringUtils.isNotBlank(category))
                && (!domainIsNeeded || StringUtils.isNotBlank(domain)))) {
            attributes = new HashMap<String, String>();
            attributes.put(TITLE, title);
            if (StringUtils.isNotBlank(category))
                attributes.put(CATEGORY, category);
            if (StringUtils.isNotBlank(subCategory))
                attributes.put(SUBCATEGORY, subCategory);
            if (StringUtils.isNotBlank(link))
                attributes.put(LINK, link);
            if (StringUtils.isNotBlank(leadtext))
                attributes.put(LEAD_TEXT, leadtext);
            if (StringUtils.isNotBlank(img_url))
                attributes.put(IMG_URL, img_url);
            if (StringUtils.isNotBlank(tags))
                attributes.put(TAGS, tags);
            attributes.put(CONTENT_TYPE, VERIFIED_CONTENT_TYPE);
            if (StringUtils.isNotBlank(description))
                attributes.put(DESCRIPTION, description);
            if (StringUtils.isNotBlank(publishDate))
                attributes.put(PUBLISH_DATE, publishDate);
            if (StringUtils.isNotBlank(domain))
                attributes.put(DOMAIN, domain);
            System.out.println("Item: " + url + "; Category: " + category + " SubCategory: " + subCategory);
            itemProcessResult.extraction_status = "EXTRACTION_SUCCEEDED";
        } else {
            logger.warn("Failed to get needed attributes for article " + url);
            logger.warn("[title=" + title + ", img_url=" + img_url + ", category=" + category + ", domain="
                    + domain + "]");
        }

        { // check for failures for the log result
            if (StringUtils.isBlank(title)) {
                itemProcessResult.attrib_failure_list = itemProcessResult.attrib_failure_list
                        + ((StringUtils.isBlank(itemProcessResult.attrib_failure_list)) ? "" : ",") + "title";
            }
            if (!imageNotNeeded && StringUtils.isBlank(img_url)) {
                itemProcessResult.attrib_failure_list = itemProcessResult.attrib_failure_list
                        + ((StringUtils.isBlank(itemProcessResult.attrib_failure_list)) ? "" : ",") + "img_url";
            }
            if (!categoryNotNeeded && StringUtils.isBlank(category)) {
                itemProcessResult.attrib_failure_list = itemProcessResult.attrib_failure_list
                        + ((StringUtils.isBlank(itemProcessResult.attrib_failure_list)) ? "" : ",")
                        + "category";
            }
        }
    } catch (Exception e) {
        logger.error("Article: " + url + ". Attributes import FAILED", e);
        itemProcessResult.error = e.toString();
    }

    AttributesImporterUtils.logResult(logger, itemProcessResult);

    return attributes;
}

From source file:com.teinproductions.tein.papyrosprogress.JSONUtils.java

public static Milestone getMilestone(JSONObject jObject) throws JSONException, ParseException {
    // Define variables
    String title = null;/*from w w w . j  av a 2s. c  o  m*/
    String state = null;
    String githubURL = null;
    long createdAt = -1, updatedAt = -1, dueOn = -1, closedAt = -1;
    int openIssues = 0, closedIssues = 0;

    @SuppressLint("SimpleDateFormat")
    DateFormat format = new SimpleDateFormat(MileStoneViewHolder.JSON_DATE_FORMAT);

    // Extract data from json
    try {
        title = jObject.getString(MILESTONE_TITLE);
    } catch (JSONException ignored) {
        /*ignore*/ }
    try {
        openIssues = jObject.getInt(OPEN_ISSUES);
    } catch (JSONException ignored) {
        /*ignore*/ }
    try {
        closedIssues = jObject.getInt(CLOSED_ISSUES);
    } catch (JSONException ignored) {
        /*ignore*/ }
    try {
        state = jObject.getString(STATE);
    } catch (JSONException ignored) {
        /*ignore*/ }
    if (state == null)
        state = "null";
    try {
        if (!jObject.isNull(CREATED_AT)) {
            createdAt = format.parse(jObject.getString(CREATED_AT)).getTime();
        }
    } catch (JSONException | ParseException ignored) {
        /*ignore*/ }
    try {
        if (!jObject.isNull(UPDATED_AT)) {
            updatedAt = format.parse(jObject.getString(UPDATED_AT)).getTime();
        }
    } catch (JSONException | ParseException ignored) {
        /*ignore*/ }
    try {
        if (!jObject.isNull(DUE_ON)) {
            dueOn = format.parse(jObject.getString(DUE_ON)).getTime();
        }
    } catch (JSONException | ParseException ignored) {
        /*ignore*/ }
    try {
        if (!jObject.isNull(CLOSED_AT)) {
            closedAt = format.parse(jObject.getString(CLOSED_AT)).getTime();
        }
    } catch (JSONException | ParseException ignored) {
        /*ignore*/ }
    try {
        if (!jObject.isNull(GITHUB_URL)) {
            githubURL = jObject.getString(GITHUB_URL);
        }
    } catch (JSONException ignored) {
        /*ignore*/ }

    // Construct Milestone object
    return new Milestone(title, openIssues, closedIssues, state, createdAt, updatedAt, dueOn, closedAt,
            githubURL);
}

From source file:com.sammyun.util.DateUtil.java

public static String obtainMonth(String dateStr, int m) {
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    String str = "";
    try {//w  w  w  .ja v a2 s . c om
        Date d1 = df.parse(dateStr);
        Calendar g = Calendar.getInstance();
        g.setTime(d1);
        g.add(Calendar.MONTH, m);
        Date d2 = g.getTime();
        str = df.format(d2);
        str = str.replace("-", "");
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return str;
}

From source file:Main.java

private int timeInMillis(String time, DateFormat format) {
    try {//from ww w.  j a va2s . c om
        Date date = format.parse(time);
        return (int) date.getTime();
    } catch (ParseException e) {
        if (format != secondaryFormat) {
            return timeInMillis(time, secondaryFormat);
        } else {
            System.out.println(e);
            return -1;
        }
    }
}

From source file:it.eng.spagobi.commons.validation.SpagoBIValidationImpl.java

public static EMFValidationError validateField(String fieldName, String fieldLabel, String value,
        String validatorName, String arg0, String arg1, String arg2) throws Exception {

    List params = null;/*from  w ww  .  j av a  2  s.  co  m*/

    if (validatorName.equalsIgnoreCase("MANDATORY")) {
        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                "Apply the MANDATORY VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
        if (GenericValidator.isBlankOrNull(value)) {
            params = new ArrayList();
            params.add(fieldLabel);
            return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_MANDATORY, params);

        }

    } else if (validatorName.equalsIgnoreCase("URL")) {
        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                "Apply the URL VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
        UrlValidator urlValidator = new SpagoURLValidator();
        if (!GenericValidator.isBlankOrNull(value) && !urlValidator.isValid(value)) {
            params = new ArrayList();
            params.add(fieldLabel);
            return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_URL, params);

        }
    } else if (validatorName.equalsIgnoreCase("LETTERSTRING")) {
        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                "Apply the LETTERSTRING VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
        if (!GenericValidator.isBlankOrNull(value)
                && !GenericValidator.matchRegexp(value, LETTER_STRING_REGEXP)) {
            params = new ArrayList();
            params.add(fieldLabel);
            return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_LETTERSTRING, params);

        }
    } else if (validatorName.equalsIgnoreCase("ALFANUMERIC")) {
        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                "Apply the ALFANUMERIC VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
        if (!GenericValidator.isBlankOrNull(value)
                && !GenericValidator.matchRegexp(value, ALPHANUMERIC_STRING_REGEXP)) {

            params = new ArrayList();
            params.add(fieldLabel);
            return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_ALFANUMERIC, params);

        }
    } else if (validatorName.equalsIgnoreCase("NUMERIC")) {
        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                "Apply the NUMERIC VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
        if (!GenericValidator.isBlankOrNull(value) && (!(GenericValidator.isInt(value)
                || GenericValidator.isFloat(value) || GenericValidator.isDouble(value)
                || GenericValidator.isShort(value) || GenericValidator.isLong(value)))) {

            // The string is not a integer, not a float, not double, not short, not long
            // so is not a number

            params = new ArrayList();
            params.add(fieldLabel);
            return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_NUMERIC, params);

        }

    } else if (validatorName.equalsIgnoreCase("EMAIL")) {
        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                "Apply the EMAIL VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
        if (!GenericValidator.isBlankOrNull(value) && !GenericValidator.isEmail(value)) {

            // Generate errors
            params = new ArrayList();
            params.add(fieldLabel);
            return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_EMAIL, params);

        }
    } else if (validatorName.equalsIgnoreCase("BOOLEAN")) {
        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                "Apply the MANDATORY VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
        if (!GenericValidator.isBlankOrNull(value) && !value.equalsIgnoreCase("true")
                && !value.equalsIgnoreCase("false")) {
            params = new ArrayList();
            params.add(fieldLabel);
            return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_BOOLEAN, params);

        }

    } else if (validatorName.equalsIgnoreCase("FISCALCODE")) {
        SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                "Apply the FISCALCODE VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
        if (!GenericValidator.isBlankOrNull(value)
                && !GenericValidator.matchRegexp(value, FISCAL_CODE_REGEXP)) {

            //             Generate errors
            params = new ArrayList();
            params.add(fieldLabel);
            return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_FISCALCODE, params);

        }
    } else if (validatorName.equalsIgnoreCase("DECIMALS")) {
        if (!GenericValidator.isBlankOrNull(value)) {
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "Apply the DECIMALS VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
            int maxNumberOfDecimalDigit = Integer.valueOf(arg0).intValue();
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "Max Numbers of decimals is [" + maxNumberOfDecimalDigit + "]");
            String decimalSeparator = arg1;

            if (GenericValidator.isBlankOrNull(decimalSeparator)) {
                decimalSeparator = ".";
            }

            int pos = value.indexOf(decimalSeparator);
            String decimalCharacters = "";
            if (pos != -1)
                decimalCharacters = value.substring(pos + 1);

            if (decimalCharacters.length() > maxNumberOfDecimalDigit) {
                // Generate errors
                params = new ArrayList();
                params.add(fieldLabel);
                params.add(String.valueOf(maxNumberOfDecimalDigit));
                return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_DECIMALS, params);
            }
        }
    } else if (validatorName.equalsIgnoreCase("NUMERICRANGE")) {
        if (!GenericValidator.isBlankOrNull(value)) {
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "Apply the NUMERICRANGE VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
            String firstValueStr = arg0;
            String secondValueStr = arg1;
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "Range is [" + firstValueStr + "< x <" + secondValueStr + "]");
            boolean syntaxCorrect = true;
            if (!GenericValidator.isDouble(value)) {
                SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                        " CANNOT APPLY THE NUMERICRANGE VALIDATOR  value [" + value + "] is not a Number");
                syntaxCorrect = false;
            }
            if (!GenericValidator.isDouble(firstValueStr)) {
                SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                        " CANNOT APPLY THE NUMERICRANGE VALIDATOR  first value of range [" + firstValueStr
                                + "] is not a Number");
                syntaxCorrect = false;
            }
            if (!GenericValidator.isDouble(secondValueStr)) {
                SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                        " CANNOT APPLY THE NUMERICRANGE VALIDATOR  second value of range [" + secondValueStr
                                + "] is not a Number");
                syntaxCorrect = false;
            }
            if (syntaxCorrect) {
                double firstValue = Double.valueOf(firstValueStr).doubleValue();
                double secondValue = Double.valueOf(secondValueStr).doubleValue();
                double valueToCheckDouble = Double.valueOf(value).doubleValue();
                if (!(GenericValidator.isInRange(valueToCheckDouble, firstValue, secondValue))) {

                    params = new ArrayList();
                    params.add(fieldLabel);
                    params.add(firstValueStr);
                    params.add(secondValueStr);
                    return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_RANGE, params);

                }
            } else {
                return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_GENERIC);
            }
        }
    } else if (validatorName.equalsIgnoreCase("DATERANGE")) {

        if (!GenericValidator.isBlankOrNull(value)) {
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "Apply the DATERANGE VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
            String firstValueStr = arg0;
            String secondValueStr = arg1;
            String dateFormat = arg2;
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "Range is [" + firstValueStr + "< x <" + secondValueStr + "]");
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "Date Format is  [" + dateFormat + "]");
            //         //boolean syntaxCorrect = false;
            boolean syntaxCorrect = true;

            //if (!GenericValidator.isDate(value,dateFormat,true)){
            if (!GenericValidator.isDate(value, dateFormat, true)) {
                SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                        " CANNOT APPLY THE DATERANGE VALIDATOR  value [" + value
                                + "] is not a is not valid Date according to [" + dateFormat + "]");
                syntaxCorrect = false;
            }
            //if (!GenericValidator.isDate(firstValueStr,dateFormat,true)){
            if (!GenericValidator.isDate(firstValueStr, dateFormat, true)) {
                SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                        " CANNOT APPLY THE DATERANGE VALIDATOR  first value of range [" + firstValueStr
                                + "] is not valid Date according to [" + dateFormat + "]");
                syntaxCorrect = false;
            }
            //if (!GenericValidator.isDate(secondValueStr,dateFormat, true)){
            if (!GenericValidator.isDate(secondValueStr, dateFormat, true)) {
                SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                        " CANNOT APPLY THE DATERANGE VALIDATOR  second value of range [" + secondValueStr
                                + "] is not a valid Date according to [" + dateFormat + "]");
                syntaxCorrect = false;
            }

            if (syntaxCorrect) {
                DateFormat df = new SimpleDateFormat(dateFormat);

                Date firstValueDate = df.parse(firstValueStr);
                Date secondValueDate = df.parse(secondValueStr);
                Date theValueDate = df.parse(value);

                if ((theValueDate.getTime() < firstValueDate.getTime())
                        || (theValueDate.getTime() > secondValueDate.getTime())) {
                    params = new ArrayList();
                    params.add(fieldLabel);
                    params.add(firstValueStr);
                    params.add(secondValueStr);
                    return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_RANGE, params);
                }
            } else {
                return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_GENERIC);
            }
        }
    } else if (validatorName.equalsIgnoreCase("STRINGRANGE")) {
        if (!GenericValidator.isBlankOrNull(value)) {
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "Apply the STRINGRANGE VALIDATOR to field [" + fieldName + "] with value [" + value + "]");

            String firstValueStr = arg0;
            String secondValueStr = arg1;
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "Range is [" + firstValueStr + "< x <" + secondValueStr + "]");
            //if (firstValueStr.compareTo(secondValueStr) > 0){
            if ((value.compareTo(firstValueStr) < 0) || (value.compareTo(secondValueStr) > 0)) {
                params = new ArrayList();
                params.add(fieldLabel);
                params.add(firstValueStr);
                params.add(secondValueStr);
                return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_RANGE, params);
            }
        }
    } else if (validatorName.equalsIgnoreCase("MAXLENGTH")) {
        if (!GenericValidator.isBlankOrNull(value)) {
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "Apply the MAXLENGTH VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
            int maxLength = Integer.valueOf(arg0).intValue();
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "maxLength is [" + maxLength + "]");
            if (!GenericValidator.maxLength(value, maxLength)) {

                params = new ArrayList();
                params.add(fieldLabel);
                params.add(String.valueOf(maxLength));

                return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_MAXLENGTH, params);

            }
        }
    } else if (validatorName.equalsIgnoreCase("MINLENGTH")) {
        if (!GenericValidator.isBlankOrNull(value)) {
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "Apply the MINLENGTH VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
            int minLength = Integer.valueOf(arg0).intValue();
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "minLength is [" + minLength + "]");
            if (!GenericValidator.minLength(value, minLength)) {

                // Generate Errors
                params = new ArrayList();
                params.add(fieldLabel);
                params.add(String.valueOf(minLength));

                return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_MINLENGTH, params);

            }
        }
    } else if (validatorName.equalsIgnoreCase("REGEXP")) {
        if (!GenericValidator.isBlankOrNull(value)) {
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "Apply the REGEXP VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
            String regexp = arg0;
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator", "regexp is [" + regexp + "]");
            if (!(GenericValidator.matchRegexp(value, regexp))) {

                // Generate Errors
                params = new ArrayList();
                params.add(fieldLabel);
                params.add(regexp);

                return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_REGEXP, params);

            }
        }
    } else if (validatorName.equalsIgnoreCase("XSS")) {
        if (!GenericValidator.isBlankOrNull(value)) {
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "Apply the XSS VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
            String toVerify = value.toUpperCase();
            if (toVerify.contains("<A") || toVerify.contains("<LINK") || toVerify.contains("<IMG")
                    || toVerify.contains("<SCRIPT") || toVerify.contains("&LT;A")
                    || toVerify.contains("&LT;LINK") || toVerify.contains("&LT;IMG")
                    || toVerify.contains("&LT;SCRIPT")) {

                // Generate Errors
                params = new ArrayList();
                params.add(fieldLabel);

                return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_XSS, params);

            }
        }
    } else if (validatorName.equalsIgnoreCase("DATE")) {

        if (!GenericValidator.isBlankOrNull(value)) {
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "Apply the DATE VALIDATOR to field [" + fieldName + "] with value [" + value + "]");
            String dateFormat = arg0;
            SpagoBITracer.info("SpagoBI", "Validator", "automaticValidator",
                    "dateFormat is [" + dateFormat + "]");
            //if (!GenericValidator.isDate(value, dateFormat, true)){
            if (!GenericValidator.isDate(value, dateFormat, true)) {

                //Generate Errors
                params = new ArrayList();
                params.add(fieldLabel);
                params.add(dateFormat);

                return new EMFValidationError(EMFErrorSeverity.ERROR, fieldName, ERROR_DATE, params);
            }
        }

    }

    // all checks had positive result (no errors)
    return null;
}

From source file:com.ms.commons.summer.web.handler.DateConver.java

@SuppressWarnings("rawtypes")
public Object convert(Class type, Object value) {
    if (value == null || !(value instanceof String)) {
        return null;
    }//from   w  ww  .ja v  a  2s  .c  o m
    String str = (String) value;
    for (DateFormat dateFormat : dateFormatList) {
        try {
            return dateFormat.parse(str);
        } catch (ParseException ex) {
        }
    }
    return null;
}

From source file:fi.vm.sade.organisaatio.api.DateParam.java

@Override
protected Date parse(String param) throws Throwable {
    if (StringUtils.isEmpty(param)) {
        return null;
    }//from  ww w. j ava  2 s.co  m
    final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    try {
        return dateFormat.parse(param);
    } catch (ParseException e) {
        throw new WebApplicationException(Response.status(Status.BAD_REQUEST)
                .entity("Couldn't parse date string: " + e.getMessage()).build());
    }
}

From source file:org.consultjr.mvc.core.components.formatters.DateFormatter.java

@Override
public Date parse(String text, Locale locale) throws ParseException {
    String srtDateFormated = text.replace(".0", "");
    DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    try {/*from w w  w. j a v  a  2 s  .  c  om*/
        return formatter.parse(srtDateFormated);
    } catch (ParseException ex) {
        Logger.getLogger(DateFormatter.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}

From source file:jessmchung.groupon.parsers.GrouponTypeParser.java

protected Date parseDate(String dateString) throws ParseException {
    DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    Date date = (Date) formatter.parse(dateString.replace("T", " ").replace("Z", ""));

    return date;/*  w  w  w.  java 2s  .  c  o  m*/
}