Example usage for java.text ParseException getLocalizedMessage

List of usage examples for java.text ParseException getLocalizedMessage

Introduction

In this page you can find the example usage for java.text ParseException getLocalizedMessage.

Prototype

public String getLocalizedMessage() 

Source Link

Document

Creates a localized description of this throwable.

Usage

From source file:org.ietr.preesm.cli.CLIWorkflowExecutor.java

@Override
public Object start(IApplicationContext context) throws Exception {
    Options options = getCommandLineOptions();

    try {/*w  w  w  .  ja v a2s .com*/
        CommandLineParser parser = new PosixParser();

        String cliOpts = StringUtils
                .join((Object[]) context.getArguments().get(IApplicationContext.APPLICATION_ARGS), " ");
        CLIWorkflowLogger.traceln("Starting workflows execution");
        CLIWorkflowLogger.traceln("Command line arguments: " + cliOpts);

        // parse the command line arguments
        CommandLine line = parser.parse(options,
                (String[]) context.getArguments().get(IApplicationContext.APPLICATION_ARGS));

        if (line.getArgs().length != 1) {
            throw new ParseException("Expected project name as first argument", 0);
        }
        // Get the project containing the scenarios and workflows to execute
        String projectName = line.getArgs()[0];
        IWorkspace workspace = ResourcesPlugin.getWorkspace();
        IWorkspaceRoot root = workspace.getRoot();
        project = root.getProject(new Path(projectName).lastSegment());

        // Handle options
        String workflowPath = line.getOptionValue('w');
        String scenarioPath = line.getOptionValue('s');

        // Set of workflows to execute
        Set<String> workflowPaths = new HashSet<String>();
        // Set of scenarios to execute
        Set<String> scenarioPaths = new HashSet<String>();

        // If paths to workflow and scenario are not specified using
        // options, find them in the project given as arguments
        if (workflowPath == null) {
            // If there is no workflow path specified, execute all the
            // workflows (files with workflowExt) found in workflowDir of
            // the project
            workflowPaths = getAllFilePathsIn(workflowExt, project, workflowDir);
        } else {
            // Otherwise, format the workflowPath and execute it
            if (!workflowPath.contains(projectName))
                workflowPath = projectName + workflowDir + "/" + workflowPath;
            if (!workflowPath.endsWith(workflowExt))
                workflowPath = workflowPath + "." + workflowExt;
            workflowPaths.add(workflowPath);
        }

        if (scenarioPath == null) {
            // If there is no scenario path specified, execute all the
            // scenarios (files with scenarioExt) found in scenarioDir of
            // the project
            scenarioPaths = getAllFilePathsIn(scenarioExt, project, scenarioDir);
        } else {
            // Otherwise, format the scenarioPath and execute it
            if (!scenarioPath.contains(projectName))
                scenarioPath = projectName + scenarioDir + "/" + scenarioPath;
            if (!scenarioPath.endsWith(scenarioExt))
                scenarioPath = scenarioPath + "." + scenarioExt;
            scenarioPaths.add(scenarioPath);
        }

        CLIWorkflowLogger.traceln("Launching workflows execution");
        // Launch the execution of the workflos with the scenarios
        DFToolsWorkflowLogger.runFromCLI();
        for (String wPath : workflowPaths) {
            for (String sPath : scenarioPaths) {
                CLIWorkflowLogger
                        .traceln("Launching execution of workflow: " + wPath + " with scenario: " + sPath);
                execute(wPath, sPath, null);
            }
        }

    } catch (UnrecognizedOptionException uoe) {
        printUsage(options, uoe.getLocalizedMessage());
    } catch (ParseException exp) {
        printUsage(options, exp.getLocalizedMessage());
    }
    return IApplication.EXIT_OK;
}

From source file:org.dd4t.core.factories.impl.PageFactoryImpl.java

/**
 * Find the source of the Page by Tcm Id.
 *
 * @param tcmId the Tcm Id of the page/*from w  w  w. j  a  v  a 2 s.  co m*/
 * @return The page source as String
 * @throws FactoryException
 */
