Example usage for java.lang NumberFormatException toString

List of usage examples for java.lang NumberFormatException toString

Introduction

In this page you can find the example usage for java.lang NumberFormatException toString.

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:org.callimachusproject.auth.DigestAuthenticationManager.java

private boolean isRecentDigest(Object target, Map<String, String[]> request,
        Map<String, String> authorization) {
    if (authorization == null)
        return false;
    String url = request.get("request-target")[0];
    String date = request.get("date")[0];
    String[] via = request.get("via");
    String realm = authorization.get("realm");
    String uri = authorization.get("uri");
    String username = authorization.get("username");
    if (username == null)
        throw new BadRequest("Missing username");
    ParsedURI parsed = new ParsedURI(url);
    String path = parsed.getPath();
    if (parsed.getQuery() != null) {
        path = path + "?" + parsed.getQuery();
    }/*from w w w.  j  av a2 s.  com*/
    if (realm == null || !url.equals(uri) && !path.equals(uri)) {
        logger.info("Bad authorization on {} using {}", url, authorization);
        throw new BadRequest("Bad Authorization");
    }
    if (!realm.equals(authName))
        return false;
    try {
        long now = DateUtil.parseDate(date).getTime();
        String nonce = authorization.get("nonce");
        if (nonce == null)
            return false;
        int first = nonce.indexOf(':');
        int last = nonce.lastIndexOf(':');
        if (first < 0 || last < 0)
            return false;
        if (!hash(via).equals(nonce.substring(last + 1)))
            return false;
        String revision = nonce.substring(first + 1, last);
        if (!revision.equals(getRevisionOf(target)))
            return false;
        String time = nonce.substring(0, first);
        Long ms = Long.valueOf(time, Character.MAX_RADIX);
        long age = now - ms;
        return age < MAX_NONCE_AGE;
    } catch (NumberFormatException e) {
        logger.debug(e.toString(), e);
        return false;
    } catch (DateParseException e) {
        logger.warn(e.toString(), e);
        return false;
    }
}

From source file:cn.code.notes.gtask.data.SqlNote.java

public void commit(boolean validateVersion) {
    if (mIsCreate) {
        if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) {
            mDiffNoteValues.remove(NoteColumns.ID);
        }//from  w w w . j  a v  a  2s.  c  o m

        Uri uri = mContentResolver.insert(Notes.CONTENT_NOTE_URI, mDiffNoteValues);
        try {
            mId = Long.valueOf(uri.getPathSegments().get(1));
        } catch (NumberFormatException e) {
            Log.e(TAG, "Get note id error :" + e.toString());
            throw new ActionFailureException("create note failed");
        }
        if (mId == 0) {
            throw new IllegalStateException("Create thread id failed");
        }

        if (mType == Notes.TYPE_NOTE) {
            for (SqlData sqlData : mDataList) {
                sqlData.commit(mId, false, -1);
            }
        }
    } else {
        if (mId <= 0 && mId != Notes.ID_ROOT_FOLDER && mId != Notes.ID_CALL_RECORD_FOLDER) {
            Log.e(TAG, "No such note");
            throw new IllegalStateException("Try to update note with invalid id");
        }
        if (mDiffNoteValues.size() > 0) {
            mVersion++;
            int result = 0;
            if (!validateVersion) {
                result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues,
                        "(" + NoteColumns.ID + "=?)", new String[] { String.valueOf(mId) });
            } else {
                result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues,
                        "(" + NoteColumns.ID + "=?) AND (" + NoteColumns.VERSION + "<=?)",
                        new String[] { String.valueOf(mId), String.valueOf(mVersion) });
            }
            if (result == 0) {
                Log.w(TAG, "there is no update. maybe user updates note when syncing");
            }
        }

        if (mType == Notes.TYPE_NOTE) {
            for (SqlData sqlData : mDataList) {
                sqlData.commit(mId, validateVersion, mVersion);
            }
        }
    }

    // refresh local info
    loadFromCursor(mId);
    if (mType == Notes.TYPE_NOTE)
        loadDataContent();

    mDiffNoteValues.clear();
    mIsCreate = false;
}

From source file:util.Check.java

