Example usage for java.text NumberFormat parse

List of usage examples for java.text NumberFormat parse

Introduction

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

Prototype

public Number parse(String source) throws ParseException 

Source Link

Document

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

Usage

From source file:web.DeletesharecontactController.java

/**
 * This method is called by the spring framework. The configuration
 * for this controller to be invoked is based on the pagetype and
 * is set in the urlMapping property in the spring config file.
 *
 * @param request the <code>HttpServletRequest</code>
 * @param response the <code>HttpServletResponse</code>
 * @throws ServletException//from  w  w  w .j  av  a  2s  .  c  om
 * @throws IOException
 * @return ModelAndView this instance is returned to spring
 */
public synchronized ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // ***************************************************************************
    // This is the only line of code you need to get all session info initialized!
    // Always be the first line before anything else is done. Add to each controller's
    // handlRequest method. Also remember to extend SessionObject.
    // ***************************************************************************
    //initSession(request, response);

    try {
        ModelAndView m = super.handleRequest(request, response);
    } catch (Exception e) {
        return handleError("error in handleRequest", e);
    }

    outOfSession(request, response);

    if (RegexStrUtil.isNull(login) || RegexStrUtil.isNull(member) || (loginInfo == null)) {
        return handleError("Login/member/loginInfo are null, DeletesharecontactController.");
    }

    String contactId = request.getParameter(DbConstants.CONTACT_ID);
    if (RegexStrUtil.isNull(contactId)) {
        return handleError("contactId is null, in DeletesharecontactController " + member);
    }
    contactId = RegexStrUtil.goodNameStr(contactId);

    try {
        NumberFormat nf = NumberFormat.getInstance();
        Number myNum = nf.parse(contactId);
    } catch (ParseException e) {
        return handleError("contactId has other than [0-9] characters, DeletesharecontactController.", e);
    }

    if (getDaoMapper() == null) {
        return handleError("DaoMapper is null, DeletesharecontactController." + login);
    }
    ContactDao contactDao = (ContactDao) getDaoMapper().getDao(DbConstants.CONTACT);
    if (contactDao == null) {
        return handleError("ContactDao is null, in DeletesharecontactController." + login);
    }

    /**
     *  Get the members login information
     */
    MemberDao myMemberDao = (MemberDao) daoMapper.getDao(DbConstants.MEMBER);
    if (myMemberDao == null) {
        return handleError("MemberDao is null in DeletesharecontactController member, " + member);
    }
    Hdlogin memberInfo = null;
    try {
        memberInfo = myMemberDao.getMemberInfo(member);
    } catch (BaseDaoException e) {
        return handleError(
                "Exception occured in getMemberInfo(), of DeletesharecontactController for member " + member,
                e);
    }
    if (memberInfo == null) {
        return handleError("memberInfo is null.");
    }

    String fname = request.getParameter(DbConstants.FIRST_NAME);
    String lname = request.getParameter(DbConstants.LAST_NAME);
    String alphabet = "";

    if (!RegexStrUtil.isNull(fname)) {
        if (!RegexStrUtil.isNull(fname) && (fname.length() > GlobalConst.firstNameSize)) {
            fname = fname.substring(0, GlobalConst.firstNameSize);
        }
        alphabet = fname.substring(0, 1);
    } else {
        if (!RegexStrUtil.isNull(lname)) {
            if (!RegexStrUtil.isNull(lname) && (lname.length() > GlobalConst.lastNameSize)) {
                lname = lname.substring(0, GlobalConst.lastNameSize);
            }
            alphabet = lname.substring(0, 1);
        }
    }
    List contacts = null;
    List sharedContacts = null;
    try {
        contactDao.deleteShareContact(loginInfo.getValue(DbConstants.LOGIN_ID), contactId, member, alphabet);
        contacts = contactDao.getAllContacts(loginInfo.getValue(DbConstants.LOGIN_ID),
                DbConstants.READ_FROM_MASTER);
        sharedContacts = contactDao.getSharedContacts(loginInfo.getValue(DbConstants.LOGIN_ID));
    } catch (BaseDaoException e) {
        return handleError(
                "Exception in deleteShareContact(), DeletesharecontactController, for member " + member, e);
    }

    /** 
     * cobrand
     */
    Userpage cobrand = null;
    CobrandDao cobrandDao = (CobrandDao) getDaoMapper().getDao(DbConstants.COBRAND);
    if (cobrandDao == null) {
        return handleError("CobrandDao is null, DeletesharecontactController");
    }
    try {
        cobrand = cobrandDao.getUserCobrand(loginInfo.getValue(DbConstants.LOGIN_ID));
    } catch (BaseDaoException e) {
        return handleError("cobrand is null, DeletesharecontactController", e);
    }

    String viewName = "showcontacts";
    Map myModel = new HashMap();
    myModel.put(DbConstants.COBRAND, cobrand);
    myModel.put(DbConstants.LOGIN_INFO, loginInfo);
    myModel.put(DbConstants.MEMBER_INFO, memberInfo);
    myModel.put(DbConstants.CONTACTS, contacts);
    myModel.put(DbConstants.PUBLISHED, "0");
    myModel.put(DbConstants.SHARED_CONTACTS, sharedContacts);
    myModel.put(DbConstants.HIGHLIGHT, "all");
    myModel.put(DbConstants.VISITOR_PAGE, memberUserpage);
    myModel.put(DbConstants.USER_PAGE, userpage);
    myModel.put(DbConstants.SHARE_INFO, shareInfo);
    myModel.put(DbConstants.BUSINESS_EXISTS, isBizExists(login));
    return new ModelAndView(viewName, "model", myModel);
}

