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:eu.xipi.bro4xipi.Bro4xipi.java

/**
 * It will display the main view page of a scenario
 * /*from w ww .  ja v  a2s  .  c om*/
 * @param actionRequest
 * @param actionResponse
 * @throws IOException
 * @throws PortletException
 */
public void addScenarioAction(ActionRequest actionRequest, ActionResponse actionResponse)
        throws IOException, PortletException {

    logger.info("==> in addScenarioAction");
    portletViewstatus = portletViewstatusEnum.PVPLANS;

    Enumeration<String> pns = actionRequest.getPortletSession().getAttributeNames();
    while (pns.hasMoreElements()) {
        String s = pns.nextElement();
        logger.info("==> in addScenarioAction getAttributeNames.nextElement() =" + s);

        Object obj = actionRequest.getPortletSession().getAttribute(s);
        logger.info("==> in addScenarioAction, obj=" + obj.toString());

        if (obj instanceof XiPiScenarioRequest) {
            XiPiScenarioRequest sr = (XiPiScenarioRequest) obj;
            logger.info("==> in addScenarioAction, srname=" + sr.getScenario().getName());
            if (sr.getBroker() == null)
                sr.setBroker(broker);

        }
    }

    XiPiScenarioRequest sr = (XiPiScenarioRequest) actionRequest.getPortletSession()
            .getAttribute("JSPxipiScenarioRequest");
    if (sr != null) {
        sr.setBroker(broker);
        logger.info("Setting broker to XiPiScenarioRequest = " + broker.toString());

        String inputScenarioName = actionRequest.getParameter("inputScenarioName");
        sr.setScenarioName(inputScenarioName);

        DateFormat df = new SimpleDateFormat("dd/MM/yyyy hh:mm z");
        Date startDate;
        try {
            startDate = df.parse(actionRequest.getParameter("startDate"));
            sr.setStartDate(startDate);
            Date endDate = df.parse(actionRequest.getParameter("endDate"));
            sr.setEndDate(endDate);

            for (Iterator<ServiceRequest> iterator = sr.getScenario().getServicesRequest()
                    .getServiceRequestList().iterator(); iterator.hasNext();) {
                ServiceRequest servReq = (ServiceRequest) iterator.next();
                if (servReq instanceof ServiceRequest) {
                    ServiceRequest serviceRequest = (ServiceRequest) servReq;
                    logger.info("serviceRequest.getName()=" + serviceRequest.getName());
                }
            }

            logger.debug("Starting ResourceAdvisor");
            //logger.info("Contracts=" + brokerJpaCtrl.countServiceContracts() );
            ResourceAdvisor ra = new ResourceAdvisor(broker, sr.getScenario(), brokerJpaCtrl);
            ra.CalculateOffers();

            Vector<OfferedPlan> offeredPlans = ra.getOfferedPlans();
            for (OfferedPlan offeredPlan : offeredPlans) {
                logger.info("========= " + offeredPlan.getProposedScenario().getName() + " #"
                        + offeredPlan.getPlanID() + " =========");
                Vector<AdvicedOffer> offer = offeredPlan.getAdvicedOffers();
                for (AdvicedOffer advicedOffer : offer) {
                    logger.info(advicedOffer.getFullOfferedResourceIDRevert());
                }
            }
            sr.setOfferedPlans(offeredPlans);

        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        logger.info("==> in addScenarioAction, XiPiScenarioRequest sr= =" + sr.getScenario().getName());
    } else {
        logger.info("==> in addScenarioAction, XiPiScenarioRequest sr= NULL !");
    }

    actionResponse.setPortletMode(PortletMode.VIEW);
}

From source file:com.rogchen.common.xml.UtilDateTime.java

/**
 * Localized String to Timestamp conversion. To be used in tandem with
 * timeStampToString().//  ww  w  . j  a va2 s  . c  om
 */
public static Timestamp stringToTimeStamp(String dateTimeString, String dateTimeFormat, TimeZone tz,
        Locale locale) throws ParseException {
    DateFormat dateFormat = toDateTimeFormat(dateTimeFormat, tz, locale);
    Date parsedDate = dateFormat.parse(dateTimeString);
    return new Timestamp(parsedDate.getTime());
}

From source file:fr.paris.lutece.plugins.suggest.utils.SuggestUtils.java

/**
 * return a timestamp Object which correspond with the string specified in
 * parameter.//from  ww w  .ja  va  2 s  . c o m
 * @param strDate the date who must convert
 * @param locale the locale
 * @return a timestamp Object which correspond with the string specified in
 *         parameter.
 */
public static Timestamp getLastMinute(String strDate, Locale locale) {
    try {
        Date date;
        DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, locale);
        dateFormat.setLenient(false);
        date = dateFormat.parse(strDate.trim());

        Calendar caldate = new GregorianCalendar();
        caldate.setTime(date);
        caldate.set(Calendar.MILLISECOND, 0);
        caldate.set(Calendar.SECOND, 0);
        caldate.set(Calendar.HOUR_OF_DAY, caldate.getActualMaximum(Calendar.HOUR_OF_DAY));
        caldate.set(Calendar.MINUTE, caldate.getActualMaximum(Calendar.MINUTE));

        Timestamp timeStamp = new Timestamp(caldate.getTimeInMillis());

        return timeStamp;
    } catch (ParseException e) {
        return null;
    }
}

