Example usage for org.json.simple JSONArray toJSONString

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

Introduction

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

Prototype

public String toJSONString() 

Source Link

Usage

From source file:org.opencastproject.adminui.endpoint.EmailEndpoint.java

@SuppressWarnings("unchecked")
@GET/*  w  w  w . j a v  a2  s . c om*/
@Path("variables.json")
@Produces(MediaType.APPLICATION_JSON)
@RestQuery(name = "getEmailTemplateVariables", description = "Returns a list of email template variables as JSON", returnDescription = "The email template variables as a JSON list.", restParameters = {}, reponses = {
        @RestResponse(description = "Returns the email template variables list as JSON", responseCode = HttpServletResponse.SC_OK) })
public Response getEmailTemplateVariables() throws UnauthorizedException {
    JSONArray array = new JSONArray();
    JSONObject optout = new JSONObject();
    optout.put(NAME_KEY, OPT_OUT_LINK_KEY);
    optout.put(VARIABLE_KEY, "${optOutLink}");
    optout.put(DESCRIPTION_EN_KEY,
            "Inserts a link for instructors to opt out of having their lectures recorded.");
    array.add(optout);

    JSONObject staff = new JSONObject();
    staff.put(NAME_KEY, STAFF_NAME_KEY);
    staff.put(VARIABLE_KEY, "${staff}");
    staff.put(DESCRIPTION_EN_KEY, "Inserts the staff member's name.");
    array.add(staff);

    JSONObject moduleName = new JSONObject();
    moduleName.put(NAME_KEY, MODULE_NAME_KEY);
    moduleName.put(VARIABLE_KEY, "<#list modules as module>${module.name}</#list>");
    moduleName.put(DESCRIPTION_EN_KEY,
            "Inserts the list of module names the staff member is involved in into the email.");
    array.add(moduleName);

    JSONObject moduleDescription = new JSONObject();
    moduleDescription.put(NAME_KEY, MODULE_DESCRIPTION_KEY);
    moduleDescription.put(VARIABLE_KEY, "<#list modules as module>${module.description}</#list>");
    moduleDescription.put(DESCRIPTION_EN_KEY, "Inserts the list of module descriptions into the email.");
    array.add(moduleDescription);

    return Response.ok(array.toJSONString()).build();
}

From source file:org.opencastproject.index.service.catalog.adapter.MetadataList.java

public void fromJSON(String json) throws MetadataParsingException {
    if (StringUtils.isBlank(json))
        throw new IllegalArgumentException("The JSON string must not be empty or null!");
    JSONParser parser = new JSONParser();
    JSONArray metadataJSON;/*  w w w . j av a 2 s. co m*/
    try {
        metadataJSON = (JSONArray) parser.parse(json);
    } catch (ParseException e) {
        throw new MetadataParsingException("Not able to parse the given string as JSON metadata list.",
                e.getCause());
    }

    ListIterator<JSONObject> listIterator = metadataJSON.listIterator();

    while (listIterator.hasNext()) {
        JSONObject item = listIterator.next();
        MediaPackageElementFlavor flavor = MediaPackageElementFlavor
                .parseFlavor((String) item.get(KEY_METADATA_FLAVOR));
        String title = (String) item.get(KEY_METADATA_TITLE);
        if (flavor == null || title == null)
            continue;

        JSONArray value = (JSONArray) item.get(KEY_METADATA_FIELDS);
        if (value == null)
            continue;

        Tuple<String, AbstractMetadataCollection> metadata = metadataList.get(flavor.toString());
        if (metadata == null)
            continue;

        metadata.getB().fromJSON(value.toJSONString());
        metadataList.put(flavor.toString(), metadata);
    }
}

From source file:org.opencastproject.index.service.catalog.adapter.MetadataList.java

