Example usage for java.lang NumberFormatException getMessage

List of usage examples for java.lang NumberFormatException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:com.streamreduce.util.JiraClient.java

/**
 * Handles the auto-tags, extra metadata, to be added to the activity message for Jira issue activity.
 *
 * @param projectKey     the project key of the inventory item
 * @param activityObject the raw <activity:object /> element of the activity
 * @param entry          the root element for the activity entry
 * @param hashtags       the hashtags set we will manipulate
 *///w ww.j  a  v  a 2s.c  o m
private void handleJiraWikiAutotags(String projectKey, org.apache.abdera.model.Element activityObject,
        Entry entry, Set<String> hashtags) {
    // Right now, the only additional auto-tags we add for wiki activity are the page's labels.  To do this, we
    // parse the page id from ref attribute of the <thr:in-reply-to /> element.  Once we get this, we make a SOAP
    // call to get the page labels for that id.
    //
    // Note: This does not appear to work for blog/article entries.  The pageId we parse from the activity entry
    //       always returns an empty array response when gathering the labels.  We will still attempt to retrieve
    //       the labels for blog/article entries just in case it gets fixed.
    org.apache.abdera.model.Element thr = entry
            .getFirstChild(new QName("http://purl.org/syndication/thread/1.0", "in-reply-to", "thr"));

    if (thr != null) {
        String pageUrl = thr.getAttributeValue("ref");
        long pageId;

        // Just in case
        if (pageUrl == null) {
            LOGGER.error("Unable to parse the thr:in-reply-to of the Jira activity:object for: "
                    + JSONUtils.xmlToJSON(activityObject.toString()));
            return;
        }

        try {
            pageId = Long.valueOf(pageUrl.substring(pageUrl.lastIndexOf("/") + 1));
        } catch (NumberFormatException e) {
            // Not much we can do so log the error and continue processing
            LOGGER.error("Unexpected wiki page id when parsing activity URL (" + pageUrl + "): ",
                    e.getMessage());
            return;
        }

        try {
            List<org.w3c.dom.Element> labels = getWikiPageLabels(pageId);

            for (org.w3c.dom.Element label : labels) {
                // Confluence labels are returned as an array and we're only interested in ones that have children.
                //
                // Note: When a page has no labels, we get back an empty array element and so we need to check that
                //       the label has children before trying to use it.
                if (!label.hasChildNodes()) {
                    continue;
                }

                NodeList labelNames = label.getElementsByTagName("name");

                if (labelNames == null) {
                    // Not much we can do at this point but log the problem
                    LOGGER.error("Unexpected response when retrieving labels for wiki page with an " + "id of "
                            + pageId + " in the " + projectKey + " project.");
                } else {
                    hashtags.add(removeIllegalHashtagCharacters("#" + labelNames.item(0).getTextContent()));
                }
            }
        } catch (SOAPException e) {
            // Not much we can do at this point but log the problem
            LOGGER.error(
                    "Unable to make SOAP call to get wiki labels for " + projectKey + ": " + e.getMessage());
        }
    }
}

From source file:com.sfs.whichdoctor.dao.MembershipDAOImpl.java

/**
 * Gets the training limit./*  w  w  w  . j  av a2  s .com*/
 *
 * @param type the type
 *
 * @return the training limit
 */
public final int getTrainingLimit(final String type) {
    int value = 0;
    if (this.trainingLimits != null) {
        if (this.trainingLimits.containsKey(type)) {
            String strValue = this.trainingLimits.getProperty(type);
            try {
                value = Integer.parseInt(strValue);
            } catch (NumberFormatException nfe) {
                dataLogger.debug("Error parsing integer: " + nfe.getMessage());
            }
        }
    }
    return value;
}

From source file:com.itcs.commons.email.impl.RunnableSendHTMLEmail.java

private void addAttachments(MultiPartEmail email, List<EmailAttachment> attachments) throws EmailException {

    if (attachments != null && attachments.size() > 0) {
        String maxStringValue = getSession().getProperty(MAX_ATTACHMENTS_SIZE_PROP_NAME);
        //            System.out.println("maxStringValue= " + maxStringValue);
        long maxAttachmentSize = DISABLE_MAX_ATTACHMENTS_SIZE;
        try {//from  www . ja  v a2 s .c om
            maxAttachmentSize = Long.parseLong(maxStringValue);
        } catch (NumberFormatException e) {
            Logger.getLogger(RunnableSendHTMLEmail.class.getName()).log(Level.WARNING,
                    "DISABLE_MAX_ATTACHMENTS_SIZE MailSession does not have property "
                            + MAX_ATTACHMENTS_SIZE_PROP_NAME);
        }

        long size = 0;
        for (EmailAttachment attach : attachments) {
            if (maxAttachmentSize != EmailClient.DISABLE_MAX_ATTACHMENTS_SIZE) {
                size += attach.getSize();
                if (size > maxAttachmentSize) {
                    throw new EmailException(
                            "Adjuntos exceden el tamao maximo permitido (" + maxAttachmentSize + "),"
                                    + " pruebe enviando menos archivos adjuntos, o de menor tamao.");
                }
            }
            if (attach.getData() != null) {
                try {
                    email.attach(new ByteArrayDataSource(attach.getData(), attach.getMimeType()),
                            attach.getName(), attach.getMimeType());
                } catch (IOException e) {
                    throw new EmailException("IOException Attachment has errors," + e.getMessage());
                } catch (EmailException e) {
                    throw new EmailException("EmailException Attachment has errors," + e.getMessage());
                }
            } else {
                email.attach(attach);
            }
        }

    }

}

