处理收到的JSON数据

@param session
@param bytes
184731
public void handle(final WebSocketSession session, byte[] bytes) {
        if (session == null) {
            throw new NullPointerException("session");
        }
        try {
            JsonRpcMessage msg = jsonRpcControl.receive(bytes);
            if (msg instanceof JsonRpcRequest) {
                handleRequest(session, (JsonRpcRequest) msg);
            } else if (msg instanceof JsonRpcResponse) {
                handleResponse(session, (JsonRpcResponse) msg);
            }
        } catch (Exception e) {
            config.getErrorProcessor().onError(session.getId(), e);
        }
    }
1138882
function (bytes) {
			for (var str = [], i = 0; i < bytes.length; i++)
				str.push(String.fromCharCode(bytes[i]));
			return str.join("");
		}
899311
@Override
	public byte[] serializeAttributes(final MemcachedBackupSession sessions, final ConcurrentMap<String, Object> attributes) {
		if (attributes == null) {
        	throw new NullPointerException();
        }

        final ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
        	// This performs a deep serialization of the target instance.
            // It's serialized to a string as flexjson doesn't like writing to
            // an OutputStreamWriter: it throws the exception "Stepping back two steps is not supported".
            // See https://github.com/moresandeep/memcached-session-manager/commit/db2faaa0a846e16d65ac0b14819689c67bf92c68#commitcomment-512505
        	final String serResult = serializer.deepSerialize(attributes);
        	if (LOG.isDebugEnabled()) {
        	    LOG.debug("JSON Serialised object: " + serResult);
        	}
        	return serResult.getBytes(); // converts to bytes
        } catch (final Exception e) {
        	LOG.warn("Caught Exception deserializing JSON " + e);
        	throw new IllegalArgumentException();
        } finally {
        	close(bos);
        }
	}
386098
function createSession (callback) {
      var path, sessionCreate;

      _log(me.setting);
      path = me.setting.apiroot + '/session/create.json?apiKey=' + me.setting.apikey;
      _log(path);

      sessionCreate = http.request({
        port: me.setting.port,
        host: me.setting.host,
        method: 'POST',
        path: path
      });

      sessionCreate.on('response', function (response) {
        var data = '';

        _log('STATUS: ' + response.statusCode);
        _log('HEADERS: ' + JSON.stringify(response.headers));

        if (200 !== response.statusCode) {
          callback(response.statusCode);
          return;
        }

        response.on('data', function (chunk) {
          data += chunk;
        });

        response.on('end', function() {
          var sessionInfo = JSON.parse(data);
          _log('SID OK: ' + sessionInfo.sid);

          callback(response.statusCode, sessionInfo);
        });
      });

      sessionCreate.on('error', function(err) {
        console.error(err);
      });

      sessionCreate.end();
    }
61028
@RequestMapping(value = "/userSession", method = RequestMethod.GET)
    @ResponseBody
    public JsonObject<?> session(HttpServletRequest request) {
        JsonObject<?> ret = JsonObject.create();
        String cookieValueUsername = CookieUtils.getCookieValue(request,
                UserWebConstant.CookieKey.USERNAME.getValue());
        String cookieValuePwd = CookieUtils.getCookieValue(request,
                UserWebConstant.CookieKey.PWDMD5.getValue());
        if (LoginValidator.isValid(cookieValueUsername, cookieValuePwd)) {
            LOG.info("Already logon with username=" + cookieValueUsername);
            ret.addData("id", UserWebConstant.USERMAP.get(cookieValueUsername).getUserId());
            ret.addData("name", cookieValueUsername);
            return ret;
        } else {
            ret.setStatus(GlobalResponseStatusMsg.NOT_LOGIN.getCode());
            ret.addStatusInfo(GlobalResponseStatusMsg.NOT_LOGIN.getMessage().getMessage());
        }

        return ret;
    }
1332623
public void doJson(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
        if (req.getParameter("jsonp") == null || permit(req)) {
            setHeaders(rsp);
            rsp.serveExposedBean(req,bean, req.getParameter("jsonp") == null ? Flavor.JSON : Flavor.JSONP);
        } else {
            rsp.sendError(HttpURLConnection.HTTP_FORBIDDEN, "jsonp forbidden; implement jenkins.security.SecureRequester");
        }
    }