/**
 * Prft Datumseingaben und stellt ggf. einen gltigen Datumsbereich von x
 * Wochen zusammen//  w  w  w . j a v  a2s.  c o m
 * 
 * @param of
 */
public void checkDateRegion(final OverviewForm of, final int defaultPeriod, final String defaultTimezone) {

    //Lngen Sicherstellen
    if (this.isExactLength(of.getYfrom(), 4) && this.isExactLength(of.getYto(), 4)
            && this.isLengthInMinMax(of.getMfrom(), 1, 2) && this.isLengthInMinMax(of.getMto(), 1, 2)
            && this.isLengthInMinMax(of.getDfrom(), 1, 2) && this.isLengthInMinMax(of.getDto(), 1, 2)) {

        try {
            final Calendar calTo = Calendar.getInstance();
            final Calendar calFrom = Calendar.getInstance();
            calTo.set(Integer.parseInt(of.getYto()), Integer.parseInt(of.getMto()) - 1,
                    Integer.parseInt(of.getDto()), 0, 0, 0);
            calFrom.set(Integer.parseInt(of.getYfrom()), Integer.parseInt(of.getMfrom()) - 1,
                    Integer.parseInt(of.getDfrom()), 0, 0, 0);
            final long time = calTo.getTime().getTime() - calFrom.getTime().getTime();

            if (time < 0) { // berprfung ob eine negativer Zeitbereicg vorliegt...
                of.setYfrom(null); // zurckstellen, damit im nchsten Schritt die Default-Werte zum Zug kommen...
            } else {
                //          System.out.println("Kalender wieder in of setzen, wegen berlufen (31.2.2008)");
                of.setYfrom(new SimpleDateFormat("yyyy").format(calFrom.getTime()));
                of.setMfrom(new SimpleDateFormat("MM").format(calFrom.getTime()));
                of.setDfrom(new SimpleDateFormat("dd").format(calFrom.getTime()));
                of.setFromdate(of.getYfrom() + "-" + of.getMfrom() + "-" + of.getDfrom() + " 00:00:00");

                of.setYto(new SimpleDateFormat("yyyy").format(calTo.getTime()));
                of.setMto(new SimpleDateFormat("MM").format(calTo.getTime()));
                of.setDto(new SimpleDateFormat("dd").format(calTo.getTime()));
                of.setTodate(of.getYto() + "-" + of.getMto() + "-" + of.getDto() + " 24:00:00");
            }

        } catch (final NumberFormatException e) {
            LOG.error("checkDateRegion: " + e.toString());
            of.setYfrom(null);
        }

    } else { //Benutzerangaben falsche anzahl Zeichen
        // zurckstellen, damit im nchsten Schritt die Default-Werte zum Zug kommen
        of.setYfrom(null);
    }

    // Defaultwerte bei bedarf Setzen
    if (of.getYfrom() == null || of.getYto() == null || of.getMfrom() == null || of.getMto() == null
            || of.getDfrom() == null || of.getDto() == null) {

        final Calendar calTo = Calendar.getInstance();
        calTo.setTimeZone(TimeZone.getTimeZone(defaultTimezone));
        final Calendar calFrom = Calendar.getInstance();
        calFrom.setTimeZone(TimeZone.getTimeZone(defaultTimezone));
        calFrom.add(Calendar.MONTH, -defaultPeriod); // bessere Verstndlichkeit wenn Monatsbereiche vorliegen...

        of.setYfrom(new SimpleDateFormat("yyyy").format(calFrom.getTime()));
        of.setMfrom(new SimpleDateFormat("MM").format(calFrom.getTime()));
        of.setDfrom(new SimpleDateFormat("dd").format(calFrom.getTime()));
        of.setFromdate(of.getYfrom() + "-" + of.getMfrom() + "-" + of.getDfrom() + " 00:00:00");

        of.setYto(new SimpleDateFormat("yyyy").format(calTo.getTime()));
        of.setMto(new SimpleDateFormat("MM").format(calTo.getTime()));
        of.setDto(new SimpleDateFormat("dd").format(calTo.getTime()));
        of.setTodate(of.getYto() + "-" + of.getMto() + "-" + of.getDto() + " 24:00:00");
    }
}

