Example usage for org.apache.commons.lang3.math NumberUtils toLong

List of usage examples for org.apache.commons.lang3.math NumberUtils toLong

Introduction

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

Prototype

public static long toLong(final String str, final long defaultValue) 

Source Link

Document

Convert a String to a long, returning a default value if the conversion fails.

If the string is null, the default value is returned.

 NumberUtils.toLong(null, 1L) = 1L NumberUtils.toLong("", 1L)   = 1L NumberUtils.toLong("1", 0L)  = 1L 

Usage

From source file:de.micromata.genome.logging.loghtmlwindow.LogHtmlWindowServlet.java

protected void poll(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String lastLog = req.getParameter("lt");
    long lastPollTime = NumberUtils.toLong(lastLog, 0L);
    List<LogWriteEntry> buffer = getLogEntries(lastPollTime);
    JsonArray ret = new JsonArray();
    for (LogWriteEntry lwe : buffer) {
        ret.add(LogJsonUtils.logEntryToJson(lwe));
    }/*www .j  av a2  s  .  co m*/
    sendResponse(resp, ret);
}

From source file:com.paladin.mvc.ActionServlet.java

/**
 * ?//from ww  w .  j  a  va  2 s  .  c o  m
 *
 * @param _reqCtxt
 * @param is_post
 * @return
 */