From source file:fr.paris.lutece.plugins.suggest.utils.SuggestUtils.java

/**
 * return a timestamp Object which correspond with the string specified in
 * parameter./*from  www  .ja v a 2 s.  c o  m*/
 * @param strDate the date who must convert
 * @param locale the locale
 * @return a timestamp Object which correspond with the string specified in
 *         parameter.
 */
public static Timestamp getFirstMinute(String strDate, Locale locale) {
    try {
        Date date;
        DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, locale);
        dateFormat.setLenient(false);
        date = dateFormat.parse(strDate.trim());

        Calendar caldate = new GregorianCalendar();
        caldate.setTime(date);
        caldate.set(Calendar.MILLISECOND, 0);
        caldate.set(Calendar.SECOND, 0);
        caldate.set(Calendar.HOUR_OF_DAY, caldate.getActualMinimum(Calendar.HOUR_OF_DAY));
        caldate.set(Calendar.MINUTE, caldate.getActualMinimum(Calendar.MINUTE));

        Timestamp timeStamp = new Timestamp(caldate.getTimeInMillis());

        return timeStamp;
    } catch (ParseException e) {
        return null;
    }
}

From source file:com.ms.commons.test.classloader.util.SimpleAntxLoader.java

protected int readCacheFile(String svnUrl, String file, StringBuilder outContent) {

    File cacheDir = new File(CACHE_DIRECTORY);
    if (!(cacheDir.exists() && cacheDir.isDirectory())) {
        cacheDir.mkdirs();//www .j  a  v  a 2s  .co  m
    }

    File fileDate = new File(CACHE_DIRECTORY + "/" + convertSvnUrlToDegist(svnUrl) + file + ".date");
    File fileData = new File(CACHE_DIRECTORY + "/" + convertSvnUrlToDegist(svnUrl) + file + ".data");

    if (!fileDate.exists()) {
        return -1;
    }

    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");

    try {
        Date date = dateFormat.parse((FileUtils.readFileToString(fileDate)));
        Date now = dateFormat.parse(dateFormat.format(new Date()));

        if (now.equals(date)) {
            System.out.println("Read file:" + file + " from cache.");
            outContent.append(FileUtils.readFileToString(fileData));
            return 200;
        }
    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    }

    return -1;
}

From source file:edu.pitt.dbmi.ccd.db.service.UserAccountServiceTest.java