From source file:com.photon.phresco.nativeapp.eshop.activity.OrderReviewActivity.java

/**
 * Show the current order information/*from w w  w  .  j  av  a  2  s.  c  o m*/
 */
private void displayOrderDetail() {
    PhrescoLogger.info(TAG + " - displayOrderDetail  ");
    try {
        ((TextView) findViewById(R.id.email)).setText(orderInfo.getCustomerInfo().getEmailID());

        // Data For Delivery Address
        PhrescoLogger.info(TAG + " - Setting Delivery Address  ");

        ((TextView) findViewById(R.id.delivery_info_first_name))
                .setText(orderInfo.getCustomerInfo().getDeliveryAddress().getFirstName());
        ((TextView) findViewById(R.id.delivery_info_last_name))
                .setText(orderInfo.getCustomerInfo().getDeliveryAddress().getLastName());
        ((TextView) findViewById(R.id.delivery_info_company))
                .setText(orderInfo.getCustomerInfo().getDeliveryAddress().getCompany());
        ((TextView) findViewById(R.id.delivery_info_address1))
                .setText(orderInfo.getCustomerInfo().getDeliveryAddress().getAddressOne());
        ((TextView) findViewById(R.id.delivery_info_address2))
                .setText(orderInfo.getCustomerInfo().getDeliveryAddress().getAddressTwo());
        ((TextView) findViewById(R.id.delivery_info_city))
                .setText(orderInfo.getCustomerInfo().getDeliveryAddress().getCity());
        ((TextView) findViewById(R.id.delivery_info_state))
                .setText(orderInfo.getCustomerInfo().getDeliveryAddress().getState());
        ((TextView) findViewById(R.id.delivery_info_country))
                .setText(orderInfo.getCustomerInfo().getDeliveryAddress().getCountry());
        ((TextView) findViewById(R.id.delivery_info_zipcode))
                .setText(String.valueOf(orderInfo.getCustomerInfo().getDeliveryAddress().getZipCode()));
        ((TextView) findViewById(R.id.delivery_info_phone))
                .setText(String.valueOf(orderInfo.getCustomerInfo().getDeliveryAddress().getPhoneNumber()));

        // Data For Billing Address
        PhrescoLogger.info(TAG + " - Setting Billing Address  ");

        ((TextView) findViewById(R.id.billing_info_first_name))
                .setText(orderInfo.getCustomerInfo().getBillingAddress().getFirstName());
        ((TextView) findViewById(R.id.billing_info_last_name))
                .setText(orderInfo.getCustomerInfo().getBillingAddress().getLastName());
        ((TextView) findViewById(R.id.billing_info_company))
                .setText(orderInfo.getCustomerInfo().getBillingAddress().getCompany());
        ((TextView) findViewById(R.id.billing_info_address1))
                .setText(orderInfo.getCustomerInfo().getBillingAddress().getAddressOne());
        ((TextView) findViewById(R.id.billing_info_address2))
                .setText(orderInfo.getCustomerInfo().getBillingAddress().getAddressTwo());
        ((TextView) findViewById(R.id.billing_info_city))
                .setText(orderInfo.getCustomerInfo().getBillingAddress().getCity());
        ((TextView) findViewById(R.id.billing_info_state))
                .setText(orderInfo.getCustomerInfo().getBillingAddress().getState());
        ((TextView) findViewById(R.id.billing_info_country))
                .setText(orderInfo.getCustomerInfo().getBillingAddress().getCountry());
        ((TextView) findViewById(R.id.billing_info_zipcode))
                .setText(String.valueOf(orderInfo.getCustomerInfo().getBillingAddress().getZipCode()));
        ((TextView) findViewById(R.id.billing_info_phone))
                .setText(String.valueOf(orderInfo.getCustomerInfo().getBillingAddress().getPhoneNumber()));

        // Payment method
        ((TextView) findViewById(R.id.lbl_currency_subtotal)).setText(Constants.getCurrency());
        ((TextView) findViewById(R.id.sub_total)).setText(String.valueOf(MyCart.getTotalPrice()));

        ((TextView) findViewById(R.id.lbl_currency_ordertotal)).setText(Constants.getCurrency());
        ((TextView) findViewById(R.id.order_total)).setText(String.valueOf(MyCart.getTotalPrice()));

        ((TextView) findViewById(R.id.payment_by)).setText(orderInfo.getPaymentMethod());

        // Order comments
        ((TextView) findViewById(R.id.order_comments)).setText(orderInfo.getComments());
    } catch (NumberFormatException ex) {
        PhrescoLogger.info(TAG + " - displayOrderDetail  - Exception : " + ex.toString());
        PhrescoLogger.warning(ex);
    }
}