From source file:org.jbpm.bpel.tutorial.atm.terminal.DepositAction.java

public void actionPerformed(ActionEvent event) {
    Map context = AtmTerminal.getContext();
    AtmPanel atmPanel = (AtmPanel) context.get(AtmTerminal.PANEL);

    // capture amount
    NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
    String amountText = JOptionPane.showInputDialog(atmPanel, "Amount", currencyFormat.format(0.0));
    if (amountText == null)
        return;//from   w ww .ja v a  2s .  com

    try {
        // parse amount
        double amount = currencyFormat.parse(amountText).doubleValue();

        // deposit funds to account
        FrontEnd atmFrontEnd = (FrontEnd) context.get(AtmTerminal.FRONT_END);
        String customerName = (String) context.get(AtmTerminal.CUSTOMER);
        double balance = atmFrontEnd.deposit(customerName, amount);

        // update atm panel
        atmPanel.setMessage("Your balance is " + currencyFormat.format(balance));
    } catch (ParseException e) {
        log.debug("invalid amount", e);
        atmPanel.setMessage("Please enter a valid amount.");
    } catch (RemoteException e) {
        log.error("remote operation failure", e);
        atmPanel.setMessage("Communication with the bank failed.\n" + "Please log on again.");
        atmPanel.clearActions();
        atmPanel.addAction(new LogOnAction());
        atmPanel.setStatus("connected");
    }
}

From source file:web.SharecontactController.java

/**
 * This method is called by the spring framework. The configuration
 * for this controller to be invoked is based on the pagetype and
 * is set in the urlMapping property in the spring config file.
 *
 * @param request the <code>HttpServletRequest</code>
 * @param response the <code>HttpServletResponse</code>
 * @throws ServletException//from   w w w  . jav  a2s . c o m
 * @throws IOException
 * @return ModelAndView this instance is returned to spring
 */