From source file:com.partnet.automation.HtmlView.java

/**
 * Waits for a page to load; a set amount of time is allotted.
 * //from  w  w  w.  j  av  a2 s .c om
 * @param ignoreWebDriverException
 *          - whether or not a {@link WebDriverException} should be ignored.
 *          In certain cases, it can be useful to not ignore exceptions thrown
 *          when waiting for the page to load, however typically this value
 *          should be true.
 */
protected void waitForPageToLoad(boolean ignoreWebDriverException) {
    LOG.debug("Wait for page to load..");
    String stringWaitProp = System.getProperty(WAIT_FOR_PAGE_PROP, "90");
    int waitProp;

    try {
        waitProp = Integer.parseInt(stringWaitProp);
    } catch (NumberFormatException e) {
        throw new NumberFormatException(
                String.format("%s, could not determine %s", e.getMessage(), WAIT_FOR_PAGE_PROP));
    }

    WebDriverWait wait = new WebDriverWait(webDriver, waitProp);

    if (ignoreWebDriverException) {
        wait.ignoring(WebDriverException.class);
    }

    wait.until(conditionPageLoaded); // wait for the page to load
}

From source file:com.novartis.opensource.yada.util.QueryUtils.java

/**
 * Calls the appropriate setter method for {@code type} in the {@code pstmt},
 * performing the appropriate type conversion or syntax change as needed
 * (e.g., for {@link java.sql.Date}s)/*from  w  ww  . jav  a  2s. c om*/
 * 
 * @param pstmt
 *          the statement to which to assign the parameter values
 * @param index
 *          the position of the parameter
 * @param type
 *          the data type of the parameter
 * @param val
 *          the value to assign
 */
@SuppressWarnings("static-method")
private void setQueryParameter(PreparedStatement pstmt, int index, char type, String val) {
    String idx = (index < 10) ? " " + String.valueOf(index) : String.valueOf(index);
    l.debug("Setting param [" + idx + "] of type [" + String.valueOf(type) + "] to: " + val);
    try {
        switch (type) {
        case DATE:

            try {
                if ("".equals(val) || val == null) {
                    pstmt.setNull(index, java.sql.Types.DATE);
                } else {
                    SimpleDateFormat sdf = new SimpleDateFormat(STANDARD_DATE_FMT);
                    ParsePosition pp = new ParsePosition(0);
                    Date dateVal = sdf.parse(val, pp);
                    if (dateVal == null) {
                        sdf = new SimpleDateFormat(ORACLE_DATE_FMT);
                        dateVal = sdf.parse(val, pp);
                    }
                    if (dateVal != null) {
                        long t = dateVal.getTime();
                        java.sql.Date sqlDateVal = new java.sql.Date(t);
                        pstmt.setDate(index, sqlDateVal);
                    }
                }
            } catch (Exception e) {
                l.error("Error: " + e.getMessage());
            }
            break;
        case INTEGER:
            try {
                int ival = Integer.parseInt(val);
                pstmt.setInt(index, ival);
            } catch (NumberFormatException nfe) {
                l.error("Error: " + nfe.getMessage());
                l.debug("Setting param [" + String.valueOf(index) + "] of type [" + String.valueOf(type)
                        + "] to: null");
                pstmt.setNull(index, java.sql.Types.INTEGER);
            } catch (NullPointerException npe) {
                l.error("Error: " + npe.getMessage());
                l.debug("Setting param [" + String.valueOf(index) + "] of type [" + String.valueOf(type)
                        + "] to: null");
                pstmt.setNull(index, java.sql.Types.INTEGER);
            } catch (Exception sqle) {
                l.error("Error: " + sqle.getMessage());
                l.debug("Setting param [" + String.valueOf(index) + "] of type [" + String.valueOf(type)
                        + "] to: 0");
                pstmt.setNull(index, java.sql.Types.INTEGER);
            }
            break;
        case NUMBER:
            try {
                float fval = Float.parseFloat(val);
                pstmt.setFloat(index, fval);
            } catch (NumberFormatException nfe) {
                l.error("Error: " + nfe.getMessage());
                l.debug("Setting param [" + String.valueOf(index) + "] of type [" + String.valueOf(type)
                        + "] to: null");
                pstmt.setNull(index, java.sql.Types.INTEGER);
            } catch (NullPointerException npe) {
                l.error("Error: " + npe.getMessage());
                l.debug("Setting param [" + String.valueOf(index) + "] of type [" + String.valueOf(type)
                        + "] to: null");
                pstmt.setNull(index, java.sql.Types.INTEGER);
            } catch (Exception sqle) {
                l.error("Error: " + sqle.getMessage());
                l.debug("Setting param [" + String.valueOf(index) + "] of type [" + String.valueOf(type)
                        + "] to: null");
                pstmt.setNull(index, java.sql.Types.INTEGER);
            }
            break;
        case OUTPARAM_DATE:
            ((CallableStatement) pstmt).registerOutParameter(index, java.sql.Types.DATE);
            break;
        case OUTPARAM_INTEGER:
            ((CallableStatement) pstmt).registerOutParameter(index, java.sql.Types.INTEGER);
            break;
        case OUTPARAM_NUMBER:
            ((CallableStatement) pstmt).registerOutParameter(index, java.sql.Types.FLOAT);
            break;
        case OUTPARAM_VARCHAR:
            ((CallableStatement) pstmt).registerOutParameter(index, java.sql.Types.VARCHAR);
            break;
        default: // VARCHAR2
            pstmt.setString(index, val);
            break;
        }
    } catch (SQLException e) {
        e.printStackTrace();
        l.error(e.getMessage());
    }
}

