List of usage examples for java.lang Exception getStackTrace
public StackTraceElement[] getStackTrace()
From source file:de.dfki.iui.opentok.cordova.plugin.OpenTokPlugin.java
private boolean sendException(String errorMessage) { Exception exc = new OpenTokPluginError(errorMessage); //remove first element form stack trace, since we want the // calling method as first entry in the stack trace // (and not this method itself) StackTraceElement[] stack = exc.getStackTrace(); exc.setStackTrace(getStackTrace(stack, 1, stack.length - 1)); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); exc.printStackTrace(pw);//from ww w . j a v a2 s . co m errorMessage = sw.toString(); if (this._exceptionCallback != null) { PluginResult excResult = new PluginResult(PluginResult.Status.ERROR, errorMessage); excResult.setKeepCallback(true); OpenTokPlugin.this._exceptionCallback.sendPluginResult(excResult); return true; } else { LOG.e(PLUGIN_NAME, errorMessage, exc); return false; } }
From source file:jp.furplag.util.commons.NumberUtilsTest.java
/** * {@link jp.furplag.util.commons.NumberUtils#multiply(java.lang.Object, java.lang.Number, java.lang.Class)}. */// w w w . ja v a 2s. c o m @SuppressWarnings("unchecked") @Test public void testMultiplyObjectNumberClassOfT() { assertEquals("null", null, multiply(null, null, null)); assertEquals("null", null, multiply(1, 23, null)); assertEquals("null", null, multiply(1, 2, null)); try { for (Class<?> type : PRIMITIVES) { Object expected = ClassUtils.primitiveToWrapper(type).getMethod("valueOf", String.class) .invoke(null, "0"); assertEquals("fallback: " + type.getSimpleName(), expected, multiply(null, null, (Class<? extends Number>) type)); } for (Class<?> type : NUMBERS) { Object expected = valueOf(new BigDecimal("12").multiply(new BigDecimal("3.456")), (Class<? extends Number>) type); assertEquals("12 * 3.456:" + type.getSimpleName(), expected, multiply(12, 3.456, (Class<? extends Number>) type)); if (ClassUtils.isPrimitiveOrWrapper(type)) { expected = valueOf(valueOf("-Infinity"), (Class<? extends Number>) type); } else { expected = INFINITY_DOUBLE.pow(2).negate(); if (BigInteger.class.equals(type)) expected = ((BigDecimal) expected).toBigInteger(); } assertEquals("Infinity * -Infinity: " + type.getSimpleName(), expected, multiply("Infinity", Double.NEGATIVE_INFINITY, (Class<? extends Number>) type)); } } catch (Exception e) { e.printStackTrace(); fail(e.getMessage() + "\n" + Arrays.toString(e.getStackTrace())); } }
From source file:org.metis.pull.WdsResourceBean.java
/** * This method gets called by the WdsRdbMapper bean to handle a HTTP * request. This method must be multi-thread capable. Note that since we're * not using Views, this method must return null. * /*from www. j a v a 2 s. c om*/ * @param request * the http request that is being serviced * @param response * the response that will be sent back to the service consumer * @return must return null since we're not using a view * @throws Exception */ @SuppressWarnings("unchecked") protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { LOG.debug(getBeanName() + ": handleRequestInternal - **** new request ****"); // dump the request if trace is on if (LOG.isTraceEnabled()) { LOG.trace(getBeanName() + ":handleRequestInternal - method = " + request.getMethod()); LOG.trace(getBeanName() + ":handleRequestInternal - uri = " + request.getRequestURI()); LOG.trace(getBeanName() + ":handleRequestInternal - protocol = " + request.getProtocol()); LOG.trace(getBeanName() + ":handleRequestInternal - secure = " + request.isSecure()); // dump all the http headers and their values Enumeration<String> headerNames = request.getHeaderNames(); if (headerNames != null) { while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); LOG.trace(getBeanName() + ":handleRequestInternal - " + headerName + " = " + request.getHeader(headerName)); } } if (request.getQueryString() != null) { LOG.trace(getBeanName() + ":handleRequestInternal - queryString = " + request.getQueryString()); } } long currentTime = System.currentTimeMillis(); // give the response a Date header with the current time response.setDateHeader(DATE_HDR, currentTime); // assign the Server header this container's info response.setHeader(SERVER_HDR, getServerInfo()); // determine the HTTP protocol version being used by the client // default version will be 0 int protocolVersion = 0; try { protocolVersion = Integer .parseInt(request.getProtocol().split(FORWARD_SLASH_STR)[1].split(ESC_DOT_STR)[1]); } catch (Exception exc) { LOG.warn(getBeanName() + ": handleRequestInternal - unable to get http protocol " + "version, stack trace follows: "); LOG.error(getBeanName() + ": exception stack trace follows:"); dumpStackTrace(exc.getStackTrace()); } LOG.trace(getBeanName() + ":handleRequestInternal - using this " + "protocol version: " + protocolVersion); /* * Ok, the request first needs to run the security gauntlet * * We do not want to send any error messages back to the client that * would give it a hint that we're invoking SQL statements. This is a * countermeasure for SQL injection probes. */ // see if this RDB is restricting user agents and if so, validate user // agent if ((getAllowedAgents() != null && !getAllowedAgents().isEmpty()) || (getNotAllowedAgents() != null && !getNotAllowedAgents().isEmpty())) { String userAgent = request.getHeader(USER_AGENT_HDR); if (userAgent != null && userAgent.length() > 0) { LOG.debug( getBeanName() + ": handleRequestInternal - validating this " + "user agent: " + userAgent); // Convert to lower case as allowed agents have been // converted to lower case as well userAgent = userAgent.toLowerCase(); boolean allow = false; if (getAllowedAgents() != null && !getAllowedAgents().isEmpty()) { for (String agent : getAllowedAgents()) { LOG.trace(getBeanName() + ": handleRequestInternal - comparing to this " + "allowed agent : " + agent); if (userAgent.indexOf(agent) >= 0) { LOG.trace(getBeanName() + ": handleRequestInternal - this allowed agent " + "was found: " + agent); allow = true; break; } } } else { allow = true; for (String agent : getNotAllowedAgents()) { LOG.trace(getBeanName() + ": handleRequestInternal - comparing to this " + "non-allowed agent : " + agent); if (userAgent.indexOf(agent) >= 0) { LOG.trace(getBeanName() + ": handleRequestInternal - this non-allowed " + "agent was found: " + agent); allow = false; break; } } } if (!allow) { response.sendError(SC_UNAUTHORIZED, "ERROR, user agent " + "is not authorized"); LOG.error(getBeanName() + ": handleRequestInternal - ERROR, user agent is " + "not authorized"); return null; } } else { response.sendError(SC_UNAUTHORIZED, "ERROR, user agent info " + "was not received and is required!"); LOG.error(getBeanName() + ": handleRequestInternal - ERROR, user agent header " + "is required but was not provided by the client"); return null; } } // we do not support chunked transfer encoding, which is a http // 1.1 feature. if (request.getHeader(TRANSFER_ENCODING_HDR) != null && request.getHeader(TRANSFER_ENCODING_HDR).equalsIgnoreCase(CHUNKED)) { response.sendError(SC_BAD_REQUEST, "Chunked tranfer encoding is not " + "supported"); return null; } /* * isSecure returns a boolean indicating whether this request was made * using a secure channel, such as HTTPS. so, if the channel must be * secure, but it is not, then throw an exception and return an error. */ if (isSecure() && !request.isSecure()) { response.sendError(SC_UNAUTHORIZED, "ERROR, channel is not secure"); LOG.error(getBeanName() + ": handleRequestInternal - ERROR, channel is not secure"); return null; } /* * getUserPrincipal() returns a java.security.Principal containing the * name of the user making this request, else it returns null if the * user has not been authenticated. so, if it is mandated that the user * be authenticated, but has not been authenticated, then throw an * exception and return an error */ if (isAuthenticated() && request.getUserPrincipal() == null) { response.sendError(SC_UNAUTHORIZED, "ERROR, user is not authenticated"); LOG.error(getBeanName() + ": handleRequestInternal - ERROR, user is not authenticated"); return null; } /* * Check for valid method - the only supported http methods are GET, * POST, PUT, and DELETE. Here are some good descriptions regarding the * methods and their use with respect to this servlet. * * The GET method is used for projecting data from the DB. So it maps to * a select statement. * * The PUT and POST methods are used for inserting or updating an entity * in the DB. So they map to either an update or insert. * * The DELETE is used for removing one or more entities from the DB. So * it maps to a delete. * * The bean must be assigned at least one of the methods to service */ Method method = null; try { method = Enum.valueOf(Method.class, request.getMethod().toUpperCase()); LOG.debug(getBeanName() + ": handleRequestInternal - processing this method: " + method.toString()); } catch (IllegalArgumentException e) { LOG.error(getBeanName() + ":handleRequestInternal - This method is not allowed [" + request.getMethod() + "]"); response.setHeader("Allow", allowedMethodsRsp); response.sendError(SC_METHOD_NOT_ALLOWED, "This method is not allowed [" + request.getMethod() + "]"); return null; } // do some more method validation; i.e., make sure requested method has // been assigned a SQL statement // // TODO: we may be able to remove this block of code String s1 = null; if (method.isGet() && sqlStmnts4Get == null || method.isPost() && sqlStmnts4Post == null || method.isPut() && sqlStmnts4Put == null || method.isDelete() && sqlStmnts4Delete == null) { response.setHeader("Allow", allowedMethodsRsp); s1 = "HTTP method [" + method + "] is not supported"; response.sendError(SC_METHOD_NOT_ALLOWED, s1); LOG.error(getBeanName() + ":handleRequestInternal - " + s1); return null; } // If the client has specified an 'Accept' header field, then determine // if it is willing or capable of accepting JSON or anything (*/*) // // TODO: what about the client accepting urlencoded strings?? s1 = request.getHeader(ACCEPT_HDR); if (s1 != null && s1.length() > 0) { LOG.debug(getBeanName() + ":handleRequestInternal - client-specified media " + "type in accept header = " + s1); // parse the accept header's content String[] mediaTypes = s1.trim().split(COMMA_STR); boolean match = false; for (String mediaType : mediaTypes) { mediaType = mediaType.trim().toLowerCase(); if (mediaType.startsWith(anyContentType) || mediaType.startsWith(jsonContentType)) { match = true; break; } } if (!match) { LOG.error(getBeanName() + ":handleRequestInternal - client-specified media type of '" + s1 + "' does not include '" + "'" + jsonContentType); response.sendError(SC_NOT_ACCEPTABLE, "client-specified media " + "type of '" + s1 + "' does not include '" + "'" + jsonContentType); return null; } } // pick up the corresponding list of SQL statements for this request List<SqlStmnt> sqlStmnts = null; switch (method) { case GET: sqlStmnts = getSqlStmnts4Get(); break; case DELETE: sqlStmnts = getSqlStmnts4Delete(); break; case PUT: sqlStmnts = getSqlStmnts4Put(); break; case POST: sqlStmnts = getSqlStmnts4Post(); break; default: response.sendError(SC_METHOD_NOT_ALLOWED, "ERROR, unsupported method type: " + method); LOG.error(getBeanName() + ": handleRequestInternal - ERROR, encountered unknown " + "method type: " + method); return null; } // ~~~~~~ EXTRACT PARAMERTERS, IF ANY ~~~~~~~~~~~ // GETs with entity bodies are illegal if (method.isGet() && request.getContentLength() > 0) { response.sendError(SC_BAD_REQUEST, "Client has issued a malformed or illegal request; " + "GET cannot include entity body"); return null; } // the DELETE method also cannot include an entity body; however, the // servlet containers already ignore them. so no need to check for that // see if json object arrived boolean jsonObjectPresent = (method.isPost() || method.isPut()) && (request.getContentLength() > 0 && request.getContentType().equalsIgnoreCase(jsonContentType)); LOG.debug(getBeanName() + ": jsonObjectPresent = " + jsonObjectPresent); // see if this is a PUT with entity. we've learned that for PUTs, // getParameterMap does not work the same across all servlet containers. // so we need take care of this ourselves boolean putWithBodyPresent = (method.isPut()) && (request.getContentLength() > 0 && request.getContentType().equalsIgnoreCase(urlEncodedContentType)); LOG.debug(getBeanName() + ": putWithBodyPresent = " + putWithBodyPresent); // collect incoming parameters and place them in a common bucket // // ~~~~ ALL PARAMETER KEY NAMES MUST BE FORCED TO LOWER CASE ~~~ // List<Map<String, String>> cParams = new ArrayList<Map<String, String>>(); // first, get the incoming query or form parameters (if any); we will // assume that each key has only one parameter. in other words, // we're not dealing with drop-down boxes or things similar if (!putWithBodyPresent && !jsonObjectPresent) { Map<String, String[]> qParams = request.getParameterMap(); if (qParams != null && !qParams.isEmpty()) { Map<String, String> qMap = new HashMap<String, String>(); for (String key : qParams.keySet()) { qMap.put(key.toLowerCase(), qParams.get(key)[0]); } if (!qMap.isEmpty()) { cParams.add(qMap); LOG.debug(getBeanName() + ": query params = " + qMap.toString()); } } } // a put with entity body arrived, so get the parameters from the // body and place them in the common bucket else if (putWithBodyPresent) { try { Map<String, String> putParams = null; // parseUrlEncoded will force keys to lower case putParams = Utils.parseUrlEncoded(request.getInputStream()); if (putParams != null && !putParams.isEmpty()) { cParams.add(putParams); } } catch (Exception exc) { LOG.error(getBeanName() + ": ERROR, caught this " + "exception while parsing urlencoded string: " + exc.toString()); LOG.error(getBeanName() + ": exception stack trace follows:"); dumpStackTrace(exc.getStackTrace()); if (exc.getCause() != null) { LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString()); LOG.error(getBeanName() + ": causing exception stack trace follows:"); dumpStackTrace(exc.getCause().getStackTrace()); } response.sendError(SC_BAD_REQUEST, "urlencoded string parsing error: " + exc.getMessage()); return null; } } // ok, a json object arrived, so get parameters defined in that object // and place them in the common bucket else { // its a json object, so parse it to extract params from it try { List<Map<String, String>> jParams = null; // parseJson will ensure that all passed-in JSON objects have // the same set of identical keys jParams = Utils.parseJson(request.getInputStream()); if (jParams != null && !jParams.isEmpty()) { // if we also got query params then ensure they have the // same set of keys as the json params. why anyone would // ever do this is beyond me, but I'll leave it in for now if (!cParams.isEmpty()) { Map<String, String> cMap = cParams.get(0); Map<String, String> jMap = jParams.get(0); for (String key : cMap.keySet()) { if (jMap.get(key) == null) { String eStr = getBeanName() + ": ERROR, json " + "object key set does not match query " + "param key set"; LOG.error(eStr); response.sendError(SC_BAD_REQUEST, eStr); return null; } } // place the passed in query params in the jParams // bucket jParams.add(cMap); } // assign the jParams bucket to the common bucket cParams = jParams; } } catch (Exception exc) { LOG.error(getBeanName() + ": ERROR, caught this " + "exception while parsing json object: " + exc.toString()); LOG.error(getBeanName() + ": exception stack trace follows:"); dumpStackTrace(exc.getStackTrace()); if (exc.getCause() != null) { LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString()); LOG.error(getBeanName() + ": causing exception stack trace follows:"); dumpStackTrace(exc.getCause().getStackTrace()); } response.sendError(SC_BAD_REQUEST, "json parsing error: " + exc.getMessage()); return null; } } // if trace is on, dump the params (if any) to the log if (LOG.isDebugEnabled()) { if (!cParams.isEmpty()) { for (int i = 0; i < cParams.size(); i++) { LOG.debug(getBeanName() + ": handleRequestInternal - received these params: " + cParams.get(i).toString()); } } else { LOG.debug(getBeanName() + ": handleRequestInternal - did not receive any params"); } } // ensure none of the params' values have been black listed if (!cParams.isEmpty() && getBlackList().length() > 0) { char[] bl = getBlackList().toCharArray(); for (int i = 0; i < cParams.size(); i++) { for (String value : cParams.get(i).values()) { if (Utils.isOnBlackList(value, bl)) { response.sendError(SC_BAD_REQUEST, "encountered black listed character in this param " + "value: " + value); LOG.error(getBeanName() + "handleRequestInternal - encountered black listed " + "character in this param value: " + value); return null; } } } } // find the proper SQL statement based on the incoming parameters' (if // any) keys SqlStmnt sqlStmnt = null; try { // getMatch will try and find a match, even if no params were // provided. // @formatter:off sqlStmnt = (cParams.isEmpty()) ? SqlStmnt.getMatch(sqlStmnts, null) : SqlStmnt.getMatch(sqlStmnts, cParams.get(0).keySet()); // @formatter:on if (sqlStmnt == null && !cParams.isEmpty()) { LOG.error(getBeanName() + ":ERROR, unable to find sql " + "statement with this incoming param set: " + cParams.toString()); response.sendError(SC_INTERNAL_SERVER_ERROR, "internal server error: mapping error"); return null; } else if (sqlStmnt == null) { LOG.warn(getBeanName() + ": warning, unable to find sql " + "statement on first pass, will use extra path info"); } else { LOG.debug(getBeanName() + ": handleRequestInternal - matching sql stmt = " + sqlStmnt.toString()); } } catch (Exception exc) { LOG.error(getBeanName() + ":ERROR, caught this exception " + "while mapping sql to params: " + exc.toString()); LOG.error(getBeanName() + ": exception stack trace follows:"); dumpStackTrace(exc.getStackTrace()); if (exc.getCause() != null) { LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString()); LOG.error(getBeanName() + ": causing exception stack trace follows:"); dumpStackTrace(exc.getCause().getStackTrace()); } response.sendError(SC_INTERNAL_SERVER_ERROR, "mapping error"); return null; } // if getMatch could not find a match - perhaps input params were not // provided - then use the URI's 'extended path' information as an input // param if (sqlStmnt == null) { LOG.debug(getBeanName() + ": invoking getExtraPathInfo"); String[] xtraPathInfo = Utils.getExtraPathInfo(request.getPathInfo()); if (xtraPathInfo != null && xtraPathInfo.length >= 2) { LOG.debug(getBeanName() + ": extra path key:value = " + xtraPathInfo[0] + ":" + xtraPathInfo[1]); } else { LOG.error(getBeanName() + ":ERROR, getExtraPathInfo failed to find info"); response.sendError(SC_INTERNAL_SERVER_ERROR, "internal server error: mapping error"); return null; } // put the xtra path info in the common param bucket and try again cParams.clear(); Map<String, String> xMap = new HashMap<String, String>(); xMap.put(xtraPathInfo[0], xtraPathInfo[1]); cParams.add(xMap); // try again with the extra path info sqlStmnt = SqlStmnt.getMatch(sqlStmnts, xMap.keySet()); if (sqlStmnt == null) { LOG.error(getBeanName() + ":ERROR, unable to find sql " + "statement with this xtra path info: " + cParams.toString()); response.sendError(SC_NOT_FOUND, "internal server error: mapping error"); return null; } } // if we've gotten this far, we've gotten past the security gauntlet and // we have a SQL statement to work with. SqlResult sqlResult = null; try { // get the output stream OutputStream os = response.getOutputStream(); // FIRE IN THE DB HOLE :) if ((sqlResult = sqlStmnt.execute(cParams)) == null) { // execute will have logged the necessary debug/error info response.sendError(SC_INTERNAL_SERVER_ERROR); return null; } // execute went through ok, lets see how to respond switch (method) { case GET: // if a resultset was returned, then set the content type, // convert it to json, and write it out List<Map<String, Object>> listMap = sqlResult.getResultSet(); if (listMap != null) { // tell the client the content type response.setContentType(rspJsonContentType); String jsonOutput = Utils.generateJson(sqlResult.getResultSet()); LOG.trace(getBeanName() + ": returning this payload - " + jsonOutput); os.write(jsonOutput.getBytes()); // ensure that only the client can cache the data and tell // the client how long the data can remain active response.setHeader(CACHE_CNTRL_HDR, (getCacheControl() != null) ? getCacheControl() : DFLT_CACHE_CNTRL_STR); response.setHeader(PRAGMA_HDR, PRAGMA_NO_CACHE_STR); response.setDateHeader(EXPIRES_HDR, currentTime + (getExpires() * 1000)); } else { LOG.debug(getBeanName() + ": NOT returning json message"); } response.setStatus(SC_OK); break; case DELETE: // a DELETE should not send back an entity body response.setStatus(SC_NO_CONTENT); break; case PUT: /* * PUTs are idempotent; therefore, they must provide ALL the * properties that pertain to the resource/entity that they are * creating or updating. Updates cannot be partial updates; they * must be full updates. A PUT is issued by a client that knows * the identifier (in our case, primary key) of the * resource/entity. Therefore, we do not have to send back a * Location header in response to a PUT that has created a * resource. */ if (sqlStmnt.isInsert()) { response.setStatus(SC_CREATED); } else { response.setStatus(SC_OK); } break; case POST: /* * A POST is not idempotent; therefore, it can be used to * perform a 'partial' update, as well as a full create. When * creating a resource via POST, the client does not know the * primary key, and it assumes it will be auto-generated; * therefore, a Location header with auto-generated key must be * returned to client. */ if (sqlStmnt.isInsert()) { response.setStatus(SC_CREATED); // we need to return the new key, but only if it was not a // batch insert. the new key should be returned via the // location header // check if a key holder exists; if not, then table was not // configured with auto-generated key. String locationPath = request.getRequestURL().toString(); if (sqlResult.getKeyHolder() != null) { // key holder exists, check and see if a key is // present if (sqlResult.getKeyHolder().getKey() != null) { String id = sqlResult.getKeyHolder().getKey().toString(); LOG.debug(getBeanName() + ": getKey() returns " + id); locationPath += ("/" + id); LOG.debug(getBeanName() + ": locationPath = " + locationPath); response.setHeader(LOCATION_HDR, locationPath); } // no key, check for multiple keys // TODO: should we send back all keys? else if (sqlResult.getKeyHolder().getKeys() != null) { Map<String, Object> keyMap = sqlResult.getKeyHolder().getKeys(); LOG.debug(getBeanName() + ": getKeys() returns " + keyMap); } // maybe map of keys? // TODO: should we send back all keys? else if (sqlResult.getKeyHolder().getKeyList() != null) { for (Map<String, Object> map : sqlResult.getKeyHolder().getKeyList()) { LOG.debug(getBeanName() + ": Map from getKeyList(): " + map); } } } else { // if it was not an insert, then it was an update. LOG.debug(getBeanName() + ": key holder was not returned for the insert"); } } else { // it was not an insert, so just send back an OK for the // update response.setStatus(SC_OK); } break; default: response.setStatus(SC_OK); break; } } catch (JsonProcessingException exc) { LOG.error(getBeanName() + ":ERROR, caught this " + "JsonProcessingException while trying to gen json " + "message: " + exc.toString()); LOG.error(getBeanName() + ": exception stack trace follows:"); dumpStackTrace(exc.getStackTrace()); if (exc.getCause() != null) { LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString()); LOG.error(getBeanName() + ": causing exception stack trace follows:"); dumpStackTrace(exc.getCause().getStackTrace()); } response.sendError(SC_INTERNAL_SERVER_ERROR, "parsing error"); return null; } catch (Exception exc) { LOG.error(getBeanName() + ":ERROR, caught this " + "Exception while trying to gen json " + "message: " + exc.toString()); LOG.error(getBeanName() + ": exception stack trace follows:"); dumpStackTrace(exc.getStackTrace()); if (exc.getCause() != null) { LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString()); LOG.error(getBeanName() + ": causing exception stack trace follows:"); dumpStackTrace(exc.getCause().getStackTrace()); } response.sendError(SC_INTERNAL_SERVER_ERROR, "parsing error"); return null; } finally { if (sqlResult != null) { SqlResult.enqueue(sqlResult); } } // must return null, because we're not using views! return null; }
From source file:jp.furplag.util.commons.NumberUtilsTest.java
/** * {@link jp.furplag.util.commons.NumberUtils#remainder(java.lang.Object, java.lang.Number, java.lang.Class)}. *//*from w ww. j a v a 2 s . c o m*/ @SuppressWarnings("unchecked") @Test public void testRemainderObjectNumberClassOfT() { assertEquals("null", null, remainder(null, null, null)); assertEquals("null", null, remainder(10, 3, null)); assertEquals("10 / 3", (Object) 1, remainder(10, 3, int.class)); assertEquals("10 / 3", (Object) 1, remainder(10d, 3, int.class)); assertEquals("10 / 3", (Object) 1f, remainder(10d, 3, float.class)); try { for (Class<?> type : NUMBERS) { Class<? extends Number> typeOfN = (Class<? extends Number>) type; Object expected = null; if (ClassUtils.isPrimitiveOrWrapper(type)) { expected = ClassUtils.primitiveToWrapper(type).getMethod("valueOf", String.class).invoke(null, "1"); } else { expected = type.getField("ONE").get(null); } for (Class<?> valueType : NUMBERS) { Object o = null; if (ClassUtils.isPrimitiveOrWrapper(valueType)) { o = ClassUtils.primitiveToWrapper(valueType).getMethod("valueOf", String.class).invoke(null, "10"); } else { o = valueType.getField("TEN").get(null); } assertEquals(o + "(" + o.getClass() + ") / 3: " + type.getSimpleName(), expected, remainder(o, 3, typeOfN)); } } } catch (Exception e) { e.printStackTrace(); fail(e.getMessage() + "\n" + Arrays.toString(e.getStackTrace())); } }
From source file:jp.furplag.util.commons.NumberUtilsTest.java
/** * {@link jp.furplag.util.commons.NumberUtils#divide(java.lang.Object, java.lang.Number, java.lang.Number, java.math.RoundingMode, java.lang.Class)}. *///from ww w . j a v a 2 s . c o m @SuppressWarnings("unchecked") @Test public void testDivideTNumberNumberRoundingModeClassOfT() { assertEquals("null", null, divide(null, null, null, null, null)); assertEquals("null", null, divide(10, 5, 0, null, null)); assertEquals("null", null, divide(10, 5, null, null, null)); assertEquals("null", null, divide(10, 3, 2, RoundingMode.DOWN, null)); assertEquals("null", (Object) 3.33f, divide(10, 3, 2, RoundingMode.DOWN, float.class)); try { for (Class<?> type : PRIMITIVES) { Object expected = ClassUtils.primitiveToWrapper(type).getMethod("valueOf", String.class) .invoke(null, "0"); assertEquals("fallback: " + type.getSimpleName(), expected, divide(null, null, null, null, (Class<? extends Number>) type)); } for (Class<?> type : NUMBERS) { Object expected = valueOf(3.33, (Class<? extends Number>) type); assertEquals("10 / 3: " + type.getSimpleName(), expected, divide(10, 3, 2, RoundingMode.DOWN, (Class<? extends Number>) type)); assertEquals("10 / 3: " + type.getSimpleName(), expected, divide(10, 3, 2, RoundingMode.HALF_EVEN, (Class<? extends Number>) type)); assertEquals("10 / 3: " + type.getSimpleName(), expected, divide(10, 3, 2, RoundingMode.HALF_UP, (Class<? extends Number>) type)); assertEquals("10 / 3: " + type.getSimpleName(), expected, divide(10, 3, 2, RoundingMode.FLOOR, (Class<? extends Number>) type)); expected = valueOf(3.34, (Class<? extends Number>) type); assertEquals("10 / 3: " + type.getSimpleName(), expected, divide(10, 3, 2, RoundingMode.UP, (Class<? extends Number>) type)); assertEquals("10 / 3: " + type.getSimpleName(), expected, divide(10, 3, 2, RoundingMode.CEILING, (Class<? extends Number>) type)); } } catch (Exception e) { e.printStackTrace(); fail(e.getMessage() + "\n" + Arrays.toString(e.getStackTrace())); } }
From source file:jp.furplag.util.commons.NumberUtilsTest.java
/** * {@link jp.furplag.util.commons.NumberUtils#round(Object, Number, RoundingMode, Class)}. *//*from w ww . j av a 2 s .co m*/ @SuppressWarnings("unchecked") @Test public void testRoundObjectNumberRoundingModeClassOfT() { assertEquals("null", null, round(null, null, null, null)); try { for (Class<?> type : NUMBERS) { Object expected = null; if (ObjectUtils.isAny(ClassUtils.primitiveToWrapper(type), Float.class, Double.class)) { expected = ClassUtils.primitiveToWrapper(type).getMethod("valueOf", String.class).invoke(null, "3.14"); } else if (ClassUtils.isPrimitiveOrWrapper(type)) { expected = ClassUtils.primitiveToWrapper(type).getMethod("valueOf", String.class).invoke(null, "3"); } else { expected = new BigDecimal("3.14"); if (BigInteger.class.equals(type)) expected = ((BigDecimal) expected).toBigInteger(); } assertEquals("PI: " + type.getSimpleName(), expected, round(Math.PI, 2, RoundingMode.HALF_UP, (Class<? extends Number>) type)); if (ObjectUtils.isAny(ClassUtils.primitiveToWrapper(type), Float.class, Double.class)) { expected = ClassUtils.primitiveToWrapper(type).getMethod("valueOf", String.class).invoke(null, "3.15"); } else if (ClassUtils.isPrimitiveOrWrapper(type)) { expected = ClassUtils.primitiveToWrapper(type).getMethod("valueOf", String.class).invoke(null, "3"); } else { expected = new BigDecimal("3.15"); if (BigInteger.class.equals(type)) expected = ((BigDecimal) expected).toBigInteger(); } assertEquals("PI: " + type.getSimpleName(), expected, round(Math.PI, 2, RoundingMode.CEILING, (Class<? extends Number>) type)); } } catch (Exception e) { e.printStackTrace(); fail(e.getMessage() + "\n" + Arrays.toString(e.getStackTrace())); } }
From source file:jp.furplag.util.commons.NumberUtilsTest.java
/** * {@link jp.furplag.util.commons.NumberUtils#add(java.lang.Object, java.lang.Number)}. *//*from w w w . ja v a 2 s. c om*/ @SuppressWarnings("unchecked") @Test public void testAddObjectT() { assertEquals("null", null, add((Object) null, null)); assertEquals("null", null, add("123.456", null)); assertEquals("null", (Object) 10, add("", 10)); assertEquals("null", (Object) 10, add((Object) null, 10)); assertEquals("null", (Object) 123, add("123.456", 0)); assertEquals("null", (Object) 123.456f, add("123.456d", 0f)); assertEquals("123 + .456: Float", (Object) 123.456f, add("123", .456f)); assertEquals("123 + .456: Float", (Object) Float.class, add("123d", .456f).getClass()); assertEquals("123 + .456: Float", (Object) Float.class, add((Object) BigDecimal.valueOf(123d), .456f).getClass()); for (Class<?> type : NUMBERS) { try { Object o = null; Class<? extends Number> typeOfN = (Class<? extends Number>) type; Class<? extends Number> wrapper = (Class<? extends Number>) ClassUtils.primitiveToWrapper(type); if (ClassUtils.isPrimitiveWrapper(wrapper)) { o = wrapper.getMethod("valueOf", String.class).invoke(null, "123"); } else { Constructor<?> c = type.getDeclaredConstructor(String.class); o = c.newInstance("123"); } assertEquals("123.456: " + type.getSimpleName(), add(".456", (Number) o, typeOfN), add(".456", (Number) o)); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage() + "\n" + Arrays.toString(e.getStackTrace())); } } }
From source file:jp.furplag.util.commons.NumberUtilsTest.java
/** * {@link jp.furplag.util.commons.NumberUtils#compareTo(java.lang.Number, java.lang.Number)}. *///from w w w . java2 s .c om @SuppressWarnings("unchecked") @Test public void testCompareToNumberNumber() { assertEquals("null", (Object) 0, compareTo(null, null)); assertEquals("null", (Object) 1, compareTo(1, null)); assertEquals("null", (Object) 1, compareTo(-1, null)); assertEquals("null", (Object) 1, compareTo(Float.NEGATIVE_INFINITY, null)); assertEquals("null", (Object) (-1), compareTo(null, 1)); assertEquals("null", (Object) (-1), compareTo(null, -1)); assertEquals("null", (Object) (-1), compareTo(null, Double.NEGATIVE_INFINITY)); assertEquals("Infinity", (Object) 0, compareTo(Float.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY)); assertEquals("Infinity", (Object) 0, compareTo(Double.POSITIVE_INFINITY, Float.POSITIVE_INFINITY)); assertEquals("NaN", (Object) 1, compareTo(Float.NaN, null)); assertEquals("NaN", (Object) 1, compareTo(Float.NaN, 1)); assertEquals("NaN", (Object) 1, compareTo(Float.NaN, -1)); assertEquals("NaN", (Object) 1, compareTo(Float.NaN, Double.POSITIVE_INFINITY)); assertEquals("NaN", (Object) 0, compareTo(Float.NaN, Double.NaN)); assertEquals("NaN", (Object) (-1), compareTo(null, Double.NaN)); assertEquals("NaN", (Object) (-1), compareTo(1, Double.NaN)); assertEquals("NaN", (Object) (-1), compareTo(-1, Double.NaN)); assertEquals("NaN", (Object) (-1), compareTo(Float.NEGATIVE_INFINITY, Double.NaN)); assertEquals("NaN", (Object) 0, compareTo(Double.NaN, Float.NaN)); for (Class<?> type : NUMBERS) { Class<? extends Number> wrapper = (Class<? extends Number>) ClassUtils.primitiveToWrapper(type); try { Number n = null; if (ClassUtils.isPrimitiveWrapper(type)) { n = (Number) wrapper.getField("MAX_VALUE").get(null); } else { n = INFINITY_DOUBLE.pow(2); if (BigInteger.class.equals(type)) n = ((BigDecimal) n).toBigInteger(); } assertEquals("equals: " + type.getSimpleName(), 0, compareTo(n, new BigDecimal(n.toString()))); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage() + "\n" + Arrays.toString(e.getStackTrace())); } } }
From source file:jp.furplag.util.commons.NumberUtilsTest.java
/** * {@link jp.furplag.util.commons.NumberUtils#add(java.lang.Number, java.lang.Number)}. *//* ww w . j a va2 s . c o m*/ @SuppressWarnings("unchecked") @Test public void testAddTNumber() { assertEquals("null", null, add(null, null)); assertEquals("null", null, add(null, 10)); assertEquals("null", (Object) 123.456d, add(123.456, 0)); assertEquals("null", (Object) 123.456f, add(123.456f, 0)); assertEquals("123 + .456: Float", (Object) 123, add(123, .456f)); assertEquals("123 + .456: Float", (Object) Double.class, add(123d, .456f).getClass()); assertEquals("123 + .456: Float", (Object) BigDecimal.class, add(BigDecimal.valueOf(123d), .456f).getClass()); for (Class<?> type : NUMBERS) { try { Object o = null; Number augend = null; Class<? extends Number> typeOfN = (Class<? extends Number>) type; Class<? extends Number> wrapper = (Class<? extends Number>) ClassUtils.primitiveToWrapper(type); if (ClassUtils.isPrimitiveWrapper(wrapper)) { o = wrapper.getMethod("valueOf", String.class).invoke(null, "123"); } else { Constructor<?> c = type.getDeclaredConstructor(String.class); o = c.newInstance("123"); } assertEquals("123.456: " + type.getSimpleName(), add((Number) o, augend, typeOfN), add((Number) o, augend)); augend = .456f; assertEquals("123.456: " + type.getSimpleName(), add((Number) o, augend, typeOfN), add((Number) o, augend)); augend = Double.NaN; assertEquals("NaN: " + type.getSimpleName(), add((Number) o, augend, typeOfN), add((Number) o, augend)); augend = Float.NEGATIVE_INFINITY; assertEquals("-Infinity: Float: " + type.getSimpleName(), add((Number) o, augend, typeOfN), add((Number) o, augend)); augend = Double.POSITIVE_INFINITY; assertEquals("Infinity: Double: : " + type.getSimpleName(), add((Number) o, augend, typeOfN), add((Number) o, augend)); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage() + "\n" + Arrays.toString(e.getStackTrace())); } } }
From source file:jp.furplag.util.commons.NumberUtilsTest.java
/** * {@link jp.furplag.util.commons.NumberUtils#ceil(java.lang.Object, java.lang.Class)}. *///from ww w . j a v a 2s . c o m @SuppressWarnings("unchecked") @Test public void testCeilObjectClassOfT() { assertEquals("null", null, ceil(null, null)); assertEquals("null", null, ceil("", null)); assertEquals("null", null, ceil("not a number.", null)); for (Class<?> type : NUMBERS) { try { Object expected = null; Class<? extends Number> typeOfN = (Class<? extends Number>) type; Class<? extends Number> wrapper = (Class<? extends Number>) ClassUtils.primitiveToWrapper(type); if (ClassUtils.isPrimitiveWrapper(wrapper)) { expected = wrapper.getMethod("valueOf", String.class).invoke(null, "4"); } else { Constructor<?> c = type.getDeclaredConstructor(String.class); expected = c.newInstance("4"); } assertEquals("PI: String: " + type.getSimpleName(), expected, ceil("3.14", typeOfN)); assertEquals("PI: Float: " + type.getSimpleName(), expected, ceil(3.141592653589793f, typeOfN)); assertEquals("PI: Double: " + type.getSimpleName(), expected, ceil(Math.PI, typeOfN)); assertEquals("PI: BigDecimal: " + type.getSimpleName(), expected, ceil(BigDecimal.valueOf(Math.PI), typeOfN)); assertEquals("(Double) (10 / 3): " + type.getSimpleName(), expected, ceil( (Object) (BigDecimal.TEN.divide(new BigDecimal("3"), MathContext.DECIMAL128)), typeOfN)); if (ObjectUtils.isAny(wrapper, Double.class, Float.class)) { expected = wrapper.getField("POSITIVE_INFINITY").get(null); } else if (ClassUtils.isPrimitiveWrapper(wrapper)) { expected = wrapper.getField("MAX_VALUE").get(null); assertEquals("Huge: " + type.getSimpleName(), expected, ceil((Object) INFINITY_DOUBLE.pow(10, MathContext.DECIMAL128), typeOfN)); } else if (BigDecimal.class.equals(type)) { expected = INFINITY_DOUBLE.pow(10, MathContext.DECIMAL128).toPlainString(); Object actual = ceil((Object) INFINITY_DOUBLE.pow(10, MathContext.DECIMAL128), BigDecimal.class) .toPlainString(); assertEquals("Huge: " + type.getSimpleName(), expected, actual); } else { expected = INFINITY_DOUBLE.pow(10, MathContext.DECIMAL128).toBigInteger(); Object actual = ceil((Object) INFINITY_DOUBLE.pow(10, MathContext.DECIMAL128), BigInteger.class); assertEquals("Huge: " + type.getSimpleName(), expected, actual); } } catch (Exception e) { e.printStackTrace(); fail(e.getMessage() + "\n" + Arrays.toString(e.getStackTrace())); } } }