public synchronized ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // ***************************************************************************
    // This is the only line of code you need to get all session info initialized!
    // Always be the first line before anything else is done. Add to each controller's
    // handlRequest method. Also remember to extend SessionObject.
    // ***************************************************************************

    try {
        ModelAndView m = super.handleRequest(request, response);
    } catch (Exception e) {
        return handleError("error in handleRequest");
    }

    outOfSession(request, response);

    if (RegexStrUtil.isNull(login) || RegexStrUtil.isNull(member) || (loginInfo == null)) {
        return handleUserpageError("Login/member/loginInfo is null, SharecontactController.");
    }

    String contactId = request.getParameter(DbConstants.CONTACT_ID);
    if (RegexStrUtil.isNull(contactId)) {
        return handleError("contactId is null, SharecontactController");
    }
    if (contactId.length() > GlobalConst.contactIdSize) {
        return handleError("contactId.length > WebConstants.contactIdSize, SharecontactController");
    }
    try {
        NumberFormat nf = NumberFormat.getInstance();
        Number myNum = nf.parse(contactId);
    } catch (ParseException e) {
        return handleError("contactId has other than [0-9] characters, SharecontactController", e);
    }
    contactId = RegexStrUtil.goodNameStr(contactId);

    String fname = request.getParameter(DbConstants.FIRST_NAME);
    if (!RegexStrUtil.isNull(fname) && (fname.length() > GlobalConst.firstNameSize)) {
        fname = fname.substring(0, GlobalConst.firstNameSize);
    }

    String lname = request.getParameter(DbConstants.LAST_NAME);
    if (!RegexStrUtil.isNull(lname) && (lname.length() > GlobalConst.lastNameSize)) {
        lname = lname.substring(0, GlobalConst.lastNameSize);
    }

    String alphabet = "";
    if (!RegexStrUtil.isNull(fname)) {
        alphabet = fname.substring(0, 1);
    } else {
        if (!RegexStrUtil.isNull(lname)) {
            alphabet = lname.substring(0, 1);
        }
    }

    if (getDaoMapper() == null) {
        return handleError("DaoMapper is null, SharecontactController." + login);
    }
    ContactDao contactDao = (ContactDao) getDaoMapper().getDao(DbConstants.CONTACT);
    if (contactDao == null) {
        return handleError("ContactDao is null, in SharecontactController." + login);
    }

    List contacts = null;
    List sharedContacts = null;
    try {
        contactDao.shareContact(contactId, loginInfo.getValue(DbConstants.LOGIN_ID), member, alphabet);
        contacts = contactDao.getAllContacts(loginInfo.getValue(DbConstants.LOGIN_ID),
                DbConstants.READ_FROM_MASTER);
        sharedContacts = contactDao.getSharedContacts(loginInfo.getValue(DbConstants.LOGIN_ID));
    } catch (BaseDaoException e) {
        return handleError("Exception in shareOneContact(), SharecontactController, for member " + member, e);
    }

    /** 
     * cobrand
     */
    Userpage cobrand = null;
    CobrandDao cobrandDao = (CobrandDao) getDaoMapper().getDao(DbConstants.COBRAND);
    if (cobrandDao == null) {
        return handleError("CobrandDao is null, SharecontactController");
    }
    try {
        cobrand = cobrandDao.getUserCobrand(loginInfo.getValue(DbConstants.LOGIN_ID));
    } catch (BaseDaoException e) {
        return handleError("cobrand is null, SharecontactController", e);
    }

    /**
     *  Get the members login information
     */
    MemberDao myMemberDao = (MemberDao) daoMapper.getDao(DbConstants.MEMBER);
    if (myMemberDao == null) {
        return handleError("MemberDao is null in ShareuserController member, " + member);
    }
    Hdlogin memberInfo = null;
    try {
        memberInfo = myMemberDao.getMemberInfo(member);
    } catch (BaseDaoException e) {
        return handleError("Exception occured in getMemberInfo(), of ShareuserController for member " + member,
                e);
    }
    if (memberInfo == null) {
        return handleError("memberInfo is null.");
    }

    String viewName = "showcontacts";
    Map myModel = new HashMap();
    myModel.put(DbConstants.COBRAND, cobrand);
    myModel.put(DbConstants.PUBLISHED, "0");
    myModel.put(DbConstants.LOGIN_INFO, loginInfo);
    myModel.put(DbConstants.CONTACTS, contacts);
    myModel.put(DbConstants.MEMBER_INFO, memberInfo);
    myModel.put(DbConstants.SHARED_CONTACTS, sharedContacts);
    myModel.put(DbConstants.HIGHLIGHT, "all");
    myModel.put(DbConstants.DIR_EXISTS, rbDirectoryExists);
    myModel.put(DbConstants.USER_PAGE, userpage);
    myModel.put(DbConstants.SHARE_INFO, shareInfo);
    myModel.put(DbConstants.VISITOR_PAGE, memberUserpage);
    myModel.put(DbConstants.BUSINESS_EXISTS, isBizExists(login));
    return new ModelAndView(viewName, "model", myModel);
}

