Example usage for java.text ParseException getMessage

List of usage examples for java.text ParseException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.alfresco.repo.web.scripts.calendar.AbstractCalendarWebScript.java

@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {
    Map<String, String> templateVars = req.getServiceMatch().getTemplateVars();
    if (templateVars == null) {
        String error = "No parameters supplied";
        if (useJSONErrors()) {
            return buildError(error);
        } else {//from   w  w w  .ja  v a 2 s.c  om
            throw new WebScriptException(Status.STATUS_BAD_REQUEST, error);
        }
    }

    // Parse the JSON, if supplied
    JSONObject json = null;
    String contentType = req.getContentType();
    if (contentType != null && contentType.indexOf(';') != -1) {
        contentType = contentType.substring(0, contentType.indexOf(';'));
    }
    if (MimetypeMap.MIMETYPE_JSON.equals(contentType)) {
        JSONParser parser = new JSONParser();
        try {
            json = (JSONObject) parser.parse(req.getContent().getContent());
        } catch (IOException io) {
            return buildError("Invalid JSON: " + io.getMessage());
        } catch (org.json.simple.parser.ParseException je) {
            return buildError("Invalid JSON: " + je.getMessage());
        }
    }

    // Get the site short name. Try quite hard to do so...
    String siteName = templateVars.get("siteid");
    if (siteName == null) {
        siteName = templateVars.get("site");
    }
    if (siteName == null) {
        siteName = req.getParameter("site");
    }
    if (siteName == null && json != null) {
        if (json.containsKey("siteid")) {
            siteName = (String) json.get("siteid");
        } else if (json.containsKey("site")) {
            siteName = (String) json.get("site");
        }
    }
    if (siteName == null) {
        String error = "No site given";
        if (useJSONErrors()) {
            return buildError("No site given");
        } else {
            throw new WebScriptException(Status.STATUS_BAD_REQUEST, error);
        }
    }

    // Grab the requested site
    SiteInfo site = siteService.getSite(siteName);
    if (site == null) {
        String error = "Could not find site: " + siteName;
        if (useJSONErrors()) {
            return buildError(error);
        } else {
            throw new WebScriptException(Status.STATUS_NOT_FOUND, error);
        }
    }

    // Event name is optional
    String eventName = templateVars.get("eventname");

    // Have the real work done
    return executeImpl(site, eventName, req, json, status, cache);
}

From source file:jp.terasoluna.fw.web.taglib.DateFormatterTagBase.java

/**
 * ^O]Jn?\bh?B//from   w w  w  .j a  va2  s. c  o  m
 *
 * @return ???w?B? <code>SKIP_BODY</code>
 * @throws JspException JSPO
 */
@Override
public int doStartTag() throws JspException {

    Object value = this.value;
    if (value == null) {
        // bean???Av?beanbNAbv
        // ???A^?[
        if (ignore) {
            if (TagUtil.lookup(pageContext, name, scope) == null) {
                return SKIP_BODY; // ?o
            }
        }

        // v?v?peBlbNAbv
        value = TagUtil.lookup(pageContext, name, property, scope);
        if (value == null) {
            return SKIP_BODY; // ?o
        }
    }

    // v?peBlString^xDate
    Date date = null;
    if (value instanceof String) {
        // Eg
        String trimed = StringUtil.rtrim((String) value);
        // ttH?[}bg
        String dateFormat = StringUtils.defaultIfEmpty(getFormat(), getDefaultDateFormat());

        // xDate^
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        try {
            date = sdf.parse(trimed);
        } catch (ParseException e) {
            log.error("Date parsing error.");

            throw new JspTagException(e.getMessage());
        }
    } else if (value instanceof Date) {
        date = (Date) value;
    } else {
        return SKIP_BODY; // ?o
    }

    // tH?[}bg
    String output = doFormat(date);

    if (id != null) {
        // idw?AXNveBO?p
        // y?[WXR?[vZbg?B
        pageContext.setAttribute(id, output);
    } else {
        // idw?Av?peBlC^vg
        // ?BK?tB^?B
        if (filter) {
            TagUtil.write(pageContext, TagUtil.filter(output));
        } else {
            TagUtil.write(pageContext, output);
        }
    }

    return SKIP_BODY;
}