@Override
public String findSourcePageByTcmId(final String tcmId) throws FactoryException {

    LOG.debug("Enter findSourcePageByTcmId with uri: {}", tcmId);

    String cacheKey = "PSE-" + tcmId;

    CacheElement<String> cacheElement = cacheProvider.loadPayloadFromLocalCache(cacheKey);
    String pageSource;

    if (cacheElement.isExpired()) {
        synchronized (cacheElement) {
            if (cacheElement.isExpired()) {
                cacheElement.setExpired(false);

                try {
                    pageSource = pageProvider.getPageContentById(tcmId);
                } catch (ParseException e) {
                    LOG.error(e.getLocalizedMessage(), e);
                    throw new SerializationException(e);
                }

                if (StringUtils.isEmpty(pageSource)) {
                    cacheElement.setPayload(null);
                    cacheProvider.storeInItemCache(cacheKey, cacheElement);
                    throw new ItemNotFoundException("Unable to find page by id " + tcmId);
                }

                cacheElement.setPayload(pageSource);
                cacheProvider.storeInItemCache(cacheKey, cacheElement);
            } else {
                LOG.debug("Return a page with uri: {} from cache", tcmId);
                pageSource = cacheElement.getPayload();
            }
        }
    } else {
        LOG.debug("Return page with uri: {} from cache", tcmId);
        pageSource = cacheElement.getPayload();
    }

    return pageSource;
}

From source file:net.osten.watermap.convert.PCTReport.java

private WaterReport processWaypoint(String waypoint, String desc, String date, String rpt) {
    log.info("processing waypoint=" + waypoint);

    WaterReport report = new WaterReport();
    report.setDescription(rpt);/*from   w w w.j  a v a2 s. c o m*/
    report.setLocation(desc);
    report.setName(waypoint);

    if (date != null && !date.isEmpty()) {
        try {
            report.setLastReport(dateFormatter.parse(date));
        } catch (ParseException e) {
            log.severe(e.getLocalizedMessage());
        }
    }
    report.setSource(SOURCE_TITLE);
    report.setUrl(SOURCE_URL);

    report.setState(WaterStateParser.parseState(rpt));

    log.info("there are " + waypoints.size() + " waypoints");
    // TODO replace with something more elegant than this brute force search
    for (WptType wpt : waypoints) {
        if (wpt.getName().equalsIgnoreCase(waypoint)) {
            log.info("found matching lat/lon");
            report.setLat(wpt.getLat());
            report.setLon(wpt.getLon());
            break;
        }
    }

    // if coords not found, try adding leading 0 (e.g. WRCS292 -> WRCS0292)
    if (report.getLat() == null) {
        String modifiedWaypoint = RegexUtils.addLeadingZerosToWaypoint(waypoint);
        for (WptType wpt : waypoints) {
            if (wpt.getName().equalsIgnoreCase(modifiedWaypoint)) {
                log.info("found matching lat/lon");
                report.setLat(wpt.getLat());
                report.setLon(wpt.getLon());
                break;
            }
        }
    }

    // if coords not found, try with leading 0 in waypoint (i.e. WR0213); this happens in Section B waypoint file
    if (report.getLat() == null && waypoint.length() > 2) {
        String modifiedWaypoint = "WR0" + waypoint.substring(2);
        for (WptType wpt : waypoints) {
            if (wpt.getName().equalsIgnoreCase(modifiedWaypoint)) {
                log.info("found matching lat/lon");
                report.setLat(wpt.getLat());
                report.setLon(wpt.getLon());
                break;
            }
        }
    }

    // if coords still not found, try with mapped name
    if (report.getLat() == null) {
        String modifiedName = fixNames(report.getName());
        for (WptType wpt : waypoints) {
            if (wpt.getName().equalsIgnoreCase(modifiedName)) {
                log.info("found matching lat/lon");
                report.setLat(wpt.getLat());
                report.setLon(wpt.getLon());
                break;
            }
        }
    }

    return report;
}

From source file:org.dd4t.core.factories.impl.PageFactoryImpl.java

/**
 * @param uri of the page//from  w ww  . j  a va 2s . com
 * @return the Page Object
 * @throws org.dd4t.core.exceptions.FactoryException
 */