From source file:com.ephesoft.dcma.batch.service.ImportBatchServiceImpl.java

private List<BatchClassPluginConfig> addBatchClassPluginConfigsForExitingPlugin(Plugin dbBatchClassPlugin,
        BatchClassPlugin zipBatchClassPlugin) {
    List<BatchClassPluginConfig> validBCPluginConfigs = new ArrayList<BatchClassPluginConfig>();
    long batchClassPluginId = -BatchConstants.ONE;
    long pluginId = dbBatchClassPlugin.getId();
    List<BatchClassPluginConfig> batchClassPluginConfigsList = new ArrayList<BatchClassPluginConfig>(0);
    try {/*from w  w w.j  a  v a 2  s  .  c  o  m*/
        List<BatchClassPlugin> batchClassPlugins = batchClassPluginService
                .getBatchClassPluginForPluginId(pluginId);
        for (BatchClassPlugin batchClassPlugin : batchClassPlugins) {
            if (batchClassPlugin.getPlugin().getPluginName().equals(dbBatchClassPlugin.getPluginName())) {
                batchClassPluginId = batchClassPlugin.getId();
                break;
            }

        }
    } catch (NumberFormatException e) {
        LOGGER.error("Error converting number: " + e.getMessage(), e);
    }
    if (batchClassPluginId != -BatchConstants.ONE) {
        batchClassPluginConfigsList = batchClassPluginConfigService
                .getPluginConfigurationForPluginId(batchClassPluginId);

        if (batchClassPluginConfigsList != null) {
            List<PluginConfig> existingPluginConfigs = new ArrayList<PluginConfig>();
            for (BatchClassPluginConfig batchClassPluginConfig : batchClassPluginConfigsList) {
                PluginConfig pluginConfig = batchClassPluginConfig.getPluginConfig();
                existingPluginConfigs.add(pluginConfig);
            }
            validBCPluginConfigs = addBatchClassPluginConfigsForNewPlugin(existingPluginConfigs,
                    zipBatchClassPlugin.getBatchClassPluginConfigs());
        }

    }
    return validBCPluginConfigs;
}

From source file:com.redsqirl.CanvasModal.java

/**
 * Open Canvas Modal/* ww  w  . j a va 2s  .  c o m*/
 * 
 * @return
 * @author Igor.Souza
 * @throws RemoteException
 */
