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:edu.sdsc.nbcr.opal.OpalClient.java

/**
 * This method instantiates the parameters needed for the submission of a
 * Opal job without metadata/* w  ww.j  a v  a  2s. c o m*/
 */
private void _createSimpleSubmission(AppMetadata app) throws IllegalActionException {
    _emptyParamtersArray();
    // TODO delete this _interfaceParameters is useless
    log.info("Creating simple submission form. For service URL: " + app.getURL());
    try {
        (new StringParameter(this, "commandLine")).setContainer(this);
        (new StringParameter(this, "cpuNumber")).setContainer(this);
        // let's try to get the number of files
        int numFiles;
        try {
            numFiles = Integer.parseInt(numberFiles.stringValue());
        } catch (NumberFormatException e) {
            throw new IllegalActionException(this,
                    "The numberFiles parameter is not a valid integer, please correct the value");
        }
        _updateUploadFileNumber(numFiles);
    } catch (NameDuplicationException e) {
        log.error("The parameter could not be instantiated. Error message: " + e.getMessage(), e);
    }

}

From source file:at.ac.tuwien.dsg.quelle.cloudDescriptionParsers.impl.AmazonCloudJSONDescriptionParser.java

private void addReservedCostOptions(String schemeName, String pricingSchemeURL, CloudProvider cloudProvider,
        Map<String, CloudOfferedService> units,
        Map<String, List<ElasticityCapability.Dependency>> costDependencies)
        throws MalformedURLException, IOException, ParseException {
    {/*  ww w. j a v a2 s.  co  m*/

        URL url = new URL(pricingSchemeURL);

        BufferedReader reader = new BufferedReader(
                new InputStreamReader(url.openConnection().getInputStream()));
        String json = "";
        String line = "";
        while ((line = reader.readLine()) != null) {
            json += line;
        }

        //remove newline
        json = json.replace("\\n", "");
        json = json.replace(" ", "");

        //for some URLs, the JSON is not json, it does not contain {"name, instead is {name
        if (!json.contains("{\"")) {
            json = json.replace("{", "{\"");
            json = json.replace(":", "\":");
            json = json.replace(",", ",\"");

            //fix overreplace from above
            json = json.replace("\"{", "{");
            json = json.replace("\"\"", "\"");
        }

        //remove "callback"
        json = json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1);
        //            System.out.println(json);
        //            System.exit(1);

        JSONObject obj = (JSONObject) JSONValue.parseWithException(json);

        //get regions
        JSONArray regions = (JSONArray) ((JSONObject) obj.get("config")).get("regions");

        for (int i = 0; i < regions.size(); i++) {
            JSONObject region = (JSONObject) regions.get(i);
            if (region.get("region").toString().equals("us-east")) {

                //types separate GeneralPurpose, and ComputeOptimized, etc
                JSONArray instanceTypes = (JSONArray) region.get("instanceTypes");
                for (int instanceIndex = 0; instanceIndex < instanceTypes.size(); instanceIndex++) {
                    JSONObject instance = (JSONObject) instanceTypes.get(instanceIndex);

                    //sizes separate m1.small, etc
                    // sizes:[{valueColumns:[{name:"yrTerm1",prices:{USD:"110"}},{name:"yrTerm1Hourly",rate:"perhr",prices:{USD:"0.064"}},{name:"yrTerm3",prices:{USD:"172"}},{name:"yrTerm3Hourly",rate:"perhr",prices:{USD:"0.05"}}],size:"m3.medium"
                    JSONArray sizes = (JSONArray) instance.get("sizes");
                    for (int sizeIndex = 0; sizeIndex < sizes.size(); sizeIndex++) {

                        JSONObject size = (JSONObject) sizes.get(sizeIndex);

                        String sizeName = size.get("size").toString();

                        if (units.containsKey(sizeName)) {

                            CostFunction _1YearReservedCost = new CostFunction(
                                    "1Year" + schemeName + "Cost_" + sizeName);
                            CostFunction _3YearReservedCost = new CostFunction(
                                    "3Year" + schemeName + "Cost_" + sizeName);

                            List<ElasticityCapability.Dependency> costElasticityTargets = null;
                            if (costDependencies.containsKey(sizeName)) {
                                costElasticityTargets = costDependencies.get(sizeName);
                            } else {
                                costElasticityTargets = new ArrayList<>();
                                costDependencies.put(sizeName, costElasticityTargets);
                            }

                            costElasticityTargets.add(new ElasticityCapability.Dependency(_1YearReservedCost,
                                    ElasticityCapability.Type.OPTIONAL_ASSOCIATION)
                                            .withVolatility(new Volatility(365 * 24, 1))); //365 days in 1 year, times 24 hours
                            costElasticityTargets.add(new ElasticityCapability.Dependency(_3YearReservedCost,
                                    ElasticityCapability.Type.OPTIONAL_ASSOCIATION)
                                            .withVolatility(new Volatility(3 * 365 * 24, 1))); //365 days in 1 year, times 24 hours

                            //                                ServiceUnit unit = units.get(sizeName);
                            JSONArray prices = (JSONArray) size.get("valueColumns");
                            for (int priceIndex = 0; priceIndex < prices.size(); priceIndex++) {
                                JSONObject price = (JSONObject) prices.get(priceIndex);
                                String priceName = price.get("name").toString();

                                //                                ServiceUnit _1YearReservationScheme = new ServiceUnit("Management", "ReservationScheme", "1YearLightUtilization");
                                //                                cloudProvider.addCloudOfferedService(_1YearReservationScheme);
                                //                                
                                //                                Resource r = new Resource("ReservationPeriod");
                                //                                r.addProperty(new Metric("Reservation", "duration"), new MetricValue("1 year"));
                                String priceValue = ((JSONObject) price.get("prices")).get("USD").toString();
                                try {
                                    Double convertedPriceValue = Double.parseDouble(priceValue);
                                    switch (priceName) {
                                    case "yrTerm1": {
                                        CostElement upfrontCost = new CostElement("UpfrontCost",
                                                new Metric("OneTimePay", "value", Metric.MetricType.COST),
                                                CostElement.Type.PERIODIC);
                                        upfrontCost.addBillingInterval(new MetricValue(1), convertedPriceValue);
                                        _1YearReservedCost.addCostElement(upfrontCost);
                                    }
                                        break;
                                    case "yrTerm1Hourly": {
                                        CostElement hourlyCost = new CostElement("vmCost",
                                                new Metric("instance", "#", Metric.MetricType.COST),
                                                CostElement.Type.PERIODIC)
                                                        .withBillingCycle(CostElement.BillingCycle.HOUR);
                                        hourlyCost.addBillingInterval(new MetricValue(1), convertedPriceValue);
                                        _1YearReservedCost.addCostElement(hourlyCost);
                                    }
                                        break;

                                    case "yrTerm3": {
                                        CostElement upfrontCost = new CostElement("UpfrontCost",
                                                new Metric("OneTimePay", "value", Metric.MetricType.COST),
                                                CostElement.Type.PERIODIC);
                                        upfrontCost.addBillingInterval(new MetricValue(1), convertedPriceValue);
                                        _3YearReservedCost.addCostElement(upfrontCost);
                                    }
                                        break;
                                    case "yrTerm3Hourly": {
                                        CostElement hourlyCost = new CostElement("vmCost",
                                                new Metric("instance", "#", Metric.MetricType.COST),
                                                CostElement.Type.PERIODIC)
                                                        .withBillingCycle(CostElement.BillingCycle.HOUR);
                                        hourlyCost.addBillingInterval(new MetricValue(1), convertedPriceValue);
                                        _3YearReservedCost.addCostElement(hourlyCost);
                                    }
                                        break;

                                    }
                                } catch (java.lang.NumberFormatException exception) {
                                    log.error(exception.getMessage(), exception);

                                }

                            }
                        }

                    }
                }

            }

        }

    }
}