private void fromJSON(AbstractMetadataCollection metadata, String json) throws MetadataParsingException {
    if (StringUtils.isBlank(json))
        throw new IllegalArgumentException("The JSON string must not be empty or null!");

    JSONParser parser = new JSONParser();
    JSONArray metadataJSON;//from www  .  j a v  a  2  s  . co m
    try {
        metadataJSON = (JSONArray) parser.parse(json);
    } catch (ParseException e) {
        throw new MetadataParsingException("Not able to parse the given string as JSON metadata list.",
                e.getCause());
    }

    ListIterator<JSONObject> listIterator = metadataJSON.listIterator();

    while (listIterator.hasNext()) {
        JSONObject item = listIterator.next();
        String flavor = (String) item.get(KEY_METADATA_FLAVOR);
        String title = (String) item.get(KEY_METADATA_TITLE);
        if (flavor == null || title == null)
            continue;

        JSONArray value = (JSONArray) item.get(KEY_METADATA_FIELDS);
        if (value == null)
            continue;

        metadata.fromJSON(value.toJSONString());
        metadataList.put(flavor, Tuple.tuple(title, metadata));
    }
}

From source file:org.opencastproject.index.service.impl.IndexServiceImpl.java

protected String createEvent(JSONObject metadataJson, MediaPackage mp) throws ParseException, IOException,
        MediaPackageException, IngestException, NotFoundException, SchedulerException, UnauthorizedException {
    if (metadataJson == null)
        throw new IllegalArgumentException("No metadata set");

    JSONObject source = (JSONObject) metadataJson.get("source");
    if (source == null)
        throw new IllegalArgumentException("No source field in metadata");

    JSONObject processing = (JSONObject) metadataJson.get("processing");
    if (processing == null)
        throw new IllegalArgumentException("No processing field in metadata");

    String workflowTemplate = (String) processing.get("workflow");
    if (workflowTemplate == null)
        throw new IllegalArgumentException("No workflow template in metadata");

    JSONArray allEventMetadataJson = (JSONArray) metadataJson.get("metadata");
    if (allEventMetadataJson == null)
        throw new IllegalArgumentException("No metadata field in metadata");

    SourceType type;/*from   ww  w .  jav  a  2 s  .co  m*/
    try {
        type = SourceType.valueOf((String) source.get("type"));
    } catch (Exception e) {
        logger.error("Unknown source type '{}'", source.get("type"));
        throw new IllegalArgumentException("Unkown source type");
    }

    DublinCoreCatalog dc;
    InputStream inputStream = null;
    Properties caProperties = new Properties();
    try {
        MetadataList metadataList = getMetadatListWithAllEventCatalogUIAdapters();
        metadataList.fromJSON(allEventMetadataJson.toJSONString());
        AbstractMetadataCollection eventMetadata = metadataList.getMetadataByAdapter(eventCatalogUIAdapter)
                .get();

        JSONObject sourceMetadata = (JSONObject) source.get("metadata");
        if (sourceMetadata != null
                && (type.equals(SourceType.SCHEDULE_SINGLE) || type.equals(SourceType.SCHEDULE_MULTIPLE))) {
            try {
                MetadataField<?> current = eventMetadata.getOutputFields().get("agent");
                eventMetadata.updateStringField(current, (String) sourceMetadata.get("device"));
            } catch (Exception e) {
                logger.warn("Unable to parse device {}", sourceMetadata.get("device"));
                throw new IllegalArgumentException("Unable to parse device");
            }
        }

        MetadataField<?> created = eventMetadata.getOutputFields().get("created");
        if (created == null || !created.isUpdated() || created.getValue().isNone()) {
            eventMetadata.removeField(created);
            MetadataField<String> newCreated = MetadataUtils.copyMetadataField(created);
            newCreated.setValue(EncodingSchemeUtils.encodeDate(new Date(), Precision.Second).getValue());
            eventMetadata.addField(newCreated);
        }

        metadataList.add(eventCatalogUIAdapter, eventMetadata);
        updateMediaPackageMetadata(mp, metadataList);

        Option<DublinCoreCatalog> dcOpt = DublinCoreUtil.loadEpisodeDublinCore(getWorkspace(), mp);
        if (dcOpt.isSome()) {
            dc = dcOpt.get();
            // make sure to bind the OC_PROPERTY namespace
            dc.addBindings(XmlNamespaceContext.mk(
                    XmlNamespaceBinding.mk(DublinCores.OC_PROPERTY_NS_PREFIX, DublinCores.OC_PROPERTY_NS_URI)));
        } else {
            dc = DublinCores.mkOpencast();
        }

        if (sourceMetadata != null
                && (type.equals(SourceType.SCHEDULE_SINGLE) || type.equals(SourceType.SCHEDULE_MULTIPLE))) {
            Date start = new Date(DateTimeSupport.fromUTC((String) sourceMetadata.get("start")));
            Date end = new Date(DateTimeSupport.fromUTC((String) sourceMetadata.get("end")));
            DublinCoreValue period = EncodingSchemeUtils.encodePeriod(new DCMIPeriod(start, end),
                    Precision.Second);
            String inputs = (String) sourceMetadata.get("inputs");

            Properties configuration;
            try {
                configuration = getCaptureAgentStateService()
                        .getAgentConfiguration((String) sourceMetadata.get("device"));
            } catch (Exception e) {
                logger.warn("Unable to parse device {}: because: {}", sourceMetadata.get("device"),
                        ExceptionUtils.getStackTrace(e));
                throw new IllegalArgumentException("Unable to parse device");
            }
            caProperties.putAll(configuration);
            String agentTimeZone = configuration.getProperty("capture.device.timezone.offset");
            dc.set(DublinCores.OC_PROPERTY_AGENT_TIMEZONE, agentTimeZone);
            dc.set(DublinCore.PROPERTY_TEMPORAL, period);
            caProperties.put(CaptureParameters.CAPTURE_DEVICE_NAMES, inputs);
        }

        if (type.equals(SourceType.SCHEDULE_MULTIPLE)) {
            String rrule = (String) sourceMetadata.get("rrule");
            dc.set(DublinCores.OC_PROPERTY_RECURRENCE, rrule);
        }

        inputStream = IOUtils.toInputStream(dc.toXmlString(), "UTF-8");

        // Update dublincore catalog
        Catalog[] catalogs = mp.getCatalogs(MediaPackageElements.EPISODE);
        if (catalogs.length > 0) {
            Catalog catalog = catalogs[0];
            URI uri = getWorkspace().put(mp.getIdentifier().toString(), catalog.getIdentifier(),
                    "dublincore.xml", inputStream);
            catalog.setURI(uri);
            // setting the URI to a new source so the checksum will most like be invalid
            catalog.setChecksum(null);
        } else {
            mp = getIngestService().addCatalog(inputStream, "dublincore.xml", MediaPackageElements.EPISODE, mp);
        }
    } catch (MetadataParsingException e) {
        logger.warn("Unable to parse event metadata {}", allEventMetadataJson.toJSONString());
        throw new IllegalArgumentException("Unable to parse metadata set");
    } finally {
        IOUtils.closeQuietly(inputStream);
    }

    Map<String, String> configuration = new HashMap<String, String>(
            (JSONObject) processing.get("configuration"));
    for (Entry<String, String> entry : configuration.entrySet()) {
        caProperties.put(WORKFLOW_CONFIG_PREFIX.concat(entry.getKey()), entry.getValue());
    }
    caProperties.put(CaptureParameters.INGEST_WORKFLOW_DEFINITION, workflowTemplate);

    AccessControlList acl = new AccessControlList();
    JSONObject accessJson = (JSONObject) metadataJson.get("access");
    if (accessJson != null) {
        try {
            acl = AccessControlParser.parseAcl(accessJson.toJSONString());
        } catch (Exception e) {
            logger.warn("Unable to parse access control list: {}", accessJson.toJSONString());
            throw new IllegalArgumentException("Unable to parse access control list!");
        }
    }

    switch (type) {
    case UPLOAD:
    case UPLOAD_LATER:
        mp = getAuthorizationService().setAcl(mp, AclScope.Episode, acl).getA();
        configuration.put("workflowDefinitionId", workflowTemplate);
        WorkflowInstance ingest = getIngestService().ingest(mp, workflowTemplate, configuration);
        return Long.toString(ingest.getId());
    case SCHEDULE_SINGLE:
        getIngestService().discardMediaPackage(mp);
        Long id = getSchedulerService().addEvent(dc, configuration);
        getSchedulerService().updateCaptureAgentMetadata(caProperties, Tuple.tuple(id, dc));
        getSchedulerService().updateAccessControlList(id, acl);
        return Long.toString(id);
    case SCHEDULE_MULTIPLE:
        getIngestService().discardMediaPackage(mp);
        // try to create event and it's recurrences
        Long[] createdIDs = getSchedulerService().addReccuringEvent(dc, configuration);
        for (long createdId : createdIDs) {
            getSchedulerService().updateCaptureAgentMetadata(caProperties,
                    Tuple.tuple(createdId, getSchedulerService().getEventDublinCore(createdId)));
            getSchedulerService().updateAccessControlList(createdId, acl);
        }
        return StringUtils.join(createdIDs, ",");
    default:
        logger.warn("Unknown source type {}", type);
        throw new IllegalArgumentException("Unknown source type");
    }
}

