List of usage examples for java.lang Long TYPE
Class TYPE
To view the source code for java.lang Long TYPE.
Click Source Link
From source file:nl.strohalm.cyclos.utils.CustomFieldHelper.java
/** * Finds a possible value label by id/*from www .j av a 2 s.c o m*/ */ public String findPossibleValueById(final Object value, final Collection<CustomFieldPossibleValue> possibleValues) { long id; try { id = CoercionHelper.coerce(Long.TYPE, value); for (final CustomFieldPossibleValue possibleValue : possibleValues) { if (id == possibleValue.getId()) { return possibleValue.getValue(); } } } catch (final Exception e) { // Keep on } return null; }
From source file:com.initialxy.cordova.themeablebrowser.ThemeableBrowserUnmarshaller.java
/** * Gracefully convert given Object to given class given the precondition * that both are primitives or one of the classes associated with * primitives. eg. If val is of type Double and cls is of type int, return * Integer type with appropriate value truncation so that it can be assigned * to field with field.set()./* www . j ava2 s . c o m*/ * * @param cls * @param val * @return * @throws com.initialxy.cordova.themeablebrowser.ThemeableBrowserUnmarshaller.TypeMismatchException */ private static Object convertToPrimitiveFieldObj(Object val, Class<?> cls) { Class<?> valClass = val.getClass(); Object result = null; try { Method getter = null; if (cls.isAssignableFrom(Byte.class) || cls.isAssignableFrom(Byte.TYPE)) { getter = valClass.getMethod("byteValue"); } else if (cls.isAssignableFrom(Short.class) || cls.isAssignableFrom(Short.TYPE)) { getter = valClass.getMethod("shortValue"); } else if (cls.isAssignableFrom(Integer.class) || cls.isAssignableFrom(Integer.TYPE)) { getter = valClass.getMethod("intValue"); } else if (cls.isAssignableFrom(Long.class) || cls.isAssignableFrom(Long.TYPE)) { getter = valClass.getMethod("longValue"); } else if (cls.isAssignableFrom(Float.class) || cls.isAssignableFrom(Float.TYPE)) { getter = valClass.getMethod("floatValue"); } else if (cls.isAssignableFrom(Double.class) || cls.isAssignableFrom(Double.TYPE)) { getter = valClass.getMethod("doubleValue"); } else if (cls.isAssignableFrom(Boolean.class) || cls.isAssignableFrom(Boolean.TYPE)) { if (val instanceof Boolean) { result = val; } else { throw new TypeMismatchException(cls, val.getClass()); } } else if (cls.isAssignableFrom(Character.class) || cls.isAssignableFrom(Character.TYPE)) { if (val instanceof String && ((String) val).length() == 1) { char c = ((String) val).charAt(0); result = Character.valueOf(c); } else if (val instanceof String) { throw new TypeMismatchException( "Expected Character, " + "but received String with length other than 1."); } else { throw new TypeMismatchException( String.format("Expected Character, accept String, but got %s.", val.getClass())); } } if (getter != null) { result = getter.invoke(val); } } catch (NoSuchMethodException e) { throw new TypeMismatchException(String.format("Cannot convert %s to %s.", val.getClass(), cls)); } catch (SecurityException e) { throw new TypeMismatchException(String.format("Cannot convert %s to %s.", val.getClass(), cls)); } catch (IllegalAccessException e) { throw new TypeMismatchException(String.format("Cannot convert %s to %s.", val.getClass(), cls)); } catch (InvocationTargetException e) { throw new TypeMismatchException(String.format("Cannot convert %s to %s.", val.getClass(), cls)); } return result; }
From source file:net.sourceforge.pmd.typeresolution.ClassTypeResolverTest.java
@Test public void testLiterals() throws JaxenException { ASTCompilationUnit acu = parseAndTypeResolveForClass15(Literals.class); List<ASTLiteral> literals = convertList(acu.findChildNodesWithXPath("//Literal"), ASTLiteral.class); int index = 0; // String s = "s"; assertEquals(0, literals.get(index).jjtGetNumChildren()); assertEquals(String.class, literals.get(index++).getType()); // boolean boolean1 = false; assertEquals(Boolean.TYPE, literals.get(index).getFirstDescendantOfType(ASTBooleanLiteral.class).getType()); assertEquals(Boolean.TYPE, literals.get(index++).getType()); // boolean boolean2 = true; assertEquals(Boolean.TYPE, literals.get(index).getFirstDescendantOfType(ASTBooleanLiteral.class).getType()); assertEquals(Boolean.TYPE, literals.get(index++).getType()); // Object obj = null; assertNull(literals.get(index).getFirstDescendantOfType(ASTNullLiteral.class).getType()); assertNull(literals.get(index++).getType()); // byte byte1 = 0; assertEquals(0, literals.get(index).jjtGetNumChildren()); assertEquals(Integer.TYPE, literals.get(index++).getType()); // byte byte2 = 0x0F; assertEquals(0, literals.get(index).jjtGetNumChildren()); assertEquals(Integer.TYPE, literals.get(index++).getType()); // byte byte3 = -007; assertEquals(0, literals.get(index).jjtGetNumChildren()); assertEquals(Integer.TYPE, literals.get(index++).getType()); // short short1 = 0; assertEquals(0, literals.get(index).jjtGetNumChildren()); assertEquals(Integer.TYPE, literals.get(index++).getType()); // short short2 = 0x0F; assertEquals(0, literals.get(index).jjtGetNumChildren()); assertEquals(Integer.TYPE, literals.get(index++).getType()); // short short3 = -007; assertEquals(0, literals.get(index).jjtGetNumChildren()); assertEquals(Integer.TYPE, literals.get(index++).getType()); // char char1 = 0; assertEquals(0, literals.get(index).jjtGetNumChildren()); assertEquals(Integer.TYPE, literals.get(index++).getType()); // char char2 = 0x0F; assertEquals(0, literals.get(index).jjtGetNumChildren()); assertEquals(Integer.TYPE, literals.get(index++).getType()); // char char3 = 007; assertEquals(0, literals.get(index).jjtGetNumChildren()); assertEquals(Integer.TYPE, literals.get(index++).getType()); // char char4 = 'a'; assertEquals(0, literals.get(index).jjtGetNumChildren()); assertEquals(Character.TYPE, literals.get(index++).getType()); // int int1 = 0; assertEquals(0, literals.get(index).jjtGetNumChildren()); assertEquals(Integer.TYPE, literals.get(index++).getType()); // int int2 = 0x0F; assertEquals(0, literals.get(index).jjtGetNumChildren()); assertEquals(Integer.TYPE, literals.get(index++).getType()); // int int3 = -007; assertEquals(0, literals.get(index).jjtGetNumChildren()); assertEquals(Integer.TYPE, literals.get(index++).getType()); // int int4 = 'a'; assertEquals(0, literals.get(index).jjtGetNumChildren()); assertEquals(Character.TYPE, literals.get(index++).getType()); // long long1 = 0; assertEquals(0, literals.get(index).jjtGetNumChildren()); assertEquals(Integer.TYPE, literals.get(index++).getType()); // long long2 = 0x0F; assertEquals(0, literals.get(index).jjtGetNumChildren()); assertEquals(Integer.TYPE, literals.get(index++).getType()); // long long3 = -007; assertEquals(0, literals.get(index).jjtGetNumChildren()); assertEquals(Integer.TYPE, literals.get(index++).getType()); // long long4 = 0L; assertEquals(0, literals.get(index).jjtGetNumChildren()); assertEquals(Long.TYPE, literals.get(index++).getType()); // long long5 = 0x0Fl; assertEquals(0, literals.get(index).jjtGetNumChildren()); assertEquals(Long.TYPE, literals.get(index++).getType()); // long long6 = -007L; assertEquals(0, literals.get(index).jjtGetNumChildren()); assertEquals(Long.TYPE, literals.get(index++).getType()); // long long7 = 'a'; assertEquals(0, literals.get(index).jjtGetNumChildren()); assertEquals(Character.TYPE, literals.get(index++).getType()); // float float1 = 0.0f; assertEquals(0, literals.get(index).jjtGetNumChildren()); assertEquals(Float.TYPE, literals.get(index++).getType()); // float float2 = -10e+01f; assertEquals(0, literals.get(index).jjtGetNumChildren()); assertEquals(Float.TYPE, literals.get(index++).getType()); // float float3 = 0x08.08p3f; assertEquals(0, literals.get(index).jjtGetNumChildren()); assertEquals(Float.TYPE, literals.get(index++).getType()); // float float4 = 0xFF; assertEquals(0, literals.get(index).jjtGetNumChildren()); assertEquals(Integer.TYPE, literals.get(index++).getType()); // float float5 = 'a'; assertEquals(0, literals.get(index).jjtGetNumChildren()); assertEquals(Character.TYPE, literals.get(index++).getType()); // double double1 = 0.0; assertEquals(0, literals.get(index).jjtGetNumChildren()); assertEquals(Double.TYPE, literals.get(index++).getType()); // double double2 = -10e+01; assertEquals(0, literals.get(index).jjtGetNumChildren()); assertEquals(Double.TYPE, literals.get(index++).getType()); // double double3 = 0x08.08p3; assertEquals(0, literals.get(index).jjtGetNumChildren()); assertEquals(Double.TYPE, literals.get(index++).getType()); // double double4 = 0xFF; assertEquals(0, literals.get(index).jjtGetNumChildren()); assertEquals(Integer.TYPE, literals.get(index++).getType()); // double double5 = 'a'; assertEquals(0, literals.get(index).jjtGetNumChildren()); assertEquals(Character.TYPE, literals.get(index++).getType()); // Make sure we got them all. assertEquals("All literals not tested", index, literals.size()); }
From source file:org.fornax.cartridges.sculptor.smartclient.server.ScServlet.java
public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {// w ww . j a va 2s. c o m printRequest(request); sessionId.set(request.getSession().getId()); String dataSource = request.getParameter("_dataSource"); // List grid export if ("export".equals(request.getParameter("_operationType"))) { exportData(dataSource, response); return; } response.setContentType("text/plain;charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Expires", "-1"); if ("getMenu".equals(dataSource)) { response.getWriter().write(listServices()); } else if ("userInfo".equals(dataSource)) { ServiceContext ctx = ServiceContextStore.get(); PrintWriter out = response.getWriter(); out.print(ctx.getUserId()); for (String role : ctx.getRoles()) { out.print(","); out.print(role); } out.flush(); } else if ("createDataSource".equals(dataSource)) { HashMap<String, String> classToServiceName = new HashMap<String, String>(); for (ServiceDescription serviceDesc : getServiceDescription()) { log.log(Level.INFO, "Service translation from {0} to {1}", new Object[] { serviceDesc.getExpectedClass().getName(), serviceDesc.getName() }); classToServiceName.put(serviceDesc.getExpectedClass().getName(), serviceDesc.getName()); } GuiDataSourceService dataSourceService = getGuiDataSourceService(); dataSourceService.setServiceMapping(ServiceContextStore.get(), classToServiceName); StringBuilder output = new StringBuilder(); output.append("dataSources###"); List<GuiDataSource> allDataSources = dataSourceService.findAll(ServiceContextStore.get()); for (GuiDataSource dataSourceDef : allDataSources) { ds2Ref.put(dataSourceDef.getBaseClass(), dataSourceDef.getTitleField()); dataSourceDef.setBaseClass(null); log.log(Level.INFO, "Entity def for {0}", dataSourceDef.getXxxID()); dataSourceDef.setDataURL(getServiceUrl(request)); output.append("$wnd.isc.RestDataSource.create(") .append(mapObjToOutput(dataSourceDef, 6, new Stack<Object>(), true, false)) .append(");\n"); } ListSettingsService listInstance = (ListSettingsService) findService(LIST_SETTINGS_SERVICE) .getInstance(); List<ListSettings> guiList = listInstance.findUserSettings(ServiceContextStore.get()); for (ListSettings listSettings : guiList) { output.append("\n###").append(listSettings.getListID()).append("###") .append(listSettings.getSettings()); } log.log(Level.INFO, "Create datasource {0}", output.toString()); response.getWriter().append(output); } else if (findService(dataSource) != null) { ServiceDescription serviceDesc = findService(dataSource); String operationType = request.getParameter("_operationType"); String methodName = request.getParameter("_operationId"); if (methodName != null && !methodName.endsWith("_fetch")) { log.log(Level.FINER, "Executing method '" + dataSource + "." + methodName + "'"); MethodDescription methodDescription = serviceDesc.getOtherMethods().get(methodName); if (methodDescription != null) { Object valObj = null; HashMap<String, Object> jsData = unifyRequest(request); Object[] params = prepareMethodParam(jsData, true, methodDescription.parameterNames, methodDescription.method.getParameterTypes()); // Resolve "ids" for iterations int iterate = -1; if (jsData.get("ids") != null) { Class<?>[] paramTypes = methodDescription.method.getParameterTypes(); for (int i = 0; i < paramTypes.length; i++) { if (Long.class.equals(paramTypes[i]) || paramTypes[i].equals(Long.TYPE) && methodDescription.parameterNames[i].equals("id") && params[i] == null) { iterate = i; break; } else if (Collection.class.isAssignableFrom(paramTypes[i]) && methodDescription.parameterNames[i].equals("ids") && params[i] == null) { List<Long> longList = new ArrayList<Long>(); String ids = (String) jsData.get("ids"); String[] idSplit = ids.split(","); for (int k = 0; k < idSplit.length; k++) { if (idSplit[i].length() > 0) { longList.add(Long.parseLong(idSplit[i])); } } params[i] = longList; break; } } } if (iterate != -1) { if (log.isLoggable(Level.FINER)) { for (int j = 0; j < params.length; j++) { log.log(Level.FINER, " Parameter[{0}]={1}", new Object[] { j, params[j] }); } } String ids = (String) jsData.get("ids"); String[] idSplit = ids.split(","); ArrayList<Object> listResult = new ArrayList<Object>(); valObj = listResult; for (int i = 0; i < idSplit.length; i++) { if (idSplit[i].length() > 0) { params[iterate] = Long.parseLong(idSplit[i]); Object subValObj = methodDescription.method.invoke(serviceDesc.getInstance(), params); if (subValObj != null && subValObj instanceof Collection) { listResult.addAll((Collection) subValObj); } else if (subValObj != null) { listResult.add(subValObj); } } } log.info("Return value: " + valObj); } else if (params != null) { if (log.isLoggable(Level.FINER)) { for (int j = 0; j < params.length; j++) { log.log(Level.FINER, " Parameter[{0}]={1}", new Object[] { j, params[j] }); } } valObj = methodDescription.method.invoke(serviceDesc.getInstance(), params); log.info("Return value: " + valObj); } Collection<Object> collResult; PagedResult<?> pagedResult = null; if (valObj == null) { collResult = new ArrayList<Object>(); for (int i = 0; i < params.length; i++) { if (params[i] != null && params[i].getClass().equals(serviceDesc.getExpectedClass())) { collResult.add(params[i]); break; } } } else if (valObj instanceof Collection) { collResult = (Collection) valObj; } else if (valObj instanceof PagedResult) { collResult = null; pagedResult = (PagedResult) valObj; } else { ArrayList<Object> serviceResultArray = new ArrayList<Object>(); serviceResultArray.add(valObj); collResult = serviceResultArray; } if (collResult != null) { sendResponse(response.getWriter(), 0, collResult.size(), collResult); } else if (pagedResult != null) { sendResponse(response.getWriter(), pagedResult); } } else { throw new IllegalArgumentException( "No " + methodName + " operation available on " + dataSource); } } else if (operationType == null) { throw makeApplicationException("Unsupported operation", "ERR9001", "NULL"); } else if (operationType.equals("fetch") && request.getParameter("id") != null) { Long idVal = Long.parseLong(request.getParameter("id")); if (serviceDesc.getFindById() != null) { Object serviceResult = serviceDesc.getFindById().invoke(serviceDesc.getInstance(), ServiceContextStore.get(), idVal); ArrayList<Object> serviceResultArray = new ArrayList<Object>(); serviceResultArray.add(serviceResult); sendResponse(response.getWriter(), 0, 1, serviceResultArray); } else { throw new IllegalArgumentException("No fetch operation available"); } } else if (operationType.equals("fetch")) { List<?> serviceResult; PagedResult<?> pagedServiceResult = null; String sRow = request.getParameter("_startRow"); int startRow = sRow == null ? 0 : Integer.parseInt(sRow); String eRow = request.getParameter("_endRow"); int endRow = eRow == null ? 0 : Integer.parseInt(eRow); ArrayList<String> queryParams = new ArrayList(); Enumeration pNames = request.getParameterNames(); while (pNames.hasMoreElements()) { String paramName = (String) pNames.nextElement(); if (!paramName.startsWith("_")) { queryParams.add(paramName); } else if ("_sortBy".equals(paramName)) { queryParams.add("sortBy"); } } if (queryParams.size() > 0) { Collection<MethodDescription> methods = serviceDesc.getOtherMethods().values(); MethodDescription matchedMethod = null; int matchLength = 1000; for (MethodDescription method : methods) { String[] methodParamNames = method.parameterNames; if (methodParamNames != null && methodParamNames.length >= queryParams.size() && (List.class.isAssignableFrom(method.method.getReturnType()) || PagedResult.class.isAssignableFrom(method.method.getReturnType()))) { boolean matchParam = false; for (String queryParam : queryParams) { matchParam = false; for (String methodParamName : methodParamNames) { if (queryParam.equals(methodParamName)) { matchParam = true; break; } } if (!matchParam) { break; } } if (matchParam && method.parameterNames.length < matchLength) { matchedMethod = method; matchLength = method.parameterNames.length; } } } Object[] params = null; if (matchedMethod != null) { HashMap<String, Object> jsData = unifyRequest(request); params = prepareMethodParam(jsData, true, matchedMethod.parameterNames, matchedMethod.method.getParameterTypes()); } else { List<ConditionalCriteria> conditions = new ArrayList(); for (MethodDescription method : methods) { if (method.getMethodName().equals("findByCondition")) { Class<?>[] parameterTypes = method.method.getParameterTypes(); if (List.class.isAssignableFrom(parameterTypes[0])) { params = new Object[] { conditions }; matchedMethod = method; break; } else if (parameterTypes.length == 3 && ServiceContext.class.isAssignableFrom(parameterTypes[0]) && List.class.isAssignableFrom(parameterTypes[1]) && PagingParameter.class.isAssignableFrom(parameterTypes[2])) { endRow = endRow < startRow + LOOK_AHEAD ? startRow + LOOK_AHEAD : endRow; PagingParameter pagingParam = PagingParameter.rowAccess(startRow, endRow, LOOK_AHEAD); params = new Object[] { ServiceContextStore.get(), conditions, pagingParam }; matchedMethod = method; break; } else if (parameterTypes.length == 2 && ServiceContext.class.isAssignableFrom(parameterTypes[0]) && List.class.isAssignableFrom(parameterTypes[1])) { params = new Object[] { ServiceContextStore.get(), conditions }; matchedMethod = method; break; } } } if (matchedMethod != null) { for (String queryParam : queryParams) { LeafProperty<?> queryProp = new LeafProperty(queryParam, ScServlet.class); String matchStyle = request.getParameter("_textMatchStyle"); String queryValue = request.getParameter(queryParam); if (queryParam.equals("sortBy")) { queryValue = normalizeAssoc(serviceDesc, request.getParameter("_sortBy")); if (queryValue.startsWith("+")) { LeafProperty<?> sortProp = new LeafProperty(queryValue.substring(1), ScServlet.class); conditions.add(ConditionalCriteria.orderAsc(sortProp)); } else if (queryValue.startsWith("-")) { LeafProperty<?> sortProp = new LeafProperty(queryValue.substring(1), ScServlet.class); conditions.add(ConditionalCriteria.orderDesc(sortProp)); } else { LeafProperty<?> sortProp = new LeafProperty(queryValue, ScServlet.class); conditions.add(ConditionalCriteria.orderAsc(sortProp)); } } else if (queryValue.indexOf('%') != -1) { conditions.add(ConditionalCriteria.ignoreCaseLike(queryProp, request.getParameter(queryParam) + "%")); } else { String[] queryParamSplit = queryParam.split("\\."); Class watchClass = serviceDesc.getExpectedClass(); Object otherEqVal = null; boolean isString = false; for (String queryParamPart : queryParamSplit) { try { Method method = watchClass.getMethod( makeGetMethodName(queryParamPart), (Class[]) null); watchClass = method.getReturnType(); if (Collection.class.isAssignableFrom(watchClass)) { // TODO look deeper into class of collection break; } else if (Enum.class.isAssignableFrom(watchClass)) { otherEqVal = Enum.valueOf(watchClass, queryValue); break; } else if (String.class.equals(watchClass)) { isString = true; break; } else if (Long.class.equals(watchClass)) { isString = true; otherEqVal = Long.parseLong(queryValue); break; } else if (Integer.class.equals(watchClass)) { isString = true; otherEqVal = Integer.parseInt(queryValue); break; } else if (Double.class.equals(watchClass)) { isString = true; otherEqVal = Double.parseDouble(queryValue); break; } else if (Date.class.equals(watchClass)) { otherEqVal = dateFormat.parse(queryValue); break; } else if (findServiceByClassName(watchClass.getName()) != null && "null".equals(queryValue)) { otherEqVal = "null"; break; } else if (findServiceByClassName(watchClass.getName()) != null && findServiceByClassName(watchClass.getName()) .getFindById() != null) { ServiceDescription srvc = findServiceByClassName( watchClass.getName()); otherEqVal = srvc.getFindById().invoke(srvc.getInstance(), ServiceContextStore.get(), Long.parseLong(queryValue)); } } catch (NoSuchMethodException nsme) { // Ignore error, isString will stay false break; } } boolean isLike = "substring".equals(matchStyle) || "startsWith".equals(matchStyle); if ("null".equals(otherEqVal)) { conditions.add(ConditionalCriteria.isNull(queryProp)); } else if (otherEqVal instanceof Date) { DateMidnight start = (new DateTime(otherEqVal)).toDateMidnight(); DateMidnight stop = start.plusDays(1); conditions.add(ConditionalCriteria.between(queryProp, start.toDate(), stop.toDate())); } else if (isString && otherEqVal != null && isLike) { conditions.add(ConditionalCriteria.like(queryProp, otherEqVal)); } else if (isString && "substring".equals(matchStyle)) { conditions.add(ConditionalCriteria.ignoreCaseLike(queryProp, "%" + request.getParameter(queryParam) + "%")); } else if (isString && "startsWith".equals(matchStyle)) { conditions.add(ConditionalCriteria.ignoreCaseLike(queryProp, request.getParameter(queryParam) + "%")); } else if (otherEqVal != null) { conditions.add(ConditionalCriteria.equal(queryProp, otherEqVal)); } else { conditions.add(ConditionalCriteria.equal(queryProp, queryValue)); } } } } } if (matchedMethod != null && params != null) { for (int j = 0; j < params.length; j++) { log.log(Level.FINER, " Parameter[{0}]={1}", new Object[] { j, params[j] }); } if (matchedMethod.method.getReturnType().equals(PagedResult.class)) { serviceResult = null; pagedServiceResult = (PagedResult) matchedMethod.method .invoke(serviceDesc.getInstance(), params); } else { serviceResult = (List<?>) matchedMethod.method.invoke(serviceDesc.getInstance(), params); } } else { throw makeApplicationException("You can''t filter with such condition.", "ERR9015", (Serializable[]) null); } } else if (queryParams.size() == 0 && serviceDesc.getFindAll() != null) { Class<?>[] paramTypes = serviceDesc.getFindAll().getParameterTypes(); if (paramTypes.length == 2 && paramTypes[0].equals(ServiceContext.class) && paramTypes[1].equals(PagingParameter.class) && serviceDesc.getFindAll().getReturnType().equals(PagedResult.class)) { endRow = endRow < startRow + LOOK_AHEAD ? startRow + LOOK_AHEAD : endRow; PagingParameter pagingParam = PagingParameter.rowAccess(startRow, endRow, LOOK_AHEAD); pagedServiceResult = (PagedResult<?>) serviceDesc.getFindAll() .invoke(serviceDesc.getInstance(), ServiceContextStore.get(), pagingParam); serviceResult = null; } else if (paramTypes.length == 1 && paramTypes[0].equals(ServiceContext.class)) { serviceResult = (List<? extends Object>) serviceDesc.getFindAll() .invoke(serviceDesc.getInstance(), ServiceContextStore.get()); } else { serviceResult = null; } } else { throw new ApplicationException("", "No fetch operation available"); } if (pagedServiceResult != null) { sendResponse(response.getWriter(), pagedServiceResult); } else { int resultSize = serviceResult == null ? 0 : serviceResult.size(); endRow = (endRow == 0 ? resultSize : endRow); sendResponse(response.getWriter(), startRow, endRow < resultSize ? endRow : resultSize, serviceResult); } } else if (operationType.equals("update") && request.getParameter("id") != null) { Object val = serviceDesc.getFindById().invoke(serviceDesc.getInstance(), ServiceContextStore.get(), Long.parseLong(request.getParameter("id"))); HashMap<String, Object> reqData = unifyRequest(request); mapRequestToObj(reqData, serviceDesc.getExpectedClass(), val); serviceDesc.getOtherMethods().get("save").method.invoke(serviceDesc.getInstance(), ServiceContextStore.get(), val); ArrayList<Object> list = new ArrayList<Object>(); list.add(val); sendResponse(response.getWriter(), 0, 1, list); } else if ((operationType.equals("add") || operationType.equals("update")) && request.getParameter("id") == null) { HashMap<String, Object> reqData = unifyRequest(request); Object val = makeNewInstance(serviceDesc.getExpectedClass(), reqData); if (val != null) { mapRequestToObj(reqData, serviceDesc.getExpectedClass(), val); serviceDesc.getOtherMethods().get("save").method.invoke(serviceDesc.getInstance(), ServiceContextStore.get(), val); ArrayList<Object> list = new ArrayList<Object>(); list.add(val); sendResponse(response.getWriter(), 0, 1, list); } else { throw makeApplicationException("Can't create new instance", "ERR9003", serviceDesc.getExpectedClass().getName()); } } else { throw makeApplicationException("Unsupported operation", "ERR9001", operationType); } } else { throw makeApplicationException("Wrong datasource name", "ERR9002", dataSource); } } catch (Throwable ex) { // Find most relevant exception in embedded exceptions ApplicationException appException = null; Throwable relevantException = ex; while (ex != null) { relevantException = ex; if (ex instanceof ApplicationException) { appException = (ApplicationException) ex; break; } if (ex instanceof ValidationException) { break; } ex = ex.getCause(); } // Prepare message String msg = null; if (appException != null) { msg = translate(appException.getMessage()); Serializable[] msgParams = appException.getMessageParameters(); if (msgParams != null) { Object[] params = new Object[msgParams.length]; for (int i = 0; i < msgParams.length; i++) { if (msgParams[i] instanceof Translatable) { params[i] = translate(((Translatable) msgParams[i]).getContent()); } else { params[i] = msgParams[i]; } } msg = MessageFormat.format(msg, params); } } else if (relevantException instanceof ValidationException) { StringBuilder b = new StringBuilder(); for (InvalidValue iv : ((ValidationException) relevantException).getInvalidValues()) { b.append("<b>").append(translate(iv.getPropertyName()) + ":</b> " + iv.getMessage()) .append("<br/>"); } msg = b.toString(); } else { msg = translate("ERR9000"); msg = MessageFormat.format(msg, new Object[] { relevantException.getClass().getName(), relevantException.getMessage() }); } // Print stack trace log.log(Level.WARNING, "Relevant exception", relevantException); if (msg != null) { log.log(Level.WARNING, "SENDING BACK ERROR '" + msg + "'"); response.getWriter() .write("{response:{ status:-1, data:\"" + msg.replaceAll("\\\\", "\\\\\\\\").replaceAll("\"", "\\\\\"") + "\", startRow:0, endRow:0, totalRows:0}}"); } response.flushBuffer(); // response.setStatus(HttpServletResponse.SC_NOT_FOUND); throw new ServletException(msg); } response.flushBuffer(); }
From source file:com.nonninz.robomodel.RoboModel.java
void saveField(Field field, TypedContentValues cv) { final Class<?> type = field.getType(); final boolean wasAccessible = field.isAccessible(); field.setAccessible(true);/*from www . ja va 2s . c o m*/ try { if (type == String.class) { cv.put(field.getName(), (String) field.get(this)); } else if (type == Boolean.TYPE) { cv.put(field.getName(), field.getBoolean(this)); } else if (type == Byte.TYPE) { cv.put(field.getName(), field.getByte(this)); } else if (type == Double.TYPE) { cv.put(field.getName(), field.getDouble(this)); } else if (type == Float.TYPE) { cv.put(field.getName(), field.getFloat(this)); } else if (type == Integer.TYPE) { cv.put(field.getName(), field.getInt(this)); } else if (type == Long.TYPE) { cv.put(field.getName(), field.getLong(this)); } else if (type == Short.TYPE) { cv.put(field.getName(), field.getShort(this)); } else if (type.isEnum()) { final Object value = field.get(this); if (value != null) { final Method method = type.getMethod("name"); final String str = (String) method.invoke(value); cv.put(field.getName(), str); } } else { // Try to JSONify it (db column must be of type text) final String json = mMapper.writeValueAsString(field.get(this)); cv.put(field.getName(), json); } } catch (final IllegalAccessException e) { final String msg = String.format("Field %s is not accessible", type, field.getName()); throw new IllegalArgumentException(msg); } catch (final JsonProcessingException e) { Ln.w(e, "Error while dumping %s of type %s to Json", field.getName(), type); final String msg = String.format("Field %s is not accessible", type, field.getName()); throw new IllegalArgumentException(msg); } catch (final NoSuchMethodException e) { // Should not happen throw new RuntimeException(e); } catch (final InvocationTargetException e) { // Should not happen throw new RuntimeException(e); } finally { field.setAccessible(wasAccessible); } }
From source file:com.sun.faces.el.impl.Coercions.java
/** * Returns true if the given class is Byte, Short, Integer, Long, * Float, Double, BigInteger, or BigDecimal *///w w w . jav a 2s. c om static boolean isNumberClass(Class pClass) { return pClass == Byte.class || pClass == Byte.TYPE || pClass == Short.class || pClass == Short.TYPE || pClass == Integer.class || pClass == Integer.TYPE || pClass == Long.class || pClass == Long.TYPE || pClass == Float.class || pClass == Float.TYPE || pClass == Double.class || pClass == Double.TYPE || pClass == BigInteger.class || pClass == BigDecimal.class; }
From source file:at.alladin.rmbt.shared.hstoreparser.HstoreParser.java
/** * get a specific key from json by preserving the fields type * @param json//from w ww .j a va2s. c o m * @param key * @param toField * @return * @throws JSONException */ public static Object getFromJsonByField(JSONObject json, String key, Field toField) throws JSONException { final Object o = json.get(key); if (o != JSONObject.NULL) { if (toField.getType().equals(Integer.class) || toField.getType().equals(Integer.TYPE)) { return Integer.parseInt(String.valueOf(o)); } else if (toField.getType().equals(String.class)) { return o; } else if (toField.getType().equals(Long.class) || toField.getType().equals(Long.TYPE)) { return Long.parseLong(String.valueOf(o)); } else if (toField.getType().equals(Boolean.class) || toField.getType().equals(Boolean.TYPE)) { return Boolean.parseBoolean(String.valueOf(o)); } else if (toField.getType().equals(Float.class) || toField.getType().equals(Float.TYPE)) { return Float.parseFloat(String.valueOf(o)); } else if (toField.getType().equals(Double.class) || toField.getType().equals(Double.TYPE)) { return Double.parseDouble(String.valueOf(o)); } else { return o; } } return JSONObject.NULL; }
From source file:com.streamsets.datacollector.execution.preview.sync.SyncPreviewer.java
private static Object getValueFromParam(Field field, String stringValue) { Class<?> type = field.getType(); if (String.class.isAssignableFrom(type)) { return stringValue; } else if (Integer.class.isAssignableFrom(type) || Integer.TYPE == type) { return Integer.parseInt(stringValue); } else if (Long.class.isAssignableFrom(type) || Long.TYPE == type) { return Long.parseLong(stringValue); } else if (Boolean.class.isAssignableFrom(type) || Boolean.TYPE == type) { return Boolean.parseBoolean(stringValue); }/*from w w w . j a v a2 s .co m*/ return null; }
From source file:com.nway.spring.jdbc.bean.AsmBeanProcessor.java
private Object processColumn(ResultSet rs, int index, Class<?> propType, String writer, String processorName, String beanName, MethodVisitor mv) throws SQLException { if (propType.equals(String.class)) { visitMethod(mv, index, beanName, "Ljava/lang/String;", "getString", writer); return rs.getString(index); } else if (propType.equals(Integer.TYPE)) { visitMethod(mv, index, beanName, "I", "getInt", writer); return rs.getInt(index); } else if (propType.equals(Integer.class)) { visitMethodWrap(mv, index, beanName, PROPERTY_TYPE_INTEGER, writer, processorName); return JdbcUtils.getResultSetValue(rs, index, Integer.class); } else if (propType.equals(Long.TYPE)) { visitMethod(mv, index, beanName, "J", "getLong", writer); return rs.getLong(index); } else if (propType.equals(Long.class)) { visitMethodWrap(mv, index, beanName, PROPERTY_TYPE_LONG, writer, processorName); return JdbcUtils.getResultSetValue(rs, index, Long.class); } else if (propType.equals(java.sql.Date.class)) { visitMethod(mv, index, beanName, "Ljava/sql/Date;", "getDate", writer); return rs.getDate(index); } else if (propType.equals(java.util.Date.class)) { visitMethodCast(mv, index, beanName, PROPERTY_TYPE_DATE, "java/util/Date", writer); return rs.getTimestamp(index); } else if (propType.equals(Timestamp.class)) { visitMethod(mv, index, beanName, "Ljava/sql/Timestamp;", "getTimestamp", writer); return rs.getTimestamp(index); } else if (propType.equals(Time.class)) { visitMethod(mv, index, beanName, "Ljava/sql/Time;", "getTime", writer); return rs.getTime(index); } else if (propType.equals(Double.TYPE)) { visitMethod(mv, index, beanName, "D", "getDouble", writer); return rs.getDouble(index); } else if (propType.equals(Double.class)) { visitMethodWrap(mv, index, beanName, PROPERTY_TYPE_DOUBLE, writer, processorName); return JdbcUtils.getResultSetValue(rs, index, Double.class); } else if (propType.equals(Float.TYPE)) { visitMethod(mv, index, beanName, "F", "getFloat", writer); return rs.getFloat(index); } else if (propType.equals(Float.class)) { visitMethodWrap(mv, index, beanName, PROPERTY_TYPE_FLOAT, writer, processorName); return JdbcUtils.getResultSetValue(rs, index, Float.class); } else if (propType.equals(Boolean.TYPE)) { visitMethod(mv, index, beanName, "Z", "getBoolean", writer); return rs.getBoolean(index); } else if (propType.equals(Boolean.class)) { visitMethodWrap(mv, index, beanName, PROPERTY_TYPE_BOOLEAN, writer, processorName); return JdbcUtils.getResultSetValue(rs, index, Boolean.class); } else if (propType.equals(Clob.class)) { visitMethod(mv, index, beanName, "Ljava/sql/Clob;", "getClob", writer); return rs.getClob(index); } else if (propType.equals(Blob.class)) { visitMethod(mv, index, beanName, "Ljava/sql/Blob;", "getBlob", writer); return rs.getBlob(index); } else if (propType.equals(byte[].class)) { visitMethod(mv, index, beanName, "[B", "getBytes", writer); return rs.getBytes(index); } else if (propType.equals(Short.TYPE)) { visitMethod(mv, index, beanName, "S", "getShort", writer); return rs.getShort(index); } else if (propType.equals(Short.class)) { visitMethodWrap(mv, index, beanName, PROPERTY_TYPE_SHORT, writer, processorName); return JdbcUtils.getResultSetValue(rs, index, Short.class); } else if (propType.equals(Byte.TYPE)) { visitMethod(mv, index, beanName, "B", "getByte", writer); return rs.getByte(index); } else if (propType.equals(Byte.class)) { visitMethodWrap(mv, index, beanName, PROPERTY_TYPE_BYTE, writer, processorName); return rs.getByte(index); } else {//from ww w.j a va 2 s . c o m visitMethodCast(mv, index, beanName, PROPERTY_TYPE_OTHER, propType.getName().replace('.', '/'), writer); return rs.getObject(index); } }
From source file:org.liveSense.api.beanprocessors.DbStandardBeanProcessor.java
/** * ResultSet.getObject() returns an Integer object for an INT column. The * setter method for the property might take an Integer or a primitive int. * This method returns true if the value can be successfully passed into * the setter method. Remember, Method.invoke() handles the unwrapping * of Integer into an int./*w ww. j a v a 2s .c o m*/ * * @param value The value to be passed into the setter method. * @param type The setter's parameter type. * @return boolean True if the value is compatible. */ private boolean isCompatibleType(Object value, Class<?> type) { // Do object check first, then primitives if (value == null || type.isInstance(value)) { return true; } else if (type.equals(Integer.TYPE) && Integer.class.isInstance(value)) { return true; } else if (type.equals(Long.TYPE) && Long.class.isInstance(value)) { return true; } else if (type.equals(Double.TYPE) && Double.class.isInstance(value)) { return true; } else if (type.equals(Float.TYPE) && Float.class.isInstance(value)) { return true; } else if (type.equals(Short.TYPE) && Short.class.isInstance(value)) { return true; } else if (type.equals(Byte.TYPE) && Byte.class.isInstance(value)) { return true; } else if (type.equals(Character.TYPE) && Character.class.isInstance(value)) { return true; } else if (type.equals(Boolean.TYPE) && Boolean.class.isInstance(value)) { return true; } else { return false; } }