From source file:com.sfs.whichdoctor.search.http.PersonInputHandler.java

/**
 * Process the RACP Membership search parameters.
 *
 * @param request the request/*from  ww w .j  a va  2 s. c o m*/
 *
 * @return the membership bean[]
 */
private MembershipBean[] processRACPMembership(final HttpServletRequest request) {

    MembershipBean criteria = membershipDAO.getInstance("RACP", "");
    MembershipBean constraints = membershipDAO.getInstance("RACP", "");

    String strCandidateA = DataFilter.getHtml(request.getParameter("candidateNumberA"));
    String strCandidateB = DataFilter.getHtml(request.getParameter("candidateNumberB"));
    String strDivision = DataFilter.getHtml(request.getParameter("division"));
    String strMemberClass = DataFilter.getHtml(request.getParameter("membershipClass"));
    String strMemberType = DataFilter.getHtml(request.getParameter("membershipType"));
    String strStatus = DataFilter.getHtml(request.getParameter("status"));
    String strTrainingType = DataFilter.getHtml(request.getParameter("trainingType"));
    String strSupervisorStatus = DataFilter.getHtml(request.getParameter("supervisorStatus"));
    String strFinancialExcemption = DataFilter.getHtml(request.getParameter("financialExcemption"));
    String strRegionRepresentative = DataFilter.getHtml(request.getParameter("regionRepresentative"));
    String strJoinedDateA = DataFilter.getHtml(request.getParameter("joinedDateA"));
    String strJoinedDateB = DataFilter.getHtml(request.getParameter("joinedDateB"));
    String strLeftDateA = DataFilter.getHtml(request.getParameter("leftDateA"));
    String strLeftDateB = DataFilter.getHtml(request.getParameter("leftDateB"));

    /* Add Candidate Number to criteria if successfully parsed to int */
    try {
        int criteriaCN = Integer.parseInt(strCandidateA);
        criteria.setField("Candidate Number", new Integer(criteriaCN));
    } catch (NumberFormatException nfe) {
        dataLogger.debug("Error parsing Candidate Number A: " + nfe.getMessage());
    }

    if (strCandidateB != null) {
        int constraintCN = 0;
        try {
            constraintCN = Integer.parseInt(strCandidateB);
        } catch (NumberFormatException nfe) {
            dataLogger.debug("Error parsing Candidate Number B: " + nfe.getMessage());
        }
        if (strCandidateB.compareTo("+") == 0) {
            constraintCN = MAX_ID;
        }
        if (strCandidateB.compareTo("-") == 0) {
            constraintCN = -1;
        }
        constraints.setField("Candidate Number", new Integer(constraintCN));
    }
    if (strSupervisorStatus != null) {
        if (strSupervisorStatus.compareTo("Null") != 0) {
            criteria.setField("Supervisor Status", strSupervisorStatus);
        }
    }

    if (strDivision != null) {
        if (strDivision.compareTo("Null") != 0) {
            ObjectTypeBean object = new ObjectTypeBean();
            object.setClassName(strDivision);
            object.setName("");
            criteria.setField("Division", object);
        }
    }

    ObjectTypeBean membership = new ObjectTypeBean();
    if (StringUtils.isNotBlank(strMemberClass) && !StringUtils.equalsIgnoreCase(strMemberClass, "Null")) {
        membership.setClassName(strMemberClass);

        if (StringUtils.isNotBlank(strMemberType) && !StringUtils.equalsIgnoreCase(strMemberType, "Any")) {
            membership.setName(strMemberType);
        }
        criteria.setField("Membership Type", membership);
    }

    if (StringUtils.isNotBlank(strStatus)) {
        if (!StringUtils.equalsIgnoreCase(strStatus, "Null")) {
            ObjectTypeBean object = new ObjectTypeBean();
            object.setClassName(strStatus);
            criteria.setField("Status", object);
        }
    }
    if (strTrainingType != null) {
        if (strTrainingType.compareTo("") != 0 && strTrainingType.compareTo("Null") != 0) {
            ObjectTypeBean object = new ObjectTypeBean();
            object.setClassName(strTrainingType);
            criteria.setField("Training Type", object);
        }
    }
    if (this.getFunctionality().isEnabled("Region Representatives")
            && StringUtils.isNotBlank(strRegionRepresentative)
            && !StringUtils.equals(strRegionRepresentative, "Null")) {

        final ObjectTypeBean object = new ObjectTypeBean();
        object.setClassName(strRegionRepresentative);
        criteria.setField("Region Representative", object);
    }

    if (StringUtils.equalsIgnoreCase(strFinancialExcemption, "Yes")) {
        criteria.setField("Financial Excemption", "Yes");
    }

    if (StringUtils.equalsIgnoreCase(strFinancialExcemption, "No")) {
        criteria.setField("Financial Excemption", "No");
    }

    if (strJoinedDateA != null) {
        if (strJoinedDateA.compareTo("") != 0) {
            criteria.setJoinedDate(DataFilter.parseDate(strJoinedDateA, false));
        }
    }
    if (strJoinedDateB != null) {
        if (strJoinedDateB.compareTo("") != 0) {

            constraints.setJoinedDate(DataFilter.parseDate(strJoinedDateB, false));

            if (strJoinedDateB.compareTo("+") == 0) {
                // All dates above Date A requested
                constraints.setJoinedDate(getMaximumDate());
            }
            if (strJoinedDateB.compareTo("-") == 0) {
                // Add dates below Date A requested
                constraints.setJoinedDate(getMinimumDate());
            }
        }
    }

    if (strLeftDateA != null) {
        if (strLeftDateA.compareTo("") != 0) {
            criteria.setLeftDate(DataFilter.parseDate(strLeftDateA, false));
        }
    }
    if (strLeftDateB != null) {
        if (strLeftDateB.compareTo("") != 0) {

            constraints.setLeftDate(DataFilter.parseDate(strLeftDateB, false));

            if (strLeftDateB.compareTo("+") == 0) {
                // All dates above Date A requested
                constraints.setLeftDate(getMaximumDate());
            }
            if (strLeftDateB.compareTo("-") == 0) {
                // Add dates below Date A requested
                constraints.setLeftDate(getMinimumDate());
            }
        }
    }

    return new MembershipBean[] { criteria, constraints };
}

