Package net.arnx.jsonic

Examples of net.arnx.jsonic.JSON


  public void init(ServletConfig servletConfig) throws ServletException {
    super.init(servletConfig);
   
    String configText = servletConfig.getInitParameter("config");
   
    JSON json = new JSON();
   
    if (configText == null) {
      Map<String, String> map = new HashMap<String, String>();
      Enumeration<String> e =  cast(servletConfig.getInitParameterNames());
      while (e.hasMoreElements()) {
        map.put(e.nextElement(), servletConfig.getInitParameter(e.nextElement()));
      }
      configText = json.format(map);
    }
   
    try {
      config = json.parse(configText, Config.class);
      if (config.container == null) config.container = Container.class;
      container = json.parse(configText, config.container);
      container.init(this);
    } catch (Exception e) {
      throw new ServletException(e);
    }
   
View Full Code Here


      status = SC_CREATED;
    }
   
    container.start(request, response);
   
    JSON json = container.createJSON(request.getLocale());
   
    try {
      String className = route.getComponentClass(container);
      Object component = container.getComponent(className);
      if (component == null) {
        throw new ClassNotFoundException("Component not found: " + className);
      }
     
      List<Object> params = null;
      if (isJSONType(request.getContentType())) {
        Object o = json.parse(request.getReader());
        if (o instanceof List<?>) {
          params = cast(o);
          if (params.isEmpty()) {
            params = new ArrayList<Object>(1);
            params.add(route.getParameterMap());
          } else if (params.get(0) instanceof Map<?, ?>) {
            params.set(0, route.mergeParameterMap((Map<?, ?>)params.get(0)));
          }
        } else if (o instanceof Map<?, ?>) {
          params = new ArrayList<Object>(1);
          params.add(route.mergeParameterMap((Map<?, ?>)o));
        } else {
          throw new IllegalArgumentException("failed to convert parameters from JSON.");
        }
      } else {
        params = new ArrayList<Object>(1);
        params.add(route.getParameterMap());       
      }
     
      Method method = container.getMethod(component, route.getRestMethod(), params);
      if (method == null) {
        throw new NoSuchMethodException("Method not found: " + route.getRestMethod());         
      }
     
      json.setContext(component);
      result = container.execute(json, component, method, params);
    } catch (Exception e) {
      if (e instanceof ClassNotFoundException) {
        container.debug("Class Not Found.", e);
        response.sendError(SC_NOT_FOUND, "Not Found");
        response.flushBuffer();
      } else if (e instanceof NoSuchMethodException) {
        container.debug("Method Not Found.", e);
        response.sendError(SC_NOT_FOUND, "Not Found");
        response.flushBuffer();
      } else if (e instanceof JSONException) {
        container.debug("Fails to parse JSON.", e);
        response.sendError(SC_BAD_REQUEST, "Bad Request");
        response.flushBuffer();
      } else if (e instanceof InvocationTargetException) {
        Throwable cause = e.getCause();
        container.debug("Cause error on invocation.", cause);
        if (cause instanceof Error) {
          throw (Error)cause;
        } else if (cause instanceof IllegalStateException || cause instanceof UnsupportedOperationException) {
          response.sendError(SC_NOT_FOUND, "Not Found");
          response.flushBuffer();
        } else if (cause instanceof IllegalArgumentException) {
          response.sendError(SC_BAD_REQUEST, "Bad Request");
          response.flushBuffer();
        } else {
          Integer errorCode = null;
          for (Map.Entry<Class<? extends Exception>, Integer> entry : config.errors.entrySet()) {
            if (entry.getKey().isAssignableFrom(cause.getClass()) && entry.getValue() != null) {
              errorCode = entry.getValue();
              break;
            }
          }
          if (errorCode != null) {
            response.setStatus(errorCode);
           
            Map<String, Object> error = new LinkedHashMap<String, Object>();
            error.put("name", cause.getClass().getSimpleName());
            error.put("message", cause.getMessage());
            error.put("data", cause);
            result = error;
          } else {
            response.sendError(SC_INTERNAL_SERVER_ERROR, "Internal Server Error");       
            response.flushBuffer();
          }
        }
      } else {
        container.error("Internal error occurred.", e);
        response.sendError(SC_INTERNAL_SERVER_ERROR, "Internal Server Error");       
        response.flushBuffer();
      }
    } finally {
      container.end(request, response);
    }
   
    if (response.isCommitted()) return;
   
    if (result == null
        || result instanceof CharSequence
        || result instanceof Boolean
        || result instanceof Number
        || result instanceof Date) {
      if (status != SC_CREATED) status = SC_NO_CONTENT;
      response.setStatus(status);
    } else {
      response.setContentType((callback != null) ? "text/javascript" : "application/json");
      Writer writer = response.getWriter();
      json.setPrettyPrint(container.isDebugMode());
     
      if (callback != null) writer.append(callback).append("(");
      json.format(result, writer);
      if (callback != null) writer.append(");");
    }
  }