From source file:web.ClonesharedcontactController.java

/**
 * This method is called by the spring framework. The configuration
 * for this controller to be invoked is based on the pagetype and
 * is set in the urlMapping property in the spring config file.
 *
 * @param request the <code>HttpServletRequest</code>
 * @param response the <code>HttpServletResponse</code>
 * @throws ServletException//w w w.jav a  2  s  . co m
 * @throws IOException
 * @return ModelAndView this instance is returned to spring
 */
public synchronized ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // ***************************************************************************
    // This is the only line of code you need to get all session info initialized!
    // Always be the first line before anything else is done. Add to each controller's
    // handlRequest method. Also remember to extend SessionObject.
    // ***************************************************************************

    try {
        ModelAndView m = super.handleRequest(request, response);
    } catch (Exception e) {
        return handleError("error in handleRequest", e);
    }

    outOfSession(request, response);
    if (!WebUtil.isLicenseProfessional(login)) {
        return handleError("Cannot access this feature in deluxe version.");
    }

    if (RegexStrUtil.isNull(login) || (loginInfo == null)) {
        return handleUserpageError("Login/loginInfo is null in ClonesharedcontactController.");
    }

    String ownerId = request.getParameter(DbConstants.OWNER_ID);
    if (RegexStrUtil.isNull(ownerId)) {
        return handleError("ownerId is null, in ClonesharedcontactController");
    }

    String contactId = request.getParameter(DbConstants.CONTACT_ID);
    if (RegexStrUtil.isNull(contactId)) {
        return handleError("contactId is null, in ClonesharedcontactController");
    }

    NumberFormat nf = NumberFormat.getInstance();
    try {
        Number myNum = nf.parse(contactId);
    } catch (ParseException e) {
        return handleError("contactId has other than [0-9] characters, DeletecontactController.", e);
    }

    String fname = request.getParameter(DbConstants.FIRST_NAME);
    if (!RegexStrUtil.isNull(fname) && (fname.length() > GlobalConst.firstNameSize)) {
        fname = fname.substring(0, GlobalConst.firstNameSize);
    }

    String lname = request.getParameter(DbConstants.LAST_NAME);
    if (!RegexStrUtil.isNull(lname) && (lname.length() > GlobalConst.lastNameSize)) {
        lname = lname.substring(0, GlobalConst.lastNameSize);
    }

    if (getDaoMapper() == null) {
        return handleError("DaoMapper is null, in ClonesharedcontactController." + login);
    }
    ContactDao contactDao = (ContactDao) getDaoMapper().getDao(DbConstants.CONTACT);
    if (contactDao == null) {
        return handleError("ContactDao is null, in ClonesharedcontactController." + login);
    }

    List contacts = null;
    List sharedContacts = null;
    try {
        String alphabet = "a";
        if (!RegexStrUtil.isNull(fname)) {
            alphabet = fname.substring(0, 1);
        } else {
            if (!RegexStrUtil.isNull(lname)) {
                alphabet = lname.substring(0, 1);
            }
        }

        try {
            Number myNum = nf.parse(ownerId);
        } catch (ParseException e) {
            return handleError("ownerId has other than [0-9] characters, DeletecontactController.", e);
        }

        contactDao.cloneSharedContact(contactId, ownerId, loginInfo.getValue(DbConstants.LOGIN_ID), alphabet);
        contacts = contactDao.getAllContacts(loginInfo.getValue(DbConstants.LOGIN_ID),
                DbConstants.READ_FROM_MASTER);
        sharedContacts = contactDao.getSharedContacts(loginInfo.getValue(DbConstants.LOGIN_ID));
    } catch (BaseDaoException e) {
        return handleError("Exception in cloneOneContact(), ClonesharedcontactController, for login " + login,
                e);
    }

    /** 
     * cobrand
     */
    Userpage cobrand = null;
    CobrandDao cobrandDao = (CobrandDao) getDaoMapper().getDao(DbConstants.COBRAND);
    if (cobrandDao == null) {
        return handleError("CobrandDao is null, ClonesharedcontactController");
    }
    try {
        cobrand = cobrandDao.getUserCobrand(loginInfo.getValue(DbConstants.LOGIN_ID));
    } catch (BaseDaoException e) {
        return handleError("cobrand is null, ClonesharedcontactController.", e);
    }

    String viewName = "showcontacts";
    Map myModel = new HashMap();
    myModel.put(DbConstants.COBRAND, cobrand);
    myModel.put(DbConstants.LOGIN_INFO, loginInfo);
    myModel.put(DbConstants.CONTACTS, contacts);
    myModel.put(DbConstants.SHARED_CONTACTS, sharedContacts);
    myModel.put(DbConstants.PUBLISHED, "0");
    myModel.put(DbConstants.HIGHLIGHT, "all");
    myModel.put(DbConstants.DIR_EXISTS, rbDirectoryExists);
    myModel.put(DbConstants.USER_PAGE, userpage);
    myModel.put(DbConstants.SHARE_INFO, shareInfo);
    myModel.put(DbConstants.VISITOR_PAGE, memberUserpage);
    myModel.put(DbConstants.BUSINESS_EXISTS, isBizExists(login));
    return new ModelAndView(viewName, "model", myModel);
}