From source file:dao.DatasetsDAO.java

public static boolean postComment(int datasetId, Map<String, String[]> commentMap, String user) {
    boolean result = false;
    if ((commentMap == null) || commentMap.size() == 0) {
        return false;
    }/* w  ww. j a  v  a 2s. co m*/

    String text = "";
    if (commentMap.containsKey("text")) {
        String[] textArray = commentMap.get("text");
        if (textArray != null && textArray.length > 0) {
            text = textArray[0];
        }
    }
    if (StringUtils.isBlank(text)) {
        return false;
    }

    String type = "Comment";
    if (commentMap.containsKey("type")) {
        String[] typeArray = commentMap.get("type");
        if (typeArray != null && typeArray.length > 0) {
            type = typeArray[0];
        }
    }

    Integer commentId = 0;
    if (commentMap.containsKey("id")) {
        String[] idArray = commentMap.get("id");
        if (idArray != null && idArray.length > 0) {
            String idStr = idArray[0];
            try {
                commentId = Integer.parseInt(idStr);
            } catch (NumberFormatException e) {
                Logger.error("DatasetDAO postComment wrong id parameter. Error message: " + e.getMessage());
                commentId = 0;
            }
        }
    }

    Integer userId = UserDAO.getUserIDByUserName(user);

    if (userId != null && userId != 0) {
        if (commentId != null && commentId != 0) {
            int row = getJdbcTemplate().update(UPDATE_DATASET_COMMENT, text, type, commentId);
            if (row > 0) {
                result = true;
            }
        } else {
            int row = getJdbcTemplate().update(CREATE_DATASET_COMMENT, text, userId, datasetId, type);
            if (row > 0) {
                result = true;
            }
        }
    }
    return result;
}