View Full Code Here

  }
 
  public void init(FilterConfig filterConfig) throws ServletException {
    this.context = filterConfig.getServletContext();
   
    JSON json = new JSON();
    json.setContext(this);

    String configText = filterConfig.getInitParameter("config");
    if (configText == null) configText = "";

    Map map = json.parse(configText, Map.class);
   
    Map<String, Object> baseMap = new LinkedHashMap<String, Object>();
    for (Field field : Config.class.getFields()) {
      baseMap.put(field.getName(), map.get(field.getName()));
    }
   
    Config base = (Config)json.convert(baseMap, Config.class);
    for (Map.Entry entry : (Set<Map.Entry>)map.entrySet()) {
      if (!baseMap.containsKey(entry.getKey()) && entry.getValue() instanceof Map) {
        Map valueMap = (Map)entry.getValue();
        for (Map.Entry<String, Object> baseEntry : baseMap.entrySet()) {
          if (valueMap.get(baseEntry.getKey()) == null) {
            valueMap.put(baseEntry.getKey(), baseEntry.getValue());
          }
        }
       
        Config config = (Config)json.convert(valueMap, Config.class);
        locations.put(Pattern.compile("^" + entry.getKey() + "$"), config);
      }
    }
    locations.put(Pattern.compile(".*"), base);
  }
View Full Code Here

    }
  }
 
  JSON createJSON(Locale locale) throws ServletException  {
    try {
      JSON json = (processor != null) ? processor.newInstance() : new JSON() {
        @Override
        protected boolean ignore(Context context, Class<?> target, Member member) {
          return member.getDeclaringClass().equals(Throwable.class)
            || super.ignore(context, target, member);
        }
      };
      json.setLocale(locale);
      return json;
    } catch (Exception e) {
      throw new ServletException(e);
    }
  }