From source file:org.jbpm.bpel.tutorial.atm.terminal.WithdrawAction.java

public void actionPerformed(ActionEvent event) {
    Map context = AtmTerminal.getContext();
    AtmPanel atmPanel = (AtmPanel) context.get(AtmTerminal.PANEL);

    // capture amount
    NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
    String amountText = JOptionPane.showInputDialog(atmPanel, "Amount", currencyFormat.format(0.0));
    if (amountText == null)
        return;//w ww. j  av a 2  s .  co m

    try {
        // parse amount
        double amount = currencyFormat.parse(amountText).doubleValue();

        // withdraw funds from account
        FrontEnd atmFrontEnd = (FrontEnd) context.get(AtmTerminal.FRONT_END);
        String customerName = (String) context.get(AtmTerminal.CUSTOMER);
        double balance = atmFrontEnd.withdraw(customerName, amount);

        // update atm panel
        atmPanel.setMessage("Your new balance is " + currencyFormat.format(balance));
    } catch (ParseException e) {
        log.debug("invalid amount", e);
        atmPanel.setMessage("Please enter a valid amount.");
    } catch (InsufficientFunds e) {
        log.debug("insufficient funds", e);
        atmPanel.setMessage("I could not fulfill your request.\n" + "Your current balance is only "
                + currencyFormat.format(e.getAmount()));
    } catch (RemoteException e) {
        log.error("remote operation failure", e);
        atmPanel.setMessage("Communication with the bank failed.\n" + "Please log on again.");
        atmPanel.clearActions();
        atmPanel.addAction(new LogOnAction());
        atmPanel.setStatus("connected");
    }
}

From source file:org.kuali.rice.core.web.format.CurrencyFormatter.java

/**
 * begin Kuali Foundation modification//from  ww  w  .  j a v  a  2 s  . c om
 * Unformats its argument and returns a KualiDecimal instance initialized with the resulting string value
 *
 * @see org.kuali.rice.core.web.format.Formatter#convertToObject(java.lang.String)
 * end Kuali Foundation modification
 */