From source file:us.mn.state.health.lims.result.action.BatchResultsEntryUpdateAction.java

private int getIndexFromName(String name) throws LIMSRuntimeException {

    int index = -1;
    if (!StringUtil.isNullorNill(name)) {
        int start = name.indexOf("[");
        int end = name.indexOf("]");
        String indexString = name.substring(start + 1, end);
        try {/*from   w  ww  .j  a v a2  s  .co  m*/
            index = Integer.parseInt(indexString);
        } catch (NumberFormatException nfe) {
            //bugzilla 2154
            LogEvent.logError("BatchResultsEntryUpdateAction", "getIndexFromName()", nfe.toString());
            throw new LIMSRuntimeException(nfe);
        }

    }
    return index;
}

From source file:org.opendatakit.aggregate.task.gae.servlet.FormDeleteTaskServlet.java

/**
 * Handler for HTTP Get request that shows the list of forms
 *
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 *//*from  www. j  a v a  2 s .  c  o  m*/
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    CallingContext cc = ContextFactory.getCallingContext(this, req);
    cc.setAsDaemon(true);

    // get parameter

    String formId = getParameter(req, ServletConsts.FORM_ID);
    if (formId == null) {
        errorMissingKeyParam(resp);
        logger.error("missing " + ServletConsts.FORM_ID);
        return;
    }
    String miscTasksString = getParameter(req, ServletConsts.MISC_TASKS_KEY);
    if (miscTasksString == null) {
        errorBadParam(resp);
        logger.error("missing " + ServletConsts.MISC_TASKS_KEY);
        return;
    }
    SubmissionKey miscTasksKey = new SubmissionKey(miscTasksString);
    String attemptCountString = getParameter(req, ServletConsts.ATTEMPT_COUNT);
    if (attemptCountString == null) {
        errorBadParam(resp);
        logger.error("missing " + ServletConsts.ATTEMPT_COUNT);
        return;
    }

    Long attemptCount;
    try {
        attemptCount = Long.valueOf(attemptCountString);
    } catch (NumberFormatException e) {
        errorBadParam(resp);
        logger.error("parsing failed: " + ServletConsts.ATTEMPT_COUNT);
        return;
    }

    IForm form;
    try {
        form = FormFactory.retrieveFormByFormId(formId, cc);
    } catch (ODKFormNotFoundException e) {
        e.printStackTrace();
        odkIdNotFoundError(resp);
        logger.error("fetching form failed: " + e.toString());
        return;
    } catch (ODKOverQuotaException e) {
        e.printStackTrace();
        quotaExceededError(resp);
        logger.error("fetching form failed: " + e.toString());
        return;
    } catch (ODKDatastoreException e) {
        e.printStackTrace();
        datastoreError(resp);
        logger.error("fetching form failed: " + e.toString());
        return;
    } catch (Exception e) {
        e.printStackTrace();
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
        logger.error("fetching form failed: " + e.toString());
        return;
    }

    try {
        FormDeleteWorkerImpl formDelete = new FormDeleteWorkerImpl(form, miscTasksKey, attemptCount, cc);
        formDelete.deleteForm();
    } catch (ODKDatastoreException e) {
        e.printStackTrace();
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
        logger.error("delete form failed: " + e.toString());
        return;
    } catch (ODKExternalServiceDependencyException e) {
        e.printStackTrace();
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
        logger.error("delete form failed: " + e.toString());
        return;
    } catch (Exception e) {
        e.printStackTrace();
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
        logger.error("delete form failed: " + e.toString());
        return;
    }
}

