Example usage for org.apache.commons.lang.math NumberUtils createLong

List of usage examples for org.apache.commons.lang.math NumberUtils createLong

Introduction

In this page you can find the example usage for org.apache.commons.lang.math NumberUtils createLong.

Prototype

public static Long createLong(String str) 

Source Link

Document

Convert a String to a Long.

Returns null if the string is null.

Usage

From source file:com.healthcit.analytics.model.ReportTemplate.java

/**
 * Explicit constructor (parameter is a JSONObject)
 * @return/*www.j  a v a2 s.c  o m*/
 */
public ReportTemplate(JSONObject json, Long ownerId, boolean shared) {
    if (json != null) {
        Object id = JSONUtils.getValue(json, JSON_ID_FIELD);
        this.id = (NumberUtils.isNumber(id + "") ? NumberUtils.createLong(id.toString()) : null);
        this.title = (String) JSONUtils.getValue(json, JSON_TITLE_FIELD);
        Object report = ((JSONObject) JSONUtils.getValue(json, JSON_REPORT_FIELD));
        this.report = report == null ? null : report.toString();
        this.timestamp = (Timestamp) JSONUtils.getValue(json, JSON_TIMESTAMP_FIELD);
        this.ownerId = ownerId;
        this.shared = shared;
    }
}

From source file:com.healthcit.analytics.service.ReportTemplateService.java

@RemoteMethod
public String deleteReportTemplate(String templateId) {
    if (!NumberUtils.isNumber(templateId))
        return null;

    Long id = NumberUtils.createLong(templateId);

    boolean isDeleted = manager.delete(id);

    log.info("Template Id " + templateId + " deleted: " + isDeleted);

    return (isDeleted ? templateId : null);
}

From source file:gr.abiss.calipso.domain.State.java

public State(Element e) {
    this.element = e;
    this.status = Integer.parseInt(e.attributeValue(STATUS));
    String xmlPlugin = e.attributeValue(PLUGIN);
    // plugin/*from  w w w. j  ava 2  s .  c o m*/
    if (StringUtils.isNotBlank(xmlPlugin)) {
        this.plugin = xmlPlugin;
    }
    String xmlAssetTypeId = e.attributeValue(ASSET_TYPE_ID);
    // asset type id
    if (StringUtils.isNotBlank(xmlAssetTypeId)) {
        assetTypeId = NumberUtils.toLong(xmlAssetTypeId);
    }
    String xmlExistingAssetTypeId = e.attributeValue(EXISTING_ASSET_TYPE_ID);
    // asset type id
    if (StringUtils.isNotBlank(xmlExistingAssetTypeId)) {
        existingAssetTypeId = NumberUtils.toLong(xmlExistingAssetTypeId);
    }
    String xmlExistingAssetTypeMultiple = e.attributeValue(EXISTING_ASSET_TYPE_MULTIPLE);
    if (StringUtils.isNotBlank(xmlExistingAssetTypeMultiple)) {
        this.existingAssetTypeMultiple = BooleanUtils.toBoolean(existingAssetTypeMultiple);
    }

    // max duration
    String sMaxDuration = e.attributeValue(MAX_DURATION);
    if (StringUtils.isNotBlank(sMaxDuration)) {
        this.maxDuration = NumberUtils.createLong(e.attributeValue(MAX_DURATION));
    }
    // transition
    for (Object o : e.elements(TRANSITION)) {
        Element t = (Element) o;
        transitions.add(new Integer(t.attributeValue(STATUS)));
    }
    // field
    for (Object o : e.elements(FIELD)) {
        Element f = (Element) o;
        String mask = f.attributeValue(MASK);
        String fieldName = f.attributeValue(NAME);
        fields.put(Field.convertToName(fieldName), NumberUtils.toInt(mask, 1));
    }
}

From source file:com.swordlord.gozer.datatypeformat.DataTypeHelper.java

/**
 * Return compatible class for typedValue based on untypedValueClass 
 * //  w  w w .ja v a2s  .c o m
 * @param untypedValueClass
 * @param typedValue
 * @return
 */