From source file:org.opencastproject.index.service.impl.IndexServiceImpl.java

@Override
public String createSeries(String metadata)
        throws IllegalArgumentException, InternalServerErrorException, UnauthorizedException {
    JSONObject metadataJson = null;/*w ww .  ja  v  a2 s. c  o m*/
    try {
        metadataJson = (JSONObject) new JSONParser().parse(metadata);
    } catch (Exception e) {
        logger.warn("Unable to parse metadata {}", metadata);
        throw new IllegalArgumentException("Unable to parse metadata" + metadata);
    }

    if (metadataJson == null)
        throw new IllegalArgumentException("No metadata set to create series");

    JSONArray seriesMetadataJson = (JSONArray) metadataJson.get("metadata");
    if (seriesMetadataJson == null)
        throw new IllegalArgumentException("No metadata field in metadata");

    JSONObject options = (JSONObject) metadataJson.get("options");
    if (options == null)
        throw new IllegalArgumentException("No options field in metadata");

    Opt<Long> themeId = Opt.<Long>none();
    Long theme = (Long) metadataJson.get("theme");
    if (theme != null) {
        themeId = Opt.some(theme);
    }

    Map<String, String> optionsMap;
    try {
        optionsMap = JSONUtils.toMap(new org.codehaus.jettison.json.JSONObject(options.toJSONString()));
    } catch (JSONException e) {
        logger.warn("Unable to parse options to map: {}", ExceptionUtils.getStackTrace(e));
        throw new IllegalArgumentException("Unable to parse options to map");
    }

    DublinCoreCatalog dc = DublinCores.mkOpencast();
    dc.set(PROPERTY_IDENTIFIER, UUID.randomUUID().toString());
    dc.set(DublinCore.PROPERTY_CREATED, EncodingSchemeUtils.encodeDate(new Date(), Precision.Second));
    for (Entry<String, String> entry : optionsMap.entrySet()) {
        dc.set(new EName(DublinCores.OC_PROPERTY_NS_URI, entry.getKey()), entry.getValue());
    }

    MetadataList metadataList;
    try {
        metadataList = getMetadataListWithAllSeriesCatalogUIAdapters();
        metadataList.fromJSON(seriesMetadataJson.toJSONString());
    } catch (Exception e) {
        logger.warn("Not able to parse the series metadata {}: {}", seriesMetadataJson,
                ExceptionUtils.getStackTrace(e));
        throw new IllegalArgumentException("Not able to parse the series metadata");
    }

    Opt<AbstractMetadataCollection> seriesMetadata = metadataList
            .getMetadataByFlavor(MediaPackageElements.SERIES.toString());
    if (seriesMetadata.isSome()) {
        DublinCoreMetadataUtil.updateDublincoreCatalog(dc, seriesMetadata.get());
    }

    AccessControlList acl = new AccessControlList();
    JSONObject access = (JSONObject) metadataJson.get("access");
    if (access != null) {
        try {
            acl = AccessControlParser.parseAcl(access.toJSONString());
        } catch (Exception e) {
            logger.warn("Unable to parse access control list: {}", access.toJSONString());
            throw new IllegalArgumentException("Unable to parse access control list!");
        }
    }

    String seriesId;
    try {
        DublinCoreCatalog createdSeries = seriesService.updateSeries(dc);
        seriesId = createdSeries.getFirst(PROPERTY_IDENTIFIER);
        seriesService.updateAccessControl(seriesId, acl);
        for (Long id : themeId)
            seriesService.updateSeriesProperty(seriesId, THEME_PROPERTY_NAME, Long.toString(id));
    } catch (Exception e) {
        logger.error("Unable to create new series: {}", ExceptionUtils.getStackTrace(e));
        throw new InternalServerErrorException("Unable to create new series");
    }

    updateSeriesMetadata(seriesId, metadataList);

    return seriesId;
}

