Example usage for org.json JSONObject write

List of usage examples for org.json JSONObject write

Introduction

In this page you can find the example usage for org.json JSONObject write.

Prototype

public Writer write(Writer writer) throws JSONException 

Source Link

Document

Write the contents of the JSONObject as JSON text to a writer.

Usage

From source file:kr.ac.cau.mecs.cass.servletcontextlistener.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    onServletInit(request, response);/*from www.  ja v a2  s .  c om*/

    response.setContentType("application/json; charset=UTF-8");
    response.setCharacterEncoding("UTF-8");
    request.setCharacterEncoding("UTF-8");

    PrintWriter out = response.getWriter();
    JSONObject jobj = new JSONObject();

    Transaction tx = null;
    Session hsession = HibernateSessionFactory.getSessionFactory().getCurrentSession();

    try {
        tx = hsession.beginTransaction();

        jobj = processGet(hsession, request, response);

        tx.commit();
    } catch (Exception e) {
        jobj.putOpt("error", 1);
        jobj.putOpt("reason", "server transaction error");
        jobj.putOpt("msg", e.getMessage());
        e.printStackTrace();
        if (tx != null && tx.isActive()) {
            try {
                tx.rollback();
            } catch (HibernateException e1) {
                e1.printStackTrace();
            }
        }
    }

    jobj.write(out);
    out.close();

}

From source file:kr.ac.cau.mecs.cass.servletcontextlistener.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    onServletInit(request, response);//from  w ww  . j  av  a 2 s  .c  o  m

    response.setContentType("application/json; charset=UTF-8");
    response.setCharacterEncoding("UTF-8");
    request.setCharacterEncoding("UTF-8");

    PrintWriter out = response.getWriter();
    JSONObject jobj = new JSONObject();

    Transaction tx = null;
    Session hsession = HibernateSessionFactory.getSessionFactory().getCurrentSession();

    try {
        tx = hsession.beginTransaction();

        jobj = processPost(hsession, request, response);

        tx.commit();
    } catch (Exception e) {
        jobj.putOpt("error", 1);
        jobj.putOpt("reason", "server transaction error");
        jobj.putOpt("msg", e.getMessage());

        e.printStackTrace();
        if (tx != null && tx.isActive()) {
            try {
                tx.rollback();
            } catch (HibernateException e1) {
                e1.printStackTrace();
            }
        }
    }

    jobj.write(out);
    out.close();
}

From source file:JSON.GenererJSONSave.java

/**
 * Methode pour sauvegarder le plateau d'un jeu
 * @param p // w ww.j  a va  2  s . c  o  m
 */
public void Save(Plateau p) {
    ArrayList<Sauvegarde> Liste = new ArrayList();
    int k = 0;
    for (int i = 0; i < p.getAbsci(); i++) {
        for (int j = 0; j < p.getOrdonne(); j++) {
            if (p.grille[i][j] != null)
                Liste.add(new Sauvegarde(i, j, p.grille[i][j].nom));

        }
    }
    JSONObject objet = new JSONObject();
    JSONArray jsArray = new JSONArray(Liste);
    objet.put("coordonne", jsArray);
    // Cration du fichier de sortie
    FileWriter fs = null;
    try {
        fs = new FileWriter("C:\\Users\\Alphonse\\Desktop\\output2.txt");
    } catch (IOException e) {
        System.err.println("Erreur lors de l'ouverture du fichier ");
        System.err.println(e);
        System.exit(-1);
    }

    // Sauvegarde dans le fichier
    try {
        objet.write(fs);
        fs.flush();
    } catch (IOException e) {
        System.err.println("Erreur lors de l'criture dans le fichier : " + e);
        System.exit(-1);
    }
}

From source file:com.ahanda.techops.noty.clientTest.ClientHandler.java

public void login(Channel ch, JSONObject credential) {
    StringWriter estr = new StringWriter();
    credential.write(estr);
    String contentStr = estr.toString();
    FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/login",
            ch.alloc().buffer().writeBytes(contentStr.getBytes()));

    request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
    request.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/json");
    if (sessCookies != null)
        request.headers().set(HttpHeaders.Names.COOKIE, ClientCookieEncoder.encode(sessCookies));

    request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, request.content().readableBytes());

    l.info("login request {}", request);

    // Send the HTTP request.
    ch.writeAndFlush(request);//from w w w. ja  va  2s.  c o m
}