private boolean doProcess(RequestContext _reqCtxt, boolean is_post) {
    try {
        String url = _decodeURL(_reqCtxt.uri(), "UTF-8");
        // split uri
        String[] parts = StringUtils.split(url, '/');
        if (parts.length < 1) {
            _reqCtxt.not_found();
            return false;
        }
        // load action
        Object action = this.loadAction(parts[0]);
        if (action == null) {
            _reqCtxt.not_found();
            return false;
        }
        String method_name = (parts.length > 1) ? parts[1] : "index";// url??index
        Method method_of_action = this.getActionMethod(action, method_name);

        //   ?  
        if (method_of_action == null) {
            method_of_action = this.getActionMethod(action, "index");
        }

        // Action?
        int arg_c = method_of_action.getParameterTypes().length;// ?
        switch (arg_c) {
        case 0: // login()
            method_of_action.invoke(action);
            break;
        case 1:// login(RequestContext)
            method_of_action.invoke(action, _reqCtxt);
            break;
        case 2:// read(RequestContext, id)
            boolean isLong = method_of_action.getParameterTypes()[1].equals(long.class);
            // ?   id,  
            if (parts.length < 3) {
                method_of_action = this.getActionMethod(action, "index");
                method_of_action.invoke(action, _reqCtxt);
            } else
                method_of_action.invoke(action, _reqCtxt,
                        isLong ? NumberUtils.toLong(parts[2], -1L) : parts[2]);
            break;
        case 3:// search(RequestContext, id, q)
               // method_of_action.invoke(action, _reqCtxt,
               // NumberUtils.toLong(parts[2], -1L), parts[3]);
            break;
        default:
            _reqCtxt.not_found();
            return false;
        }
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

From source file:com.netsteadfast.greenstep.sys.CxfServerBean.java

public static Long getBeforeValue(String paramValue) throws Exception {
    String value = EncryptorUtils.decrypt(Constants.getEncryptorKey1(), Constants.getEncryptorKey2(),
            SimpleUtils.deHex(paramValue));
    byte datas[] = UploadSupportUtils.getDataBytes(value);
    String jsonData = new String(datas, Constants.BASE_ENCODING);
    ObjectMapper mapper = new ObjectMapper();
    @SuppressWarnings("unchecked")
    Map<String, Object> dataMap = (Map<String, Object>) mapper.readValue(jsonData, HashMap.class);
    return NumberUtils.toLong((String) dataMap.get("before"), 0);
}

From source file:com.axibase.tsd.client.ClientConfigurationFactory.java

private static long loadLong(String name, Properties clientProperties, long defaultValue) {
    return NumberUtils.toLong(load(name, clientProperties, ""), defaultValue);
}

From source file:com.moviejukebox.tools.PropertiesUtil.java

/**
 * Convert the value to a Long//from ww  w  .  j a va  2s  .c o m
 *
 * @param key
 * @param valueToConvert
 * @param defaultValue
 * @return
 */
private static long convertLongProperty(String valueToConvert, long defaultValue) {
    return NumberUtils.toLong(StringUtils.trimToEmpty(valueToConvert), defaultValue);
}

From source file:ezbake.common.properties.EzProperties.java

/**
 * Get a property as a long, if the property doesn't exist or can't be converted then we return the default value
 *
 * @param propertyName is the name of the property we are looking for (the key)
 * @param defaultValue is the value to return if the key doesn't exist or the value can't be converted to a long
 *
 * @return either the properly parsed long or the default value if the key doesn't exist or can't be converted
 *///w  w  w .  java 2  s . c o m
public long getLong(String propertyName, long defaultValue) {
    return NumberUtils.toLong(getProperty(propertyName), defaultValue);
}

From source file:ching.icecreaming.action.ResourceDescriptors.java

@Action(value = "resource-descriptors", results = { @Result(name = "success", location = "json.jsp") })
public String execute() throws Exception {
    int int1 = 401, int0 = 0;
    String string1 = null;/* ww w  .j  av  a2 s .com*/
    URL url1 = null;
    URI uri1 = null;
    HttpGet httpGet1 = null;
    HttpResponse httpResponse1 = null;
    HttpEntity httpEntity1 = null;
    HttpPost httpPost1 = null;
    HttpHost httpHost1 = null;
    DefaultHttpClient httpClient1 = null;
    File file1 = null;
    InputStream inputStream1 = null;
    OutputStream outputStream1 = null;
    BeanComparator beanComparator1 = null;
    List<Map<String, Object>> list1 = null, list2 = null;
    Map<String, Object> map1 = null;
    Object object1 = null;
    int toIndex = rows * page;
    int fromIndex = toIndex - rows;
    GridModel1 jsonObject1 = null;
    Gson gson = null;
    Long long1 = -1L;
    java.util.Date date1 = null;
    URIBuilder uriBuilder1 = null;
    Node node1 = null;
    Element element1 = null;
    NodeList nodeList1 = null;
    Document document1 = null;
    DocumentBuilder documentBuilder1 = null;
    DocumentBuilderFactory documentBuilderFactory1 = null;
    org.joda.time.DateTime dateTime1 = null, dateTime2 = null;

    try {
        if (StringUtils.isNotEmpty(sid) && StringUtils.isNotEmpty(uid) && StringUtils.isNotEmpty(pid)) {
            sid = new String(Base64.decodeBase64(sid.getBytes()));
            uid = new String(Base64.decodeBase64(uid.getBytes()));
            pid = new String(Base64.decodeBase64(pid.getBytes()));
            httpClient1 = new DefaultHttpClient();
            url1 = new URL(sid);
            uriBuilder1 = new URIBuilder(sid);
            uriBuilder1.setParameter("j_username", uid);
            uriBuilder1.setParameter("j_password", pid);
            uriBuilder1.setPath(url1.getPath() + "/rest/resources" + urlString);
            uriBuilder1.setUserInfo(uid, pid);
            uri1 = uriBuilder1.build();
            httpGet1 = new HttpGet(uri1);
            httpResponse1 = httpClient1.execute(httpGet1);
            int1 = httpResponse1.getStatusLine().getStatusCode();
            if (int1 == HttpStatus.SC_OK) {
                httpEntity1 = httpResponse1.getEntity();
                inputStream1 = httpResponse1.getEntity().getContent();
                if (inputStream1 != null) {
                    documentBuilderFactory1 = DocumentBuilderFactory.newInstance();
                    documentBuilder1 = documentBuilderFactory1.newDocumentBuilder();
                    document1 = documentBuilder1.parse(inputStream1);
                    document1.getDocumentElement().normalize();
                    nodeList1 = document1.getElementsByTagName("resourceDescriptor");
                    int1 = nodeList1.getLength();
                    list1 = new ArrayList<Map<String, Object>>();
                    for (int0 = 0; int0 < int1; int0++) {
                        node1 = nodeList1.item(int0);
                        if (node1.getNodeType() == Node.ELEMENT_NODE) {
                            element1 = (Element) node1;
                            map1 = new HashMap<String, Object>();
                            map1.put("wsType", element1.getAttribute("wsType"));
                            map1.put("uriString", element1.getAttribute("uriString"));
                            string1 = getTagValue("label", element1);
                            map1.put("label1", StringUtils.defaultString(string1));
                            string1 = getTagValue("description", element1);
                            map1.put("description", StringUtils.defaultString(string1));
                            string1 = getTagValue("creationDate", element1);
                            long1 = (string1 == null) ? -1L
                                    : NumberUtils.toLong(StringUtils.trim(string1), -1L);
                            if (long1 > 0) {
                                if (StringUtils.isNotBlank(timeZone1)) {
                                    dateTime1 = new org.joda.time.DateTime(long1);
                                    dateTime2 = dateTime1.withZone(DateTimeZone.forID(timeZone1));
                                    date1 = dateTime2.toLocalDateTime().toDate();
                                } else {
                                    date1 = new java.util.Date(long1);
                                }
                            } else {
                                date1 = null;
                            }
                            map1.put("creationDate", date1);
                            map1.put("type1", getText(element1.getAttribute("wsType")));
                            list1.add(map1);
                        }
                    }
                }
                EntityUtils.consume(httpEntity1);
            }
        }
    } catch (UnsupportedEncodingException | URISyntaxException | ParserConfigurationException
            | SAXException exception1) {
        exception1.printStackTrace();
        return ERROR;
    } catch (org.apache.http.conn.HttpHostConnectException | java.net.NoRouteToHostException
            | java.net.MalformedURLException | java.net.UnknownHostException exception1) {
        exception1.printStackTrace();
        return ERROR;
    } catch (IOException exception1) {
        httpGet1.abort();
        exception1.printStackTrace();
        return ERROR;
    } finally {
        if (httpClient1 != null)
            httpClient1.getConnectionManager().shutdown();
        if (list1 != null) {
            records = list1.size();
            if (list1.size() > 0) {
                if (StringUtils.isNotEmpty(sidx)) {
                    if (StringUtils.equals(sord, "desc")) {
                        beanComparator1 = new BeanComparator(sidx,
                                new ReverseComparator(new ComparableComparator()));
                    } else {
                        beanComparator1 = new BeanComparator(sidx);
                    }
                    Collections.sort(list1, beanComparator1);
                }
                if (StringUtils.isNotBlank(searchField) && StringUtils.isNotEmpty(searchOper)) {
                    Iterator iterator1 = list1.iterator();
                    while (iterator1.hasNext()) {
                        map1 = (Map<String, Object>) iterator1.next();
                        for (Map.Entry<String, Object> entry1 : map1.entrySet()) {
                            if (StringUtils.equals(entry1.getKey(), searchField)) {
                                object1 = entry1.getValue();
                                if (searchFilter(searchField, searchOper, searchString, object1))
                                    iterator1.remove();
                                break;
                            }
                        }
                    }
                    records = list1.size();
                }
                if (toIndex > records)
                    toIndex = records;
                if (fromIndex > toIndex) {
                    fromIndex = toIndex - rows;
                    if (fromIndex < 0)
                        fromIndex = 0;
                }
                if (list1.size() > 0 && fromIndex >= 0 && toIndex <= list1.size() && fromIndex <= toIndex)
                    list2 = list1.subList(fromIndex, toIndex);

            }
            total = (int) Math.ceil((double) records / (double) rows);
            if (page > total)
                page = total;
            jsonObject1 = new GridModel1(rows, page, sord, sidx, searchField, searchString, searchOper, total,
                    records, id, list2);
            gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss.SSS").create();
            jsonData = gson.toJson(jsonObject1);
        }
        IOUtils.closeQuietly(inputStream1);
    }
    return SUCCESS;
}

From source file:com.thruzero.common.web.model.container.builder.xml.XmlPanelSetBuilder.java

/**
 * Builds a <code>PanelSet</code> from the given <code>panelSetNode</code>.
 *
 * @param panelSetNode node containing the set of panels (each child of this node will be a panel node).
 * @param panelBuilderTypeRegistry registry that specifies which builder to use for a given panel definition (based on
 * panel name - e.g., 'listPanel')./* w  w  w .  j  a  v a2 s .co m*/
 */
@SuppressWarnings("unchecked")
public XmlPanelSetBuilder(InfoNodeElement panelSetNode, XmlPanelBuilderTypeRegistry panelBuilderTypeRegistry) {
    this(panelSetNode.getAttributeValue(ID),
            NumberUtils.toLong(panelSetNode.getAttributeValue(TIME_OUT_IN_SECONDS), 0),
            panelSetNode.getChildren(), panelBuilderTypeRegistry);
}

From source file:com.erudika.para.rest.Api1.java

private Inflector<ContainerRequestContext, Response> utilsHandler() {
    return new Inflector<ContainerRequestContext, Response>() {
        public Response apply(ContainerRequestContext ctx) {
            MultivaluedMap<String, String> params = ctx.getUriInfo().getQueryParameters();
            String method = pathParam("method", ctx);
            method = StringUtils.isBlank(method) ? params.getFirst("method") : method;
            if ("newid".equals(method)) {
                return Response.ok(Utils.getNewId(), MediaType.TEXT_PLAIN_TYPE).build();
            } else if ("timestamp".equals(method)) {
                return Response.ok(Utils.timestamp(), MediaType.TEXT_PLAIN_TYPE).build();
            } else if ("formatdate".equals(method)) {
                String format = params.getFirst("format");
                String locale = params.getFirst("locale");
                Locale loc = getLocale(locale);
                return Response.ok(Utils.formatDate(format, loc), MediaType.TEXT_PLAIN_TYPE).build();
            } else if ("formatmessage".equals(method)) {
                String msg = params.getFirst("message");
                Object[] paramz = params.get("fields").toArray();
                return Response.ok(Utils.formatMessage(msg, paramz), MediaType.TEXT_PLAIN_TYPE).build();
            } else if ("nospaces".equals(method)) {
                String str = params.getFirst("string");
                String repl = params.getFirst("replacement");
                return Response.ok(Utils.noSpaces(str, repl), MediaType.TEXT_PLAIN_TYPE).build();
            } else if ("nosymbols".equals(method)) {
                String str = params.getFirst("string");
                return Response.ok(Utils.stripAndTrim(str), MediaType.TEXT_PLAIN_TYPE).build();
            } else if ("md2html".equals(method)) {
                String md = params.getFirst("md");
                return Response.ok(Utils.markdownToHtml(md), MediaType.TEXT_HTML).build();
            } else if ("timeago".equals(method)) {
                String d = params.getFirst("delta");
                long delta = NumberUtils.toLong(d, 1);
                return Response.ok(HumanTime.approximately(delta), MediaType.TEXT_PLAIN_TYPE).build();
            }/*from  w  w  w  . jav  a 2s  .c  o m*/
            return RestUtils.getStatusResponse(Response.Status.BAD_REQUEST,
                    "Unknown method: " + ((method == null) ? "empty" : method));
        }
    };
}

From source file:com.erudika.para.rest.Api1.java

protected final Inflector<ContainerRequestContext, Response> linksHandler() {
    return new Inflector<ContainerRequestContext, Response>() {
        public Response apply(ContainerRequestContext ctx) {
            MultivaluedMap<String, String> params = ctx.getUriInfo().getQueryParameters();
            MultivaluedMap<String, String> pathp = ctx.getUriInfo().getPathParameters();
            String id = pathp.getFirst(Config._ID);
            String type = pathp.getFirst(Config._TYPE);
            String id2 = pathp.getFirst("id2");
            String type2 = pathp.getFirst("type2");
            App app = RestUtils.getPrincipalApp();

            if (app == null) {
                return RestUtils.getStatusResponse(Response.Status.BAD_REQUEST);
            }//from  w  w  w  .j  a  v a2  s.c om

            String typeSingular = (type == null) ? null : ParaObjectUtils.getAllTypes(app).get(type);
            type = (typeSingular == null) ? type : typeSingular;

            id2 = StringUtils.isBlank(id2) ? params.getFirst(Config._ID) : id2;
            type2 = StringUtils.isBlank(type2) ? params.getFirst(Config._TYPE) : type2;

            ParaObject pobj = ParaObjectUtils.toObject(type);
            pobj.setId(id);
            pobj = dao.read(app.getAppIdentifier(), pobj.getId());

            Pager pager = new Pager();
            pager.setPage(NumberUtils.toLong(params.getFirst("page"), 0));
            pager.setSortby(params.getFirst("sort"));
            pager.setDesc(Boolean.parseBoolean(params.containsKey("desc") ? params.getFirst("desc") : "true"));
            pager.setLimit(NumberUtils.toInt(params.getFirst("limit"), pager.getLimit()));

            String childrenOnly = params.getFirst("childrenonly");

            if (pobj != null) {
                if (POST.equals(ctx.getMethod()) || PUT.equals(ctx.getMethod())) {
                    if (id2 != null) {
                        String linkid = pobj.link(id2);
                        if (linkid == null) {
                            return RestUtils.getStatusResponse(Response.Status.BAD_REQUEST,
                                    "Failed to create link.");
                        } else {
                            return Response.ok(linkid, MediaType.TEXT_PLAIN_TYPE).build();
                        }
                    } else {
                        return RestUtils.getStatusResponse(Response.Status.BAD_REQUEST,
                                "Parameters 'type' and 'id' are missing.");
                    }
                } else if (GET.equals(ctx.getMethod())) {
                    Map<String, Object> result = new HashMap<String, Object>();
                    if (type2 != null) {
                        if (id2 != null) {
                            return Response.ok(pobj.isLinked(type2, id2), MediaType.TEXT_PLAIN_TYPE).build();
                        } else {
                            List<ParaObject> items = new ArrayList<ParaObject>();
                            if (childrenOnly == null) {
                                if (params.containsKey("count")) {
                                    pager.setCount(pobj.countLinks(type2));
                                } else {
                                    items = pobj.getLinkedObjects(type2, pager);
                                }
                            } else {
                                if (params.containsKey("count")) {
                                    pager.setCount(pobj.countChildren(type2));
                                } else {
                                    if (params.containsKey("field") && params.containsKey("term")) {
                                        items = pobj.getChildren(type2, params.getFirst("field"),
                                                params.getFirst("term"), pager);
                                    } else {
                                        items = pobj.getChildren(type2, pager);
                                    }
                                }
                            }
                            result.put("items", items);
                            result.put("totalHits", pager.getCount());
                            return Response.ok(result).build();
                        }
                    } else {
                        return RestUtils.getStatusResponse(Response.Status.BAD_REQUEST,
                                "Parameter 'type' is missing.");
                    }
                } else if (DELETE.equals(ctx.getMethod())) {
                    if (type2 == null && id2 == null) {
                        pobj.unlinkAll();
                    } else if (type2 != null) {
                        if (id2 != null) {
                            pobj.unlink(type2, id2);
                        } else if (childrenOnly != null) {
                            pobj.deleteChildren(type2);
                        }
                    }
                    return Response.ok().build();
                }
            }
            return RestUtils.getStatusResponse(Response.Status.NOT_FOUND, "Object not found: " + id);
        }
    };
}