Example usage for org.json.simple JSONObject toJSONString

List of usage examples for org.json.simple JSONObject toJSONString

Introduction

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

Prototype

public String toJSONString() 

Source Link

Usage

From source file:hoot.services.controllers.info.ReportsResourceTest.java

@Test
@Category(UnitTest.class)
public void testGetReportFile() throws Exception {
    String storePath = _rps._homeFolder + "/" + _rps._rptStorePath;
    File f = new File(storePath);
    File fWks = new File(storePath + "/123_test_file");
    if (fWks.exists()) {
        FileUtils.forceDelete(fWks);//from  w ww.j a  v a 2 s  . c  o m
    }
    FileUtils.forceMkdir(f);

    FileUtils.forceMkdir(fWks);
    String currTime = "" + System.currentTimeMillis();
    JSONObject metaData = new JSONObject();
    metaData.put("name", "Test Report1");
    metaData.put("description", "This is test report 1");
    metaData.put("created", currTime);
    metaData.put("reportpath", _rps._homeFolder + "/test-files/test_report1.pdf");
    File meta = new File(storePath + "/123_test_file/meta.data");
    FileUtils.write(meta, metaData.toJSONString());

    File fout = _rps._getReportFile("123_test_file");

    assertNotNull(fout);

    fout = _rps._getReportFile("123_test_file_not_there");

    assertNull(fout);

    FileUtils.forceDelete(fWks);
}

From source file:compare.handler.get.MetadataHandler.java

/**
 * Save the version1 metadata item to the METADATA database
 * @param jObj1 the object retrieved from the metadata database or null
 * @param conn the database connection/*  w  w w. jav  a2 s  . co  m*/
 * @throws CompareException if database save failed
 */
protected void saveToMetadata(JSONObject jObj1, Connection conn) throws CompareException {
    try {
        if (!saved && metadataValue != null && metadataValue.length() > 0) {
            if (jObj1 == null)
                jObj1 = new JSONObject();
            // update metadata for next time
            jObj1.put(metadataKey, metadataValue);
            if (jObj1.containsKey(JSONKeys._ID))
                jObj1.remove(JSONKeys._ID);
            conn.putToDb(Database.METADATA, docid, jObj1.toJSONString());
        }
    } catch (Exception e) {
        throw new CompareException(e);
    }
}

From source file:com.piusvelte.hydra.ApiServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (request.getParameter(PARAM_TOKEN) == null)
        response.getWriter().write(/*w  w w  .  j  a v  a2 s  .c  om*/
                "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><title>Hydra</title></head><body><h3>Hydra API</h3>");
    else {
        ServletContext ctx = getServletContext();
        HydraRequest hydraRequest;
        try {
            hydraRequest = HydraRequest.fromGet(request);
        } catch (Exception e) {
            ctx.log(e.getMessage());
            JSONObject j = new JSONObject();
            JSONArray errors = new JSONArray();
            errors.add(e.getMessage());
            response.setStatus(402);
            j.put("errors", errors);
            response.getWriter().write(j.toJSONString());
            return;
        }
        ConnectionManager connMgr = ConnectionManager.getInstance(ctx);
        if (connMgr.isAuthenticated(request.getParameter(PARAM_TOKEN))) {
            if (hydraRequest.hasDatabase()) {
                if (hydraRequest.hasTarget()) {
                    DatabaseConnection databaseConnection = null;
                    connMgr.queueDatabaseRequest(hydraRequest.database);
                    try {
                        while (databaseConnection == null)
                            databaseConnection = connMgr.getDatabaseConnection(hydraRequest.database);
                    } catch (Exception e) {
                        ctx.log("Hydra: " + e.getMessage());
                    }
                    connMgr.dequeueDatabaseRequest(hydraRequest.database);
                    if (databaseConnection != null) {
                        response.getWriter().write(databaseConnection
                                .query(hydraRequest.target, hydraRequest.columns, hydraRequest.selection)
                                .toJSONString());
                        databaseConnection.release();
                    } else if (hydraRequest.queueable) {
                        JSONObject j = new JSONObject();
                        JSONArray errors = new JSONArray();
                        errors.add("no database connection");
                        connMgr.queueRequest(hydraRequest.toJSONString());
                        errors.add("queued");
                        response.setStatus(200);
                        j.put("errors", errors);
                        response.getWriter().write(j.toJSONString());
                    } else {
                        response.setStatus(502);
                    }
                    connMgr.cleanDatabaseConnections(hydraRequest.database);
                } else {
                    response.getWriter().write(connMgr.getDatabase(hydraRequest.database).toJSONString());
                }
            } else {
                response.getWriter().write(connMgr.getDatabases().toJSONString());
            }
        } else {
            ctx.log("not authenticated");
            JSONObject j = new JSONObject();
            JSONArray errors = new JSONArray();
            errors.add("not authenticated");
            j.put("errors", errors);
            response.getWriter().write(j.toJSONString());
            response.setStatus(401);
        }
    }
}