View Full Code Here

  public void init(ServletConfig servletConfig) throws ServletException {
    super.init(servletConfig);
   
    String configText = servletConfig.getInitParameter("config");
   
    JSON json = new JSON();
   
    if (configText == null) {
      Map<String, String> map = new HashMap<String, String>();
      Enumeration<String> e =  cast(servletConfig.getInitParameterNames());
      while (e.hasMoreElements()) {
        map.put(e.nextElement(), servletConfig.getInitParameter(e.nextElement()));
      }
      configText = json.format(map);
    }
   
    try {
      config = json.parse(configText, Config.class);
      if (config.container == null) config.container = Container.class;
      container = json.parse(configText, config.container);
      container.init(this);
    } catch (Exception e) {
      throw new ServletException(e);
    }
   
View Full Code Here

    List<Object> requestList = new ArrayList<Object>(0);
    List<Object> responseList = new ArrayList<Object>();
   
    Object component = null;
   
    JSON json = container.createJSON(request.getLocale());
   
    container.start(request, response);
    try {
      // request processing
      Object value = json.parse(request.getReader());
      if (value instanceof List<?> && !((List<?>)value).isEmpty()) {
        requestList = cast(value);         
        isBatch = true;
      } else if (value instanceof Map<?,?> && !((Map<?,?>)value).isEmpty()) {
        requestList = Arrays.asList(value);
      } else {
        throw new IllegalArgumentException("Request is empty.");
      }
     
      for (int i = 0; i < requestList.size(); i++) {
        Map<?,?> req = (Map<?,?>)requestList.get(i);
       
        String rjsonrpc = null;
        String rmethod = null;
        Object rparams = null;
        Object rid = null;
       
        Object result = null;
        Map<String, Object> error = null;
 
        try {
          if (req.get("jsonrpc") == null || "2.0".equals(req.get("jsonrpc"))) {
            rjsonrpc = (String)req.get("jsonrpc");
          } else {
            throw new IllegalArgumentException("jsonrpc is unrecognized version: " + req.get("jsonrpc"));
          }
         
          if (req.get("method") instanceof String) {
            rmethod = (String)req.get("method");
            if (rjsonrpc != null && rmethod.startsWith("rpc.")) {
              container.warn("Method names that begin with 'rpc.' are reserved for system extensions.");
            }
          } else {
            throw new IllegalArgumentException("method must " + ((req.get("method") == null) ? "not be null." : "be string."));
          }
         
          if (req.get("params") instanceof List<?> || (rjsonrpc != null && req.get("params") instanceof Map<?, ?>)) {
            rparams = req.get("params");
          } else if (rjsonrpc != null && req.get("params") == null) {
            rparams = new ArrayList<Object>(0);
          } else {
            throw new IllegalArgumentException("params must be array" + ((rjsonrpc != null) ? " or object." : "."));
          }
         
          if (rjsonrpc == null || (req.get("id") == null || req.get("id") instanceof String || req.get("id") instanceof Number)) {
            rid = req.get("id");
          } else {
            throw new IllegalArgumentException("id must be string, number or null.");
          }
         
          String subcompName = null;
          String methodName = rmethod;
          if (route.getParameter("class") == null) {
            int sep = rmethod.lastIndexOf('.');
            subcompName = (sep != -1) ? rmethod.substring(0, sep) : null;
            methodName = (sep != -1) ? rmethod.substring(sep+1) : rmethod;
          }
         
          component = container.getComponent(route.getComponentClass(container, subcompName));
          if (component == null) {
            throw new NoSuchMethodException("Method not found: " + rmethod);
          }
         
          List<?> params = (rparams instanceof List<?>) ? (List<?>)rparams : Arrays.asList(rparams);
          Method method = container.getMethod(component, methodName, params);
          if (method == null) {
            throw new NoSuchMethodException("Method not found: " + rmethod);         
          }
         
          json.setContext(component);
          result = container.execute(json, component, method, params);
        } catch (Exception e) {
          error = new LinkedHashMap<String, Object>();
          if (e instanceof IllegalArgumentException) {
            container.debug("Invalid Request.", e);
            error.put("code", -32600);
            error.put("message", "Invalid Request.");
          } else if (e instanceof ClassNotFoundException) {
            container.debug("Class Not Found.", e);
            error.put("code", -32601);
            error.put("message", "Method not found.");
          } else if (e instanceof NoSuchMethodException) {
            container.debug("Method Not Found.", e);
            error.put("code", -32601);
            error.put("message", "Method not found.");
          } else if (e instanceof JSONException) {
            container.debug("Invalid params.", e);
            error.put("code", -32602);
            error.put("message", "Invalid params.");
          } else if (e instanceof InvocationTargetException) {
            Throwable cause = e.getCause();
            container.debug("Fails to invoke method.", cause);
            if (cause instanceof Error) {
              throw (Error)cause;
            } else   if (cause instanceof IllegalStateException || cause instanceof UnsupportedOperationException) {
              error.put("code", -32601);
              error.put("message", "Method not found.");
            } else if (cause instanceof IllegalArgumentException) {
              error.put("code", -32602);
              error.put("message", "Invalid params.");
            } else {
              Integer errorCode = null;
              for (Map.Entry<Class<? extends Exception>, Integer> entry : config.errors.entrySet()) {
                if (entry.getKey().isAssignableFrom(cause.getClass()) && entry.getValue() != null) {
                  errorCode = entry.getValue();
                  break;
                }
              }
              if (errorCode != null) {
                error.put("code", errorCode);
                error.put("message",  cause.getClass().getSimpleName() + ": " + cause.getMessage());
                error.put("data", cause);
              } else {
                container.error("Internal error occurred.", cause);
                error.put("code", -32603);
                error.put("message", "Internal error.");
              }
            }
          } else {
            container.error("Internal error occurred.", e);
            error.put("code", -32603);
            error.put("message", "Internal error.");
          }
        }
       
        // it's notification when id was null
        if (rmethod != null && (rjsonrpc == null && rid == null) || (rjsonrpc != null && req != null && !req.containsKey("id"))) {
          continue;
        }
       
        Map<String, Object> responseData = new LinkedHashMap<String, Object>();
        if (rjsonrpc != null) responseData.put("jsonrpc", rjsonrpc);
        if (rjsonrpc == null || result != null) responseData.put("result", result);
        if (rjsonrpc == null || error != null) responseData.put("error", error);
        responseData.put("id", rid);
       
        responseList.add(responseData);
      }
    } catch (Exception e) {
      Map<String, Object> error = new LinkedHashMap<String, Object>();
      if (e instanceof JSONException) {
        container.debug("Fails to parse JSON.", e);
        error.put("code", -32700);
        error.put("message", "Parse error.");
        error.put("data", e);
      } else {
        container.debug("Invalid Request.", e);
        error.put("code", -32600);
        error.put("message", "Invalid Request.");
      }
     
      Map<String, Object> responseData = new LinkedHashMap<String, Object>();
      responseData.put("jsonrpc", "2.0");
      responseData.put("error", error);
      responseData.put("id", null);
     
      responseList.add(responseData);
    } finally {
      container.end(request, response);
    }
   
    if (response.isCommitted()) return;
   
    // it's notification when id was null for all requests.
    if (responseList.isEmpty()) {
      response.setStatus(SC_ACCEPTED);
      return;
    }
   
    // response processing
    response.setContentType("application/json");
   
    Writer writer = response.getWriter();
   
    Object target = (isBatch) ? responseList : responseList.get(0);
    json.setContext(target);
    json.setPrettyPrint(container.isDebugMode());
    json.format(target, writer);
  }