210012
private byte[] entityToBytes(HttpEntity entity) throws IOException, ServerError {
		PoolingByteArrayOutputStream bytes = new PoolingByteArrayOutputStream(mPool, (int) entity.getContentLength());
		byte[] buffer = null;
		try {
			InputStream in = entity.getContent();
			if (in == null) {
				throw new ServerError();
			}
			buffer = mPool.getBuf(1024);
			int count;
			while ((count = in.read(buffer)) != -1) {
				bytes.write(buffer, 0, count);
			}
			return bytes.toByteArray();
		} finally {
			try {
				// Close the InputStream and release the resources by "consuming the content".
				entity.consumeContent();
			} catch (IOException e) {
				// This can happen if there was an exception above that left the entity in
				// an invalid state.
				VolleyLog.v("Error occured when calling consumingContent");
			}
			mPool.returnBuf(buffer);
			bytes.close();
		}
	}
1161579
@Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    JsonGenerator jg = null;
    String jsonpcb = null;
    PrintWriter writer = null;
    try {

      writer = response.getWriter();

      // "callback" parameter implies JSONP output
      jsonpcb = request.getParameter(CALLBACK_PARAM);
      if (jsonpcb != null) {
        response.setContentType("application/javascript; charset=utf8");
        writer.write(jsonpcb + "(");
      } else {
        response.setContentType("application/json; charset=utf8");
      }

      jg = jsonFactory.createJsonGenerator(writer);
      jg.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET);
      jg.useDefaultPrettyPrinter();

      int statusCode = renderMBeans(jg, request.getParameterValues("qry"));
      response.setStatus(statusCode);

    } catch (IOException e) {
      writeException(jg, e);
      response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (MalformedObjectNameException e) {
      writeException(jg, e);
      response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    } finally {
      if (jg != null) {
        jg.close();
      }
      if (jsonpcb != null) {
        writer.write(");");
      }
      if (writer != null) {
        writer.close();
      }
    }

  }
1041337
def post_json(session, url, json):
    
    res = session.post(url, json=json)
    if res.status_code >= 400:
        raise parse_error(res)
    return res
233330
public static Session loadFromHttpSession(Preset preset, HttpSession httpSession) {
		String mnoSessEntry = (String) httpSession.getAttribute(MAESTRANO_SESSION_ID);
		if (mnoSessEntry == null) {
			return new Session(preset);
		}
		Map<String, String> sessionObj;

		try {
			Gson gson = new Gson();
			String decryptedSession = new String(DatatypeConverter.parseBase64Binary(mnoSessEntry), "UTF-8");

			Type type = new TypeToken<Map<String, String>>() {
			}.getType();
			sessionObj = gson.fromJson(decryptedSession, type);
		} catch (Exception e) {
			logger.error("could not deserialized maestrano session: " + mnoSessEntry, e);
			throw new RuntimeException("could not deserialized maestrano session: " + mnoSessEntry, e);
		}

		// Assign attributes
		String uid = sessionObj.get("uid");
		String groupUid = sessionObj.get("group_uid");
		String sessionToken = sessionObj.get("session");
		Date recheck;
		// Session Recheck
		try {
			recheck = MnoDateHelper.fromIso8601(sessionObj.get("session_recheck"));
		} catch (Exception e) {
			recheck = new Date((new Date()).getTime() - 1 * 60 * 1000);
		}
		return new Session(preset, uid, groupUid, recheck, sessionToken);
	}
784941
public static byte[] readEntityBytes(InputStream in) {
		byte[] jsonEntity = null;
		try {
			if (in != null && in.available() > 0) {
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				byte[] buf = new byte[1024];
				int length;
				while ((length = in.read(buf)) > 0) {
					baos.write(buf, 0, length);
				}
				jsonEntity = baos.toByteArray();
			} else {
				jsonEntity = new byte[0];
			}
		} catch (IOException ex) {
			logger.error(null, ex);
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				logger.error(null, ex);
			}
		}
		return jsonEntity;
	}
109132
public void sendBinarySync(Session session, InputStream inputStream) throws IOException {
        if (session == null) {
            return;
        }

        if (inputStream == null) {
            throw new IllegalArgumentException("inputStream must not be null");
        }

        log.debugf("Attempting to send binary data to client [%s]", session.getId());

        if (session.isOpen()) {
            long size = new CopyStreamRunnable(session, inputStream).copyInputToOutput();
            log.debugf("Finished sending binary data to client [%s]: size=[%s]", session.getId(), size);
        }

        return;
    }