From source file:dao.DatasetsDAO.java

public static String watchURN(Map<String, String[]> params, String user) {
    String message = "Internal error";
    if (params == null || params.size() == 0) {
        return "Empty post body";
    }//  w ww  .ja va2 s . c o  m

    String urn = "";
    if (params.containsKey("urn")) {
        String[] urnArray = params.get("urn");
        if (urnArray != null && urnArray.length > 0) {
            urn = urnArray[0];
        }
    }
    if (StringUtils.isBlank(urn)) {
        return "urn parameter is missing";
    }

    String notificationType = "";
    if (params.containsKey("notification_type")) {
        String[] notificationTypeArray = params.get("notification_type");
        if (notificationTypeArray != null && notificationTypeArray.length > 0) {
            notificationType = notificationTypeArray[0];
        }
    }
    if (StringUtils.isBlank(notificationType)) {
        return "notification_type is missing";
    }

    Long watchId = 0L;
    if (params.containsKey("id")) {
        String[] watchIdArray = params.get("id");
        if (watchIdArray != null && watchIdArray.length > 0) {
            try {
                watchId = Long.parseLong(watchIdArray[0]);
            } catch (NumberFormatException e) {
                Logger.error("DatasetDAO watchURN wrong watch_id parameter. Error message: " + e.getMessage());
                watchId = 0L;
            }
        }
    }

    Integer userId = UserDAO.getUserIDByUserName(user);

    if (userId != null && userId != 0) {
        List<Map<String, Object>> rows = null;
        rows = getJdbcTemplate().queryForList(GET_WATCHED_URN_ID, userId, urn);
        if (rows != null && rows.size() > 0) {
            message = "watch item is already exist";
        } else {
            int row = 0;
            if (watchId > 0) {
                row = getJdbcTemplate().update(UPDATE_URN_WATCH, userId, urn, notificationType, watchId);
            } else {
                row = getJdbcTemplate().update(WATCH_URN, userId, urn, notificationType);
            }
            if (row > 0) {
                message = "";
            }
        }
    } else {
        message = "User not found";
    }
    return message;
}