From source file:org.artifactory.rest.resource.ci.BuildResource.java

/**
 * Promotes a build/*ww  w  .  j  ava2  s  .com*/
 *
 * @param buildName   Name of build to promote
 * @param buildNumber Number of build to promote
 * @param promotion   Promotion settings
 * @return Promotion result
 */
@POST
@Path("/promote/{buildName: .+}/{buildNumber: .+}")
@Consumes({ BuildRestConstants.MT_PROMOTION_REQUEST, MediaType.APPLICATION_JSON })
@Produces({ BuildRestConstants.MT_PROMOTION_RESULT, MediaType.APPLICATION_JSON })
public Response promote(@PathParam("buildName") String buildName, @PathParam("buildNumber") String buildNumber,
        Promotion promotion) throws IOException {

    if (authorizationService.isAnonUserAndAnonBuildInfoAccessDisabled()) {
        throw new AuthorizationRestException(anonAccessDisabledMsg);
    }
    RestAddon restAddon = addonsManager.addonByType(RestAddon.class);
    try {
        if (RestUtils.shouldDecodeParams(request)) {
            buildName = URLDecoder.decode(buildName, "UTF-8");
            buildNumber = URLDecoder.decode(buildNumber, "UTF-8");
        }
        PromotionResult promotionResult = restAddon.promoteBuild(buildName, buildNumber, promotion);
        return Response.status(
                promotionResult.errorsOrWarningHaveOccurred() ? HttpStatus.SC_BAD_REQUEST : HttpStatus.SC_OK)
                .entity(promotionResult).build();
    } catch (IllegalArgumentException | ItemNotFoundRuntimeException iae) {
        throw new BadRequestException(iae.getMessage());
    } catch (DoesNotExistException dnee) {
        throw new NotFoundException(dnee.getMessage());
    } catch (ParseException pe) {
        throw new RestException("Unable to parse given build start date: " + pe.getMessage());
    }
}

From source file:net.sourceforge.msscodefactory.cflib.v1_11.CFLib.Swing.CFJNumberEditor.java

public boolean isEditValid() {
    final String S_ProcName = "isEditValid";
    if (!hasValue()) {
        setValue(null);/*  www. j a v a 2s . com*/
        return (true);
    }

    boolean retval = super.isEditValid();
    if (retval) {
        try {
            commitEdit();
        } catch (ParseException e) {
            throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                    "Field is not valid - " + e.getMessage(), e);

        }
        Object obj = getValue();
        if (obj == null) {
            retval = false;
        } else if (obj instanceof Short) {
            Short s = (Short) obj;
            BigDecimal v;
            if (precis > 0) {
                v = new BigDecimal(s.toString() + "." + S_Zeroes.substring(0, precis));
            } else {
                v = new BigDecimal(s.toString());
            }
            BigDecimal min = getMinValue();
            BigDecimal max = getMaxValue();
            if ((v.compareTo(min) < 0) || (v.compareTo(max) > 0)) {
                retval = false;
            }
        } else if (obj instanceof Integer) {
            Integer i = (Integer) obj;
            BigDecimal v;
            if (precis > 0) {
                v = new BigDecimal(i.toString() + "." + S_Zeroes.substring(0, precis));
            } else {
                v = new BigDecimal(i.toString());
            }
            BigDecimal min = getMinValue();
            BigDecimal max = getMaxValue();
            if ((v.compareTo(min) < 0) || (v.compareTo(max) > 0)) {
                retval = false;
            }
        } else if (obj instanceof Long) {
            Long l = (Long) obj;
            BigDecimal v;
            if (precis > 0) {
                v = new BigDecimal(l.toString() + "." + S_Zeroes.substring(0, precis));
            } else {
                v = new BigDecimal(l.toString());
            }
            BigDecimal min = getMinValue();
            BigDecimal max = getMaxValue();
            if ((v.compareTo(min) < 0) || (v.compareTo(max) > 0)) {
                retval = false;
            }
        } else if (obj instanceof BigDecimal) {
            BigDecimal v = (BigDecimal) obj;
            BigDecimal min = getMinValue();
            BigDecimal max = getMaxValue();
            if ((v.compareTo(min) < 0) || (v.compareTo(max) > 0)) {
                retval = false;
            }
        } else if (obj instanceof Number) {
            Number n = (Number) obj;
            BigDecimal v = new BigDecimal(n.toString());
            BigDecimal min = getMinValue();
            BigDecimal max = getMaxValue();
            if ((v.compareTo(min) < 0) || (v.compareTo(max) > 0)) {
                retval = false;
            }
        } else {
            throw CFLib.getDefaultExceptionFactory().newUnsupportedClassException(getClass(), S_ProcName,
                    "EditedValue", obj, "Short, Integer, Long, BigDecimal or Number");
        }
    }
    return (retval);
}