From source file:org.opencastproject.serviceregistry.remote.IncidentServiceRemoteImpl.java

@Override
@SuppressWarnings("unchecked")
public Incident storeIncident(Job job, Date timestamp, String code, Severity severity,
        Map<String, String> descriptionParameters, List<Tuple<String, String>> details)
        throws IncidentServiceException, IllegalStateException {
    HttpPost post = new HttpPost();
    try {/*from w  w w .  ja va2  s. c  o m*/
        List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
        params.add(new BasicNameValuePair("job", JobParser.toXml(job)));
        params.add(new BasicNameValuePair("date", DateTimeSupport.toUTC(timestamp.getTime())));
        params.add(new BasicNameValuePair("code", code));
        params.add(new BasicNameValuePair("severity", severity.name()));
        if (descriptionParameters != null)
            params.add(new BasicNameValuePair("params", mapToString(descriptionParameters)));
        if (details != null) {
            JSONArray json = new JSONArray();
            for (Tuple<String, String> detail : details) {
                JSONObject jsTuple = new JSONObject();
                jsTuple.put("title", detail.getA());
                jsTuple.put("content", detail.getB());
                json.add(jsTuple);
            }
            params.add(new BasicNameValuePair("details", json.toJSONString()));
        }
        post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
    } catch (Exception e) {
        throw new IncidentServiceException("Unable to assemble a remote incident service request", e);
    }
    HttpResponse response = getResponse(post, SC_CREATED, SC_CONFLICT);
    try {
        if (response != null) {
            if (response.getStatusLine().getStatusCode() == SC_CONFLICT) {
                throw new IllegalStateException("No related job " + job.getId() + " of incident job found");
            } else if (response.getStatusLine().getStatusCode() == SC_CREATED) {
                Incident incident = parser.parseIncidentFromXml(response.getEntity().getContent()).toIncident();
                logger.info("Incident '{}' created", incident.getId());
                return incident;
            }
        }
    } catch (Exception e) {
        throw new IncidentServiceException(e);
    } finally {
        closeConnection(response);
    }
    throw new IncidentServiceException("Unable to store an incident of job " + job.getId());
}