public static Object fromDataType(Class<?> untypedValueClass, Object typedValue) {
    Log LOG = LogFactory.getLog(DataTypeHelper.class);

    if (typedValue == null) {
        return null;
    }

    if (untypedValueClass == null) {
        return typedValue;
    }

    if (ClassUtils.isAssignable(typedValue.getClass(), untypedValueClass)) {
        return typedValue;
    }

    String strTypedValue = null;
    boolean isStringTypedValue = typedValue instanceof String;

    Number numTypedValue = null;
    boolean isNumberTypedValue = typedValue instanceof Number;

    Boolean boolTypedValue = null;
    boolean isBooleanTypedValue = typedValue instanceof Boolean;

    Date dateTypedValue = null;
    boolean isDateTypedValue = typedValue instanceof Date;

    if (isStringTypedValue) {
        strTypedValue = (String) typedValue;
    }
    if (isNumberTypedValue) {
        numTypedValue = (Number) typedValue;
    }
    if (isBooleanTypedValue) {
        boolTypedValue = (Boolean) typedValue;
    }
    if (isDateTypedValue) {
        dateTypedValue = (Date) typedValue;
    }

    Object v = null;
    if (String.class.equals(untypedValueClass)) {
        v = ObjectUtils.toString(typedValue);
    } else if (BigDecimal.class.equals(untypedValueClass)) {
        if (isStringTypedValue) {
            v = NumberUtils.createBigDecimal(strTypedValue);
        } else if (isNumberTypedValue) {
            v = new BigDecimal(numTypedValue.doubleValue());
        } else if (isBooleanTypedValue) {
            v = new BigDecimal(BooleanUtils.toInteger(boolTypedValue.booleanValue()));
        } else if (isDateTypedValue) {
            v = new BigDecimal(dateTypedValue.getTime());
        }
    } else if (Boolean.class.equals(untypedValueClass)) {
        if (isStringTypedValue) {
            v = BooleanUtils.toBooleanObject(strTypedValue);
        } else if (isNumberTypedValue) {
            v = BooleanUtils.toBooleanObject(numTypedValue.intValue());
        } else if (isDateTypedValue) {
            v = BooleanUtils.toBooleanObject((int) dateTypedValue.getTime());
        }
    } else if (Byte.class.equals(untypedValueClass)) {
        if (isStringTypedValue) {
            v = Byte.valueOf(strTypedValue);
        } else if (isNumberTypedValue) {
            v = new Byte(numTypedValue.byteValue());
        } else if (isBooleanTypedValue) {
            v = new Byte((byte) BooleanUtils.toInteger(boolTypedValue.booleanValue()));
        } else if (isDateTypedValue) {
            v = new Byte((byte) dateTypedValue.getTime());
        }
    } else if (byte[].class.equals(untypedValueClass)) {
        if (isStringTypedValue) {
            v = strTypedValue.getBytes();
        }
    } else if (Double.class.equals(untypedValueClass)) {
        if (isStringTypedValue) {
            v = NumberUtils.createDouble(strTypedValue);
        } else if (isNumberTypedValue) {
            v = new Double(numTypedValue.doubleValue());
        } else if (isBooleanTypedValue) {
            v = new Double(BooleanUtils.toInteger(boolTypedValue.booleanValue()));
        } else if (isDateTypedValue) {
            v = new Double(dateTypedValue.getTime());
        }
    } else if (Float.class.equals(untypedValueClass)) {
        if (isStringTypedValue) {
            v = NumberUtils.createFloat(strTypedValue);
        } else if (isNumberTypedValue) {
            v = new Float(numTypedValue.floatValue());
        } else if (isBooleanTypedValue) {
            v = new Float(BooleanUtils.toInteger(boolTypedValue.booleanValue()));
        } else if (isDateTypedValue) {
            v = new Float(dateTypedValue.getTime());
        }
    } else if (Short.class.equals(untypedValueClass)) {
        if (isStringTypedValue) {
            v = NumberUtils.createInteger(strTypedValue);
        } else if (isNumberTypedValue) {
            v = new Integer(numTypedValue.intValue());
        } else if (isBooleanTypedValue) {
            v = BooleanUtils.toIntegerObject(boolTypedValue.booleanValue());
        } else if (isDateTypedValue) {
            v = new Integer((int) dateTypedValue.getTime());
        }
    } else if (Integer.class.equals(untypedValueClass)) {
        if (isStringTypedValue) {
            v = NumberUtils.createInteger(strTypedValue);
        } else if (isNumberTypedValue) {
            v = new Integer(numTypedValue.intValue());
        } else if (isBooleanTypedValue) {
            v = BooleanUtils.toIntegerObject(boolTypedValue.booleanValue());
        } else if (isDateTypedValue) {
            v = new Integer((int) dateTypedValue.getTime());
        }
    } else if (Long.class.equals(untypedValueClass)) {
        if (isStringTypedValue) {
            v = NumberUtils.createLong(strTypedValue);
        } else if (isNumberTypedValue) {
            v = new Long(numTypedValue.longValue());
        } else if (isBooleanTypedValue) {
            v = new Long(BooleanUtils.toInteger(boolTypedValue.booleanValue()));
        } else if (isDateTypedValue) {
            v = new Long(dateTypedValue.getTime());
        }
    } else if (java.sql.Date.class.equals(untypedValueClass)) {
        if (isNumberTypedValue) {
            v = new java.sql.Date(numTypedValue.longValue());
        } else if (isDateTypedValue) {
            v = new java.sql.Date(dateTypedValue.getTime());
        }
    } else if (java.sql.Time.class.equals(untypedValueClass)) {
        if (isNumberTypedValue) {
            v = new java.sql.Time(numTypedValue.longValue());
        } else if (isDateTypedValue) {
            v = new java.sql.Time(dateTypedValue.getTime());
        }
    } else if (java.sql.Timestamp.class.equals(untypedValueClass)) {
        if (isNumberTypedValue) {
            v = new java.sql.Timestamp(numTypedValue.longValue());
        } else if (isDateTypedValue) {
            v = new java.sql.Timestamp(dateTypedValue.getTime());
        }
    } else if (Date.class.equals(untypedValueClass)) {
        if (isNumberTypedValue) {
            v = new Date(numTypedValue.longValue());
        } else if (isStringTypedValue) {
            try {
                v = DateFormat.getDateInstance().parse(strTypedValue);
            } catch (ParseException e) {
                LOG.error("Unable to parse the date : " + strTypedValue);
                LOG.debug(e.getMessage());
            }
        }
    }
    return v;
}