308051
private static void insertFromJson(CqlSession session) {

    JsonObject alice = Json.createObjectBuilder().add("name", "alice").add("age", 30).build();

    JsonObject bob = Json.createObjectBuilder().add("name", "bob").add("age", 35).build();

    JsonObject aliceScores =
        Json.createObjectBuilder().add("call_of_duty", 4.8).add("pokemon_go", 9.7).build();

    JsonObject bobScores =
        Json.createObjectBuilder().add("zelda", 8.3).add("pokemon_go", 12.4).build();

    // Build and execute a simple statement
    Statement stmt =
        insertInto("examples", "json_jsr353_function")
            .value("id", literal(1))
            // client-side, the JsonObject will be converted into a JSON String;
            // then, server-side, the fromJson() function will convert that JSON string
            // into an instance of the json_jsr353_function_user user-defined type (UDT),
            // which will be persisted into the column "user"
            .value(
                "user",
                function("fromJson", literal(alice, session.getContext().getCodecRegistry())))
            // same thing, but this time converting from
            // a JsonObject to a JSON string, then from this string to a map<varchar,float>
            .value(
                "scores",
                function("fromJson", literal(aliceScores, session.getContext().getCodecRegistry())))
            .build();
    session.execute(stmt);

    // The JSON object can be a bound value if the statement is prepared
    // (subsequent calls to the prepare() method will return cached statement)
    PreparedStatement pst =
        session.prepare(
            insertInto("examples", "json_jsr353_function")
                .value("id", bindMarker("id"))
                .value("user", function("fromJson", bindMarker("user")))
                .value("scores", function("fromJson", bindMarker("scores")))
                .build());
    session.execute(
        pst.bind()
            .setInt("id", 2)
            // note that the codec requires that the type passed to the set() method
            // be always JsonStructure, and not a subclass of it, such as JsonObject
            .set("user", bob, JsonStructure.class)
            .set("scores", bobScores, JsonStructure.class));
  }
588945
private byte[] serializeAppData(BackedSession d2) {
        if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
            LoggingUtil.SESSION_LOGGER_WAS.entering(methodClassName, methodNames[SERIALIZE_APP_DATA]);
        }
        // return either the byte array input stream for the app
        // data or a vector of byte array input streams if their is a
        // row for each piece of app data
        ByteArrayOutputStream baos = null;
        ObjectOutputStream oos = null;
        byte[] objbuf = null;

        try {
            Map<Object, Object> ht = null;
            if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
                LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[SERIALIZE_APP_DATA], "get swappableData and convert to byte array");
            }
            synchronized (d2) {
                ht = d2.getSwappableData();
            }

            // serialize session (app data only) into byte array buffer
            baos = new ByteArrayOutputStream();
            oos = createObjectOutputStream(baos);
            oos.writeObject(ht);
            oos.flush();
            objbuf = baos.toByteArray();
            if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
                LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[SERIALIZE_APP_DATA], "success - size of byte array is " + objbuf.length);
            }

            oos.close();
            baos.close();
        } catch (ConcurrentModificationException cme) {
            LoggingUtil.SESSION_LOGGER_WAS.logp(Level.INFO, methodClassName, methodNames[SERIALIZE_APP_DATA], "DatabaseHashMap.deferWrite", /* + d2.deferWriteUntilNextTick */
                                                d2.getId());
        } catch (Exception e) {
            com.ibm.ws.ffdc.FFDCFilter.processException(e, "com.ibm.ws.session.store.db.DatabaseHashMap.commonSetup", "2052", d2);
            LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[SERIALIZE_APP_DATA], "DatabaseHashMap.commonSetupError");
            LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[SERIALIZE_APP_DATA], "CommonMessage.exception", e);
        }
        if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINER)) {
            LoggingUtil.SESSION_LOGGER_WAS.exiting(methodClassName, methodNames[SERIALIZE_APP_DATA]);
        }
        return objbuf;
    }
1104835
@Override
    public void encode(IoSession session, Object message,
            ProtocolEncoderOutput out) throws Exception {
        out.write(message);
    }
945736
@Override
    protected final void unserialize(ByteBuffer bytes)
    {
        int indexDataLength = m_dataOffset_ + m_dataLength_;
        m_index_ = ICUBinary.getChars(bytes, indexDataLength, 0);
        m_data_           = m_index_;
        m_initialValue_   = m_data_[m_dataOffset_];
    }
752822
private Result sessionInfo() {

        Map<String, Object> dataEachSession = new HashMap<>();
        for (Map.Entry<String, StatsStorage> entry : knownSessionIDs.entrySet()) {
            String sid = entry.getKey();
            StatsStorage ss = entry.getValue();
            Map<String, Object> dataThisSession = sessionData(sid, ss);
            dataEachSession.put(sid, dataThisSession);
        }
        return Results.ok(asJson(dataEachSession)).as("application/json");
    }