From source file:io.github.grahambell.taco.TacoTransport.java

/**
 * Write a message to the output stream.
 *
 * @param message the message to be written
 * @throws TacoException on error converting the message to JSON or
 *     writing it to the output stream// w  w  w  . j  ava 2s . c o  m
 */
public void write(Map<String, Object> message) throws TacoException {
    try {
        JSONObject json = mapToJson(message);
        json.write(out);
        out.write("\n// END\n");
        out.flush();
    } catch (JSONException e) {
        throw new TacoException("json write error: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new TacoException("i/o write error: " + e.getMessage(), e);
    }
}

From source file:JSON.JasonJSON.java

public static void main(String[] args) throws Exception {

    URL Url = new URL("http://api.wunderground.com/api/22b4347c464f868e/conditions/q/Colorado/COS.json");
    //This next URL is still being played with. Some of the formatting is hard to figure out, but Wunderground 
    //writes a perfectly formatted JSON file that is easy to read with Java.
    // URL Url = new URL("https://api.darksky.net/forecast/08959bb1e2c7eae0f3d1fafb5d538032/38.886,-104.7201");

    try {//from   www  .  j av a  2s.  co  m

        HttpURLConnection urlCon = (HttpURLConnection) Url.openConnection();

        //          This part will read the data returned thru HTTP and load it into memory
        //          I have this code left over from my CIT260 project.
        InputStream stream = urlCon.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
        StringBuilder result = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            result.append(line);
        }

        // The next lines read certain parts of the JSON data and print it out on the screen
        //Creates the JSONObject object and loads the JSON file from the URLConnection
        //Into a StringWriter object. I am printing this out in raw format just so I can see it doing something

        JSONObject json = new JSONObject(result.toString());

        JSONObject coloradoInfo = (JSONObject) json.get("current_observation");

        StringWriter out = new StringWriter();
        json.write(out);
        String jsonTxt = json.toString();
        System.out.print(jsonTxt);

        List<String> list = new ArrayList<>();
        JSONArray array = json.getJSONArray(jsonTxt);
        System.out.print(jsonTxt);

        // for (int i =0;i<array.length();i++){
        //list.add(array.getJSONObject(i).getString("current_observation"));
        //}

        String wunderGround = "Data downloaded from: " +

                coloradoInfo.getJSONObject("image").getString("title") + "\nLink\t\t: "
                + coloradoInfo.getJSONObject("image").getString("link") + "\nCity\t\t: "
                + coloradoInfo.getJSONObject("display_location").getString("city") + "\nState\t\t: "
                + coloradoInfo.getJSONObject("display_location").getString("state_name") + "\nTime\t\t: "
                + coloradoInfo.get("observation_time_rfc822") + "\nTemperature\t\t: "
                + coloradoInfo.get("temperature_string") + "\nWindchill\t\t: "
                + coloradoInfo.get("windchill_string") + "\nRelative Humidity\t: "
                + coloradoInfo.get("relative_humidity") + "\nWind\t\t\t: " + coloradoInfo.get("wind_string")
                + "\nWind Direction\t\t: " + coloradoInfo.get("wind_dir") + "\nBarometer Pressure\t\t: "
                + coloradoInfo.get("pressure_in");

        System.out.println("\nColorado Springs Weather:");
        System.out.println("____________________________________");
        System.out.println(wunderGround);

    } catch (IOException e) {
        System.out.println("***ERROR*******************ERROR********************. " + "\nURL: " + Url.toString()
                + "\nERROR: " + e.toString());
    }

}

From source file:org.hydracache.client.partition.PartitionAwareClientTest.java

@Test
public void ensureStorageInfoCanBeRetrieved() throws Exception {
    client = new PartitionAwareClient(Arrays.asList(new Identity(8080)), mockTransport, poller);

    ResponseMessage responseMsg = new ResponseMessage(true);
    JSONObject output = new JSONObject();
    output.put("testField", "100");
    StringWriter writer = new StringWriter();
    output.write(writer);
    responseMsg.setResponseBody(writer.toString().getBytes());

    when(messenger.sendMessage(any(Identity.class), any(SubstancePartition.class), any(RequestMessage.class)))
            .thenReturn(responseMsg);/*from  www. j a v a  2s  . co  m*/

    client.setMessager(messenger);

    Map<String, String> info = client.getStorageInfo();

    assertEquals("Test field value is incorrect", "100", info.get("testField"));
}