From source file:org.jahia.services.importexport.FilesAclImportHandler.java

private boolean setPropertyField(ExtendedNodeType baseType, String localName, JCRNodeWrapper node,
        String propertyName, String value) throws RepositoryException {
    if (propertyName == null || "#skip".equals(propertyName)) {
        return false;
    }/*from   ww w.  j  a  v a  2s .  c  om*/
    JCRNodeWrapper parent = node;
    String mixinType = null;
    if (propertyName.contains("|")) {
        mixinType = StringUtils.substringBefore(propertyName, "|");
        propertyName = StringUtils.substringAfter(propertyName, "|");
    }
    if (StringUtils.contains(propertyName, "/")) {
        String parentPath = StringUtils.substringBeforeLast(propertyName, "/");
        if (parent.hasNode(parentPath)) {
            parent = parent.getNode(parentPath);
        }
        propertyName = StringUtils.substringAfterLast(propertyName, "/");
    }
    parent = checkoutNode(parent);
    if (!StringUtils.isEmpty(mixinType) && !parent.isNodeType(mixinType)) {
        parent.addMixin(mixinType);
    }

    ExtendedPropertyDefinition propertyDefinition = null;
    propertyDefinition = parent.getApplicablePropertyDefinition(propertyName);
    if (propertyDefinition == null) {
        return false;

    }
    if (propertyDefinition.isProtected()) {
        // System.out.println("protected : " + propertyName);
        return false;
    }
    Node n = parent;

    // System.out.println("setting " + propertyName);

    if (value != null && value.length() != 0 && !value.equals("<empty>")) {
        switch (propertyDefinition.getRequiredType()) {
        case PropertyType.DATE:
            GregorianCalendar cal = new GregorianCalendar();
            try {
                DateFormat df = new SimpleDateFormat(ImportExportService.DATE_FORMAT);
                Date d = df.parse(value);
                cal.setTime(d);
                n.setProperty(propertyName, cal);
            } catch (java.text.ParseException e) {
                logger.error(e.getMessage(), e);
            }
            break;

        default:
            switch (propertyDefinition.getSelector()) {
            case SelectorType.CATEGORY: {
                String[] cats = Patterns.COMMA.split(value);
                List<Value> values = new ArrayList<Value>();
                for (int i = 0; i < cats.length; i++) {
                    String cat = cats[i];
                    Query q = session.getWorkspace().getQueryManager()
                            .createQuery("select * from [jnt:category] as cat where NAME(cat) = '"
                                    + JCRContentUtils.sqlEncode(cat) + "'", Query.JCR_SQL2);
                    NodeIterator ni = q.execute().getNodes();
                    if (ni.hasNext()) {
                        values.add(session.getValueFactory().createValue(ni.nextNode()));
                    }
                }
                n.setProperty(propertyName, values.toArray(new Value[values.size()]));
                break;
            }
            case SelectorType.RICHTEXT: {
                n.setProperty(propertyName, value);
                break;
            }
            default: {
                String[] vcs = propertyDefinition.getValueConstraints();
                List<String> constraints = Arrays.asList(vcs);
                if (!propertyDefinition.isMultiple()) {
                    if (value.startsWith("<jahia-resource")) {
                        value = ResourceBundleMarker.parseMarkerValue(value).getResourceKey();
                        if (value.startsWith(propertyDefinition.getResourceBundleKey())) {
                            value = value.substring(propertyDefinition.getResourceBundleKey().length() + 1);
                        }
                    }
                    value = baseType != null && mapping != null
                            ? mapping.getMappedPropertyValue(baseType, localName, value)
                            : value;
                    if (constraints.isEmpty() || constraints.contains(value)) {
                        try {
                            n.setProperty(propertyName, value);
                        } catch (Exception e) {
                            logger.error(e.getMessage(), e);
                        }
                    }
                } else {
                    String[] strings = Patterns.TRIPPLE_DOLLAR.split(value);
                    List<Value> values = new ArrayList<Value>();
                    for (int i = 0; i < strings.length; i++) {
                        String string = strings[i];

                        if (string.startsWith("<jahia-resource")) {
                            string = ResourceBundleMarker.parseMarkerValue(string).getResourceKey();
                            if (string.startsWith(propertyDefinition.getResourceBundleKey())) {
                                string = string
                                        .substring(propertyDefinition.getResourceBundleKey().length() + 1);
                            }
                        }
                        value = baseType != null ? mapping.getMappedPropertyValue(baseType, localName, value)
                                : value;
                        if (constraints.isEmpty() || constraints.contains(value)) {
                            values.add(new ValueImpl(string, propertyDefinition.getRequiredType()));
                        }
                    }
                    ;
                    n.setProperty(propertyName, values.toArray(new Value[values.size()]));
                }
                break;
            }
            }
        }
    } else {
        return false;
    }

    return true;
}