@Override
public Page getPage(String uri) throws FactoryException {
    LOG.debug("Enter getPage with uri: {}", uri);

    CacheElement<Page> cacheElement = cacheProvider.loadPayloadFromLocalCache(uri);
    Page page;

    if (cacheElement.isExpired()) {
        synchronized (cacheElement) {
            if (cacheElement.isExpired()) {
                cacheElement.setExpired(false);
                String pageSource;
                try {
                    pageSource = pageProvider.getPageContentById(uri);
                } catch (ParseException e) {
                    LOG.error(e.getLocalizedMessage(), e);
                    throw new SerializationException(e);
                }

                if (StringUtils.isEmpty(pageSource)) {
                    cacheElement.setPayload(null);
                    cacheProvider.storeInItemCache(uri, cacheElement);
                    throw new ItemNotFoundException("Unable to find page by id " + uri);
                }

                try {
                    page = deserialize(pageSource, PageImpl.class);
                    LOG.debug("Running pre caching processors");
                    this.executeProcessors(page, RunPhase.BEFORE_CACHING, getRequestContext());
                    cacheElement.setPayload(page);
                    final TCMURI tcmUri = new TCMURI(uri);
                    cacheProvider.storeInItemCache(uri, cacheElement, tcmUri.getPublicationId(),
                            tcmUri.getItemId());
                    LOG.debug("Added page with uri: {} to cache", uri);
                } catch (ParseException e) {
                    throw new SerializationException(e);
                }
            } else {
                LOG.debug("Return a page with uri: {} from cache", uri);
                page = cacheElement.getPayload();
            }
        }
    } else {
        LOG.debug("Return page with uri: {} from cache", uri);
        page = cacheElement.getPayload();
    }
    if (page != null) {
        LOG.debug("Running Post caching Processors");
        try {
            this.executeProcessors(page, RunPhase.AFTER_CACHING, getRequestContext());
        } catch (ProcessorException e) {
            LOG.error(e.getLocalizedMessage(), e);
        }
    }
    return page;
}

From source file:net.osten.watermap.convert.AZTReport.java

private WaterReport parseDataLine(String line) {
    WaterReport result = new WaterReport();

    try {//  w  ww .j  a  v  a2 s.  c o m
        // Example line:
        // 8.3 8.3 Tub Spring (aka Bathtub Spring) spring 3 full tub; good trickle3/28/15 3/28/15 Bird Food 4/5/15

        // Mileages = first two decimals
        MatchResult decimalsMatch = RegexUtils.matchFirstOccurance(line, decimalPattern);
        if (decimalsMatch == null) {
            log.fine("Mileages not found");
            return null;
        }
        int decimalsEnd = decimalsMatch.end();

        // Type = spring | creek | spring fed | windmill | store | dirt tank | pipe | Town | etc..
        MatchResult typeMatch = RegexUtils.matchFirstOccurance(line, typesPattern);
        if (typeMatch == null) {
            log.fine("Type not found");
            return null;
        }
        log.finer("type=" + typeMatch.group());
        int typeEnd = typeMatch.end();

        // Name = text from second decimal number to type (spring,creek,etc.)
        log.finer("decimalsEnd=" + decimalsEnd + " typeEnd=" + typeEnd);
        String name = line.substring(decimalsEnd, typeEnd);
        result.setName(name.trim());

        // Historic Reliability = int after Type (can be "1 to 2" or "0-2")
        MatchResult histRelMatch = RegexUtils.matchFirstOccurance(line, histRelPattern3, typeEnd);
        if (histRelMatch == null) {
            histRelMatch = RegexUtils.matchFirstOccurance(line, histRelPattern2, typeEnd);
            if (histRelMatch == null) {
                histRelMatch = RegexUtils.matchFirstOccurance(line, histRelPattern1, typeEnd);
                if (histRelMatch == null) {
                    log.fine("Historical Reliability not found");
                    return null;
                }
            }
        }
        log.finer("histRel=" + histRelMatch.group());
        String historicReliability = mapHistoricReliability(histRelMatch.group().trim());
        int histRelEnd = histRelMatch.end();

        // Report Date = second date from right
        int reportDateEnd = -1;
        int reportDateStart = -1;
        List<MatchResult> dates = RegexUtils.matchOccurences(line, datePattern);
        if (dates.size() >= 2) {
            reportDateEnd = dates.get(dates.size() - 2).end();
            reportDateStart = dates.get(dates.size() - 2).start();
        } else {
            log.fine("Only found " + dates.size() + " dates");
            reportDateStart = Math.max(line.length() - 1, histRelEnd);
        }

        // Report = Historic Reliability to Report Date
        log.finer("histRelEnd=" + histRelEnd + " reportDateStart=" + reportDateStart);
        if (histRelEnd >= 0 && reportDateStart >= 0 && reportDateStart >= histRelEnd) {
            String report = line.substring(histRelEnd, reportDateStart);
            result.setDescription(report.trim() + "<br />Historical Reliability:" + historicReliability);
        } else {
            log.fine("cannot find historic reliability");
        }

        // Post Date = first date from right
        int postDateStart = -1;
        MatchResult postDate = RegexUtils.matchLastOccurence(line, datePattern);
        if (postDate == null) {
            log.fine("Post Date not found");
        } else {
            result.setLastReport(dateFormatter.parse(postDate.group()));
            postDateStart = postDate.start();
            log.finer("postDate=" + postDate.group());
        }

        // Reported By = text between Report Date and Post Date
        if (postDateStart >= 0 && reportDateEnd >= 0 && postDateStart > reportDateEnd) {
            String reportedBy = line.substring(reportDateEnd, postDateStart);
            log.finer("reportedBy=" + reportedBy);
        } else {
            log.finer("cannot find reportedBy");
        }

        result.setState(WaterStateParser.parseState(result.getDescription()));
        result.setSource(SOURCE_TITLE);
        result.setUrl(SOURCE_URL);
    } catch (

    ParseException e)

    {
        log.fine("ParseException:" + e.getLocalizedMessage());
    }

    return result;

}