@Override
protected Object convertToObject(String target) {
    // begin Kuali Foundation modification
    KualiDecimal value = null;

    LOG.debug("convertToObject '" + target + "'");

    if (target != null) {
        target = target.trim();

        String rawString = target;

        // parseable values are $1.23 and ($1.23), not (1.23)
        if (target.startsWith("(")) {
            if (!target.startsWith("($")) {
                target = "($" + StringUtils.substringAfter(target, "(");
            }
        }

        // Insert currency symbol if absent
        if (!(target.startsWith("(") || target.startsWith(getSymbol()))) {
            target = interpolateSymbol(target);
        }

        // preemptively detect non-numeric-related symbols, since NumberFormat.parse seems to be silently deleting them
        // (i.e. 9aaaaaaaaaaaaaaa is silently converted into 9)
        if (!CURRENCY_PATTERN.matcher(target).matches()) {
            throw new FormatException("parsing", RiceKeyConstants.ERROR_CURRENCY, rawString);
        }

        // preemptively detect String with excessive digits after the decimal, to prevent them from being silently rounded
        if (rawString.contains(".") && !TRAILING_DECIMAL_PATTERN
                .matcher(target.substring(target.indexOf("."), target.length())).matches()) {
            throw new FormatException("parsing", RiceKeyConstants.ERROR_CURRENCY_DECIMAL, rawString);
        }

        // actually reformat the numeric value
        NumberFormat formatter = getCurrencyInstanceUsingParseBigDecimal();
        try {
            Number parsedNumber = formatter.parse(target);
            value = new KualiDecimal(parsedNumber.toString());
        } catch (NumberFormatException e) {
            throw new FormatException("parsing", RiceKeyConstants.ERROR_CURRENCY, rawString, e);
        } catch (ParseException e) {
            throw new FormatException("parsing", RiceKeyConstants.ERROR_CURRENCY, rawString, e);
        }
    }

    return value;
    // end Kuali Foundation modification
}

From source file:org.dataone.proto.trove.mn.rest.v1.ExceptionController.java

@RequestMapping(value = "/{errorId}", method = RequestMethod.GET)
public void get(HttpServletRequest request, HttpServletResponse response, @PathVariable String errorId)
        throws NotFound, ServiceFailure, NotImplemented, InvalidRequest, InvalidCredentials, NotAuthorized,
        AuthenticationTimeout, InsufficientResources {

    int status = 500;
    log.info("received error of " + errorId);
    NumberFormat nf = NumberFormat.getInstance();
    nf.setParseIntegerOnly(true);/*from   w w  w.  j  av a2  s . c  om*/
    try {
        Number nstatus = nf.parse(errorId);
        status = nstatus.intValue();
    } catch (ParseException ex) {
        throw new ServiceFailure("500", "Could not determine the server error thrown");
    }
    response.setStatus(status);
    switch (status) {
    case 400: {
        throw new InvalidRequest("400",
                "Bad Request: The request could not be understood by the server due to malformed syntax.");
    }
    case 401: {
        throw new InvalidCredentials("401", "Unauthorized: The request requires user authentication.");
    }
    case 403: {
        throw new NotAuthorized("403",
                "Forbidden: The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated.");
    }
    case 404: {
        throw new NotFound("404", "Not Found: The server has not found anything matching the Request-URI.");
    }
    case 405: {
        throw new InvalidRequest("405",
                "Method Not Allowed: The method specified in the Request-Line is not allowed for the resource identified by the Request-URI.");
    }
    case 406: {
        throw new InvalidRequest("406",
                "Not Acceptable: The resource identified by the request is only capable of generating response entities which have content characteristics not acceptable according to the accept headers sent in the request.");
    }
    case 407: {
        throw new NotAuthorized("407",
                "Proxy Authentication Required: The client must first authenticate itself with the proxy.");
    }
    case 408: {
        throw new AuthenticationTimeout("408",
                "Request Timeout: The client did not produce a request within the time that the server was prepared to wait.");
    }
    case 409: {
        throw new InvalidRequest("409",
                "Conflict: The request could not be completed due to a conflict with the current state of the resource.");
    }
    case 410: {
        throw new NotFound("410",
                "Gone: The requested resource is no longer available at the server and no forwarding address is known.");
    }
    case 411: {
        throw new InvalidRequest("411",
                "Length Required: The server refuses to accept the request without a defined Content-Length.");
    }
    case 412: {
        throw new InvalidRequest("412",
                "Precondition Failed: The precondition given in one or more of the request-header fields evaluated to false when it was tested on the server.");
    }
    case 413: {
        throw new InsufficientResources("413",
                "Request Entity Too Large: The server is refusing to process a request because the request entity is larger than the server is willing or able to process.");
    }
    case 414: {
        throw new InvalidRequest("414",
                "Request-URI Too Long: The server is refusing to service the request because the Request-URI is longer than the server is willing to interpret.");
    }
    case 415: {
        throw new InvalidRequest("415",
                "Unsupported Media Type: The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method.");
    }
    case 416: {
        throw new InvalidRequest("416",
                "Requested Range Not Satisfiable: A server SHOULD return a response with this status code if a request included a Range request-header field.");
    }
    case 417: {
        throw new InvalidRequest("417",
                "Expectation Failed: The expectation given in an Expect request-header field could not be met by this server.");
    }
    case 500: {
        throw new ServiceFailure("500",
                "Internal Server Error: The server encountered an unexpected condition which prevented it from fulfilling the request.");
    }
    case 501: {
        throw new NotImplemented("501",
                "Not Implemented: The server does not support the functionality required to fulfill the request.");
    }
    case 502: {
        throw new ServiceFailure("502",
                "Bad Gateway: The server, while acting as a gateway or proxy, received an invalid response from the upstream server it accessed in attempting to fulfill the request.");
    }
    case 503: {
        throw new ServiceFailure("503",
                "Service Unavailable: The server is currently unable to handle the request due to a temporary overloading or maintenance of the server.");
    }
    case 504: {
        throw new ServiceFailure("504",
                "Gateway Timeout: The server, while acting as a gateway or proxy, did not receive a timely response from the upstream server specified by the URI (e.g. HTTP, FTP, LDAP) or some other auxiliary server (e.g. DNS) it needed to access in attempting to complete the request.");
    }
    case 505: {
        throw new ServiceFailure("505",
                "HTTP Version Not Supported: The server does not support, or refuses to support, the HTTP protocol version that was used in the request message.");
    }
    default: {
        throw new ServiceFailure("500", "Could not determine the server error thrown");
    }
    }

    //            this.writeToResponse(errorXml.getInputStream(), response.getOutputStream());
}