From source file:fll.web.admin.UploadSubjectiveData.java

protected void processRequest(final HttpServletRequest request, final HttpServletResponse response,
        final ServletContext application, final HttpSession session) throws IOException, ServletException {

    final StringBuilder message = new StringBuilder();

    final File file = File.createTempFile("fll", null);
    Connection connection = null;
    try {//from  www . j  a  v a  2 s  .c  o m
        // must be first to ensure the form parameters are set
        UploadProcessor.processUpload(request);

        final FileItem subjectiveFileItem = (FileItem) request.getAttribute("subjectiveFile");
        subjectiveFileItem.write(file);

        final DataSource datasource = ApplicationAttributes.getDataSource(application);
        connection = datasource.getConnection();
        saveSubjectiveData(file, Queries.getCurrentTournament(connection),
                ApplicationAttributes.getChallengeDescription(application), connection, application);
        message.append("<p id='success'><i>Subjective data uploaded successfully</i></p>");
    } catch (final SAXParseException spe) {
        final String errorMessage = String.format(
                "Error parsing file line: %d column: %d%n Message: %s%n This may be caused by using the wrong version of the software attempting to parse a file that is not subjective data.",
                spe.getLineNumber(), spe.getColumnNumber(), spe.getMessage());
        message.append("<p class='error'>" + errorMessage + "</p>");
        LOGGER.error(errorMessage, spe);
    } catch (final SAXException se) {
        final String errorMessage = "The subjective scores file was found to be invalid, check that you are parsing a subjective scores file and not something else";
        message.append("<p class='error'>" + errorMessage + "</p>");
        LOGGER.error(errorMessage, se);
    } catch (final SQLException sqle) {
        message.append("<p class='error'>Error saving subjective data into the database: " + sqle.getMessage()
                + "</p>");
        LOGGER.error(sqle, sqle);
        throw new RuntimeException("Error saving subjective data into the database", sqle);
    } catch (final ParseException e) {
        message.append(
                "<p class='error'>Error saving subjective data into the database: " + e.getMessage() + "</p>");
        LOGGER.error(e, e);
        throw new RuntimeException("Error saving subjective data into the database", e);
    } catch (final FileUploadException e) {
        message.append("<p class='error'>Error processing subjective data upload: " + e.getMessage() + "</p>");
        LOGGER.error(e, e);
        throw new RuntimeException("Error processing subjective data upload", e);
    } catch (final Exception e) {
        message.append(
                "<p class='error'>Error saving subjective data into the database: " + e.getMessage() + "</p>");
        LOGGER.error(e, e);
        throw new RuntimeException("Error saving subjective data into the database", e);
    } finally {
        if (!file.delete()) {
            LOGGER.warn("Unable to delete file " + file.getAbsolutePath() + ", setting to delete on exit");
            file.deleteOnExit();
        }
        SQLFunctions.close(connection);
    }

    session.setAttribute("message", message.toString());
    response.sendRedirect(response.encodeRedirectURL("index.jsp"));
}