From source file:org.kuali.mobility.events.service.EventsServiceImpl.java

@GET
@Path("/findByDateRange")
public List<EventImpl> getEventsByDateRange(@QueryParam(value = "campus") String campus,
        @QueryParam(value = "fromDate") String fromDate, @QueryParam(value = "toDate") String toDate,
        @QueryParam(value = "categoryId") String categoryId) {
    Date startDate, endDate;/*  ww  w.  j  a  v a  2  s. co  m*/
    List<EventImpl> events = new ArrayList<EventImpl>();
    try {
        startDate = DateUtils.parseDateStrictly(fromDate, DATE_PATTERNS);
        endDate = DateUtils.parseDateStrictly(toDate, DATE_PATTERNS);
    } catch (ParseException pe) {
        LOG.error(pe.getLocalizedMessage(), pe);
        startDate = new Date();
        endDate = new Date();
    }
    if (null == categoryId || categoryId.isEmpty()) {
        events = getEventsForDateRange(fromDate, toDate);
    } else {
        events = getAllEventsByDateFromTo(campus, categoryId, startDate, endDate);
    }
    return events;
}

From source file:com.intelligentz.appointmentz.controllers.addSession.java

@SuppressWarnings("Since15")
@Override/*from w ww.j a va2  s . c  o  m*/
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    try {
        String room_id = null;
        String doctor_id = null;
        String start_time = null;
        String date_picked = null;
        ArrayList<SessonCustomer> sessonCustomers = new ArrayList<>();
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // maximum size that will be stored in memory
        factory.setSizeThreshold(maxMemSize);
        // Location to save data that is larger than maxMemSize.
        factory.setRepository(new File(filePath + "temp"));

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        // maximum file size to be uploaded.
        upload.setSizeMax(maxFileSize);

        // Parse the request to get file items.
        List fileItems = upload.parseRequest(req);

        // Process the uploaded file items
        Iterator i = fileItems.iterator();

        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                String fileName = fi.getName();
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();
                // Write the file
                if (fileName.lastIndexOf("\\") >= 0) {
                    filePath = filePath + fileName.substring(fileName.lastIndexOf("\\"));
                    file = new File(filePath);
                } else {
                    filePath = filePath + fileName.substring(fileName.lastIndexOf("\\") + 1);
                    file = new File(filePath);
                }
                fi.write(file);
                Files.lines(Paths.get(filePath)).forEach((line) -> {
                    String[] cust = line.split(",");
                    sessonCustomers.add(new SessonCustomer(cust[0].trim(), Integer.parseInt(cust[1].trim())));
                });
            } else {
                if (fi.getFieldName().equals("room_id"))
                    room_id = fi.getString();
                else if (fi.getFieldName().equals("doctor_id"))
                    doctor_id = fi.getString();
                else if (fi.getFieldName().equals("start_time"))
                    start_time = fi.getString();
                else if (fi.getFieldName().equals("date_picked"))
                    date_picked = fi.getString();
            }
        }

        con = new connectToDB();
        if (con.connect()) {
            Connection connection = con.getConnection();
            Class.forName("com.mysql.jdbc.Driver");
            Statement stmt = connection.createStatement();
            String SQL, SQL1, SQL2;
            SQL1 = "insert into db_bro.session ( doctor_id, room_id, date, start_time) VALUES (?,?,?,?)";
            PreparedStatement preparedStmt = connection.prepareStatement(SQL1);
            preparedStmt.setString(1, doctor_id);
            preparedStmt.setString(2, room_id);
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH:mm");
            try {
                java.util.Date d = formatter.parse(date_picked + "-" + start_time);
                Date d_sql = new Date(d.getTime());
                java.util.Date N = new java.util.Date();
                if (N.compareTo(d) > 0) {
                    res.sendRedirect("./error.jsp?error=Invalid Date!");
                }
                //String [] T = start_time.split(":");
                //Time t = Time.valueOf(start_time);
                //Time t = new Time(Integer.parseInt(T[0]),Integer.parseInt(T[1]),0);

                //java.sql.Time t_sql = new java.sql.Date(d.getTime());
                preparedStmt.setString(4, start_time + ":00");
                preparedStmt.setDate(3, d_sql);
            } catch (ParseException e) {
                displayMessage(res, "Invalid Date!" + e.getLocalizedMessage());
            }

            // execute the preparedstatement
            preparedStmt.execute();

            SQL = "select * from db_bro.session ORDER BY session_id DESC limit 1";
            ResultSet rs = stmt.executeQuery(SQL);

            boolean check = false;
            while (rs.next()) {
                String db_doctor_id = rs.getString("doctor_id");
                String db_date_picked = rs.getString("date");
                String db_start_time = rs.getString("start_time");
                String db_room_id = rs.getString("room_id");

                if ((doctor_id == null ? db_doctor_id == null : doctor_id.equals(db_doctor_id))
                        && (start_time == null ? db_start_time == null
                                : (start_time + ":00").equals(db_start_time))
                        && (room_id == null ? db_room_id == null : room_id.equals(db_room_id))
                        && (date_picked == null ? db_date_picked == null
                                : date_picked.equals(db_date_picked))) {
                    check = true;
                    //displayMessage(res,"Authentication Success!");
                    SQL2 = "insert into db_bro.session_customers ( session_id, mobile, appointment_num) VALUES (?,?,?)";
                    for (SessonCustomer sessonCustomer : sessonCustomers) {
                        preparedStmt = connection.prepareStatement(SQL2);
                        preparedStmt.setString(1, rs.getString("session_id"));
                        preparedStmt.setString(2, sessonCustomer.getMobile());
                        preparedStmt.setInt(3, sessonCustomer.getAppointment_num());
                        preparedStmt.execute();
                    }
                    try {
                        connection.close();
                    } catch (SQLException e) {
                        displayMessage(res, "SQLException");
                    }

                    res.sendRedirect("./home");

                }
            }
            if (!check) {

                try {
                    connection.close();
                } catch (SQLException e) {
                    displayMessage(res, "SQLException");
                }
                displayMessage(res, "SQL query Failed!");
            }
        } else {
            con.showErrormessage(res);
        }

        /*res.setContentType("text/html");//setting the content type
        PrintWriter pw=res.getWriter();//get the stream to write the data
                
        //writing html in the stream
        pw.println("<html><body>");
        pw.println("Welcome to servlet: "+username);
        pw.println("</body></html>");
                
        pw.close();//closing the stream
        */
    } catch (Exception ex) {
        Logger.getLogger(authenticate.class.getName()).log(Level.SEVERE, null, ex);
        displayMessage(res, "Error!" + ex.getLocalizedMessage());
    }
}