public String[] getOpenCanvasModal() throws RemoteException {
    logger.info("openCanvasModal");

    String error = null;

    FacesContext context = FacesContext.getCurrentInstance();
    canvasBean = (CanvasBean) context.getApplication().evaluateExpressionGet(context, "#{canvasBean}",
            CanvasBean.class);

    HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
            .getRequest();

    // set the first tab for obj
    String selTab = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap()
            .get("paramSelectedTab");
    if (selTab == null || selTab.isEmpty() || selTab.equalsIgnoreCase("undefined")) {
        selTab = "confTabCM";
    }
    //logger.info("selected tab: " + selTab);
    setSelectedTab(selTab);

    // Don't update the element if you it close immediately
    elementToUpdate = false;
    cleanEl = false;

    // Get the image
    pathImage = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap()
            .get("paramPathImage");

    // Get the Element
    idGroup = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap()
            .get("paramGroupId");

    Integer pageNb = 0;
    String pageNbParam = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap()
            .get("paramPageNb");
    if (pageNbParam != null && !pageNbParam.isEmpty() && !pageNbParam.equalsIgnoreCase("undefined")) {
        try {
            pageNb = Integer.parseInt(FacesContext.getCurrentInstance().getExternalContext()
                    .getRequestParameterMap().get("paramPageNb"));
        } catch (NumberFormatException e) {
            pageNb = 0;
            logger.warn("Page nb issue: " + e.getMessage(), e);
        }
    }

    try {
        dfe = canvasBean.getDf().getElement(canvasBean.getIdElement(idGroup));
        //logger.info("Get element dfe");
    } catch (RemoteException e) {
        logger.error(e.getMessage(), e);
    }

    String paramLMW = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap()
            .get("paramLoadMainWindow");
    if (paramLMW != null) {
        loadMainWindow = !paramLMW.equalsIgnoreCase("false");
    } else {
        loadMainWindow = true;
    }

    if (dfe == null) {
        logger.info("The element is null!");
        error = getMessageResources("msg_error_oops");
    } else {
        elementId = getComponentId();
        //logger.info("Element id: "+elementId);
        elementComment = dfe.getComment();
        if (loadMainWindow) {
            //logger.info("load Main window");
            try {

                // validate if you can open or not the dynamic form of the object
                error = dfe.checkIn();

                //logger.info("error " + error);

                if (error == null) {

                    // mount output tab
                    outputTab = new CanvasModalOutputTab(datastores, dfe);
                    Iterator<DFEInteraction> iterIt = dfe.getInteractions().iterator();
                    sourceNode = false;
                    while (iterIt.hasNext() && !sourceNode) {
                        sourceNode = iterIt.next().getDisplay().equals(DisplayType.browser);
                    }

                    if (sourceNode && dfe.getDFEOutput().size() <= 1) {
                        outputTab.setShowOutputForm("N");
                    }

                    listPageSize = getPageList().size();

                    //initialise the position of list and check all pages before
                    setListPosition(pageNb);
                    String e = null;
                    if (pageNb > 0) {
                        int i = -1;
                        while (e == null && i < Math.min(pageNb, listPageSize)) {
                            ++i;
                            dfe.update(i);
                            e = getPageList().get(i).checkPage();
                        }
                        setListPosition(i);
                    }
                    //specific error message to validation object
                    if (e != null) {
                        logger.info("openCanvasModal checkpages before " + e);
                        MessageUseful.addErrorMessage(e);
                        request.setAttribute("msnErrorPage", "msnErrorPage");
                        usageRecordLog().addError("ERROR OPENCANVASMODAL", e);
                    }

                    // retrieves the correct page
                    setCanvasTitle(
                            WordUtils.capitalizeFully(dfe.getName().replace("_", " ")) + ": " + elementId);

                    if (listPageSize > 0) {
                        mountInteractionForm();
                    } else {
                        updateOutputElement();
                    }

                    outputTab.mountOutputForm(!sourceNode || dfe.getDFEOutput().size() > 1);

                    checkVoronoiTab();

                    checkFirstPage();

                    //logger.info("List size " + getListPageSize());

                    checkLastPage();

                }

            } catch (RemoteException e) {
                logger.error(e, e);
            } catch (Exception e) {
                logger.error(e, e);
            }
        }

    }

    //logger.info("listPage:"+ Integer.toString(getListPageSize()) + " getIdGroup:" + getIdGroup()+ " getCurElId:"+getCurElId()+ " getCurElComment:"+getCurElComment());
    boolean loadOutputTab = false;
    String cloneWFId = null;
    try {
        loadOutputTab = loadMainWindow
                && ((canvasBean.getWorkflowType().equals("W") && (getOutputTab().getShowOutputForm() != null
                        && getOutputTab().getShowOutputForm().equals("Y")) || getListPageSize() > 0));
        cloneWFId = canvasBean.cloneWorkflowGetId();
    } catch (Exception e) {
    }

    displayErrorMessage(error, "OPENCANVASMODAL");

    String[] ans = new String[] { Boolean.toString(loadOutputTab), Integer.toString(pageNb), getIdGroup(),
            getCurElId(), getCurElComment(), Boolean.toString(loadMainWindow), cloneWFId };

    logger.info(ans[0] + ", " + ans[1] + ", " + ans[2] + ", " + ans[3] + ", " + ans[4] + ", " + ans[5] + ", "
            + ans[6]);

    return ans;
}

From source file:com.collabnet.ccf.teamforge.TFTrackerHandler.java

/**
 * Updates the artifact if conflict resolution priority allows it
 * /*w  w  w . jav a 2  s  . c  o  m*/
 * @param ga
 *            generic artifact passed to the update method
 * @param sessionId
 * @param trackerId
 * @param description
 * @param category
 * @param group
 * @param status
 * @param statusClass
 * @param customer
 * @param priority
 * @param estimatedEfforts
 * @param actualEfforts
 * @param closeDate
 * @param assignedTo
 * @param reportedReleaseId
 * @param resolvedReleaseId
 * @param flexFieldNames
 * @param flexFieldValues
 * @param flexFieldTypes
 * @param flexFieldPreserve
 * @param title
 * @param Id
 * @param comments
 * @param newParentId
 * @param associateWithParent
 * @param currentParentId
 * @param deleteOldParentAssociation
 * @param packageReleaseSeparatorString
 * @param conflictResolutionPriority
 * @return updated artifact or null if conflict resolution has decided not
 *         to update the artifact
 * @throws RemoteException
 * @throws PlanningFolderRuleViolationException
 */