From source file:gemlite.shell.commands.Import.java

@SuppressWarnings({ "rawtypes", "unchecked" })
@CliCommand(value = "describe job", help = "describe job by id")
public String describeJob(@CliOption(key = {
        "id" }, mandatory = true, optionContext = "disable-string-converter param.context.job.id") String jobExecutionId) {
    BatchService batchService = JpaContext.getService(BatchService.class);
    Map jobExecution = batchService.getJobExecution(NumberUtils.createLong(jobExecutionId));
    //duration//from  w  w  w  .j ava 2  s.c o  m
    Timestamp t1 = (Timestamp) jobExecution.get("start_time");
    Timestamp t2 = (Timestamp) jobExecution.get("last_updated");
    String duration = "";
    if (t2 != null)
        duration = DateUtil.format(new Date(t2.getTime() - t1.getTime()), "mm:ss.SSS");
    jobExecution.put("duration", duration);
    List<Map> steps = batchService.getStepExecutions(NumberUtils.createLong(jobExecutionId));
    jobExecution.put("steps", steps);

    //?ws
    put(CommandMeta.DESCRIBE_JOB, jobExecution);

    //??
    StringBuilder sb = new StringBuilder();
    sb.append("JobName:").append(jobExecution.get("job_name")).append("\n");
    sb.append("Status:").append(jobExecution.get("status")).append("\n");
    sb.append("StartTime:").append(jobExecution.get("start_time")).append("\n");
    sb.append("LastUpdateTime:").append(jobExecution.get("last_updated")).append("\n");
    sb.append("Duration:").append(jobExecution.get("duration")).append("\n");
    sb.append("StepDetails:\n");
    for (Map step : steps) {
        sb.append("StepName:").append(step.get("step_name"));
        sb.append(" Status:").append(step.get("status"));
        sb.append(" ReadCount:").append(step.get("read_count"));
        sb.append(" WriteCount:").append(step.get("write_count"));
        sb.append(" CommitCount:").append(step.get("commit_count"));
        sb.append("\n");

        String exit_message = (String) step.get("exit_message");
        if (!StringUtils.isEmpty(exit_message)) {
            sb.append("EXIT_MESSAGE:\n");
            sb.append(exit_message);
            sb.append("\n");
        }
    }

    return sb.toString();
}

From source file:com.pc.dailymile.DailyMileClient.java