From source file:com.hybris.mobile.lib.http.manager.volley.VolleyPersistenceManager.java

/**
 * Ignore cache headers on Webservice response
 *
 * @param response Data and Headers/*from   w w w  . java 2s  .  c o m*/
 * @return Data and metadata for entry returned by the cache
 */
protected Cache.Entry ignoreCacheHeaders(NetworkResponse response) {
    long now = System.currentTimeMillis();

    // In PersistenceHelper.CACHE_EXPIRE_IN_DAY cache will be refreshed on
    // background
    long cacheHitButRefreshed = PersistenceHelper.CACHE_EXPIRE_IN_DAYS * 60 * 60 * 60 * 1000;

    // In PersistenceHelper.CACHE_EXPIRE_IN_DAY cache will expire completely
    long cacheExpired = PersistenceHelper.CACHE_EXPIRE_IN_DAYS * 60 * 60 * 60 * 1000;

    Map<String, String> headers = response.headers;

    long serverDate = 0;
    String serverEtag;
    String headerValue;

    headerValue = headers.get(HEADER_DATE);
    if (headerValue != null) {
        try {
            // Parse date in RFC1123 format if this header contains one
            serverDate = org.apache.commons.lang3.time.DateUtils
                    .parseDate(headerValue, "EEE, dd MMM yyyy HH:mm:ss zzz").getTime();
        } catch (ParseException e) {
            Log.e(TAG, "Error parsing date. Details: " + e.getLocalizedMessage());
            // Date in invalid format, fallback to 0
            serverDate = 0;
        }
    }

    serverEtag = headers.get(HEADER_ETAG);

    long softExpire = now + cacheHitButRefreshed;
    long ttl = now + cacheExpired;

    Cache.Entry entry = new Cache.Entry();
    entry.data = response.data;
    entry.etag = serverEtag;
    entry.softTtl = softExpire;
    entry.ttl = ttl;
    entry.serverDate = serverDate;
    entry.responseHeaders = headers;

    return entry;
}