From source file:com.orange.datavenue.StreamListFragment.java

/**
 *
 *//*from w ww  .  jav a 2  s . c o  m*/
private void createStream() {
    final android.app.Dialog dialog = new android.app.Dialog(getActivity());

    dialog.setContentView(R.layout.create_stream_dialog);

    dialog.setTitle(R.string.add_stream);

    final LinearLayout callbackLayout = (LinearLayout) dialog.findViewById(R.id.callback_layout);
    final EditText name = (EditText) dialog.findViewById(R.id.name);
    final EditText description = (EditText) dialog.findViewById(R.id.description);
    final EditText unit = (EditText) dialog.findViewById(R.id.unit);
    final EditText symbol = (EditText) dialog.findViewById(R.id.symbol);
    final EditText callback = (EditText) dialog.findViewById(R.id.callback);
    final EditText latitude = (EditText) dialog.findViewById(R.id.latitude);
    final EditText longitude = (EditText) dialog.findViewById(R.id.longitude);

    Button actionButton = (Button) dialog.findViewById(R.id.add_button);

    callbackLayout.setVisibility(View.VISIBLE);
    actionButton.setText(getString(R.string.add_stream));

    actionButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Log.d(TAG_NAME, "name : " + name.getText().toString());
            Log.d(TAG_NAME, "description : " + description.getText().toString());
            Log.d(TAG_NAME, "unit : " + unit.getText().toString());
            Log.d(TAG_NAME, "symbol : " + symbol.getText().toString());

            Stream newStream = new Stream();

            newStream.setName(name.getText().toString());
            newStream.setDescription(description.getText().toString());

            /**
             * Allocate new Location
             */
            Double[] location = null;

            String strLatitude = latitude.getText().toString();
            String strLongitude = longitude.getText().toString();

            try {
                if ((!"".equals(strLatitude)) && (!"".equals(strLongitude))) {
                    location = new Double[2];
                    location[0] = Double.parseDouble(strLatitude);
                    location[1] = Double.parseDouble(strLongitude);
                }
            } catch (NumberFormatException e) {
                Log.e(TAG_NAME, e.toString());
                location = null;
            }

            if (location != null) {
                newStream.setLocation(location);
            }
            /**************************************************************************/

            /**
             * Allocate new Unit & Symbol
             */
            Unit newUnit = null;
            String strUnit = unit.getText().toString();
            String strSymbol = symbol.getText().toString();

            if (!"".equals(strUnit)) {
                if (newUnit == null) {
                    newUnit = new Unit();
                }
                newUnit.setName(strUnit);
            }

            if (!"".equals(strSymbol)) {
                if (newUnit == null) {
                    newUnit = new Unit();
                }
                newUnit.setSymbol(strSymbol);
            }

            if (newUnit != null) {
                newStream.setUnit(newUnit);
            }

            /**
             * Allocate new Callback
             */
            Callback newCallback = null;
            String callbackUrl = callback.getText().toString();

            if (!"".equals(callbackUrl)) {
                try {
                    URL url = new URL(callbackUrl);
                    newCallback = new Callback();
                    newCallback.setUrl(url.toString());
                    newCallback.setName("Callback");
                    newCallback.setDescription("application callback");
                    newCallback.setStatus("activated");
                } catch (MalformedURLException e) {
                    Log.e(TAG_NAME, e.toString());
                    callback.setText("");
                }
            }

            if (newCallback != null) {
                newStream.setCallback(newCallback);
            }

            /**************************************************************************/

            CreateStreamOperation createStreamOperation = new CreateStreamOperation(Model.instance.oapiKey,
                    Model.instance.key, Model.instance.currentDatasource, newStream, new OperationCallback() {
                        @Override
                        public void process(Object object, Exception exception) {
                            if (exception == null) {
                                getStreams();
                            } else {
                                Errors.displayError(getActivity(), exception);
                            }
                        }
                    });

            createStreamOperation.execute("");

            dialog.dismiss();

        }
    });

    Button cancelButton = (Button) dialog.findViewById(R.id.cancel_button);
    cancelButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            dialog.dismiss();
        }
    });

    dialog.setCancelable(false);
    dialog.show();
}