public Long addNoteWithImage(String note, File imageFile) throws Exception {
    HttpPost request = new HttpPost(DailyMileUtil.ENTRIES_URL);
    HttpResponse response = null;//from  w ww .  ja  va 2 s.  c om
    try {
        MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        mpEntity.addPart("media[data]", new FileBody(imageFile, "image/jpeg"));
        mpEntity.addPart("media[type]", new StringBody("image"));
        mpEntity.addPart("message", new StringBody(note));
        mpEntity.addPart("[share_on_services][facebook]", new StringBody("false"));
        mpEntity.addPart("[share_on_services][twitter]", new StringBody("false"));
        mpEntity.addPart("oauth_token", new StringBody(oauthToken));

        request.setEntity(mpEntity);
        // send the request
        response = httpClient.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == 401) {
            throw new RuntimeException(
                    "unable to execute POST - url: " + DailyMileUtil.ENTRIES_URL + " body: " + note);
        }

        if (statusCode == 201) {
            Header loc = response.getFirstHeader("Location");
            if (loc != null) {
                String locS = loc.getValue();
                if (!StringUtils.isBlank(locS) && locS.matches(".*/[0-9]+$")) {
                    try {
                        return NumberUtils.createLong(locS.substring(locS.lastIndexOf("/") + 1));
                    } catch (NumberFormatException e) {
                        return null;
                    }
                }
            }
        }

        return null;
    } finally {
        try {
            if (response != null) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    entity.consumeContent();
                }
            }
            //EntityUtils.consume(response.getEntity());
        } catch (IOException e) {
            // ignore
        }
    }
}

From source file:gr.abiss.calipso.domain.Metadata.java

@SuppressWarnings("unchecked")
public void setXmlString(String xmlString) {
    //init();//from www .j  a  v  a2 s.  c  o  m
    //logger.info("setXmlString: "+xmlString);
    if (xmlString == null) {
        return;
    }
    Document document = XmlUtils.parse(xmlString);

    // date formats

    for (Element e : (List<Element>) document.selectNodes(DATEFORMATS_XPATH)) {
        String dfKey = e.attribute(NAME).getValue();
        String dfExpression = e.attribute(EXPRESSION).getValue();
        this.dateFormats.put(dfKey, dfExpression);
    }

    // field groups
    fieldGroups.clear();
    for (Element e : (List<Element>) document.selectNodes(FIELD_GROUP_XPATH)) {
        FieldGroup fieldGroup = new FieldGroup(e);
        fieldGroups.add(fieldGroup);
        fieldGroupsById.put(fieldGroup.getId(), fieldGroup);
    }
    if (fieldGroups.isEmpty()) {
        addDefaultFieldGroup();
    }

    // sort by priority
    TreeSet<FieldGroup> fieldGroupSet = new TreeSet<FieldGroup>();
    fieldGroupSet.addAll(fieldGroups);
    fieldGroups.clear();
    fieldGroups.addAll(fieldGroupSet);

    if (logger.isDebugEnabled())
        logger.debug("Loaded fieldGroups:" + fieldGroups);
    for (Element e : (List<Element>) document.selectNodes(FIELD_XPATH)) {

        Field field = new Field(e);
        fields.put(field.getName(), field);
        fieldsByLabel.put(field.getLabel(), field);
        // link to full field group object or 
        // of default if none is set

        //logger.info("field name: "+field.getName().getText()+", group id: "+field.getGroupId()+", group: "+fieldGroupsById.get(field.getGroupId()).getName());
        if (field.getGroupId() != null) {
            FieldGroup fieldGroup = fieldGroupsById.get(field.getGroupId());
            if (fieldGroup == null) {
                logger.warn("Field belongs to undefined field-group element with id: " + field.getGroupId()
                        + ", adding to default group");
                fieldGroup = fieldGroupsById.get("default");
            } else {
                fieldGroup.addField(field);
            }
        } else {
            // add field to default group if it does not
            // belong to any
            FieldGroup defaultFieldGroup = fieldGroups.get(0);
            field.setGroup(defaultFieldGroup);
            defaultFieldGroup.addField(field);
        }
    }
    for (Element e : (List<Element>) document.selectNodes(ROLE_XPATH)) {
        Role role = new Role(e);
        roles.put(role.getName(), role);
    }
    for (Element e : (List<Element>) document.selectNodes(STATE_XPATH)) {
        String key = e.attributeValue(STATUS);
        String value = e.attributeValue(LABEL);
        states.put(Integer.parseInt(key), value);
        statesByName.put(value, Integer.parseInt(key));
        statesPlugins.put(Integer.parseInt(key), e.attributeValue(PLUGIN));
        String sDurations = e.attributeValue(MAX_DURATION);
        if (StringUtils.isNotBlank(sDurations)) {
            maxDurations.put(Integer.parseInt(key), NumberUtils.createLong(sDurations));
        }
        String asTypeId = e.attributeValue(ASSET_TYPE_ID);
        if (StringUtils.isNotBlank(asTypeId)) {
            assetTypeIdMap.put(Integer.parseInt(key), NumberUtils.createLong(asTypeId));
        }
        String existingAssetTypeId = e.attributeValue(EXISTING_ASSET_TYPE_ID);
        if (StringUtils.isNotBlank(existingAssetTypeId)) {
            existingAssetTypeIdsMap.put(Integer.parseInt(key), NumberUtils.createLong(existingAssetTypeId));
        }

        String existingAssetTypeMultiple = e.attributeValue(EXISTING_ASSET_TYPE_MULTIPLE);
        if (StringUtils.isNotBlank(existingAssetTypeMultiple)) {
            existingAssetTypeMultipleMap.put(Integer.parseInt(key),
                    BooleanUtils.toBoolean(existingAssetTypeMultiple));
        }
    }
    fieldOrder.clear();
    for (Element e : (List<Element>) document.selectNodes(FIELD_ORDER_XPATH)) {
        String fieldName = e.attributeValue(NAME);
        fieldOrder.add(Field.convertToName(fieldName));
    }
}