public ArtifactDO updateArtifact(GenericArtifact ga, Connection connection, GenericArtifactField trackerId,
        GenericArtifactField description, GenericArtifactField category, GenericArtifactField group,
        GenericArtifactField status, GenericArtifactField statusClass, GenericArtifactField customer,
        GenericArtifactField priority, GenericArtifactField estimatedEfforts,
        GenericArtifactField actualEfforts, GenericArtifactField closeDate, GenericArtifactField assignedTo,
        GenericArtifactField reportedReleaseId, GenericArtifactField resolvedReleaseId,
        List<String> flexFieldNames, List<Object> flexFieldValues, List<String> flexFieldTypes,
        Set<String> overriddenFlexFields, GenericArtifactField title, String Id, String[] comments,
        boolean translateTechnicalReleaseIds, GenericArtifactField remainingEfforts,
        GenericArtifactField autosumming, GenericArtifactField storyPoints,
        GenericArtifactField planningFolderId, boolean deleteOldParentAssociation, String currentParentId,
        boolean associateWithParent, String newParentId, String packageReleaseSeparatorString)
        throws RemoteException, PlanningFolderRuleViolationException {

    boolean mainArtifactNotUpdated = true;
    boolean oldParentRemoved = false;
    ArtifactDO artifactData = null;
    while (mainArtifactNotUpdated) {
        try {
            mainArtifactNotUpdated = false;
            artifactData = connection.getTrackerClient().getArtifactData(Id);
            // do conflict resolution
            if (!AbstractWriter.handleConflicts(artifactData.getVersion(), ga)) {
                return null;
            }

            if (deleteOldParentAssociation && !oldParentRemoved) {
                removeArtifactDependency(connection, currentParentId, Id);
                oldParentRemoved = true;
            }

            // here we store the values which will be really sent
            ArrayList<String> finalFlexFieldNames = new ArrayList<String>();
            ArrayList<String> finalFlexFieldTypes = new ArrayList<String>();
            ArrayList<Object> finalFlexFieldValues = new ArrayList<Object>();

            FieldValues currentFlexFields = artifactData.getFlexFields();
            String[] currentFlexFieldNames = currentFlexFields.getNames();
            Object[] currentFlexFieldValues = currentFlexFields.getValues();
            String[] currentFlexFieldTypes = currentFlexFields.getTypes();

            // first we filter out all current flex fields that should be
            // overridden
            for (int i = 0; i < currentFlexFieldNames.length; ++i) {
                if (!overriddenFlexFields.contains(currentFlexFieldNames[i])) {
                    finalFlexFieldNames.add(currentFlexFieldNames[i]);
                    finalFlexFieldTypes.add(currentFlexFieldTypes[i]);
                    finalFlexFieldValues.add(currentFlexFieldValues[i]);
                }
            }

            // now we have to add all anticipated flex fields
            finalFlexFieldNames.addAll(flexFieldNames);
            finalFlexFieldValues.addAll(flexFieldValues);
            finalFlexFieldTypes.addAll(flexFieldTypes);

            FieldValues flexFields = new FieldValues();
            flexFields.setNames(finalFlexFieldNames.toArray(new String[0]));
            flexFields.setValues(finalFlexFieldValues.toArray());
            flexFields.setTypes(finalFlexFieldTypes.toArray(new String[0]));

            // we need this property to determine whether we may update the
            // efforts fields
            boolean autoSummingTurnedOn = artifactData.getAutosumming();

            if (autosumming != null && autosumming.getFieldValueHasChanged()) {
                Object fieldValueObj = autosumming.getFieldValue();
                Boolean fieldValue = false;
                if (fieldValueObj instanceof String) {
                    String fieldValueString = (String) fieldValueObj;
                    fieldValue = Boolean.parseBoolean(fieldValueString);
                } else if (fieldValueObj instanceof Boolean) {
                    fieldValue = (Boolean) fieldValueObj;
                }
                autoSummingTurnedOn = fieldValue;
                artifactData.setAutosumming(fieldValue);
            }

            // check if we do not support the autosumming flag at all
            if (!connection.supports53()) {
                autoSummingTurnedOn = false;
            }

            String folderIdString = artifactData.getFolderId();
            if (trackerId != null && trackerId.getFieldValueHasChanged()) {
                folderIdString = (String) trackerId.getFieldValue();
                artifactData.setFolderId(folderIdString);
            }

            if (title != null && title.getFieldValueHasChanged()) {
                artifactData.setTitle((String) title.getFieldValue());
            }

            if (description != null && description.getFieldValueHasChanged()) {
                artifactData.setDescription((String) description.getFieldValue());
            }

            if (group != null && group.getFieldValueHasChanged()) {
                artifactData.setGroup((String) group.getFieldValue());
            }

            if (category != null && category.getFieldValueHasChanged()) {
                artifactData.setCategory((String) category.getFieldValue());
            }

            if (status != null && status.getFieldValueHasChanged()) {
                artifactData.setStatus((String) status.getFieldValue());
            }

            if (customer != null && customer.getFieldValueHasChanged()) {
                artifactData.setCustomer((String) customer.getFieldValue());
            }

            if (priority != null && priority.getFieldValueHasChanged()) {
                Object fieldValueObj = priority.getFieldValue();
                int fieldValue = 0;
                if (fieldValueObj instanceof String) {
                    String fieldValueString = (String) fieldValueObj;
                    try {
                        fieldValue = Integer.parseInt(fieldValueString);
                    } catch (NumberFormatException e) {
                        throw new CCFRuntimeException(
                                "Could not parse value of mandatory field priority: " + e.getMessage(), e);
                    }
                } else if (fieldValueObj instanceof Integer) {
                    fieldValue = ((Integer) fieldValueObj).intValue();
                }
                artifactData.setPriority(fieldValue);
            }

            if (!autoSummingTurnedOn && estimatedEfforts != null
                    && estimatedEfforts.getFieldValueHasChanged()) {
                Object fieldValueObj = estimatedEfforts.getFieldValue();
                int fieldValue = 0;
                if (fieldValueObj instanceof String) {
                    String fieldValueString = (String) fieldValueObj;
                    try {
                        fieldValue = Integer.parseInt(fieldValueString);
                    } catch (NumberFormatException e) {
                        throw new CCFRuntimeException(
                                "Could not parse value of mandatory field estimatedEffort: " + e.getMessage(),
                                e);
                    }
                } else if (fieldValueObj instanceof Integer) {
                    fieldValue = ((Integer) fieldValueObj).intValue();
                }
                artifactData.setEstimatedEffort(fieldValue);
            }

            if (!autoSummingTurnedOn && actualEfforts != null && actualEfforts.getFieldValueHasChanged()) {
                Object fieldValueObj = actualEfforts.getFieldValue();
                int fieldValue = 0;
                if (fieldValueObj instanceof String) {
                    String fieldValueString = (String) fieldValueObj;
                    try {
                        fieldValue = Integer.parseInt(fieldValueString);
                    } catch (NumberFormatException e) {
                        throw new CCFRuntimeException(
                                "Could not parse value of mandatory field actualEffort: " + e.getMessage(), e);
                    }
                } else if (fieldValueObj instanceof Integer) {
                    fieldValue = ((Integer) fieldValueObj).intValue();
                }
                artifactData.setActualEffort(fieldValue);
            }

            if (!autoSummingTurnedOn && remainingEfforts != null
                    && remainingEfforts.getFieldValueHasChanged()) {
                Object fieldValueObj = remainingEfforts.getFieldValue();
                int fieldValue = 0;
                if (fieldValueObj instanceof String) {
                    String fieldValueString = (String) fieldValueObj;
                    try {
                        fieldValue = Integer.parseInt(fieldValueString);
                    } catch (NumberFormatException e) {
                        throw new CCFRuntimeException(
                                "Could not parse value of mandatory field remainingEffort: " + e.getMessage(),
                                e);
                    }
                } else if (fieldValueObj instanceof Integer) {
                    fieldValue = ((Integer) fieldValueObj).intValue();
                }
                artifactData.setRemainingEffort(fieldValue);
            }

            if (assignedTo != null && assignedTo.getFieldValueHasChanged()) {
                artifactData.setAssignedTo((String) assignedTo.getFieldValue());
            }

            if (planningFolderId != null && planningFolderId.getFieldValueHasChanged()) {
                artifactData.setPlanningFolderId((String) planningFolderId.getFieldValue());
            }

            if (statusClass != null && statusClass.getFieldValueHasChanged()) {
                artifactData.setStatusClass((String) statusClass.getFieldValue());
            }

            if (closeDate != null && closeDate.getFieldValueHasChanged()) {
                Object fieldValueObj = closeDate.getFieldValue();
                Date fieldValue = null;
                if (fieldValueObj instanceof String) {
                    String fieldValueString = (String) fieldValueObj;
                    fieldValue = DateUtil.parse(fieldValueString);
                } else if (fieldValueObj instanceof Date) {
                    fieldValue = (Date) fieldValueObj;
                }
                artifactData.setCloseDate(fieldValue);
            }

            if (reportedReleaseId != null && reportedReleaseId.getFieldValueHasChanged()) {
                String reportedReleaseIdString = (String) reportedReleaseId.getFieldValue();
                if (translateTechnicalReleaseIds) {
                    reportedReleaseIdString = convertReleaseId(connection, reportedReleaseIdString,
                            folderIdString, packageReleaseSeparatorString);
                }
                artifactData.setReportedReleaseId(reportedReleaseIdString);
            }

            if (resolvedReleaseId != null && resolvedReleaseId.getFieldValueHasChanged()) {
                String resolvedReleaseIdString = (String) resolvedReleaseId.getFieldValue();
                if (translateTechnicalReleaseIds) {
                    resolvedReleaseIdString = convertReleaseId(connection, resolvedReleaseIdString,
                            folderIdString, packageReleaseSeparatorString);
                }
                artifactData.setResolvedReleaseId(resolvedReleaseIdString);
            }

            if (storyPoints != null && storyPoints.getFieldValueHasChanged()) {
                Object fieldValueObj = storyPoints.getFieldValue();
                int fieldValue = 0;
                if (fieldValueObj instanceof String) {
                    String fieldValueString = (String) fieldValueObj;
                    try {
                        fieldValue = Integer.parseInt(fieldValueString);
                    } catch (NumberFormatException e) {
                        throw new CCFRuntimeException(
                                "Could not parse value of mandatory field points: " + e.getMessage(), e);
                    }
                } else if (fieldValueObj instanceof Integer) {
                    fieldValue = ((Integer) fieldValueObj).intValue();
                }
                artifactData.setPoints(fieldValue);
            }

            artifactData.setFlexFields(flexFields);
            String firstComment = comments.length > 0 ? comments[0] : null;
            connection.getTrackerClient().setArtifactData(artifactData, firstComment, null, null, null);
        } catch (AxisFault e) {
            javax.xml.namespace.QName faultCode = e.getFaultCode();
            if (!faultCode.getLocalPart().equals("VersionMismatchFault")) {
                throw e;
            }
            logConflictResolutor.warn("Stale update for TF tracker item " + Id + " in tracker " + trackerId
                    + ". Trying again ...", e);
            mainArtifactNotUpdated = true;
        }
    }
    // increase version number for comment updates
    if (comments.length != 0) {
        artifactData.setVersion(artifactData.getVersion() + 1);
    }

    boolean first = true;
    for (String comment : comments) {
        if (first) {
            // we already processed the first comment above.
            first = false;
            continue;
        }
        boolean commentNotUpdated = true;
        while (commentNotUpdated) {
            try {
                commentNotUpdated = false;
                if (StringUtils.isEmpty(comment)) {
                    continue;
                }
                connection.getTrackerClient().setArtifactData(artifactData, comment, null, null, null);
                artifactData.setVersion(artifactData.getVersion() + 1);
            } catch (AxisFault e) {
                javax.xml.namespace.QName faultCode = e.getFaultCode();
                if (!faultCode.getLocalPart().equals("VersionMismatchFault")) {
                    throw e;
                }
                logConflictResolutor.warn("Stale comment update, trying again ...:", e);
                artifactData = connection.getTrackerClient().getArtifactData(Id);
                commentNotUpdated = true;
            }
        }
    }

    // it looks as if since TF 5.3, not every update call automatically
    // increases the version number
    // hence we retrieve the artifact version here again
    //if (comments.length == 0) {
    // artifactData.setVersion(artifactData.getVersion() + 1);
    artifactData = connection.getTrackerClient().getArtifactData(Id);
    //}

    if (associateWithParent) {
        createArtifactDependency(connection, newParentId, Id, "CCF generated parent-child relationship");
    }

    log.info("Artifact updated id: " + artifactData.getId() + " in " + artifactData.getFolderId());
    return artifactData;
}