From source file:com.gemstone.gemfire.management.internal.cli.functions.DataCommandFunction.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private Object getClassObject(String string, String klassString)
        throws ClassNotFoundException, IllegalArgumentException {
    if (klassString == null || klassString.isEmpty())
        return string;
    else {/*from  www  .  j  av  a2 s  .c om*/
        Object o = null;
        Class klass = ClassPathLoader.getLatest().forName(klassString);

        if (klass.equals(String.class))
            return string;

        if (JsonUtil.isPrimitiveOrWrapper(klass)) {
            try {
                if (klass.equals(Byte.class)) {
                    o = Byte.parseByte(string);
                    return o;
                } else if (klass.equals(Short.class)) {
                    o = Short.parseShort(string);
                    return o;
                } else if (klass.equals(Integer.class)) {
                    o = Integer.parseInt(string);
                    return o;
                } else if (klass.equals(Long.class)) {
                    o = Long.parseLong(string);
                    return o;
                } else if (klass.equals(Double.class)) {
                    o = Double.parseDouble(string);
                    return o;
                } else if (klass.equals(Boolean.class)) {
                    o = Boolean.parseBoolean(string);
                    return o;
                } else if (klass.equals(Float.class)) {
                    o = Float.parseFloat(string);
                    return o;
                }
                return o;
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException(
                        "Failed to convert input key to " + klassString + " Msg : " + e.getMessage());
            }
        }

        try {
            o = getObjectFromJson(string, klass);
            return o;
        } catch (IllegalArgumentException e) {
            throw e;
        }
    }
}

From source file:dao.DatasetsDAO.java

public static String watchDataset(int datasetId, Map<String, String[]> params, String user) {
    String message = "Internal error";
    if (params == null || params.size() == 0) {
        return "Empty post body";
    }//from  ww w  . j  a v  a 2s  .  com

    String notificationType = "";
    if (params.containsKey("notification_type")) {
        String[] notificationTypeArray = params.get("notification_type");
        if (notificationTypeArray != null && notificationTypeArray.length > 0) {
            notificationType = notificationTypeArray[0];
        }
    }
    if (StringUtils.isBlank(notificationType)) {
        return "notification_type is missing";
    }

    Long watchId = 0L;
    if (params.containsKey("id")) {
        String[] watchIdArray = params.get("id");
        if (watchIdArray != null && watchIdArray.length > 0) {
            try {
                watchId = Long.parseLong(watchIdArray[0]);
            } catch (NumberFormatException e) {
                Logger.error(
                        "DatasetDAO watchDataset wrong watch_id parameter. Error message: " + e.getMessage());
                watchId = 0L;
            }
        }
    }

    Integer userId = UserDAO.getUserIDByUserName(user);

    if (userId != null && userId != 0) {
        List<Map<String, Object>> rows = null;
        rows = getJdbcTemplate().queryForList(GET_WATCHED_DATASET_ID, userId, datasetId);
        if (rows != null && rows.size() > 0) {
            message = "watch item already exist";
        } else {
            int row = 0;
            if (watchId > 0) {
                row = getJdbcTemplate().update(UPDATE_DATASET_WATCH, userId, datasetId, notificationType,
                        watchId);
            } else {
                row = getJdbcTemplate().update(WATCH_DATASET, userId, datasetId, notificationType);
            }
            if (row > 0) {
                message = "";
            }
        }
    } else {
        message = "User not found";
    }
    return message;
}