From source file:ru.iris.noolite4j.gateway.HTTPCommand.java

/**
 *   ? ??/*from www . j a va 2s  .c o  m*/
 * @return ?? ??
 */
public List<Sensor> getSensors() {
    List<Sensor> sensors = new ArrayList<>();

    try {

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse("http://" + PR1132.getHost() + "/sens.xml");

        doc.getDocumentElement().normalize();

        String text = doc.getDocumentElement().getTextContent();
        String[] values = text.split("\n");

        for (int idx = 1; idx <= values.length - 1; idx++) {
            if (values[idx].isEmpty())
                continue;

            double value = 0;

            if (!values[idx].equals("-")) {
                NumberFormat format = NumberFormat.getInstance();
                Number number = format.parse(values[idx]);
                value = number.doubleValue();
            }

            /**
             * ?   ?? ?  ??
             */

            byte channel = 0;

            if (idx <= 3)
                channel = 1;
            else if (idx >= 4 && idx <= 6)
                channel = 2;
            else if (idx >= 7 && idx <= 9)
                channel = 3;
            else if (idx >= 10 && idx <= 12)
                channel = 4;

            Sensor sensor;

            if (sensors.size() >= channel) {
                sensor = sensors.get(channel - 1);
            } else {
                sensor = new Sensor();
            }

            if (sensor == null)
                sensor = new Sensor();

            sensor.setChannel(channel);

            /**
             *   
             */

            if (idx == 1 || idx == 4 || idx == 7 || idx == 10) {
                value /= 10;
                sensor.setTemperature(value);
            } else if (idx == 2 || idx == 5 || idx == 8 || idx == 11) {
                sensor.setHumidity((byte) value);
            } else if (idx == 3 || idx == 6 || idx == 9 || idx == 12) {
                sensor.setState(SensorState.values()[(int) value]);
            }

            boolean isNew = true;

            for (int i = 0; i < sensors.size(); i++) {
                if (sensors.get(i).getChannel() == sensor.getChannel()) {
                    sensors.remove(i);
                    sensors.add(i, sensor);
                    isNew = false;
                }
            }

            if (isNew) {
                sensors.add(sensor);
            }
        }
    } catch (Exception e) {
        LOGGER.error("   ?   PR1132: "
                + e.getMessage());
        e.printStackTrace();
    }

    return sensors;

}