From source file:org.opencastproject.workflow.endpoint.WorkflowRestService.java

@GET
@Path("handlers.json")
@SuppressWarnings("unchecked")
@RestQuery(name = "handlers", description = "List all registered workflow operation handlers (implementations).", returnDescription = "A JSON representation of the registered workflow operation handlers.", reponses = {
        @RestResponse(responseCode = SC_OK, description = "A JSON representation of the registered workflow operation handlers") })
public Response getOperationHandlers() {
    JSONArray jsonArray = new JSONArray();
    for (HandlerRegistration reg : ((WorkflowServiceImpl) service).getRegisteredHandlers()) {
        WorkflowOperationHandler handler = reg.getHandler();
        JSONObject jsonHandler = new JSONObject();
        jsonHandler.put("id", handler.getId());
        jsonHandler.put("description", handler.getDescription());
        JSONObject jsonConfigOptions = new JSONObject();
        for (Entry<String, String> configEntry : handler.getConfigurationOptions().entrySet()) {
            jsonConfigOptions.put(configEntry.getKey(), configEntry.getValue());
        }/*  ww w.  ja  va2s. c  o m*/
        jsonHandler.put("options", jsonConfigOptions);
        jsonArray.add(jsonHandler);
    }
    return Response.ok(jsonArray.toJSONString()).header("Content-Type", MediaType.APPLICATION_JSON).build();
}