From source file:ac.elements.parser.SimpleDBConverter.java

public static Object getStringOrNumber(String number) {
    if (number.equalsIgnoreCase("null")) {
        return null;
    }/*from   w  w w  .j a va2  s.  c  o  m*/
    boolean hasOnlyDigits = NumberUtils.isDigits(number);
    if (hasOnlyDigits) {

        return NumberUtils.createInteger(number);

    } else if (NumberUtils.isNumber(number)) {
        if (SimpleDBParser.indexOfIgnoreCase(number, "l") == number.length() - 1) {
            return NumberUtils.createLong(number.substring(0, number.length() - 1));
        } else if (SimpleDBParser.indexOfIgnoreCase(number, "d") == number.length() - 1) {
            return NumberUtils.createDouble(number);
        } else {
            return NumberUtils.createFloat(number);
        }

    }
    return ExtendedFunctions.trimCharacter(ExtendedFunctions.trimCharacter(number, '\''), '"');
}

From source file:com.pc.dailymile.DailyMileClient.java

private Long doAuthenticatedPost(String url, String body) throws Exception {
    HttpPost request = new HttpPost(url + "?oauth_token=" + oauthToken);
    HttpResponse response = null;/*  w w  w  .  j av a  2  s  . co  m*/
    try {
        HttpEntity entity = new StringEntity(body, HTTP.UTF_8);
        // set the content type to json
        request.setHeader("Content-Type", "application/json; charset=utf-8");
        request.setEntity(entity);
        // sign the request
        // send the request
        response = httpClient.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == 401) {
            throw new RuntimeException("unable to execute POST - url: " + url + " body: " + body);
        }

        if (statusCode == 201) {
            Header loc = response.getFirstHeader("Location");
            if (loc != null) {
                String locS = loc.getValue();
                if (!StringUtils.isBlank(locS) && locS.matches(".*/[0-9]+$")) {
                    try {
                        return NumberUtils.createLong(locS.substring(locS.lastIndexOf("/") + 1));
                    } catch (NumberFormatException e) {
                        return null;
                    }
                }
            }
        }

        return null;
    } finally {
        try {
            if (response != null) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    entity.consumeContent();
                }
            }
            //EntityUtils.consume(response.getEntity());
        } catch (IOException e) {
            // ignore
        }
    }
}

From source file:jef.tools.StringUtils.java

/**
 * ?Long// w  ww.jav  a2  s . com
 * 
 * @param o
 * @param defaultValue
 * @return
 */
public static long toLong(String o, Long defaultValue) {
    if (isBlank(o))
        return defaultValue;// ?nullnull
    try {
        return NumberUtils.createLong(o);
    } catch (NumberFormatException e) {
        if (defaultValue == null)// null?
            throw e;
        return defaultValue;
    }
}