From source file:mml.test.Editor.java

/**
 * Get the opts for this editor/*from w w  w. java2s.  c  o  m*/
 * @return an Element (div) containing the content
 */
private String getOpts(String docid, String version1) throws MMLTestException {
    JSONObject opts = new JSONObject();
    opts.put("source", "source");
    opts.put("target", "target");
    opts.put("images", "images");
    opts.put("formid", "tostil");
    return opts.toJSONString();
}

From source file:com.piusvelte.hydra.ApiServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ConnectionManager connMgr = ConnectionManager.getInstance(getServletContext());
    if (connMgr.isAuthenticated(request.getParameter(PARAM_TOKEN))) {
        HydraRequest hydraRequest;//from  w  ww. ja va2  s .  co  m
        try {
            hydraRequest = HydraRequest.fromPost(request);
        } catch (Exception e) {
            JSONObject j = new JSONObject();
            JSONArray errors = new JSONArray();
            errors.add(e.getMessage());
            response.setStatus(402);
            j.put("errors", errors);
            response.getWriter().write(j.toJSONString());
            return;
        }
        if (hydraRequest.database != null) {
            DatabaseConnection databaseConnection = null;
            connMgr.queueDatabaseRequest(hydraRequest.database);
            try {
                while (databaseConnection == null)
                    databaseConnection = connMgr.getDatabaseConnection(hydraRequest.database);
            } catch (Exception e) {
                e.printStackTrace();
            }
            connMgr.dequeueDatabaseRequest(hydraRequest.database);
            if (databaseConnection != null) {
                if (hydraRequest.isInsert())
                    response.getWriter()
                            .write(databaseConnection
                                    .insert(hydraRequest.target, hydraRequest.columns, hydraRequest.values)
                                    .toJSONString());
                else if (hydraRequest.isSubroutine())
                    response.getWriter().write(databaseConnection
                            .subroutine(hydraRequest.target, hydraRequest.arguments).toJSONString());
                else if (hydraRequest.isExecute())
                    response.getWriter().write(databaseConnection.execute(hydraRequest.command).toJSONString());
                else {
                    JSONObject j = new JSONObject();
                    JSONArray errors = new JSONArray();
                    errors.add("invalid request");
                    response.setStatus(403);
                    j.put("errors", errors);
                    response.getWriter().write(j.toJSONString());
                }
                databaseConnection.release();
            } else if (hydraRequest.queueable) {
                JSONObject j = new JSONObject();
                JSONArray errors = new JSONArray();
                errors.add("no database connection");
                connMgr.queueRequest(hydraRequest.toJSONString());
                errors.add("queued");
                response.setStatus(200);
                j.put("errors", errors);
                response.getWriter().write(j.toJSONString());
            } else {
                response.setStatus(502);
                JSONObject j = new JSONObject();
                JSONArray errors = new JSONArray();
                errors.add("no database connection available");
                j.put("errors", errors);
                response.getWriter().write(j.toJSONString());
            }
            connMgr.cleanDatabaseConnections(hydraRequest.database);
        } else
            response.setStatus(402);
    } else {
        response.setStatus(401);
    }
}

From source file:org.kitodo.data.index.elasticsearch.type.TemplateType.java

@SuppressWarnings("unchecked")
@Override// w  ww . j a  va 2s  . c  om
public HttpEntity createDocument(Template template) {

    LinkedHashMap<String, String> orderedTemplateMap = new LinkedHashMap<>();
    String process = template.getProcess() != null ? template.getProcess().getId().toString() : "null";
    orderedTemplateMap.put("process", process);

    JSONObject processObject = new JSONObject(orderedTemplateMap);

    JSONArray properties = new JSONArray();
    List<TemplateProperty> templateProperties = template.getProperties();
    for (TemplateProperty property : templateProperties) {
        JSONObject propertyObject = new JSONObject();
        propertyObject.put("title", property.getTitle());
        propertyObject.put("value", property.getValue());
        properties.add(propertyObject);
    }
    processObject.put("properties", properties);

    return new NStringEntity(processObject.toJSONString(), ContentType.APPLICATION_JSON);
}

