List of usage examples for org.json JSONWriter JSONWriter
public JSONWriter(Writer w)
From source file:uk.ac.horizon.ug.mrcreator.http.CRUDServlet.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try {// w w w . java2 s. com // TODO move to static method and reuse logger.log(Level.INFO, "doGet(" + req.getPathInfo() + ")"); String pathParts[] = getPathParts(req); if (pathParts.length < discardPathParts) { throw new RequestException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Not enough part in path (" + pathParts.length + " vs " + discardPathParts + ") for " + req.getPathInfo()); } if (pathParts.length == discardPathParts) { // get all doList(req, resp); return; } // possible filtered query... String id = pathParts[discardPathParts]; Key key = idToKey(id); if (key == null) { throw new RequestException(HttpServletResponse.SC_NOT_FOUND, getObjectClass().getSimpleName() + " " + id + " could not map to key"); } if (pathParts.length > discardPathParts + 1) { String childScope = pathParts[discardPathParts + 1]; CRUDServlet childScopeServlet = getChildScopeServlet(id, childScope); childScopeServlet.doGet(req, resp); return; } EntityManager em = EMF.get().createEntityManager(); try { Class clazz = getObjectClass(); Object obj = em.find(clazz, key); if (obj == null) { throw new RequestException(HttpServletResponse.SC_NOT_FOUND, getObjectClass().getSimpleName() + " " + id + " not found"); } if (filterByCreator) { String creator = getCreator(obj); String requestCreator = getRequestCreator(req); if (!requestCreator.equals(creator)) throw new RequestException(HttpServletResponse.SC_UNAUTHORIZED, "Requestor is not creator of " + getObjectClass().getSimpleName() + " " + id); } resp.setCharacterEncoding(ENCODING); resp.setContentType(JSON_MIME_TYPE); Writer w = new OutputStreamWriter(resp.getOutputStream(), ENCODING); JSONWriter jw = new JSONWriter(w); writeObject(jw, obj); w.close(); } catch (RequestException re) { throw re; } catch (Exception e) { logger.log(Level.WARNING, "Getting object " + id + " of type " + getObjectClass(), e); throw new RequestException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); } finally { em.close(); } } catch (RequestException re) { resp.sendError(re.getErrorCode(), re.getMessage()); return; } }
From source file:uk.ac.horizon.ug.mrcreator.http.CRUDServlet.java
private void doList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { List results = null;//ww w .j a v a 2s . com EntityManager em = EMF.get().createEntityManager(); try { Class clazz = getObjectClass(); Query q = null; if (!filterByCreator) { if (listFilterPropertyName == null) { q = em.createQuery("SELECT x FROM " + clazz.getSimpleName() + " x"); } else { q = em.createQuery("SELECT x FROM " + clazz.getSimpleName() + " x WHERE x." + listFilterPropertyName + " = :" + listFilterPropertyName); q.setParameter(listFilterPropertyName, listFilterPropertyValue); } } else { // filter String creator = getRequestCreator(req); String prop = getCreatorPropertyName(); if (listFilterPropertyName == null) { q = em.createQuery( "SELECT x FROM " + clazz.getSimpleName() + " x WHERE x." + prop + " = :creator"); q.setParameter("creator", creator); } else { q = em.createQuery( "SELECT x FROM " + clazz.getSimpleName() + " x WHERE x." + listFilterPropertyName + " = :" + listFilterPropertyName + " AND x." + prop + " = :creator"); q.setParameter(listFilterPropertyName, listFilterPropertyValue); q.setParameter("creator", creator); } } // TODO order? results = q.getResultList(); // warning: lazy resp.setCharacterEncoding(ENCODING); resp.setContentType(JSON_MIME_TYPE); Writer w = new OutputStreamWriter(resp.getOutputStream(), ENCODING); JSONWriter jw = new JSONWriter(w); jw.array(); for (Object o : results) { listObject(jw, o); } jw.endArray(); w.close(); } catch (Exception e) { logger.log(Level.WARNING, "Getting object of type " + getObjectClass(), e); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); return; } finally { em.close(); } }
From source file:uk.ac.horizon.ug.mrcreator.http.CRUDServlet.java
/** Create on POST. * E.g. curl -d '{...}' http://localhost:8888/author/configuration/ * @param req/*from w w w . j a v a 2 s.c o m*/ * @param resp * @throws ServletException * @throws IOException */ private void doCreate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub try { Object o = parseObject(req); if (filterByCreator) { String creator = getRequestCreator(req); setCreator(o, creator); } Key key = validateCreate(o); // try adding EntityManager em = EMF.get().createEntityManager(); EntityTransaction et = em.getTransaction(); try { et.begin(); if (em.find(getObjectClass(), key) != null) throw new RequestException(HttpServletResponse.SC_CONFLICT, "object already exists (" + key + ")"); em.persist(o); et.commit(); logger.info("Added " + o); } finally { if (et.isActive()) et.rollback(); em.close(); } resp.setCharacterEncoding(ENCODING); resp.setContentType(JSON_MIME_TYPE); Writer w = new OutputStreamWriter(resp.getOutputStream(), ENCODING); JSONWriter jw = new JSONWriter(w); listObject(jw, o); w.close(); } catch (RequestException e) { resp.sendError(e.getErrorCode(), e.getMessage()); } catch (Exception e) { logger.log(Level.WARNING, "Getting object of type " + getObjectClass(), e); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); return; } }
From source file:uk.ac.horizon.ug.mrcreator.http.CRUDServlet.java
@Override protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub //logger.log(Level.INFO, "doPost("+req.getContextPath()+")"); try {/* w w w . ja v a 2s .c o m*/ // get ID logger.log(Level.INFO, "doPut(" + req.getPathInfo() + ")"); String pathParts[] = getPathParts(req); if (pathParts.length < discardPathParts) { throw new RequestException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Not enough part in path (" + pathParts.length + " vs " + discardPathParts + ") for " + req.getPathInfo()); } if (pathParts.length == discardPathParts) { throw new RequestException(HttpServletResponse.SC_BAD_REQUEST, "Cannot PUT to collection " + req.getPathInfo()); } // possible filtered query... String id = pathParts[discardPathParts]; Key key = idToKey(id); if (key == null) { throw new RequestException(HttpServletResponse.SC_NOT_FOUND, getObjectClass().getSimpleName() + " " + id + " could not map to key"); } if (pathParts.length > discardPathParts + 1) { String childScope = pathParts[discardPathParts + 1]; CRUDServlet childScopeServlet = getChildScopeServlet(id, childScope); childScopeServlet.doPut(req, resp); return; } // parse new value Object newobj = parseObject(req); EntityManager em = EMF.get().createEntityManager(); try { // check that object exists Class clazz = getObjectClass(); Object obj = em.find(clazz, key); if (obj == null) { throw new RequestException(HttpServletResponse.SC_NOT_FOUND, getObjectClass().getSimpleName() + " " + id + " not found"); } // check (if required) that object is owned by requestor if (filterByCreator) { String creator = getCreator(obj); String requestCreator = getRequestCreator(req); if (!requestCreator.equals(creator)) throw new RequestException(HttpServletResponse.SC_UNAUTHORIZED, "Requestor is not creator of " + getObjectClass().getSimpleName() + " " + id); // set creator setCreator(newobj, creator); } // validate update validateUpdate(newobj, obj); // perform update em.merge(newobj); resp.setCharacterEncoding(ENCODING); resp.setContentType(JSON_MIME_TYPE); Writer w = new OutputStreamWriter(resp.getOutputStream(), ENCODING); JSONWriter jw = new JSONWriter(w); writeObject(jw, newobj); w.close(); } catch (RequestException re) { throw re; } catch (Exception e) { logger.log(Level.WARNING, "Updating object " + id + " of type " + getObjectClass(), e); throw new RequestException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); } finally { em.close(); } } catch (RequestException re) { resp.sendError(re.getErrorCode(), re.getMessage()); return; } }
From source file:uk.ac.horizon.ug.mrcreator.http.CRUDServlet.java
@Override protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try {/* w w w . ja va2 s . c o m*/ // get ID logger.log(Level.INFO, "doDelete(" + req.getPathInfo() + ")"); String pathParts[] = getPathParts(req); if (pathParts.length < discardPathParts) { throw new RequestException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Not enough part in path (" + pathParts.length + " vs " + discardPathParts + ") for " + req.getPathInfo()); } if (pathParts.length == discardPathParts) { throw new RequestException(HttpServletResponse.SC_BAD_REQUEST, "Cannot PUT to collection " + req.getPathInfo()); } // possible filtered query... String id = pathParts[discardPathParts]; Key key = idToKey(id); if (key == null) { throw new RequestException(HttpServletResponse.SC_NOT_FOUND, getObjectClass().getSimpleName() + " " + id + " could not map to key"); } if (pathParts.length > discardPathParts + 1) { String childScope = pathParts[discardPathParts + 1]; CRUDServlet childScopeServlet = getChildScopeServlet(id, childScope); childScopeServlet.doDelete(req, resp); return; } EntityManager em = EMF.get().createEntityManager(); try { // check that object exists Class clazz = getObjectClass(); Object obj = em.find(clazz, key); if (obj == null) { throw new RequestException(HttpServletResponse.SC_NOT_FOUND, getObjectClass().getSimpleName() + " " + id + " not found"); } // check (if required) that object is owned by requestor if (filterByCreator) { String creator = getCreator(obj); String requestCreator = getRequestCreator(req); if (!requestCreator.equals(creator)) throw new RequestException(HttpServletResponse.SC_UNAUTHORIZED, "Requestor is not creator of " + getObjectClass().getSimpleName() + " " + id); } // validate delete validateDelete(obj); // perform update em.remove(obj); // write back old value? resp.setCharacterEncoding(ENCODING); resp.setContentType(JSON_MIME_TYPE); Writer w = new OutputStreamWriter(resp.getOutputStream(), ENCODING); JSONWriter jw = new JSONWriter(w); writeObject(jw, obj); w.close(); } catch (RequestException re) { throw re; } catch (Exception e) { logger.log(Level.WARNING, "Deleting object " + id + " of type " + getObjectClass(), e); throw new RequestException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); } finally { em.close(); } } catch (RequestException re) { resp.sendError(re.getErrorCode(), re.getMessage()); return; } }
From source file:com.kise.kairosdb.core.groupby.FiscalCalendarGroubBy.java
@Override public GroupByResult getGroupByResult(int id) { return new GroupByResult() { @Override/* w ww . j a va 2 s.c o m*/ public String toJson() throws FormatterException { StringWriter stringWriter = new StringWriter(); try { JSONWriter writer = new JSONWriter(stringWriter); FiscalPeriod p = periods.get(id); writer.object(); writer.key("name").value("fiscal_period"); writer.key("group").object(); writer.key("name").value("FY" + p.getFiscalYear() + "-P" + p.getFiscalPeriod()); writer.key("fiscal_year").value(p.getFiscalYear()); writer.key("quarter").value("Q" + p.getQuarter()); writer.key("fiscal_period").value(p.getFiscalPeriod()); writer.endObject(); writer.endObject(); } catch (JSONException e) { throw new FormatterException(e); } return stringWriter.toString(); } }; }
From source file:com.vaynberg.wicket.select2.AbstractSelect2Choice.java
@Override public void onResourceRequested() { // this is the callback that retrieves matching choices used to populate the dropdown Request request = getRequestCycle().getRequest(); IRequestParameters params = request.getRequestParameters(); // retrieve choices matching the search term String term = params.getParameterValue("term").toOptionalString(); int page = params.getParameterValue("page").toInt(1); // select2 uses 1-based paging, but in wicket world we are used to // 0-based//from www .j a v a 2s. c o m page -= 1; Response<T> response = new Response<T>(); provider.query(term, page, response); // jsonize and write out the choices to the response WebResponse webResponse = (WebResponse) getRequestCycle().getResponse(); webResponse.setContentType("application/json"); OutputStreamWriter out = new OutputStreamWriter(webResponse.getOutputStream(), getRequest().getCharset()); JSONWriter json = new JSONWriter(out); try { json.object(); json.key("results").array(); for (T item : response) { json.object(); provider.toJson(item, json); json.endObject(); } json.endArray(); json.key("more").value(response.getHasMore()).endObject(); } catch (JSONException e) { throw new RuntimeException("Could not write Json response", e); } try { out.flush(); } catch (IOException e) { throw new RuntimeException("Could not write Json to servlet response", e); } }