From source file:lux.solr.XQueryComponent.java

private String handleEXPathResponse(SolrQueryRequest req, SolrQueryResponse rsp, NamedList<Object> xpathResults,
        XdmItem xpathResult) {/*from  w w w.ja  va  2  s.com*/
    XdmNode expathResponse;
    expathResponse = (XdmNode) xpathResult;
    HttpServletRequest httpReq = (HttpServletRequest) req.getContext()
            .get(SolrQueryContext.LUX_HTTP_SERVLET_REQUEST);
    HttpServletResponse httpResp = (HttpServletResponse) httpReq
            .getAttribute(SolrQueryContext.LUX_HTTP_SERVLET_RESPONSE);
    TinyElementImpl responseNode = (TinyElementImpl) expathResponse.getUnderlyingNode();
    // Get the status code and message
    String status = responseNode.getAttributeValue("", "status");
    String message = responseNode.getAttributeValue("", "message");
    int istatus = 200;
    if (status != null) {
        try {
            istatus = Integer.parseInt(status);
        } catch (NumberFormatException e) {
            throw new LuxException("Non-numeric response status code: " + status);
        }
        if (istatus >= 400) {
            try {
                if (message != null) {
                    httpResp.sendError(istatus, message);
                } else {
                    httpResp.sendError(istatus);
                }
            } catch (IOException e) {
                logger.error("sendError failed: " + e.getMessage());
            }
        }
        // if an error is generated by the query, call sendError?
        httpResp.setStatus(istatus);
    }
    // Get the body, its charset and content-type and return the body to be used as the result
    XdmSequenceIterator children = expathResponse.axisIterator(Axis.CHILD);
    while (children.hasNext()) {
        XdmNode child = (XdmNode) children.next();
        net.sf.saxon.s9api.QName childName = child.getNodeName();
        if (!childName.getNamespaceURI().equals(EXPATH_HTTP_NS)) {
            logger.warn("ignoring unknown response child element: " + childName.getClarkName());
            continue;
        }
        if (childName.getLocalName().equals("body")) {
            // got the body
            String src = child.getAttributeValue(qnameFor("src"));
            if (src != null) {
                throw new LuxException("The body/@src attribute is not supported");
            }
            String characterSet = child.getAttributeValue(qnameFor("charset"));
            if (characterSet == null) {
                characterSet = "utf-8";
            }
            String contentType = child.getAttributeValue(qnameFor("content-type"));
            if (contentType != null) {
                contentType += "; charset=" + characterSet;
            }
            if (contentType == null) {
                contentType = req.getParams().get("lux.contentType", contentType);
                if (contentType != null) {
                    contentType = contentType.replaceFirst("(?<=; charset=).*", characterSet);
                }
            }
            if (contentType != null) {
                req.getContext().put("lux.contentType", contentType);
            }
            XdmSequenceIterator bodyKids = child.axisIterator(Axis.CHILD);
            while (bodyKids.hasNext()) {
                XdmNode result = (XdmNode) bodyKids.next();
                String err = safeAddResult(xpathResults, result);
                if (err != null) {
                    return err;
                }
            }
        } else if (childName.getLocalName().equals("header")) {
            String header = child.getAttributeValue(qnameFor("name"));
            String value = child.getAttributeValue(qnameFor("value"));
            httpResp.addHeader(header, value);
        } else if (childName.getLocalName().equals("multipart")) {
            throw new LuxException("Multipart HTTP responses not implemented");
        }
    }
    /*
    if (istatus >= 300 && istatus < 400) {
    httpResp.sendRedirect(location);
    }
    */
    if (expathResponse != null) {
        // TODO: pass the expathResponse to the LuxResponseWriter -- why?
        req.getContext().put("expath:response", expathResponse);
    }
    return null;
}