From source file:com.ibm.iot.auto.bluemix.samples.ui.Connection.java

private HttpURLConnection createHttpURLPostConnection(String urlTail, JSONObject parameters)
        throws IOException, JSONException {
    URL url = new URL(apiBaseUrl + urlTail + "?tenant_id=" + tenantId);
    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
    httpURLConnection.setRequestProperty("Authorization", "Basic " + authorizationValue);
    httpURLConnection.setRequestMethod("POST");
    httpURLConnection.setDoOutput(true);
    OutputStreamWriter connectionOutputStreamWriter = new OutputStreamWriter(
            httpURLConnection.getOutputStream());
    parameters.write(connectionOutputStreamWriter);
    return httpURLConnection;
}

From source file:org.boris.xlloop.http.JSONCodec.java

public static void encodeXLoper(XLoper x, Writer w) throws IOException, JSONException {
    JSONObject o = encode(x);
    o.write(w);
}

From source file:com.google.appengine.tools.mapreduce.MapReduceServlet.java

/**
 * Handles all status page commands.//  ww  w.  j  a v  a 2s.c o m
 */
public void handleCommand(String command, HttpServletRequest request, HttpServletResponse response) {
    JSONObject retValue = null;
    response.setContentType("application/json");
    boolean isPost = "POST".equals(request.getMethod());
    try {
        if (command.equals(LIST_CONFIGS_PATH) && !isPost) {
            MapReduceXml xml;
            try {
                xml = MapReduceXml.getMapReduceXmlFromFile();
                retValue = handleListConfigs(xml);
            } catch (FileNotFoundException e) {
                retValue = new JSONObject();
                retValue.put("status", "Couldn't find mapreduce.xml file");
            }
        } else if (command.equals(LIST_JOBS_PATH) && !isPost) {
            String cursor = request.getParameter("cursor");
            String countString = request.getParameter("count");
            int count = DEFAULT_JOBS_PER_PAGE_COUNT;
            if (countString != null) {
                count = Integer.parseInt(countString);
            }

            retValue = handleListJobs(cursor, count);
        } else if (command.equals(CLEANUP_JOB_PATH) && isPost) {
            retValue = handleCleanupJob(request.getParameter("mapreduce_id"));
        } else if (command.equals(ABORT_JOB_PATH) && isPost) {
            retValue = handleAbortJob(request.getParameter("mapreduce_id"));
        } else if (command.equals(GET_JOB_DETAIL_PATH) && !isPost) {
            retValue = handleGetJobDetail(request.getParameter("mapreduce_id"));
        } else if (command.equals(START_JOB_PATH) && isPost) {
            Map<String, String> templateParams = new TreeMap<String, String>();
            Map httpParams = request.getParameterMap();
            for (Object paramObject : httpParams.keySet()) {
                String param = (String) paramObject;
                if (param.startsWith("mapper_params.")) {
                    templateParams.put(param.substring("mapper_params.".length()),
                            ((String[]) httpParams.get(param))[0]);
                }
            }
            retValue = handleStartJob(templateParams, ((String[]) httpParams.get("name"))[0], request);
        } else {
            response.sendError(404);
            return;
        }
    } catch (Throwable t) {
        log.log(Level.SEVERE, "Got exception while running command", t);
        try {
            retValue = new JSONObject();
            retValue.put("error_class", t.getClass().getName());
            retValue.put("error_message",
                    "Full stack trace is available in the server logs. Message: " + t.getMessage());
        } catch (JSONException e) {
            throw new RuntimeException("Couldn't create error JSON object", e);
        }
    }
    try {
        retValue.write(response.getWriter());
        response.getWriter().flush();
    } catch (JSONException e) {
        throw new RuntimeException("Couldn't write command response", e);
    } catch (IOException e) {
        throw new RuntimeException("Couldn't write command response", e);
    }
}