From source file:info.magnolia.module.admininterface.dialogs.RolesEditDialog.java

protected boolean onPostSave(SaveHandler saveControl) {
    Content role = this.getStorageNode();

    // for each repository
    Iterator repositoryNames = ContentRepository.getAllRepositoryNames();
    while (repositoryNames.hasNext()) {
        String repository = (String) repositoryNames.next();

        // ######################
        // # acl/*from   w w  w  .jav a 2  s.  c  o m*/
        // ######################
        // remove existing
        try {
            role.delete("acl_" + repository); //$NON-NLS-1$
        } catch (RepositoryException re) {
            // ignore, not existing
        }
        // rewrite
        try {
            Content acl = role.createContent("acl_" + repository, ItemType.CONTENTNODE); //$NON-NLS-1$
            String aclValueStr = form.getParameter("acl" + repository + "List"); //$NON-NLS-1$ //$NON-NLS-2$
            if (StringUtils.isNotEmpty(aclValueStr)) {
                String[] aclEntries = aclValueStr.split(";"); //$NON-NLS-1$
                for (int i = 0; i < aclEntries.length; i++) {
                    String path = StringUtils.EMPTY;
                    long accessRight = 0;
                    int accessType = 0;

                    String[] aclValuePairs = aclEntries[i].split(","); //$NON-NLS-1$
                    for (int j = 0; j < aclValuePairs.length; j++) {
                        String[] aclValuePair = aclValuePairs[j].split(":"); //$NON-NLS-1$
                        String aclName = aclValuePair[0].trim();
                        String aclValue = StringUtils.EMPTY;
                        if (aclValuePair.length > 1) {
                            aclValue = aclValuePair[1].trim();
                        }

                        if (aclName.equals("path")) { //$NON-NLS-1$
                            path = aclValue;
                        } else if (aclName.equals("accessType")) { //$NON-NLS-1$
                            accessType = Integer.valueOf(aclValue).intValue();
                        } else if (aclName.equals("accessRight")) { //$NON-NLS-1$
                            try {
                                accessRight = Long.parseLong(aclValue);
                            } catch (NumberFormatException e) {
                                accessRight = 0;
                            }
                        }
                    }

                    if (StringUtils.isNotEmpty(path)) {
                        if (path.equals("/")) { //$NON-NLS-1$
                            accessType = RolesACLPage.TYPE_SUBS; //$NON-NLS-1$
                            path = StringUtils.EMPTY;
                        }

                        if ((accessType & RolesACLPage.TYPE_THIS) != 0) {
                            try {
                                String newLabel = Path.getUniqueLabel(hm, acl.getHandle(), "0"); //$NON-NLS-1$
                                Content r = acl.createContent(newLabel, ItemType.CONTENTNODE);
                                r.createNodeData("path").setValue(path); //$NON-NLS-1$
                                r.createNodeData("permissions").setValue(accessRight); //$NON-NLS-1$
                            } catch (Exception e) {
                                log.error(e.getMessage(), e);
                            }
                        }

                        if ((accessType & RolesACLPage.TYPE_SUBS) != 0) {
                            try {
                                String newLabel = Path.getUniqueLabel(hm, acl.getHandle(), "0"); //$NON-NLS-1$
                                Content r = acl.createContent(newLabel, ItemType.CONTENTNODE);
                                r.createNodeData("path").setValue(path + "/*"); //$NON-NLS-1$ //$NON-NLS-2$
                                r.createNodeData("permissions").setValue(accessRight); //$NON-NLS-1$
                            } catch (Exception e) {
                                log.error(e.getMessage(), e);
                            }
                        }
                    }
                }
            }
            hm.save();
        } catch (RepositoryException re) {
            log.error(re.getMessage(), re);
        }
    }
    return true;
}