@Ignore
@Test//from  w  w w  . j ava 2 s . c om
public void testMigration() throws ParseException {
    System.out.println("testMigration");

    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    Path dataFile = Paths.get("data", "data.txt");
    try (BufferedReader reader = Files.newBufferedReader(dataFile, Charset.defaultCharset())) {
        reader.readLine();
        for (String line = reader.readLine(); line != null; line = reader.readLine()) {
            line = line.trim();
            String[] fields = line.split(";");
            Date createdDate = df.parse(fields[0].trim());
            Date lastLoginDate = df.parse(fields[1].trim());
            String password = fields[2].trim();
            String username = fields[3].trim();
            String email = fields[4].trim();
            String firstName = fields[5].trim();
            String lastName = fields[6].trim();
            String workspace = fields[7].trim();

            Person person = new Person(firstName, lastName, email, workspace);
            UserAccount userAccount = new UserAccount(person, username, password, true,
                    "61b2b10c-9d3a-11e6-8c7a-38c9860967a0", createdDate, lastLoginDate);
            userAccountService.save(userAccount);
        }
    } catch (IOException exception) {
        exception.printStackTrace(System.err);
    }
}

From source file:com.microsoft.azure.storage.analytics.LogRecordStreamReader.java

/**
 * Read a Date from the stream.//from   ww w  .j a  v a  2 s.  c o  m
 * 
 * @param format
 *            the format in which the date is stored, for parsing purposes.
 * @return
 *         the Date read.
 * @throws IOException
 * @throws ParseException
 */
public Date readDate(DateFormat format) throws IOException, ParseException {
    String temp = this.readField(false /* isQuotedString */);

    if (Utility.isNullOrEmpty(temp)) {
        return null;
    } else {
        return format.parse(temp);
    }
}

From source file:it.eng.spagobi.tools.downloadFiles.service.DownloadZipAction.java