From source file:org.polymap.core.project.ui.properties.NumberPropertyDescriptor.java

public CellEditor createPropertyEditor(Composite parent) {
    if (!editable) {
        return null;
    }//from   ww  w.ja  v a 2 s. co m
    CellEditor editor = new RWTTextCellEditor(parent) {
        protected void doSetValue(Object value) {
            if (value instanceof Number) {
                super.doSetValue(format.format(value));
            } else {
                super.doSetValue("unknown type: " + value.getClass().getSimpleName());
            }
        }

        protected Object doGetValue() {
            try {
                return format.parse((String) super.doGetValue());
            } catch (ParseException e) {
                throw new RuntimeException("should never happen: ", e);
            }
        }
    };

    editor.setValidator(new ICellEditorValidator() {
        public String isValid(Object value) {
            if (value instanceof String) {
                try {
                    format.parse((String) value);
                    return null;
                } catch (ParseException e) {
                    return e.getLocalizedMessage();
                }
            } else if (value instanceof Number) {
                return "";
            }
            return "";
        }
    });
    return editor;
}

From source file:ca.phon.app.session.RecordFilterPanel.java

/**
 * Get the defined filter//from   ww w . ja va 2 s.c  om
 */
public RecordFilter getRecordFilter() {
    RecordFilter retVal = null;

    if (allBtn.isSelected()) {
        retVal = new AbstractRecordFilter() {

            @Override
            public boolean checkRecord(Record utt) {
                return true;
            }

        };
    } else if (rangeBtn.isSelected()) {
        try {
            retVal = new RangeRecordFilter(t, rangeField.getText());
        } catch (ParseException e) {
            LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e);
        }
    } else if (speakerBtn.isSelected()) {
        retVal = new ParticipantRecordFilter(selectedParticipants);
    } else if (searchBtn.isSelected()) {
        retVal = new ResultSetRecordFilter(t, selectedSearch);
    }

    return retVal;
}