Example usage for java.text SimpleDateFormat applyPattern

List of usage examples for java.text SimpleDateFormat applyPattern

Introduction

In this page you can find the example usage for java.text SimpleDateFormat applyPattern.

Prototype

public void applyPattern(String pattern) 

Source Link

Document

Applies the given pattern string to this date format.

Usage

From source file:ws.project.languagebasedlexiconanalisys.TwitterStreamAnalizer.java

void parseStream() throws IOException {
    //Inizializza file JSON
    FileWriter file = new FileWriter("data.json");
    JSONObject obj = new JSONObject();
    final JSONArray data = new JSONArray();
    obj.put("data", data);
    file.write(obj.toJSONString());/*from w  w  w. j ava  2 s .com*/
    file.flush();
    file.close();

    SimpleDateFormat currentDate = new SimpleDateFormat();
    currentDate.applyPattern("dd-MM-yyyy");
    final String currentDateStr = currentDate.format(new Date());

    ConfigurationBuilder cfg = new ConfigurationBuilder();
    cfg.setOAuthAccessToken("3065669171-9Hp3VZbz7f0BCsvWWFfgywgqimSIp1AlT98745S");
    cfg.setOAuthAccessTokenSecret("AUmg0AdhHzMXisnP1WV7Wnsw5amWFQPyIojI5aBG5qV4A");
    cfg.setOAuthConsumerKey("arieQRhL2WwgRFfXFLAJp5Hkw");
    cfg.setOAuthConsumerSecret("NvmWqgN1UKKPUWoh9d9Z2PuQobOah8IR5faqX2WjDGBL053sWE");

    StatusListener listener;
    listener = new StatusListener() {
        @Override
        public void onStatus(Status status) {
            SimpleDateFormat tweetDate = new SimpleDateFormat();
            tweetDate.applyPattern("dd-MM-yyyy");
            String tweetDateStr = tweetDate.format(status.getCreatedAt());

            try {
                indexer.openWriter(currentDateStr);
            } catch (IOException ex) {
                Logger.getLogger(TwitterStreamAnalizer.class.getName()).log(Level.SEVERE, null, ex);
            }

            //CHIUDO se cambio giorno ma non ho raggiunto l'1%
            if (!tweetDateStr.equals(currentDateStr)) {
                try {
                    indexer.closeWriter();
                } catch (IOException ex) {
                    Logger.getLogger(TwitterStreamAnalizer.class.getName()).log(Level.SEVERE, null, ex);
                }
                writeOnJson(currentDateStr);
                System.out.println("Giorno successivo, completato senza aver raggiunto 1%");
                System.exit(0);
            }
            tot_count++;

            if (status.getLang().equals("it")) {
                it_count++;
                try {
                    indexer.addTweet(id, status.getText());
                } catch (IOException ex) {
                    Logger.getLogger(TwitterStreamAnalizer.class.getName()).log(Level.SEVERE, null, ex);
                }

            }
            try {
                indexer.closeWriter();
            } catch (IOException ex) {
                Logger.getLogger(TwitterStreamAnalizer.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice sdn) {
        }

        @Override
        public void onTrackLimitationNotice(int i) {
        }

        @Override
        public void onScrubGeo(long l, long l1) {
        }

        @Override
        public void onStallWarning(StallWarning sw) {
        }

        @Override
        public void onException(Exception excptn) {
            TwitterException exc = (TwitterException) excptn;
            if (exc.exceededRateLimitation()) {
                try {
                    indexer.closeWriter();
                } catch (IOException ex) {
                    Logger.getLogger(TwitterStreamAnalizer.class.getName()).log(Level.SEVERE, null, ex);
                }
                writeOnJson(currentDateStr);
                System.out.println("1% raccolto, dati raccolti. Amen");
            }
        }

    };

    TwitterStream twitterStream = new TwitterStreamFactory(cfg.build()).getInstance();
    twitterStream.addListener(listener);

    indexer.addIndex(currentDateStr);
    indexer.openWriter(currentDateStr);
    twitterStream.sample();

}

From source file:org.openehealth.coms.cc.web_frontend.consentcreator.controller.PrivilegedDispatcher.java

/**
 * This method handles requests regarding the page showing user conflicts.
 * After the request, needed data for presentation is obtained and the user
 * then forwarded to the requested page.
 *//*  ww  w  . ja va 2 s .  c  o m*/
@SuppressWarnings("unchecked")
private void requestTypeUserConflictsPage() {

    try {

        request.setAttribute("show", "userconflictspage");

        SimpleDateFormat displaysdf = new SimpleDateFormat();
        displaysdf.applyPattern("dd.MM.yyyy");

        List<Object> ul = ccService.getListofUserConflicts();
        Vector<JSONObject> vjo = new Vector<JSONObject>();

        for (int i = 0; i < ul.size(); i++) {

            Vector<Object> veco = (Vector<Object>) ul.get(i);
            User u = (User) veco.get(0);

            JSONObject jso = new JSONObject();
            jso.put("name", u.getName());
            jso.put("forename", u.getForename());
            jso.put("birthdate", displaysdf.format(u.getBirthdate()));
            jso.put("emailaddress", u.getEmailaddress());

            if (u.getGender().equalsIgnoreCase("male")) {

                jso.put("gender", "Mnnlich");

            } else {

                jso.put("gender", "Weiblich");

            }

            jso.put("timestamp", displaysdf.format(new Date(((Timestamp) veco.get(1)).getTime())));

            vjo.add(jso);
        }
        request.setAttribute("conflictlist", new JSONArray(vjo));
        this.dispatch("/index.jsp");

    } catch (Exception e) {
        Logger.getLogger(this.getClass()).error(e);
    }
}

From source file:cn.newcapec.framework.core.utils.dataUtils.DateMorpherEx.java

public Object morph(Object value) {
    if (value == null) {
        return null;
    }/*from  www .j  a v a  2s  .c  o  m*/

    if (Date.class.isAssignableFrom(value.getClass())) {
        return (Date) value;
    }

    if (!supports(value.getClass())) {
        throw new MorphException(value.getClass() + " is not supported");
    }

    String strValue = (String) value;
    SimpleDateFormat dateParser = null;

    for (int i = 0; i < this.formats.length; ++i) {
        if (dateParser == null)
            dateParser = new SimpleDateFormat(this.formats[i], this.locale);
        else {
            dateParser.applyPattern(this.formats[i]);
        }
        dateParser.setLenient(this.lenient);
        try {
            return dateParser.parse(strValue.toLowerCase());
        } catch (ParseException localParseException) {
        }

    }

    if (super.isUseDefault()) {
        return this.defaultValue;
    }
    throw new MorphException("Unable to parse the date " + value);
}

From source file:org.posterita.core.TimeSeriesChart.java

/**
 * Takes a sql as input and generates a Timeseries that is added to
 * the dataset.    /*from  w w  w . ja v  a 2 s.c o m*/
 * Note: The sql must return 3 columns only Series, date & value
 * Column 1: Type -> String
 * Column 2: Type -> String or Date. For String the format must be as dd-MM-yyyy
 * Column 3: Type -> BigDecimal
 * 
 * @param sql
 */
public void getDataSetFromSQL(String sql) throws OperationException {
    PreparedStatement pstmt = DB.prepareStatement(sql, null);

    ArrayList<Object[]> dataSource = ReportManager.getReportData(pstmt);
    int count = 0;

    String seriesName = null;
    TimeSeries series = null;
    BigDecimal value = null;
    int day = 0;
    int month = 0;
    int year = 0;

    TimeSeriesCollection timeSeriesCollection = new TimeSeriesCollection();

    for (Object[] data : dataSource) {
        if (data.length != 3)
            throw new OperationException(
                    "Unable to generate timeseries. Cause:Invalid sql, the return resultset must have 3 columns only");

        count++;
        if (count == 1) {
            continue;
        }

        seriesName = (String) data[0];
        String date = (String) data[1];
        value = (BigDecimal) data[2];
        String s[] = date.split("-");

        if (s.length != 3)
            throw new OperationException("Unable to generate timeseries. "
                    + "Cause:Invalid date format, the date returned should have the following format 'DD-MM-YYYY'");

        SimpleDateFormat sdf = new SimpleDateFormat();
        Calendar cal = Calendar.getInstance();
        Date d = null;

        try {
            sdf.applyPattern("DD-MM-YYYY");
            d = sdf.parse(date);
        } catch (ParseException e1) {
            try {
                sdf.applyPattern("DD-MMM-YYYY");
                d = sdf.parse(date);
            } catch (ParseException e) {
                throw new OperationException("Unable to generate timeseries. "
                        + "Cause:Invalid date format, the date returned should have one of the following formats 'DD-MM-YYYY' or 'DD-MMM-YYYY'",
                        e);
            }
        }

        cal.setTime(d);

        day = cal.get(Calendar.DATE);
        month = cal.get(Calendar.MONTH) + 1;
        year = cal.get(Calendar.YEAR);

        series = timeSeriesCollection.getSeries(seriesName);

        if (series == null) {
            series = new TimeSeries(seriesName, Day.class);
            series.add(new Day(day, month, year), value);

            timeSeriesCollection.addSeries(series);
        } else {
            series.add(new Day(day, month, year), value);
        } //if   

    } //for

    dataset = timeSeriesCollection;
}

From source file:org.openehealth.coms.cc.web_frontend.consentcreator.controller.PrivilegedDispatcher.java

/**
 * /*from  www .jav a 2  s. co  m*/
 * This method handles requests regarding the clear consent page. After
 * needed data has been gathered, the requesting person is then forwarded to
 * the requested page.
 */
@SuppressWarnings("unchecked")
private void requestTypeClearConsentPage() {

    try {

        request.setAttribute("show", "clearconsentpage");

        SimpleDateFormat displaysdf = new SimpleDateFormat();
        displaysdf.applyPattern("dd.MM.yyyy");

        List<Object> ul = ccService.getListofUnclearedConsents();
        Vector<JSONObject> vjo = new Vector<JSONObject>();

        for (int i = 0; i < ul.size(); i++) {

            JSONObject jso = new JSONObject();

            Vector<Object> vecU = (Vector<Object>) ul.get(i);
            User u = (User) vecU.get(0);

            jso.put("name", u.getName());
            jso.put("forename", u.getForename());
            jso.put("birthdate", displaysdf.format(u.getBirthdate()));
            jso.put("emailaddress", u.getEmailaddress());

            if (u.getGender().equalsIgnoreCase("male")) {

                jso.put("gender", "Mnnlich");

            } else {

                jso.put("gender", "Weiblich");
            }

            if (((String) vecU.get(1)).equalsIgnoreCase("1")) {

                jso.put("participation", "true");

            } else {

                jso.put("participation", "false");
            }

            jso.put("timestamp", displaysdf.format(new Date(((Timestamp) vecU.get(2)).getTime())));

            vjo.add(jso);

        }
        request.setAttribute("consentlist", new JSONArray(vjo));
        this.dispatch("/index.jsp");

    } catch (Exception e) {
        Logger.getLogger(this.getClass()).error(e);
    }
}

From source file:org.kordamp.ezmorph.object.DateMorpher.java

public Object morph(Object value) {
    if (value == null) {
        return null;
    }//from   w w w .j a v a 2s.  c  om

    if (Date.class.isAssignableFrom(value.getClass())) {
        return (Date) value;
    }

    if (!supports(value.getClass())) {
        throw new MorphException(value.getClass() + " is not supported");
    }

    String strValue = (String) value;
    SimpleDateFormat dateParser = null;

    for (String format : formats) {
        if (dateParser == null) {
            dateParser = new SimpleDateFormat(format, locale);
        } else {
            dateParser.applyPattern(format);
        }
        dateParser.setLenient(lenient);
        try {
            return dateParser.parse(strValue.toLowerCase());
        } catch (ParseException pe) {
            // ignore exception, try the next format
        }
    }

    // unable to parse the date
    if (isUseDefault()) {
        return defaultValue;
    } else {
        throw new MorphException("Unable to parse the date " + value);
    }
}

From source file:org.syncope.console.wicket.markup.html.form.DateTimeFieldPanel.java

@Override
public FieldPanel setNewModel(final ListItem item, final Class reference) {
    final SimpleDateFormat formatter = DATE_FORMAT.get();

    if (datePattern != null) {
        formatter.applyPattern(datePattern);
    }/*from www .j  av a2s.c  o  m*/

    IModel<Date> model = new Model() {

        private static final long serialVersionUID = 6799404673615637845L;

        @Override
        public Serializable getObject() {
            Date date = null;

            if (StringUtils.hasText((String) item.getModelObject())) {
                if (reference.equals(String.class)) {
                    // Parse string using datePattern
                    try {
                        date = formatter.parse((String) item.getModelObject());
                    } catch (ParseException e) {
                        LOG.error("While parsing date", e);
                    }
                } else if (reference.equals(Date.class)) {
                    // Don't parse anything
                    date = (Date) item.getModelObject();
                } else {
                    // consider Long
                    date = new Date((Long) item.getModelObject());
                }
            }

            return date;
        }

        @Override
        public void setObject(final Serializable object) {
            if (object != null) {
                if (reference.equals(String.class)) {
                    // Parse string using datePattern
                    item.setModelObject((String) formatter.format((Date) object));
                } else if (reference.equals(Date.class)) {
                    // Don't parse anything
                    item.setModelObject((Date) object);
                } else {
                    // consider Long
                    item.setModelObject(((Date) object).getTime());
                }
            } else {
                item.setModelObject(null);
            }
        }
    };

    field.setModel(model);
    return this;
}

From source file:org.openTwoFactor.clientExt.net.sf.ezmorph.object.DateMorpher.java

public Object morph(Object value) {
    if (value == null) {
        return null;
    }//from  w  ww  . j  a v  a2  s  .  com

    if (Date.class.isAssignableFrom(value.getClass())) {
        return (Date) value;
    }

    if (!supports(value.getClass())) {
        throw new MorphException(value.getClass() + " is not supported");
    }

    String strValue = (String) value;
    SimpleDateFormat dateParser = null;

    for (int i = 0; i < formats.length; i++) {
        if (dateParser == null) {
            dateParser = new SimpleDateFormat(formats[i], locale);
        } else {
            dateParser.applyPattern(formats[i]);
        }
        dateParser.setLenient(lenient);
        try {
            return dateParser.parse(strValue.toLowerCase());
        } catch (ParseException pe) {
            // ignore exception, try the next format
        }
    }

    // unable to parse the date
    if (isUseDefault()) {
        return defaultValue;
    } else {
        throw new MorphException("Unable to parse the date " + value);
    }
}

From source file:org.opentaps.rest.ezmorph.TimestampMorpher.java

@Override
public Object morph(Object value) {
    if (value == null) {
        return null;
    }//from w w w .j a  va2s.c om

    if (Timestamp.class.isAssignableFrom(value.getClass())) {
        return value;
    }

    if (!supports(value.getClass())) {
        throw new MorphException(value.getClass() + " is not supported");
    }

    String strValue = (String) value;
    SimpleDateFormat dateParser = null;

    for (int i = 0; i < formats.length; i++) {
        if (dateParser == null) {
            dateParser = new SimpleDateFormat(formats[i], locale);
        } else {
            dateParser.applyPattern(formats[i]);
        }
        dateParser.setLenient(lenient);
        try {
            return new Timestamp(dateParser.parse(strValue.toLowerCase()).getTime());
        } catch (ParseException pe) {
            // ignore exception, try the next format
        }
    }

    // unable to parse the date
    if (isUseDefault()) {
        return defaultValue;
    } else {
        throw new MorphException("Unable to parse the date " + value);
    }
}

From source file:nl.b3p.viewer.admin.stripes.ChooseApplicationActionBean.java

public Resolution deleteApplication() {
    try {/* ww  w  . j av  a  2s.c o m*/
        if (applicationToDelete.isMashup()) {
            applicationToDelete.setRoot(null);
            Stripersist.getEntityManager().remove(applicationToDelete);
            Stripersist.getEntityManager().getTransaction().commit();

            getContext().getMessages().add(new SimpleMessage("Mashup is verwijderd"));
        } else if (applicationToDelete.getVersion() == null) {
            Date nowDate = new Date(System.currentTimeMillis());
            SimpleDateFormat sdf = (SimpleDateFormat) SimpleDateFormat.getDateInstance();
            sdf.applyPattern("HH-mm_dd-MM-yyyy");
            String now = sdf.format(nowDate);
            String uniqueVersion = ApplicationSettingsActionBean
                    .findUniqueVersion(applicationToDelete.getName(), "B_" + now);
            applicationToDelete.setVersion(uniqueVersion);
            Stripersist.getEntityManager().getTransaction().commit();
        } else {
            Stripersist.getEntityManager().remove(applicationToDelete);
            Stripersist.getEntityManager().getTransaction().commit();

            getContext().getMessages().add(new SimpleMessage("Applicatie is verwijderd"));
        }
        if (applicationToDelete.equals(application)) {
            setApplication(null);
        }
    } catch (Exception e) {
        log.error(String.format("Error deleting application #%d named %s", applicationToDelete.getId(),
                applicationToDelete.getName(),
                applicationToDelete.getVersion() == null ? "" : "v" + applicationToDelete.getVersion() + " "),
                e);
        String ex = e.toString();
        Throwable cause = e.getCause();
        while (cause != null) {
            ex += ";\n<br>" + cause.toString();
            cause = cause.getCause();
        }
        getContext().getValidationErrors()
                .addGlobalError(new SimpleError("Fout bij verwijderen applicatie: " + ex));
    }
    return new ForwardResolution(EDITJSP);
}