public void service(SourceBean request, SourceBean response) throws Exception {
    logger.debug("IN");
    freezeHttpResponse();/*from  ww  w . j ava  2  s  . com*/

    HttpServletRequest httpRequest = getHttpRequest();
    HttpServletResponse httpResponse = getHttpResponse();

    // get Attribute DATE, MINUTE, DIRECTORY
    String directory = (String) request.getAttribute(DIRECTORY);

    String beginDate = (String) request.getAttribute(BEGIN_DATE);
    String beginTime = (String) request.getAttribute(BEGIN_TIME);
    String endDate = (String) request.getAttribute(END_DATE);
    String endTime = (String) request.getAttribute(END_TIME);
    String prefix1 = (request.getAttribute(PREFIX1) != null) ? (String) request.getAttribute(PREFIX1) + "_"
            : "";
    String prefix2 = (request.getAttribute(PREFIX2) != null) ? (String) request.getAttribute(PREFIX2) + "_"
            : "";
    //String prefix1 = (request.getAttribute(PREFIX1) != null)?(String) request.getAttribute(PREFIX1): "";
    //String prefix2 = (request.getAttribute(PREFIX2) != null)?(String) request.getAttribute(PREFIX2): "";

    // build begin Date         

    if (directory == null) {
        logger.error("search directory not specified");
        throw new SpagoBIServiceException(SERVICE_NAME, "Missing directory parameter");
    }

    if (beginDate == null || beginTime == null) {
        throw new SpagoBIServiceException(SERVICE_NAME, "Missing begin date parameter");
    }

    if (endDate == null || endTime == null) {
        throw new SpagoBIServiceException(SERVICE_NAME, "Missing end date parameter");
    }

    try {

        // remove / from days name
        beginDate = beginDate.replaceAll("/", "");
        endDate = endDate.replaceAll("/", "");
        beginTime = beginTime.replaceAll(":", "");
        endTime = endTime.replaceAll(":", "");

        String beginWhole = beginDate + " " + beginTime;
        String endWhole = endDate + " " + endTime;

        java.text.DateFormat myTimeFormat = new java.text.SimpleDateFormat(PARAMETERS_FORMAT);

        Date begin = myTimeFormat.parse(beginWhole);
        Date end = myTimeFormat.parse(endWhole);

        logger.debug("earch file from begin date " + begin.toString() + " to end date " + end.toString());

        directory = directory.replaceAll("\\\\", "/");

        File dir = new File(directory);
        if (!dir.isDirectory()) {
            logger.error("Not a valid directory specified");
            return;
        }

        // get all files that has to be zipped
        Vector filesToZip = searchDateFiles(dir, begin, end, prefix1 + prefix2);
        if (filesToZip.size() == 0) {
            /*throw new Exception ("Warning: Files not found with these parameters: <p><br>" +
                    " <b>Directory:</b> " + dir + "<p>" +
                    " <b>Begin date:</b> " + begin + "<p>" + 
                    " <b>End date:</b> " + end + "<p>" + 
                    " <b>Prefix:</b> " + prefix1 + prefix2 ); */
            throw new Exception("Warning: Missing files in specified interval!");
        }

        Date today = (new Date());
        DateFormat formatter = new SimpleDateFormat("dd-MMM-yy hh:mm:ss");
        //date = (Date)formatter.parse("11-June-07");    
        String randomName = formatter.format(today);
        randomName = randomName.replaceAll(" ", "_");
        randomName = randomName.replaceAll(":", "-");

        String directoryZip = System.getProperty("java.io.tmpdir");
        if (!directoryZip.endsWith(System.getProperty("file.separator"))) {
            directoryZip += System.getProperty("file.separator");
        }
        String fileZip = randomName + ".zip";
        String pathZip = directoryZip + fileZip;
        pathZip = pathZip.replaceAll("\\\\", "/");
        directoryZip = directoryZip.replaceAll("\\\\", "/");

        //         String directoryZip="C:/logs";
        //         String fileZip="prova.zip";
        //         String pathZip=directoryZip+"/"+fileZip;

        createZipFromFiles(filesToZip, pathZip, directory);

        //Vector<File> filesToZip = searchDateFiles(dir, beginDate, endDate)

        manageDownloadZipFile(httpRequest, httpResponse, directoryZip, fileZip);

        //manageDownloadExportFile(httpRequest, httpResponse);
    } catch (Throwable t) {
        logger.error("Error in writing the zip ", t);
        throw new SpagoBIServiceException(SERVICE_NAME, t.getMessage(), t);
        /* this manage defines a file with the error message and returns it.
        try{                     
           File file = new File("exception.txt");
           String text = t.getMessage() + " \n" + (( t.getStackTrace()!=null)?t.getStackTrace():"");
           FileUtils.writeStringToFile(file, text, "UTF-8");
           writeBackToClient(file, null, false, "exception.txt", "text/plain");                        
        }catch(Throwable t2){
           logger.error("Error in defining error file ",t2);
           throw new SpagoBIServiceException(SERVICE_NAME, "Server Error in writing the zip", t2);
        }
         */
    } finally {
        logger.debug("OUT");
    }
}

From source file:UserInterface.CustomerRole.CustomerTaxJPanel.java