From source file:org.cerberus.engine.execution.impl.SeleniumServerService.java

private Integer getTimeoutSetInParameterTable(String system, String parameter, Integer defaultWait,
        String logPrefix) {/*from w ww  .  ja  va  2  s . co  m*/
    try {
        AnswerItem timeoutParameter = parameterService.readWithSystem1ByKey("", parameter, system);
        if (timeoutParameter != null
                && timeoutParameter.isCodeStringEquals(MessageEventEnum.DATA_OPERATION_OK.getCodeString())) {
            if (((Parameter) timeoutParameter.getItem()).getSystem1value().isEmpty()) {
                return Integer.valueOf(((Parameter) timeoutParameter.getItem()).getValue());
            } else {
                return Integer.valueOf(((Parameter) timeoutParameter.getItem()).getSystem1value());
            }
        } else {
            LOG.warn(logPrefix + "Parameter (" + parameter
                    + ") not set in Parameter table, default value set to " + defaultWait + " milliseconds. ");
        }
    } catch (NumberFormatException ex) {
        LOG.warn(logPrefix + "Parameter (" + parameter + ") must be an integer, default value set to "
                + defaultWait + " milliseconds. " + ex.toString());
    }
    return defaultWait;
}

From source file:us.mn.state.health.lims.result.action.AmendedResultsEntryUpdateAction.java