From source file:xml.sk.Parser.java

/**
 * Parses SectorSk.xml.//from  w  w w .  j a v  a2 s .  com
 *
 * @param manager sector manager to store data
 * @throws javax.xml.parsers.ParserConfigurationException
 * @throws org.xml.sax.SAXException
 * @throws java.io.IOException
 */
public void parseSectorSk(SectorManagerImpl manager)
        throws ParserConfigurationException, SAXException, IOException, ParseException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse("src/main/java/xml/sk/SectorSk.xml");

    NodeList sectorList = doc.getElementsByTagName("PRAC_mzdyNace");
    for (int i = 0; i < sectorList.getLength(); i++) {
        Element sectorNode = (Element) sectorList.item(i);

        String name = sectorNode.getElementsByTagName("UKAZ2").item(0).getTextContent();
        String[] splited = name.split(" ", 2);

        NodeList years = sectorNode.getChildNodes();

        for (int j = 0; j < years.getLength(); j++) {
            if (years.item(j).getNodeType() == Node.TEXT_NODE) {
                continue;
            }
            Element yearNode = (Element) years.item(j);
            if ("UKAZ2".equals(yearNode.getNodeName()))
                continue;

            String year = yearNode.getNodeName().substring(1);
            if (".".equals(yearNode.getTextContent())) {
                continue;
            }
            String salaryStr = yearNode.getTextContent().replaceAll(" ", "");
            NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
            Number number = format.parse(salaryStr);
            double salaryDouble = number.doubleValue();

            Sector sector = new Sector();
            sector.setCode(splited[0]);
            sector.setName(splited[1]);
            sector.setCountry("sk");
            sector.setYear(year);
            sector.setAverageSalary(salaryDouble);

            manager.createSector(sector);
        }
    }
}

From source file:xml.sk.Parser.java

/**
 * Parses EducationSk.xml./* w  w  w.j  a  v  a  2s  .  c  om*/
 *
 * @param manager education manager to store data
 * @throws javax.xml.parsers.ParserConfigurationException
 * @throws org.xml.sax.SAXException
 * @throws java.io.IOException
 */
public void parseEducationSk(EducationManagerImpl manager) throws ParserConfigurationException, SAXException,
        IOException, XPathExpressionException, ParseException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse("src/main/java/xml/sk/EducationSk.xml");

    NodeList educationList = doc.getElementsByTagName("PRAC_strMzdyVzdelanie");
    for (int i = 0; i < educationList.getLength(); i++) {
        Element educationNode = (Element) educationList.item(i);

        if (!"EUR".equals(educationNode.getElementsByTagName("MJ").item(0).getTextContent()))
            continue;

        String name = educationNode.getElementsByTagName("UKAZ2").item(0).getTextContent();
        String sex = educationNode.getElementsByTagName("UKAZ1").item(0).getTextContent();
        String[] splited = sex.split(" ");
        sex = splited[splited.length - 1];

        NodeList years = educationNode.getChildNodes();

        for (int j = 0; j < years.getLength(); j++) {
            if (years.item(j).getNodeType() == Node.TEXT_NODE) {
                continue;
            }
            Element yearNode = (Element) years.item(j);
            if ("MJ".equals(yearNode.getNodeName()) || "UKAZ".equals(yearNode.getNodeName().substring(0, 4)))
                continue;

            String year = yearNode.getNodeName().substring(1);
            if (".".equals(yearNode.getTextContent()) || "".equals(yearNode.getTextContent())) {
                continue;
            }
            String salaryStr = yearNode.getTextContent().replaceAll(" ", "");
            NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
            Number number = format.parse(salaryStr);
            double salaryDouble = number.doubleValue();

            Education education = new Education();
            education.setDegree(name);
            education.setCountry("sk");
            education.setYear(year);
            education.setAverageSalary(salaryDouble);
            if (!"spolu".equals(sex))
                education.setSex(sex);

            manager.createEducation(education);
        }
    }
}