public void displayChart(Date date1) {
    int total = 0;
    int k;//w ww.  j  a va  2 s.c o m
    int count = 0;
    int avg = 0;

    Sensor s = (Sensor) jTable1.getValueAt(0, 0);
    Date b = s.getDate();
    DateFormat formatter = new SimpleDateFormat("MM/dd/yy");
    Date date = new Date();
    try {
        date = formatter.parse("12/11/16");
    } catch (Exception e) {

    }
    //date = 
    System.out.println(jTable1.getValueAt(0, 5));
    System.out.println(jTable1.getValueAt(0, 4));
    list = new ArrayList<>();

    for (int l = 0; l < jTable1.getRowCount(); l++) {
        if (date.getDate() == b.getDate()) {
            Sensor s1 = (Sensor) jTable1.getValueAt(l, 0);
            total = total + s1.getCurrentEmissionCO2();
            count++;
        }
    }
    avg = total / count;
    list.add(avg);

    int avg1 = 0;

    for (int l = 0; l < jTable1.getRowCount(); l++) {
        if (date.getDate() == b.getDate()) {
            Sensor s1 = (Sensor) jTable1.getValueAt(l, 0);
            total = total + s1.getCurrentEmissionCO2();
            count++;
        }
    }

    avg = total / count;
    list.add(avg);
    for (int l = 0; l < jTable1.getRowCount(); l++) {
        if (date.getDate() == b.getDate()) {
            Sensor s1 = (Sensor) jTable1.getValueAt(l, 0);
            total = total + s1.getNormalCO2();
            count++;
        }
    }
    avg1 = total / count;
    int avg3 = 0;
    for (int l = 0; l < jTable1.getRowCount(); l++) {
        if (date.getDate() == b.getDate()) {
            Sensor s1 = (Sensor) jTable1.getValueAt(l, 0);
            total = total + s1.getCurrentEmissionNOx();
            count++;
        }
    }
    avg3 = total / count;

    int avg4 = 0;
    for (int l = 0; l < jTable1.getRowCount(); l++) {
        if (date.getDate() == b.getDate()) {
            Sensor s1 = (Sensor) jTable1.getValueAt(l, 0);
            total = total + s1.getNormalNOx();
            count++;
        }
    }
    avg4 = total / count;

    int avg5 = 0;
    for (int l = 0; l < jTable1.getRowCount(); l++) {
        if (date.getDate() == b.getDate()) {
            Sensor s1 = (Sensor) jTable1.getValueAt(l, 0);
            total = total + s1.getSolarCurrentEmissionCO2();
            count++;
        }
    }
    avg5 = total / count;
    int avg6 = 0;

    for (int l = 0; l < jTable1.getRowCount(); l++) {
        if (date.getDate() == b.getDate()) {
            Sensor s1 = (Sensor) jTable1.getValueAt(l, 0);
            total = total + s1.getSolarNormalCO2();
            count++;
        }
    }

    avg6 = total / count;
    int avg7 = 0;
    for (int l = 0; l < jTable1.getRowCount(); l++) {
        if (date.getDate() == b.getDate()) {
            Sensor s1 = (Sensor) jTable1.getValueAt(l, 0);
            total = total + s1.getSolarCurrentEmissionNOx();
            count++;
        }
    }
    avg7 = total / count;
    int avg8 = 0;
    for (int l = 0; l < jTable1.getRowCount(); l++) {
        if (date.getDate() == b.getDate()) {
            Sensor s1 = (Sensor) jTable1.getValueAt(l, 0);
            total = total + s1.getSolarNormalNOx();
            count++;
        }
    }
    avg8 = total / count;

    int combo = avg + avg3;
    int combo1 = avg5 + avg7;

    DefaultPieDataset dataset22 = new DefaultPieDataset();
    dataset22.setValue("Fuel Emission", new Integer(combo));
    dataset22.setValue("Solar Emission ", new Integer(combo1));

    JFreeChart chart22 = ChartFactory.createPieChart3D("Comparison Chart ", // chart title                   
            dataset22, // data 
            true, // include legend                   
            true, false);

    final PiePlot3D plot = (PiePlot3D) chart22.getPlot();
    plot.setStartAngle(270);
    plot.setForegroundAlpha(0.60f);
    plot.setInteriorGap(0.02);

    ChartFrame frame33 = new ChartFrame("3D Pie Chart for EMission Comparison from different sources", chart22);
    frame33.setVisible(true);
    frame33.setSize(500, 400);

    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    dataset.setValue(avg, b, "curr CO2");
    dataset.setValue(avg1, b, "normal CO2");
    dataset.setValue(avg3, b, "current NOx");
    dataset.setValue(avg4, b, "normal NOx");
    //dataset.setValue(a1,b1,"current");
    JFreeChart chart = ChartFactory.createBarChart("Normal Fuel Emission Chart", "CO2 Emission", "in (g/KM)",
            dataset, PlotOrientation.VERTICAL, false, false, false);
    CategoryPlot p = chart.getCategoryPlot();
    p.setRangeGridlinePaint(Color.BLACK);
    ChartFrame frame = new ChartFrame("Bar Chart for Customer", chart);
    frame.setVisible(true);
    frame.setSize(500, 400);

    DefaultCategoryDataset dataset1 = new DefaultCategoryDataset();
    dataset1.setValue(avg5, b, "curr CO2");
    dataset1.setValue(avg6, b, "normal CO2");
    dataset1.setValue(avg7, b, "current NOx");
    dataset1.setValue(avg8, b, "normal NOx");
    //dataset.setValue(a1,b1,"current");
    JFreeChart chart2 = ChartFactory.createBarChart("Solar Emission Chart", "CO2 Emission", "in (g/KM)",
            dataset1, PlotOrientation.VERTICAL, false, false, false);
    CategoryPlot p1 = chart.getCategoryPlot();
    p1.setRangeGridlinePaint(Color.BLACK);
    ChartFrame frame1 = new ChartFrame("Bar Chart for Customer", chart2);
    frame1.setVisible(true);
    frame1.setSize(500, 400);
}