From source file:net.sourceforge.msscodefactory.cflib.v1_11.CFLib.Swing.CFJNumberEditor.java

public BigDecimal getNumberValue() {
    final String S_ProcName = "getNumberValue";
    BigDecimal retval;/*  ww w . ja va  2s.co m*/
    String text = getText();
    if ((text == null) || (text.length() <= 0)) {
        retval = null;
    } else {
        if (!isEditValid()) {
            throw CFLib.getDefaultExceptionFactory().newInvalidArgumentException(getClass(), S_ProcName,
                    "Field is not valid");
        }
        try {
            commitEdit();
        } catch (ParseException e) {
            throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                    "Field is not valid - " + e.getMessage(), e);

        }
        Object obj = getValue();
        if (obj == null) {
            retval = null;
        } else if (obj instanceof Short) {
            Short s = (Short) obj;
            BigDecimal v;
            if (precis > 0) {
                v = new BigDecimal(s.toString() + "." + S_Zeroes.substring(0, precis));
            } else {
                v = new BigDecimal(s.toString());
            }
            BigDecimal min = getMinValue();
            BigDecimal max = getMaxValue();
            if ((v.compareTo(min) < 0) || (v.compareTo(max) > 0)) {
                throw CFLib.getDefaultExceptionFactory().newArgumentRangeException(getClass(), S_ProcName, 0,
                        "EditedValue", v, min, max);
            }
            retval = v;
        } else if (obj instanceof Integer) {
            Integer i = (Integer) obj;
            BigDecimal v;
            if (precis > 0) {
                v = new BigDecimal(i.toString() + "." + S_Zeroes.substring(0, precis));
            } else {
                v = new BigDecimal(i.toString());
            }
            BigDecimal min = getMinValue();
            BigDecimal max = getMaxValue();
            if ((v.compareTo(min) < 0) || (v.compareTo(max) > 0)) {
                throw CFLib.getDefaultExceptionFactory().newArgumentRangeException(getClass(), S_ProcName, 0,
                        "EditedValue", v, min, max);
            }
            retval = v;
        } else if (obj instanceof Long) {
            Long l = (Long) obj;
            BigDecimal v;
            if (precis > 0) {
                v = new BigDecimal(l.toString() + "." + S_Zeroes.substring(0, precis));
            } else {
                v = new BigDecimal(l.toString());
            }
            BigDecimal min = getMinValue();
            BigDecimal max = getMaxValue();
            if ((v.compareTo(min) < 0) || (v.compareTo(max) > 0)) {
                throw CFLib.getDefaultExceptionFactory().newArgumentRangeException(getClass(), S_ProcName, 0,
                        "EditedValue", v, min, max);
            }
            retval = v;
        } else if (obj instanceof BigDecimal) {
            BigDecimal v = (BigDecimal) obj;
            BigDecimal min = getMinValue();
            BigDecimal max = getMaxValue();
            if ((v.compareTo(min) < 0) || (v.compareTo(max) > 0)) {
                throw CFLib.getDefaultExceptionFactory().newArgumentRangeException(getClass(), S_ProcName, 0,
                        "EditedValue", v, min, max);
            }
            retval = v;
        } else if (obj instanceof Number) {
            Number n = (Number) obj;
            BigDecimal v = new BigDecimal(n.toString());
            BigDecimal min = getMinValue();
            BigDecimal max = getMaxValue();
            if ((v.compareTo(min) < 0) || (v.compareTo(max) > 0)) {
                throw CFLib.getDefaultExceptionFactory().newArgumentRangeException(getClass(), S_ProcName, 0,
                        "EditedValue", v, min, max);
            }
            retval = v;
        } else {
            throw CFLib.getDefaultExceptionFactory().newUnsupportedClassException(getClass(), S_ProcName,
                    "EditedValue", obj, "Short, Integer, Long, BigDecimal or Number");
        }
    }
    return (retval);
}

