/** * Serializes the given object and wraps it in a callback function * i.e. <callback>(<json>) * Note: This will not append a trailing semicolon * @param callback The name of the Javascript callback to prepend * @param object The object to serialize * @return A JSONP formatted string * @throws IllegalArgumentException if the callback method name was missing * or object was null * @throws JSONException if the object could not be serialized */ public static final String serializeToJSONPString(final String callback, final Object object) { if (callback == null || callback.isEmpty()) throw new IllegalArgumentException("Missing callback name"); if (object == null) throw new IllegalArgumentException("Object was null"); try { return jsonMapper.writeValueAsString(new JSONPObject(callback, object)); } catch (JsonProcessingException e) { throw new JSONException(e); } }
/** * This method takes an object and creates a <code>Response</code> object * out of it which will be returned. If <code>messages</code> contains error * messages they will be send back instead. * The format of the <code>Response</code> * depends on the <code>responseType</code>. * Supported types are <code>application/xml</code> and <code>application/json</code> * * @param respondData an object which will be returned as a * <code>Response</code> object * @param messages a list of <code>Message</code> objects which contain * error messages of the API request * @param callback if set and responseType is json the result will be returned * via this javascript callback function (optional) * @return a <code>Response</code> object containing the <code>responseData</code> * in the format defined with <code>responseType</code> */ private Response formatResponse(Object respondData, List<Message> messages, String serviceName, String callback) { //handle error messages if existing if (messages.size() > 0) { throw new EasyRecException(messages, serviceName, WS.RESPONSE_TYPE_JSON, callback); } if (respondData instanceof List) { respondData = new ResponseSuccessMessage(serviceName, (List<SuccessMessage>) respondData); } //convert respondData to Respond object if (callback != null) { return Response.ok(new JSONPObject(callback, respondData), WS.RESPONSE_TYPE_JSCRIPT).build(); } else { return Response.ok(respondData, WS.RESPONSE_TYPE_JSON).build(); } }
@RequestMapping(value = "/search", method = RequestMethod.GET, produces = "application/javascript") public ResponseEntity<JSONPObject> searchAPIJSONP( @RequestParam(value = "query", required = false) String query, @RequestParam(value = "limit", required = false, defaultValue = "24") Integer limit, @RequestParam(value = "start", required = false, defaultValue = "0") Integer start, @RequestParam(value = "facet", required = false) @FacetRequestFormat List<FacetRequest> facets, @RequestParam(value = "x1", required = false) Double x1, @RequestParam(value = "y1", required = false) Double y1, @RequestParam(value = "x2", required = false) Double x2, @RequestParam(value = "y2", required = false) Double y2, @RequestParam(value = "sort", required = false) String sort, @RequestParam(value = "callback", required = true) String callback, Model model) throws SolrServerException { spatial(query,x1, y1, x2, y2, null, limit,start,facets,sort,null,model); return new ResponseEntity<JSONPObject>(new JSONPObject(callback,(Page) model.asMap().get("result")),HttpStatus.OK); }
/** * 按应用获取未读消息对象 */ @RequestMapping("/unread/{userId}") @ResponseBody public JSONPObject unread(@PathVariable("userId") String userId, @RequestParam(value = "jsonp") String function) { Map<String, Object> result = new LinkedHashMap<>(); int totalUnread = getTotalUnread(userId); result.put("totalUnread", totalUnread); if (totalUnread > 0) { History example = new History(); example.userId = userId; example.unread = true; example.ack = false; example.limit = totalUnread; History history = timelineService.find(example); result.put("messages", history.messages); } return new JSONPObject(function, result); }
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("application/json"); if (servletPlugin.getMetricsServletAllowedOrigin() != null) { resp.setHeader("Access-Control-Allow-Origin", servletPlugin.getMetricsServletAllowedOrigin()); } resp.setHeader("Cache-Control", "must-revalidate,no-cache,no-store"); resp.setStatus(HttpServletResponse.SC_OK); final OutputStream output = resp.getOutputStream(); try { String jsonpParamName = servletPlugin.getMetricsServletJsonpParamName(); if (jsonpParamName != null && req.getParameter(jsonpParamName) != null) { getWriter(req).writeValue(output, new JSONPObject(req.getParameter(jsonpParamName), registry)); } else { getWriter(req).writeValue(output, registry); } } finally { output.close(); } }
/** * TODO: replace JSONWithPadding to JSONPObject */ @GET @Path("search") @Produces(MediaType.APPLICATION_JSON) public JSONPObject getPartyEntitiesByType( @QueryParam("callback") String callback, @QueryParam("typeId") long typeId, @QueryParam("q") String q) { String hql = "from PartyEntity where partyType.id=? and name like ? order by name"; Page page = partyEntityManager.pagedQuery(hql, 1, DFAULT_PAGE_SIZE, typeId, q.replace("_", "\\_") + "%"); List<PartyEntity> partyEntities = (List<PartyEntity>) page.getResult(); List<PartyEntityDTO> partyEntityDtos = new ArrayList<PartyEntityDTO>(); for (PartyEntity partyEntity : partyEntities) { PartyEntityDTO partyEntityDto = new PartyEntityDTO(); partyEntityDto.setId(partyEntity.getId()); partyEntityDto.setName(partyEntity.getName()); partyEntityDtos.add(partyEntityDto); } return new JSONPObject(callback, partyEntityDtos); }
@RequestMapping(value = "/jsonpInfo", method = {RequestMethod.GET}) @ResponseBody public Object jsonpInfo(String callback, String userId) throws IOException { UUser user = userFService.getUserById(userId); JSONPObject jsonpObject = new JSONPObject(callback, user); return jsonpObject; }
/** * Serializes the given object and wraps it in a callback function * i.e. <callback>(<json>) * Note: This will not append a trailing semicolon * @param callback The name of the Javascript callback to prepend * @param object The object to serialize * @return A JSONP formatted byte array * @throws IllegalArgumentException if the callback method name was missing * or object was null * @throws JSONException if the object could not be serialized * @throws IOException Thrown when there was an issue reading the object */ public static final byte[] serializeToJSONPBytes(final String callback, final Object object) { if (callback == null || callback.isEmpty()) throw new IllegalArgumentException("Missing callback name"); if (object == null) throw new IllegalArgumentException("Object was null"); try { return jsonMapper.writeValueAsBytes(new JSONPObject(callback, object)); } catch (JsonProcessingException e) { throw new JSONException(e); } }
@RequestMapping(value = "/jsonpInfo",method = { RequestMethod.GET }) @ResponseBody public Object jsonpInfo(String callback,Integer userId) throws IOException { User user = userService.getUserById(userId); JSONPObject jsonpObject = new JSONPObject(callback,user) ; return jsonpObject ; }
public EasyRecException(List<Message> messages, String action, String type, String callback) { //GenericEntity<List<Message>> entity = new GenericEntity<List<Message>>(messages) {}; super(callback != null ? Response.ok(new JSONPObject(callback, messagesToArray(messages)), WS.RESPONSE_TYPE_JSCRIPT).build() : Response.ok(messagesToArray(messages), type).build()); }
/** * This method takes an object and creates a <code>Response</code> object * out of it which will be returned. If <code>messages</code> contains error * messages they will be send back instead. * The format of the <code>Response</code> * depends on the <code>responseType</code>. * Supported types are <code>application/xml</code> and <code>application/json</code> * * @param respondData an object which will be returned as a * <code>Response</code> object * @param messages a list of <code>Message</code> objects which contain * error messages of the API request * @param responseType defines the format of the <code>Response</code> object * @param callback if set and responseType is json the result will be returned * via this javascript callback function (optional) * @return a <code>Response</code> object containing the <code>responseData</code> * in the format defined with <code>responseType</code> */ private Response formatResponse(Object respondData, List<Message> messages, String serviceName, String responseType, String callback) { //handle error messages if existing if (messages.size() > 0) { if ((WS.RESPONSE_TYPE_PATH_JSON.equals(responseType))) throw new EasyRecException(messages, serviceName, WS.RESPONSE_TYPE_JSON, callback); else throw new EasyRecException(messages, serviceName); } if (respondData instanceof List) { respondData = new ResponseSuccessMessage(serviceName, (List<SuccessMessage>) respondData); } //convert respondData to Respond object if (WS.RESPONSE_TYPE_PATH_JSON.equals(responseType)) { if (callback != null) { return Response.ok(new JSONPObject(callback, respondData), WS.RESPONSE_TYPE_JSCRIPT).build(); } else { return Response.ok(respondData, WS.RESPONSE_TYPE_JSON).build(); } } else if (WS.RESPONSE_TYPE_PATH_XML.equals(responseType)) { return Response.ok(respondData, WS.RESPONSE_TYPE_XML).build(); } else { return Response.status(Response.Status.UNSUPPORTED_MEDIA_TYPE).build(); } }
/** * This method takes an object and creates a <code>Response</code> object * out of it which will be returned. If <code>messages</code> contains error * messages they will be send back instead. * The format of the <code>Response</code> * depends on the <code>responseType</code>. * Supported types are <code>application/xml</code> and <code>application/json</code> * * @param respondData an object which will be returned as a * <code>Response</code> object * @param messages a list of <code>Message</code> objects which contain * error messages of the API request * @param responseType defines the format of the <code>Response</code> object * @param callback if set and responseType is jason the result will be returned * via this javascript callback function (optional) * @return a <code>Response</code> object containing the <code>responseData</code> * in the format defined with <code>responseType</code> */ private Response formatResponse(Object respondData, List<Message> messages, String serviceName, String responseType, String callback) { //handle error messages if existing if (messages.size() > 0) { if (responseType.endsWith(WS.RESPONSE_TYPE_PATH_JSON)) throw new EasyRecException(messages, serviceName, WS.RESPONSE_TYPE_JSON, callback); else throw new EasyRecException(messages, serviceName); } if (respondData instanceof List) { respondData = new ResponseSuccessMessage(serviceName, (List<SuccessMessage>) respondData); } //convert respondData to Respond object if (responseType.endsWith(WS.RESPONSE_TYPE_PATH_JSON)) { if (callback != null) { return Response.ok(new JSONPObject(callback, respondData), WS.RESPONSE_TYPE_JSCRIPT).build(); } else { return Response.ok(respondData, WS.RESPONSE_TYPE_JSON).build(); } } else if (WS.XML_PATH.equals(responseType)) { return Response.ok(respondData, WS.RESPONSE_TYPE_XML).build(); } else { return Response.status(Response.Status.UNSUPPORTED_MEDIA_TYPE).build(); } }
@Override public void toJsonP( OutputStream output, Object value, String callback ) throws IOException { if ( StringUtils.isEmpty( callback ) ) { callback = "callback"; } jsonMapper.writeValue( output, new JSONPObject( callback, value ) ); }
/** * @param identifier * Set the identifier of the image * @return A model and view containing a image */ @RequestMapping(value = "/{identifier}", params = "callback", method = RequestMethod.GET, produces = "application/javascript") public ResponseEntity<JSONPObject> getJsonP(@PathVariable String identifier, @RequestParam(value = "fetch", required = false) String fetch, @RequestParam(value = "callback", required = true) String callback) { return new ResponseEntity<JSONPObject>(new JSONPObject(callback,service.find(identifier,fetch)), HttpStatus.OK); }
@RequestMapping(value = "/{identifier}", params = "callback", method = RequestMethod.GET, produces = "application/javascript") public ResponseEntity<JSONPObject> getJsonP(@PathVariable String identifier, @RequestParam(value = "fetch", required = false) String fetch, @RequestParam(value = "callback", required = true) String callback) { return new ResponseEntity<JSONPObject>(new JSONPObject(callback,service.find(identifier,fetch)), HttpStatus.OK); }
@Override protected void exceptionResponse(HttpServletRequest request, HttpServletResponse response, APIException e) throws IOException { ErrorBean bean = new ErrorBean(e); String jsonpCallback = request.getParameter("jsonpCallback"); final ObjectMapper objectMapper = new ObjectMapper(); response.setContentType("application/json"); if (StringUtils.isBlank(jsonpCallback)) { objectMapper.writeValue(response.getOutputStream(), bean); } else { JSONPObject jsonp = new JSONPObject(jsonpCallback, bean); objectMapper.writeValue(response.getOutputStream(), jsonp); } }
@ExceptionHandler(value = APIException.class) public @ResponseBody JSONPObject handleException(APIException ex, HttpServletRequest request) { String jsonpCallback = request.getParameter("jsonpCallback"); if (StringUtils.isBlank(jsonpCallback)) { jsonpCallback = "jsonpCallback"; } return asCallback(jsonpCallback, new ErrorBean(ex)); }
@RequestMapping("/action/new") public @ResponseBody JSONPObject registerAction(HttpSession session, @RequestParam("user") String userId, @RequestParam("item") String itemId, @RequestParam("type") Integer type, @RequestParam("jsonpCallback") String callback, @RequestParam(value = "source", required = false) String referrer, @RequestParam(value = "rectag", required = false) String recTag, @RequestParam(value = "pos", required = false) Integer pos, @RequestParam(value = "rlabs", required = false) String rlabs, @RequestParam(value = "extra_data", required = false) String extraData, @RequestParam(value = "click_only", required = false) Boolean click_only, @RequestParam(value = "zehtg", required = false) String req) { final ConsumerBean consumerBean = retrieveConsumer(session); MDCKeys.addKeys(consumerBean, userId, itemId,recTag); //added zehtg parameter as additional option for rlabs if(StringUtils.isNotBlank(req)) { rlabs=req; } if (logger.isDebugEnabled()) logger.debug("Creating action for consumer: " + consumerBean.getShort_name()); ActionBean actionBean = createAction(userId, itemId, type, referrer,recTag,extraData); boolean isCTR = StringUtils.isNotBlank(rlabs); boolean clickOnly = (isCTR && (click_only != null) && (click_only == true)) ? true : false; int clickPos = -1; if (pos != null) clickPos = pos.intValue(); return asCallback(callback, actionBusinessService.addAction(consumerBean, actionBean, isCTR, rlabs,recTag,clickPos, clickOnly)); }
@RequestMapping("/user/new") public @ResponseBody JSONPObject registerUser(HttpSession session, @RequestParam("user") String userId, @RequestParam(value = "username", required = false) String username, @RequestParam("jsonpCallback") String callback) { username = (username != null) ? username : userId; final ConsumerBean consumerBean = retrieveConsumer(session); UserBean user = new UserBean(userId, username); user.setType(1); logger.debug("Creating user: " + userId + " for consumer: " + consumerBean.getShort_name()); ResourceBean responseBean = userBusinessService.updateUser((ConsumerBean) consumerBean, user, null, false, false); return asCallback(callback, responseBean); }
@RequestMapping("/user/profile") public @ResponseBody JSONPObject userProfile(HttpSession session, @RequestParam("user") String userId, @RequestParam(value = "models", required = false) String models, @RequestParam("jsonpCallback") String callback) { final ConsumerBean consumerBean = retrieveConsumer(session); if (logger.isDebugEnabled()) logger.debug("get user profile: " + userId + " for consumer: " + consumerBean.getShort_name()); ResourceBean responseBean = userProfileService.getProfile(consumerBean, userId, models); return asCallback(callback, responseBean); }
@RequestMapping("/event/new") public @ResponseBody JSONPObject registerEvent(HttpSession session, HttpServletRequest request, @RequestParam("jsonpCallback") String callback) { final ConsumerBean consumerBean = retrieveConsumer(session); @SuppressWarnings("unchecked") Map<String,String[]> parameters = request.getParameterMap(); return asCallback(callback, predictionBusinessService.addEvent(consumerBean, parameters)); }
@RequestMapping("/predict") public @ResponseBody JSONPObject predict(HttpSession session, HttpServletRequest request, @RequestParam(value = "json", required = false) String json, @RequestParam("jsonpCallback") String callback) { final ConsumerBean consumerBean = retrieveConsumer(session); @SuppressWarnings("unchecked") Map<String,String[]> parameters = request.getParameterMap(); return asCallback(callback, predictionBusinessService.predict(consumerBean, parameters)); }
@Override public void toJsonP( OutputStream output, Object value, Class<?> klass, String callback ) throws IOException { if ( StringUtils.isEmpty( callback ) ) { callback = "callback"; } jsonMapper.writerWithView( klass ).writeValue( output, new JSONPObject( callback, value ) ); }
@Override public String toJSONPString( String callbackFunctionName, Object object ) { try { return mapper.writeValueAsString( new JSONPObject( callbackFunctionName, object ) ); } catch( JsonProcessingException ex ) { throw new JsonPluginException( ex ); } }
@Override public String toJSONPString( String callbackFunctionName, Object object, Class<?> jsonView ) { try { return mapper.writeValueAsString( new JSONPObject( callbackFunctionName, toNode( object, jsonView ) ) ); } catch( JsonProcessingException ex ) { throw new JsonPluginException( ex ); } }
/** * 标记未读为已读 */ @RequestMapping("/ack/{userId}") @ResponseBody public JSONPObject ack(@PathVariable("userId") String userId, @RequestParam(value = "jsonp") String function) { // timelineService.ackAll(userId,System.currentTimeMillis()); Map map = ArrayUtils.toMap(new Object[][]{ {"successful", true} }); return new JSONPObject(function, map); }
/** * 輸出JSONP格式數據. */ public String toJsonP(String functionName, Object object) { return toJson(new JSONPObject(functionName, object)); }
public String toJsonP(String functionName, Object object) throws IOException { return toJson(new JSONPObject(functionName, object)); }
/** * 输出JSONP格式数据. */ public String toJsonP(String functionName, Object object) { return toJson(new JSONPObject(functionName, object)); }
@RequestMapping(value = "/jsonp") @ResponseBody public JSONPObject getJsonp(ModelMap map, @RequestParam String callback) { map.put("pi", "hello,I'm Fjt"); return new JSONPObject(callback, map); }