From source file:eu.serco.dhus.plugin.sral.SralPlugin.java

public List<Request> retrieveRequests(String productType, String startTime, String stopTime) {

    List<Request> requests = new ArrayList<Request>();
    Date startDate;// w  ww .  j a v a 2 s .  c om
    Date stopDate;
    long startDateInMillis;
    long stopDateInMillis;

    DateFormat inputFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
    //2016-07-16T00:00:00.000Z
    DateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

    try {
        startDate = inputFormat.parse(startTime);
        stopDate = inputFormat.parse(stopTime);
        startDateInMillis = startDate.getTime();
        stopDateInMillis = stopDate.getTime();

        if (taskTables.get(productType) != null) {

            for (Task task : taskTables.get(productType).getTasks()) {
                logger.info("task.getName()" + task.getName());
                logger.info("task.getInputs()" + task.getInputs());
                Request request;
                for (Input in : task.getInputs()) {
                    request = new Request();
                    request.setMandatory(in.getMandatory());
                    // TODO: Manage Mode when getting requests to perform
                    request.setMode(in.getMode());
                    List<InputRequest> inputRequests = new ArrayList<InputRequest>();
                    for (Alternative alternative : in.getAlternatives()) {
                        InputRequest inReq = new InputRequest();
                        //logger.info("alternative.getRetrievalMode() " + alternative.getRetrievalMode());
                        String url = propFiles.get(productType)
                                .getProperty(alternative.getRetrievalMode().trim());
                        //logger.info("URL " + url);
                        //logger.info("alternative.getFileType() " + alternative.getFileType());
                        url = url.replace("<filename>", alternative.getFileType());
                        long startValidity;
                        long stopValidity;
                        if (alternative.getT0() > 0) {
                            startValidity = startDateInMillis - (long) Math.ceil(alternative.getT0() * 1000);
                        } else {
                            startValidity = startDateInMillis;
                        }
                        if (alternative.getT1() > 0) {
                            stopValidity = stopDateInMillis + (long) Math.ceil(alternative.getT1() * 1000);
                        } else {
                            stopValidity = stopDateInMillis;
                        }
                        Date startValidityDate = new Date(startValidity);
                        String beginPosition = outputFormat.format(startValidityDate) + ".000Z";
                        Date stopValidityDate = new Date(stopValidity);
                        String endPosition = outputFormat.format(stopValidityDate) + ".000Z";
                        url = url.replace("<beginPosition>", beginPosition);
                        url = url.replace("<endPosition>", endPosition);
                        url = externalDHuSUrl + url;
                        inReq.setUrl(url);
                        inReq.setType(alternative.getFileType());
                        inReq.setRetrievalMode(alternative.getRetrievalMode());
                        inputRequests.add(inReq);
                        logger.info("----------");
                        logger.info("Request to perform: " + externalDHuSUrl + url);
                    }
                    logger.info("How many urls???: " + inputRequests.size());
                    request.setRequests(inputRequests);
                    requests.add(request);
                }
            }
        }

    } catch (ParseException pe) {

        pe.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    logger.info("Request size is:    ????? **** " + requests.size());
    return requests;
}