From source file:org.kuali.kra.iacuc.committee.print.IacucScheduleXmlStream.java

public ScheduleMasterDataType setScheduleMasterData(CommitteeScheduleBase scheduleDetailsBean,
        ScheduleMasterDataType scheduleMasterDataType) {
    scheduleDetailsBean.refreshNonUpdateableReferences();
    String committeeId = scheduleDetailsBean.getParentCommittee().getCommitteeId();
    scheduleMasterDataType.setScheduleId(scheduleDetailsBean.getScheduleId());
    scheduleMasterDataType.setCommitteeId(committeeId);
    scheduleMasterDataType.setCommitteeName(scheduleDetailsBean.getParentCommittee().getCommitteeName());
    scheduleMasterDataType//w  w w .  j a va  2  s . c o m
            .setScheduleStatusCode(BigInteger.valueOf(scheduleDetailsBean.getScheduleStatusCode()));
    scheduleMasterDataType.setScheduleStatusDesc(scheduleDetailsBean.getScheduleStatus().getDescription());
    if (scheduleDetailsBean.getScheduledDate() != null) {
        scheduleMasterDataType
                .setScheduledDate(getDateTimeService().getCalendar(scheduleDetailsBean.getScheduledDate()));
    } else {
        scheduleMasterDataType.setScheduledDate(getDateTimeService().getCurrentCalendar());
    }
    try {
        if (scheduleDetailsBean.getTime() != null) {
            Date date;
            date = getDateTimeService().convertToSqlDate(scheduleDetailsBean.getTime());
            scheduleMasterDataType.setScheduledTime(getDateTimeService().getCalendar(date));
        }

        scheduleMasterDataType.setPlace(scheduleDetailsBean.getPlace());

        if (scheduleDetailsBean.getProtocolSubDeadline() != null) {
            scheduleMasterDataType.setProtocolSubDeadline(
                    getDateTimeService().getCalendar(scheduleDetailsBean.getProtocolSubDeadline()));
        }
        if (scheduleDetailsBean.getMeetingDate() != null) {
            scheduleMasterDataType
                    .setMeetingDate(getDateTimeService().getCalendar(scheduleDetailsBean.getMeetingDate()));
        }

        if (scheduleDetailsBean.getStartTime() != null) {
            scheduleMasterDataType.setStartTime(getDateTimeService()
                    .getCalendar(getDateTimeService().convertToSqlDate(scheduleDetailsBean.getStartTime())));
        }

        if (scheduleDetailsBean.getEndTime() != null) {
            scheduleMasterDataType.setEndTime(getDateTimeService()
                    .getCalendar(getDateTimeService().convertToSqlDate(scheduleDetailsBean.getEndTime())));
        }
        if (scheduleDetailsBean.getAgendaProdRevDate() != null) {
            scheduleMasterDataType.setAgendaProdRevDate(
                    getDateTimeService().getCalendar(scheduleDetailsBean.getAgendaProdRevDate()));
        }
    } catch (ParseException e) {
        LOG.error(e.getMessage(), e);
    }

    scheduleMasterDataType
            .setMaxProtocols(new BigInteger(String.valueOf(scheduleDetailsBean.getMaxProtocols())));
    if (scheduleDetailsBean.getComments() != null) {
        scheduleMasterDataType.setComments(scheduleDetailsBean.getComments());
    }

    return scheduleMasterDataType;
}

From source file:jp.classmethod.aws.brian.web.TriggerController.java

/**
 * Create trigger.// ww  w.j a  va 2  s. co m
 * 
 * @param triggerGroupName groupName
 * @return trigger names
 * @throws SchedulerException
 */