From source file:org.opencastproject.workingfilerepository.impl.WorkingFileRepositoryRestEndpoint.java

@SuppressWarnings("unchecked")
@GET/*from w  ww.j  a  v  a2s  .co m*/
@Produces(MediaType.APPLICATION_JSON)
@Path("/list/{collectionId}.json")
@RestQuery(name = "filesInCollection", description = "Lists files in a collection", returnDescription = "Links to the URLs in a collection", pathParameters = {
        @RestParameter(name = "collectionId", description = "the collection identifier", isRequired = true, type = STRING) }, reponses = {
                @RestResponse(responseCode = SC_OK, description = "URLs returned"),
                @RestResponse(responseCode = SC_NOT_FOUND, description = "Collection not found") })
public Response restGetCollectionContents(@PathParam("collectionId") String collectionId)
        throws NotFoundException {
    try {
        URI[] uris = super.getCollectionContents(collectionId);
        JSONArray jsonArray = new JSONArray();
        for (URI uri : uris) {
            jsonArray.add(uri.toString());
        }
        return Response.ok(jsonArray.toJSONString()).build();
    } catch (NotFoundException e) {
        throw e;
    } catch (Exception e) {
        return Response.serverError().entity(e.getMessage()).build();
    }
}

From source file:org.openiot.gsn.http.restapi.GetRequestHandler.java

public String getSensorsInfoAsJSON() {

    JSONArray sensorsInfo = new JSONArray();

    Iterator<VSensorConfig> vsIterator = Mappings.getAllVSensorConfigs();

    while (vsIterator.hasNext()) {

        JSONObject aSensor = new JSONObject();

        VSensorConfig sensorConfig = vsIterator.next();

        String vs_name = sensorConfig.getName();

        aSensor.put("name", vs_name);

        JSONArray listOfFields = new JSONArray();

        for (DataField df : sensorConfig.getOutputStructure()) {

            String field_name = df.getName().toLowerCase();
            String field_type = df.getType().toLowerCase();

            if (field_type.indexOf("double") >= 0) {
                listOfFields.add(field_name);
            }/*w w  w  .  j  a  va 2s  .c  om*/
        }

        aSensor.put("fields", listOfFields);

        Double alt = 0.0;
        Double lat = 0.0;
        Double lon = 0.0;

        for (KeyValue df : sensorConfig.getAddressing()) {

            String adressing_key = df.getKey().toString().toLowerCase().trim();
            String adressing_value = df.getValue().toString().toLowerCase().trim();

            if (adressing_key.indexOf("altitude") >= 0)
                alt = Double.parseDouble(adressing_value);

            if (adressing_key.indexOf("longitude") >= 0)
                lon = Double.parseDouble(adressing_value);

            if (adressing_key.indexOf("latitude") >= 0)
                lat = Double.parseDouble(adressing_value);
        }

        aSensor.put("lat", lat);
        aSensor.put("lon", lon);
        aSensor.put("alt", alt);

        sensorsInfo.add(aSensor);

    }

    return sensorsInfo.toJSONString();
}

From source file:org.openlegacy.ide.eclipse.actions.DeployToServerAction.java

@SuppressWarnings("unchecked")
private static void saveServer(IProject project, String serverName, String serverPort, String userName) {
    JSONArray serversList = loadServersList(project);
    // modify existing
    for (Object obj : serversList) {
        JSONObject jsonObject = (JSONObject) obj;
        if (StringUtils.equals((String) jsonObject.get("serverName"), serverName)) {
            jsonObject.put("serverPort", serverPort);
            jsonObject.put("userName", userName);
            EclipseDesignTimeExecuter.instance().savePreference(project, "SERVERS_LIST",
                    serversList.toJSONString());
            return;
        }//from w  w w .ja v a  2  s .  com
    }
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("serverName", serverName);
    jsonObject.put("serverPort", serverPort);
    jsonObject.put("userName", userName);
    serversList.add(jsonObject);
    EclipseDesignTimeExecuter.instance().savePreference(project, "SERVERS_LIST", serversList.toJSONString());
}