From source file:dao.DatasetsDAO.java

public static String postColumnComment(int datasetId, int columnId, Map<String, String[]> params, String user) {
    String result = "Post comment failed. Please try again.";
    if (params == null || params.size() == 0) {
        return result;
    }/* w  ww . j a v a  2 s . co m*/

    String text = "";
    if (params.containsKey("text")) {
        String[] textArray = params.get("text");
        if (textArray != null && textArray.length > 0) {
            text = textArray[0];
        }
    }
    if (StringUtils.isBlank(text)) {
        return "Please input valid comment.";
    }

    Long commentId = 0L;
    if (params.containsKey("id")) {
        String[] idArray = params.get("id");
        if (idArray != null && idArray.length > 0) {
            String idStr = idArray[0];
            try {
                commentId = Long.parseLong(idStr);
            } catch (NumberFormatException e) {
                Logger.error(
                        "DatasetDAO postColumnComment wrong id parameter. Error message: " + e.getMessage());
                commentId = 0L;
            }
        }
    }

    Integer userId = 0;
    try {
        userId = (Integer) getJdbcTemplate().queryForObject(GET_USER_ID, Integer.class, user);
    } catch (EmptyResultDataAccessException e) {
        Logger.error("Dataset postColumnComment get user id failed, username = " + user);
        Logger.error("Exception = " + e.getMessage());
    }

    if (userId != null && userId != 0) {
        if (commentId != null && commentId != 0) {
            int row = getJdbcTemplate().update(UPDATE_COLUMN_COMMENT, text, commentId);
            if (row > 0) {
                result = "";
            }
        } else {
            if (isSameColumnCommentExist(text)) {
                return "Same comment already exists.";
            }
            KeyHolder keyHolder = new GeneratedKeyHolder();
            final String comment = text;
            final int authorId = userId;
            getJdbcTemplate().update(new PreparedStatementCreator() {
                public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                    PreparedStatement pst = con.prepareStatement(CREATE_COLUMN_COMMENT, new String[] { "id" });
                    pst.setString(1, comment);
                    pst.setInt(2, authorId);
                    pst.setString(3, comment);
                    return pst;
                }
            }, keyHolder);
            commentId = (Long) keyHolder.getKey();
            result = "";
        }
    }

    try {
        getJdbcTemplate().update(CREATE_DATASET_COLUMN_COMMENT_REFERENCE, datasetId, columnId, commentId);
    } catch (DataAccessException e) {
        Logger.error("Dataset postColumnComment insert ignore reference, datasetId = "
                + Integer.toString(datasetId) + " columnId = " + Integer.toString(columnId));
        Logger.error("Exception = " + e.getMessage());
    }

    List<Map<String, Object>> defaultComment = null;
    try {
        defaultComment = getJdbcTemplate().queryForList(CHECK_COLUMN_COMMENT_HAS_DEFAULT, datasetId, columnId);
    } catch (DataAccessException e) {
        Logger.error("Dataset postColumnComment - check for default, datasetId = " + Integer.toString(datasetId)
                + " columnId = " + Integer.toString(columnId));
        Logger.error("Exception = " + e.getMessage());
    }

    Boolean hasDefault = false;
    if (defaultComment.size() > 0) {
        hasDefault = true;
    }

    if (hasDefault) {
        result = "";
    } else {
        try {
            getJdbcTemplate().update(SET_COLUMN_COMMENT_DEFAULT, datasetId, columnId, commentId);
            result = "";
        } catch (DataAccessException e) {
            result = "Post comment failed. Please try again.";
            Logger.error("Dataset postColumnComment set default comment, datasetId = "
                    + Integer.toString(datasetId) + " columnId = " + Integer.toString(columnId));
            Logger.error("Exception = " + e.getMessage());
        }
    }
    return result;
}