From source file:com.liferay.portal.struts.PortalTilesDefinitionsFactory.java

/**
 * Initialization method./*from  w  w w.  j  a  v a2  s  .c  om*/
 * Init the factory by reading appropriate configuration file.
 * This method is called exactly once immediately after factory creation in
 * case of internal creation (by DefinitionUtil).
 * @param servletContext Servlet Context passed to newly created factory.
 * @param properties Map of name/property passed to newly created factory. Map can contains
 * more properties than requested.
 * @throws DefinitionsFactoryException An error occur during initialization.
 */
public void initFactory(ServletContext servletContext, Map properties) throws DefinitionsFactoryException {
    // Set some property values
    String value = (String) properties.get(PARSER_VALIDATE_PARAMETER_NAME);
    if (value != null) {
        isValidatingParser = Boolean.valueOf(value).booleanValue();
    }

    value = (String) properties.get(PARSER_DETAILS_PARAMETER_NAME);
    if (value != null) {
        try {
            parserDetailLevel = Integer.valueOf(value).intValue();

        } catch (NumberFormatException ex) {
            log.error("Bad format for parameter '" + PARSER_DETAILS_PARAMETER_NAME + "'. Integer expected.");
        }
    }

    // init factory withappropriate configuration file
    // Try to use provided filename, if any.
    // If no filename are provided, try to use default ones.
    String filename = (String) properties.get(DEFINITIONS_CONFIG_PARAMETER_NAME);
    if (filename != null) { // Use provided filename
        try {
            initFactory(servletContext, filename);
            if (log.isDebugEnabled()) {
                log.debug("Factory initialized from file '" + filename + "'.");
            }

        } catch (FileNotFoundException ex) { // A filename is specified, throw appropriate error.
            log.error(ex.getMessage() + " : Can't find file '" + filename + "'");
            throw new FactoryNotFoundException(ex.getMessage() + " : Can't find file '" + filename + "'");
        }

    } else { // try each default file names
        for (int i = 0; i < DEFAULT_DEFINITION_FILENAMES.length; i++) {
            filename = DEFAULT_DEFINITION_FILENAMES[i];
            try {
                initFactory(servletContext, filename);
                if (log.isInfoEnabled()) {
                    log.info("Factory initialized from file '" + filename + "'.");
                }
            } catch (FileNotFoundException ex) {
                // Do nothing
            }
        }
    }

}