From source file:com.fujitsu.dc.core.DcCoreAuthnException.java

@SuppressWarnings("unchecked")
@Override/*from   w ww .  j av a2s.co  m*/
public Response createResponse() {
    JSONObject errorJson = new JSONObject();

    errorJson.put(Key.ERROR, this.error);

    String errDesc = String.format("[%s] - %s", this.code, this.message);
    errorJson.put(Key.ERROR_DESCRIPTION, errDesc);

    int statusCode = parseCode(this.code);
    ResponseBuilder rb = Response.status(statusCode)
            .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).entity(errorJson.toJSONString());

    // ??????WWW-Authenticate??
    // __auth?????(401?)????? Auth Scheme?Basic????????????
    if (this.realm != null && statusCode == HttpStatus.SC_UNAUTHORIZED) {
        rb = rb.header(HttpHeaders.WWW_AUTHENTICATE, Scheme.BASIC + " realm=\"" + this.realm + "\"");
    }
    return rb.build();
}

From source file:name.yumaa.ChromeLogger4J.java

/**
 * Add header to HTTP response/*from ww  w.j  a va 2  s . com*/
 * @param data    response JSON data
 */
private void writeHeader(JSONObject data) {
    String encodedData = Base64.encode(data.toJSONString(), "UTF-8").replaceAll("\\n", "");
    //FIXME if there is long header it rises "header full: java.lang.ArrayIndexOutOfBoundsException: 16384" uncatchable exception
    response.setHeader(HEADER_NAME, encodedData);
}

From source file:hoot.services.controllers.ogr.TranslatorResource.java

/**
  * <NAME>Translation Service Node Server Stop</NAME>
  * <DESCRIPTION>/*  w  w  w.  j  a v a2s .  c  o  m*/
  *  Destroys all translation server process where it effectively shutting them down.
  * </DESCRIPTION>
  * <PARAMETERS>
  * </PARAMETERS>
  * <OUTPUT>
  *    JSON containing state
  * </OUTPUT>
  * <EXAMPLE>
  *    <URL>http://localhost:8080/hoot-services/ogr/translationserver/stop</URL>
  *    <REQUEST_TYPE>GET</REQUEST_TYPE>
  *    <INPUT>
  *   </INPUT>
  * <OUTPUT>{"isRunning":"false"}</OUTPUT>
  * </EXAMPLE>
 * @return
 */
@GET
@Path("/translationserver/stop")
@Produces(MediaType.TEXT_PLAIN)
public Response stopTranslationService() {
    // This also gets called automatically from HootServletContext when service exits but
    // should not be reliable since there are many path where it will not be invoked.
    try {
        stopServer(homeFolder + "/scripts/" + translationServerScript);
    } catch (Exception ex) {
        ResourceErrorHandler.handleError("Error starting translation service request: " + ex.toString(),
                Status.INTERNAL_SERVER_ERROR, log);
    }

    JSONObject res = new JSONObject();
    res.put("isRunning", "false");
    return Response.ok(res.toJSONString(), MediaType.APPLICATION_JSON).build();
}

From source file:org.kitodo.data.index.elasticsearch.type.WorkpieceType.java

@SuppressWarnings("unchecked")
@Override//from w  ww  . ja v  a 2 s .  c  o m
public HttpEntity createDocument(Workpiece workpiece) {

    LinkedHashMap<String, String> orderedWorkpieceMap = new LinkedHashMap<>();
    String process = workpiece.getProcess() != null ? workpiece.getProcess().getId().toString() : "null";
    orderedWorkpieceMap.put("process", process);

    JSONObject processObject = new JSONObject(orderedWorkpieceMap);

    JSONArray properties = new JSONArray();
    List<WorkpieceProperty> workpieceProperties = workpiece.getProperties();
    for (WorkpieceProperty property : workpieceProperties) {
        JSONObject propertyObject = new JSONObject();
        propertyObject.put("title", property.getTitle());
        propertyObject.put("value", property.getValue());
        properties.add(propertyObject);
    }
    processObject.put("properties", properties);

    return new NStringEntity(processObject.toJSONString(), ContentType.APPLICATION_JSON);
}