View Full Code Here

    }
  }
 
  JSON createJSON(Locale locale) throws ServletException  {
    try {
      JSON json = (processor != null) ? processor.newInstance() : new JSON() {
        @Override
        protected boolean ignore(Context context, Class<?> target, Member member) {
          return member.getDeclaringClass().equals(Throwable.class)
            || super.ignore(context, target, member);
        }
      };
      json.setLocale(locale);
      return json;
    } catch (Exception e) {
      throw new ServletException(e);
    }
  }
View Full Code Here

  public void init(ServletConfig servletConfig) throws ServletException {
    super.init(servletConfig);
   
    String configText = servletConfig.getInitParameter("config");
   
    JSON json = new JSON();
   
    if (configText == null) {
      Map<String, String> map = new HashMap<String, String>();
      Enumeration<String> e =  cast(servletConfig.getInitParameterNames());
      while (e.hasMoreElements()) {
        map.put(e.nextElement(), servletConfig.getInitParameter(e.nextElement()));
      }
      configText = json.format(map);
    }
   
    try {
      config = json.parse(configText, Config.class);
      if (config.container == null) config.container = Container.class;
      container = json.parse(configText, config.container);
      container.init(this);
    } catch (Exception e) {
      throw new ServletException(e);
    }
   
View Full Code Here

 
  protected void doREST(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
   
    int status = SC_OK;
    JSON json = null;
    String callback = null;
    Object result = null;
   
    try {
      ExternalContext.start(getServletConfig(), getServletContext(), request, response);   
      container.start(request, response);
     
      String uri = (request.getContextPath().equals("/")) ?
          request.getRequestURI() :
          request.getRequestURI().substring(request.getContextPath().length());
     
      Route route = null;
      for (RouteMapping m : config.mappings.values()) {
        if ((route = m.matches(request, uri)) != null) {
          container.debug("Route found: " + request.getMethod() + " " + uri);
          break;
        }
      }
     
      if (route == null) {
        response.sendError(SC_NOT_FOUND, "Not Found");
        return;
      }
     
      if (route.getHttpMethod() == null || route.getRestMethod() == null) {
        container.debug("Method mapping not found: " + route.getHttpMethod());
        response.sendError(SC_METHOD_NOT_ALLOWED, "Method Not Allowed");
        return;     
      }
     
      if ("GET".equals(request.getMethod())) {
        callback = route.getParameter("callback");
      } else if ("POST".equals(route.getHttpMethod())) {
        status = SC_CREATED;
      }
     
      json = container.createJSON(request.getLocale());
   
      String className = route.getComponentClass(container);
      Object component = container.getComponent(className);
      if (component == null) {
        throw new ClassNotFoundException("Component not found: " + className);
      }
     
      List<Object> params = null;
      if (isJSONType(request.getContentType())) {
        Object o = json.parse(request.getReader());
        if (o instanceof List<?>) {
          params = cast(o);
          if (params.isEmpty()) {
            params = new ArrayList<Object>(1);
            params.add(route.getParameterMap());
          } else if (params.get(0) instanceof Map<?, ?>) {
            params.set(0, route.mergeParameterMap((Map<?, ?>)params.get(0)));
          }
        } else if (o instanceof Map<?, ?>) {
          params = new ArrayList<Object>(1);
          params.add(route.mergeParameterMap((Map<?, ?>)o));
        } else {
          throw new IllegalArgumentException("failed to convert parameters from JSON.");
        }
      } else {
        params = new ArrayList<Object>(1);
        params.add(route.getParameterMap());       
      }
     
      Method method = container.getMethod(component, route.getRestMethod(), params);
      if (method == null) {
        throw new NoSuchMethodException("Method not found: " + route.getRestMethod());         
      }
     
      json.setContext(component);
      result = container.execute(json, component, method, params);
    } catch (Exception e) {
      if (e instanceof ClassNotFoundException) {
        container.debug("Class Not Found.", e);
        response.sendError(SC_NOT_FOUND, "Not Found");
        response.flushBuffer();
      } else if (e instanceof NoSuchMethodException) {
        container.debug("Method Not Found.", e);
        response.sendError(SC_NOT_FOUND, "Not Found");
        response.flushBuffer();
      } else if (e instanceof JSONException) {
        container.debug("Fails to parse JSON.", e);
        response.sendError(SC_BAD_REQUEST, "Bad Request");
        response.flushBuffer();
      } else if (e instanceof InvocationTargetException) {
        Throwable cause = e.getCause();
        container.debug("Cause error on invocation.", cause);
        if (cause instanceof Error) {
          throw (Error)cause;
        } else if (cause instanceof IllegalStateException || cause instanceof UnsupportedOperationException) {
          response.sendError(SC_NOT_FOUND, "Not Found");
          response.flushBuffer();
        } else if (cause instanceof IllegalArgumentException) {
          response.sendError(SC_BAD_REQUEST, "Bad Request");
          response.flushBuffer();
        } else {
          Integer errorCode = null;
          for (Map.Entry<String, Integer> entry : config.errors.entrySet()) {
            Class<?> cls = ClassUtil.findClass(entry.getKey());
            if (cls.isAssignableFrom(cause.getClass()) && entry.getValue() != null) {
              errorCode = entry.getValue();
              break;
            }
          }
          if (errorCode != null) {
            response.setStatus(errorCode);
           
            Map<String, Object> error = new LinkedHashMap<String, Object>();
            error.put("name", cause.getClass().getSimpleName());
            error.put("message", cause.getMessage());
            error.put("data", cause);
            result = error;
          } else {
            response.sendError(SC_INTERNAL_SERVER_ERROR, "Internal Server Error");       
            response.flushBuffer();
          }
        }
      } else {
        container.error("Internal error occurred.", e);
        response.sendError(SC_INTERNAL_SERVER_ERROR, "Internal Server Error");       
        response.flushBuffer();
      }
    } finally {
      try {
        container.end(request, response);       
      } finally {
        ExternalContext.end();       
      }
    }
   
    if (response.isCommitted()) return;
   
    if (result == null
        || result instanceof CharSequence
        || result instanceof Boolean
        || result instanceof Number
        || result instanceof Date) {
      if (status != SC_CREATED) status = SC_NO_CONTENT;
      response.setStatus(status);
    } else {
      response.setContentType((callback != null) ? "text/javascript" : "application/json");
      Writer writer = response.getWriter();
      json.setPrettyPrint(container.isDebugMode());
     
      if (callback != null) writer.append(callback).append("(");
      json.format(result, writer);
      if (callback != null) writer.append(");");
    }
  }
View Full Code Here

  public void init(ServletConfig servletConfig) throws ServletException {
    super.init(servletConfig);
   
    String configText = servletConfig.getInitParameter("config");
   
    JSON json = new JSON();
   
    if (configText == null) {
      Map<String, String> map = new HashMap<String, String>();
      Enumeration<String> e =  cast(servletConfig.getInitParameterNames());
      while (e.hasMoreElements()) {
        map.put(e.nextElement(), servletConfig.getInitParameter(e.nextElement()));
      }
      configText = json.format(map);
    }
   
    try {
      config = json.parse(configText, Config.class);
      if (config.container == null) config.container = Container.class;
      container = json.parse(configText, config.container);
      container.init(this);
    } catch (Exception e) {
      throw new ServletException(e);
    }
   
View Full Code Here

TOP

Related Classes of net.arnx.jsonic.JSON

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.