@ResponseBody
@RequestMapping(value = "/triggers/{triggerGroupName}", method = RequestMethod.POST)
public ResponseEntity<?> createTrigger(@PathVariable("triggerGroupName") String triggerGroupName,
        @RequestBody BrianTriggerRequest triggerRequest) throws SchedulerException {
    logger.info("createTrigger {}.{}", triggerGroupName, triggerRequest.getTriggerName());
    logger.info("{}", triggerRequest);

    String triggerName = triggerRequest.getTriggerName();
    if (Strings.isNullOrEmpty(triggerName)) {
        return new ResponseEntity<>(new BrianResponse<>(false, "triggerName is not found"),
                HttpStatus.BAD_REQUEST);
    }

    try {
        TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
        if (scheduler.checkExists(triggerKey)) {
            String message = String.format("trigger %s.%s already exists.", triggerGroupName, triggerName);
            return new ResponseEntity<>(new BrianResponse<>(false, message), HttpStatus.CONFLICT);
        }

        Trigger trigger = getTrigger(triggerRequest, triggerKey);

        Date nextFireTime = scheduler.scheduleJob(trigger);
        logger.info("scheduled {}", triggerKey);

        SimpleDateFormat df = CalendarUtil.newSimpleDateFormat(TimePoint.ISO8601_FORMAT_UNIVERSAL, Locale.US,
                TimeZones.UNIVERSAL);
        Map<String, Object> map = new HashMap<>();
        map.put("nextFireTime", df.format(nextFireTime));
        return new ResponseEntity<>(new BrianResponse<>(true, "created", map), HttpStatus.CREATED); // TODO return URI
    } catch (ParseException e) {
        logger.warn("parse cron expression failed", e);
        String message = "parse cron expression failed - " + e.getMessage();
        return ResponseEntity.badRequest().body(new BrianResponse<>(false, message));
    }
}

From source file:jp.classmethod.aws.brian.web.TriggerController.java

/**
 * Update the trigger./*from w  w w  . j a v  a2s .co  m*/
 * 
 * @param triggerGroupName trigger group name
 * @param triggerName trigger name
 * @param triggerRequest triggerRequest
 * @return {@link HttpStatus#CREATED} if the trigger is created, {@link HttpStatus#OK} if the trigger is updated.
 *   And nextFireTime property which is represent that the trigger's next fire time.
 * @throws SchedulerException
 */
@ResponseBody
@RequestMapping(value = "/triggers/{triggerGroupName}/{triggerName}", method = RequestMethod.PUT)
public ResponseEntity<?> updateTrigger(@PathVariable("triggerGroupName") String triggerGroupName,
        @PathVariable("triggerName") String triggerName, @RequestBody BrianTriggerRequest triggerRequest)
        throws SchedulerException {
    logger.info("updateTrigger {}.{}: {}", triggerGroupName, triggerName, triggerRequest);

    if (triggerName.equals(triggerRequest.getTriggerName()) == false) {
        String message = String.format(
                "trigger names '%s' in the path and '%s' in the request body is not equal", triggerName,
                triggerRequest.getTriggerName());
        return ResponseEntity.badRequest().body(new BrianResponse<>(false, message));
    }

    try {
        TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
        if (scheduler.checkExists(triggerKey) == false) {
            String message = String.format("trigger %s.%s is not found.", triggerGroupName, triggerName);
            return new ResponseEntity<>(new BrianResponse<>(false, message), HttpStatus.NOT_FOUND);
        }

        Trigger trigger = getTrigger(triggerRequest, triggerKey);

        Date nextFireTime = scheduler.rescheduleJob(triggerKey, trigger);
        logger.info("rescheduled {}", triggerKey);

        Map<String, Object> map = new HashMap<>();
        map.put("nextFireTime",
                new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US).format(nextFireTime));
        return ResponseEntity.ok(new BrianResponse<>(true, "ok", map));
    } catch (ParseException e) {
        logger.warn("parse cron expression failed", e);
        String message = "parse cron expression failed - " + e.getMessage();
        return ResponseEntity.badRequest().body(new BrianResponse<>(false, message));
    }
}