protected ActionForward performAction(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    String forward = FWD_SUCCESS;
    request.setAttribute(ALLOW_EDITS_KEY, "true");
    request.setAttribute(PREVIOUS_DISABLED, "true");
    request.setAttribute(NEXT_DISABLED, "true");
    String amendedAnalysisId = null;

    if (request.getParameter(ANALYSIS_ID) != null) {
        amendedAnalysisId = (String) request.getParameter(ANALYSIS_ID);
    }/*  w  w w.j  av  a2 s. c  o  m*/

    BaseActionForm dynaForm = (BaseActionForm) form;

    List testTestAnalytes = (List) dynaForm.get("testTestAnalytes");
    String accessionNumber = (String) dynaForm.get("accessionNumber");
    Timestamp sampleLastupdated = (Timestamp) dynaForm.get("sampleLastupdated");

    ActionMessages errors = null;

    // initialize the form
    dynaForm.initialize(mapping);

    // 1926 get sysUserId from login module
    UserSessionData usd = (UserSessionData) request.getSession().getAttribute(USER_SESSION_DATA);
    String sysUserId = String.valueOf(usd.getSystemUserId());

    org.hibernate.Transaction tx = HibernateUtil.getSession().beginTransaction();

    if (!StringUtil.isNullorNill(amendedAnalysisId)) {

        ResultDAO resultDAO = new ResultDAOImpl();
        AnalysisDAO analysisDAO = new AnalysisDAOImpl();
        NoteDAO noteDAO = new NoteDAOImpl();
        SampleDAO sampleDAO = new SampleDAOImpl();
        AnalysisQaEventDAO analysisQaEventDAO = new AnalysisQaEventDAOImpl();
        AnalysisQaEventActionDAO analysisQaEventActionDAO = new AnalysisQaEventActionDAOImpl();

        try {

            // get old analysis and copy to new one
            Analysis analysisToAmend = new Analysis();
            analysisToAmend.setId(amendedAnalysisId);
            analysisDAO.getData(analysisToAmend);
            Analysis amendedAnalysis = new Analysis();

            PropertyUtils.copyProperties(amendedAnalysis, analysisToAmend);
            amendedAnalysis.setId(null);
            amendedAnalysis.setLastupdated(null);
            amendedAnalysis.setSysUserId(sysUserId);

            String revisionString = analysisToAmend.getRevision();
            int revision = 0;
            if (!StringUtil.isNullorNill(revisionString)) {
                try {
                    revision = Integer.parseInt(revisionString);
                } catch (NumberFormatException nfe) {
                    //bugzilla 2154
                    LogEvent.logError("AmendedResultsEntryUpdateAction", "performAction()", nfe.toString());
                }
            }
            amendedAnalysis.setRevision(String.valueOf(++revision));
            amendedAnalysis.setStatus(SystemConfiguration.getInstance().getAnalysisStatusResultCompleted());
            amendedAnalysis.setPrintedDate(null);
            //bugzilla 2013 added duplicateCheck parameter
            analysisDAO.insertData(amendedAnalysis, false);

            //find qa events attached to analysisToAmend and clone them to the amenedAnalysis
            AnalysisQaEvent analysisQaEventToAmend = new AnalysisQaEvent();
            analysisQaEventToAmend.setAnalysis(analysisToAmend);
            List qaEvents = analysisQaEventDAO.getAnalysisQaEventsByAnalysis(analysisQaEventToAmend);
            if (qaEvents != null && qaEvents.size() > 0) {
                for (int y = 0; y < qaEvents.size(); y++) {
                    analysisQaEventToAmend = (AnalysisQaEvent) qaEvents.get(y);
                    AnalysisQaEvent amendedAnalysisQaEvent = new AnalysisQaEvent();

                    AnalysisQaEventAction analysisQaEventActionToAmend = new AnalysisQaEventAction();
                    analysisQaEventActionToAmend.setAnalysisQaEvent(analysisQaEventToAmend);
                    List qaEventActionsToAmend = analysisQaEventActionDAO
                            .getAnalysisQaEventActionsByAnalysisQaEvent(analysisQaEventActionToAmend);
                    PropertyUtils.copyProperties(amendedAnalysisQaEvent, analysisQaEventToAmend);

                    amendedAnalysisQaEvent.setId(null);
                    amendedAnalysisQaEvent.setAnalysis(amendedAnalysis);
                    amendedAnalysisQaEvent.setLastupdated(null);
                    amendedAnalysisQaEvent.setSysUserId(sysUserId);
                    analysisQaEventDAO.insertData(amendedAnalysisQaEvent);

                    //get actions also
                    if (qaEventActionsToAmend != null && qaEventActionsToAmend.size() > 0) {
                        for (int z = 0; z < qaEventActionsToAmend.size(); z++) {
                            analysisQaEventActionToAmend = (AnalysisQaEventAction) qaEventActionsToAmend.get(z);
                            AnalysisQaEventAction amendedAnalysisQaEventAction = new AnalysisQaEventAction();
                            PropertyUtils.copyProperties(amendedAnalysisQaEventAction,
                                    analysisQaEventActionToAmend);

                            amendedAnalysisQaEventAction.setId(null);
                            amendedAnalysisQaEventAction.setAnalysisQaEvent(amendedAnalysisQaEvent);
                            amendedAnalysisQaEventAction.setLastupdated(null);
                            amendedAnalysisQaEventAction.setSysUserId(sysUserId);
                            analysisQaEventActionDAO.insertData(amendedAnalysisQaEventAction);
                        }
                    }
                }
            }

            //create copies of results
            List resultsToAmend = resultDAO.getResultsByAnalysis(analysisToAmend);

            for (int i = 0; i < resultsToAmend.size(); i++) {
                Result resultToAmend = (Result) resultsToAmend.get(i);
                Result amendedResult = new Result();

                PropertyUtils.copyProperties(amendedResult, resultToAmend);
                amendedResult.setId(null);
                amendedResult.setAnalysis(amendedAnalysis);
                amendedResult.setLastupdated(null);
                amendedResult.setSysUserId(sysUserId);
                resultDAO.insertData(amendedResult);

                //find other analyses on this sample that have this result/analysis as a parent and unlink/link to this one
                List childAnalyses = analysisDAO.getAllChildAnalysesByResult(resultToAmend);
                for (int j = 0; j < childAnalyses.size(); j++) {
                    Analysis childAnalysis = (Analysis) childAnalyses.get(j);
                    childAnalysis.setParentAnalysis(amendedAnalysis);
                    childAnalysis.setParentResult(amendedResult);
                    childAnalysis.setSysUserId(sysUserId);

                    //this is for optimistic locking - we need the correct lastupdated 
                    for (int x = 0; x < testTestAnalytes.size(); x++) {
                        Test_TestAnalyte test_testAnalyte = (Test_TestAnalyte) testTestAnalytes.get(x);
                        Analysis analysis = test_testAnalyte.getAnalysis();

                        if (analysis.getId().equals(childAnalysis.getId())) {
                            childAnalysis.setLastupdated(analysis.getLastupdated());
                            break;
                        }

                    }

                    analysisDAO.updateData(childAnalysis);
                }

                //create copies of notes (attached to new results)
                Note note = new Note();
                //bugzilla 2571 go through ReferenceTablesDAO to get reference tables info
                ReferenceTables referenceTables = new ReferenceTables();
                referenceTables.setId(SystemConfiguration.getInstance().getResultReferenceTableId());
                note.setReferenceTables(referenceTables);
                note.setReferenceId(resultToAmend.getId());
                List notesByResult = noteDAO.getAllNotesByRefIdRefTable(note);

                for (int x = 0; x < notesByResult.size(); x++) {
                    Note noteToAmend = (Note) notesByResult.get(x);
                    Note amendedNote = new Note();
                    PropertyUtils.copyProperties(amendedNote, noteToAmend);
                    amendedNote.setId(null);
                    amendedNote.setReferenceId(amendedResult.getId());
                    amendedNote.setLastupdated(null);
                    //per Nancy retain user id of original author of note
                    // Also!!!! Note needs to have systemUser (for Note mapping) AND sysUserId (for audit trail) set!!!!
                    amendedNote.setSystemUser(noteToAmend.getSystemUser());
                    amendedNote.setSysUserId(sysUserId);
                    noteDAO.insertData(amendedNote);
                }

            }

            //update sample status
            Sample sample = sampleDAO.getSampleByAccessionNumber(accessionNumber);
            //this is for optimistic locking...(sampleLastupdated was stored in form from initial read)
            sample.setLastupdated(sampleLastupdated);
            sample.setSysUserId(sysUserId);
            sample.setStatus(SystemConfiguration.getInstance().getSampleStatusEntry2Complete());
            sampleDAO.updateData(sample);

            tx.commit();
        } catch (LIMSRuntimeException lre) {
            //bugzilla 2154
            LogEvent.logError("AmendedResultsEntryUpdateAction", "performAction()", lre.toString());
            tx.rollback();

            errors = new ActionMessages();
            ActionError error = null;
            if (lre.getException() instanceof org.hibernate.StaleObjectStateException) {

                error = new ActionError("errors.OptimisticLockException", null, null);
            } else {
                error = new ActionError("errors.InsertException", null, null);
            }
            errors.add(ActionMessages.GLOBAL_MESSAGE, error);
            saveErrors(request, errors);
            request.setAttribute(Globals.ERROR_KEY, errors);

            forward = FWD_FAIL;

        } finally {
            HibernateUtil.closeSession();
        }

    } else {
        forward = FWD_FAIL;
    }

    return getForward(mapping.findForward(forward), accessionNumber);

}

From source file:biz.varkon.shelvesom.provider.gadgets.GadgetsStore.java

private void parsePrices(XmlPullParser parser, Gadget gadget) throws IOException, XmlPullParserException {

    int type;// w  w  w  .j a v a  2 s .  c o  m
    String name;
    final int depth = parser.getDepth();

    while (((type = parser.next()) != XmlPullParser.END_TAG || parser.getDepth() > depth)
            && type != XmlPullParser.END_DOCUMENT) {
        if (type != XmlPullParser.START_TAG) {
            continue;
        }

        name = parser.getName();
        if (RESPONSE_TAG_FORMATTEDPRICE.equals(name)) {
            if (parser.next() == XmlPullParser.TEXT) {
                String price = parser.getText();

                try {
                    if (gadget.mRetailPrice == null || (gadget.mRetailPrice != null && Double
                            .valueOf(gadget.mRetailPrice.substring(1)) > Double.valueOf(price.substring(1)))) {
                        gadget.mRetailPrice = price;
                    }
                } catch (NumberFormatException n) {
                    Log.e(LOG_TAG, n.toString());
                    if (gadget.mRetailPrice == null)
                        gadget.mRetailPrice = "";
                }
            }
        }
    }
}