Search in sources :

Example 36 with ParseException

use of org.json.simple.parser.ParseException in project opencast by opencast.

the class MetadataField method createMixedIterableStringMetadataField.

/**
 * Create a metadata field of type mixed iterable String
 *
 * @param inputID
 *          The identifier of the new metadata field
 * @param label
 *          The label of the new metadata field
 * @param readOnly
 *          Define if the new metadata field can be or not edited
 * @param required
 *          Define if the new metadata field is or not required
 * @param isTranslatable
 *          If the field value is not human readable and should be translated before
 * @param collection
 *          If the field has a limited list of possible value, the option should contain this one. Otherwise it should
 *          be none.
 * @param order
 *          The ui order for the new field, 0 at the top and progressively down from there.
 * @return the new metadata field
 */
public static MetadataField<Iterable<String>> createMixedIterableStringMetadataField(String inputID, Opt<String> outputID, String label, boolean readOnly, boolean required, Opt<Boolean> isTranslatable, Opt<Map<String, String>> collection, Opt<String> collectionId, Opt<Integer> order, Opt<String> namespace) {
    Fn<Opt<Iterable<String>>, JValue> iterableToJSON = new Fn<Opt<Iterable<String>>, JValue>() {

        @Override
        public JValue apply(Opt<Iterable<String>> value) {
            if (value.isNone())
                return arr();
            Object val = value.get();
            List<JValue> list = new ArrayList<>();
            if (val instanceof String) {
                // The value is a string so we need to split it.
                String stringVal = (String) val;
                for (String entry : stringVal.split(",")) {
                    if (StringUtils.isNotBlank(entry))
                        list.add(v(entry, Jsons.BLANK));
                }
            } else {
                // The current value is just an iterable string.
                for (Object v : value.get()) {
                    list.add(v(v, Jsons.BLANK));
                }
            }
            return arr(list);
        }
    };
    Fn<Object, Iterable<String>> jsonToIterable = new Fn<Object, Iterable<String>>() {

        @Override
        public Iterable<String> apply(Object arrayIn) {
            JSONParser parser = new JSONParser();
            JSONArray array;
            if (arrayIn instanceof String) {
                try {
                    array = (JSONArray) parser.parse((String) arrayIn);
                } catch (ParseException e) {
                    throw new IllegalArgumentException("Unable to parse Mixed Iterable value into a JSONArray:", e);
                }
            } else {
                array = (JSONArray) arrayIn;
            }
            if (array == null)
                return new ArrayList<>();
            String[] arrayOut = new String[array.size()];
            for (int i = 0; i < array.size(); i++) {
                arrayOut[i] = (String) array.get(i);
            }
            return Arrays.asList(arrayOut);
        }
    };
    return new MetadataField<>(inputID, outputID, label, readOnly, required, new ArrayList<String>(), isTranslatable, Type.MIXED_TEXT, JsonType.MIXED_TEXT, collection, collectionId, iterableToJSON, jsonToIterable, order, namespace);
}
Also used : Fn(com.entwinemedia.fn.Fn) ArrayList(java.util.ArrayList) JSONArray(org.json.simple.JSONArray) Opt(com.entwinemedia.fn.data.Opt) JValue(com.entwinemedia.fn.data.json.JValue) JObject(com.entwinemedia.fn.data.json.JObject) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException)

Example 37 with ParseException

use of org.json.simple.parser.ParseException in project opencast by opencast.

the class IBMWatsonTranscriptionRestService method reportStatus.

/**
 * { "id": "{job_id}", "event": "{recognitions_status}", "user_token": "{user_token}" } If the event is
 * recognitions.completed_with_results, the object includes a results field that provides the results of the
 * recognition request. The client should respond to the callback notification with status code 200.
 */
@POST
@Path("results")
@Produces(MediaType.TEXT_PLAIN)
@RestQuery(name = "results", description = "Called by the speech-to-text service to report status.", returnDescription = "", reponses = { @RestResponse(responseCode = HttpServletResponse.SC_OK, description = "Got notification!") })
public Response reportStatus(String body) {
    logger.trace("Body is: " + body);
    JSONObject jsonObj = null;
    try {
        JSONParser parser = new JSONParser();
        jsonObj = (JSONObject) parser.parse(body);
        // jsonObj = (JSONObject) parser.parse(request.getReader());
        String mpId = (String) jsonObj.get("user_token");
        String event = (String) jsonObj.get("event");
        logger.info("Transcription notification for mp {} is {}", mpId, event);
        if (IBMWatsonTranscriptionService.JobEvent.COMPLETED_WITH_RESULTS.equals(event))
            service.transcriptionDone(mpId, jsonObj);
        else if (IBMWatsonTranscriptionService.JobEvent.FAILED.equals(event))
            service.transcriptionError(mpId, jsonObj);
        // return Response.ok().build();
        return Response.ok().type(MediaType.APPLICATION_JSON).build();
    } catch (ParseException e) {
        logger.warn("{} occurred. Notification results could not be parsed: {}", e.getClass(), jsonObj == null ? jsonObj : jsonObj.toJSONString());
        return Response.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
    } catch (Exception e) {
        logger.warn(e.getMessage());
        return Response.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
    }
}
Also used : JSONObject(org.json.simple.JSONObject) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException) ParseException(org.json.simple.parser.ParseException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 38 with ParseException

use of org.json.simple.parser.ParseException in project opencast by opencast.

the class EventsEndpoint method updateEventMetadataByType.

@PUT
@Path("{eventId}/metadata")
@Produces({ "application/json", "application/v1.0.0+json" })
@RestQuery(name = "updateeventmetadata", description = "Update the metadata with the matching type of the specified event. For a metadata catalog there is the flavor such as 'dublincore/episode' and this is the unique type.", returnDescription = "", pathParameters = { @RestParameter(name = "eventId", description = "The event id", isRequired = true, type = STRING) }, restParameters = { @RestParameter(name = "type", isRequired = true, description = "The type of metadata to update", type = STRING), @RestParameter(name = "metadata", description = "Metadata catalog in JSON format", isRequired = true, type = STRING) }, reponses = { @RestResponse(description = "The metadata of the given namespace has been updated.", responseCode = HttpServletResponse.SC_OK), @RestResponse(description = "The request is invalid or inconsistent.", responseCode = HttpServletResponse.SC_BAD_REQUEST), @RestResponse(description = "The specified event does not exist.", responseCode = HttpServletResponse.SC_NOT_FOUND) })
public Response updateEventMetadataByType(@HeaderParam("Accept") String acceptHeader, @PathParam("eventId") String id, @QueryParam("type") String type, @FormParam("metadata") String metadataJSON) throws Exception {
    Map<String, String> updatedFields;
    JSONParser parser = new JSONParser();
    try {
        updatedFields = RequestUtils.getKeyValueMap(metadataJSON);
    } catch (ParseException e) {
        logger.debug("Unable to update event '{}' with metadata type '{}' and content '{}' because: {}", id, type, metadataJSON, ExceptionUtils.getStackTrace(e));
        return RestUtil.R.badRequest(String.format("Unable to parse metadata fields as json from '%s' because '%s'", metadataJSON, ExceptionUtils.getStackTrace(e)));
    } catch (IllegalArgumentException e) {
        logger.debug("Unable to update event '{}' with metadata type '{}' and content '{}' because: {}", id, type, metadataJSON, ExceptionUtils.getStackTrace(e));
        return RestUtil.R.badRequest(e.getMessage());
    }
    if (updatedFields == null || updatedFields.size() == 0) {
        return RestUtil.R.badRequest(String.format("Unable to parse metadata fields as json from '%s' because there were no fields to update.", metadataJSON));
    }
    Opt<MediaPackageElementFlavor> flavor = getFlavor(type);
    if (flavor.isNone()) {
        return R.badRequest(String.format("Unable to parse type '%s' as a flavor so unable to find the matching catalog.", type));
    }
    MetadataCollection collection = null;
    EventCatalogUIAdapter adapter = null;
    for (final Event event : indexService.getEvent(id, externalIndex)) {
        MetadataList metadataList = new MetadataList();
        // Try the main catalog first as we load it from the index.
        if (flavor.get().equals(eventCatalogUIAdapter.getFlavor())) {
            collection = EventUtils.getEventMetadata(event, eventCatalogUIAdapter);
            adapter = eventCatalogUIAdapter;
        } else {
            metadataList.add(eventCatalogUIAdapter, EventUtils.getEventMetadata(event, eventCatalogUIAdapter));
        }
        // Try the other catalogs
        List<EventCatalogUIAdapter> catalogUIAdapters = getEventCatalogUIAdapters();
        catalogUIAdapters.remove(eventCatalogUIAdapter);
        MediaPackage mediaPackage = indexService.getEventMediapackage(event);
        if (catalogUIAdapters.size() > 0) {
            for (EventCatalogUIAdapter catalogUIAdapter : catalogUIAdapters) {
                if (flavor.get().equals(catalogUIAdapter.getFlavor())) {
                    collection = catalogUIAdapter.getFields(mediaPackage);
                    adapter = eventCatalogUIAdapter;
                } else {
                    metadataList.add(catalogUIAdapter, catalogUIAdapter.getFields(mediaPackage));
                }
            }
        }
        if (collection == null) {
            return ApiResponses.notFound("Cannot find a catalog with type '%s' for event with id '%s'.", type, id);
        }
        for (String key : updatedFields.keySet()) {
            if ("subjects".equals(key)) {
                MetadataField<?> field = collection.getOutputFields().get(DublinCore.PROPERTY_SUBJECT.getLocalName());
                Opt<Response> error = validateField(field, key, id, type, updatedFields);
                if (error.isSome()) {
                    return error.get();
                }
                collection.removeField(field);
                JSONArray subjectArray = (JSONArray) parser.parse(updatedFields.get(key));
                collection.addField(MetadataField.copyMetadataFieldWithValue(field, StringUtils.join(subjectArray.iterator(), ",")));
            } else if ("startDate".equals(key)) {
                // Special handling for start date since in API v1 we expect start date and start time to be separate fields.
                MetadataField<String> field = (MetadataField<String>) collection.getOutputFields().get(key);
                Opt<Response> error = validateField(field, key, id, type, updatedFields);
                if (error.isSome()) {
                    return error.get();
                }
                String apiPattern = field.getPattern().get();
                if (configuredMetadataFields.containsKey("startDate")) {
                    apiPattern = configuredMetadataFields.get("startDate").getPattern().getOr(apiPattern);
                }
                SimpleDateFormat apiSdf = MetadataField.getSimpleDateFormatter(apiPattern);
                SimpleDateFormat sdf = MetadataField.getSimpleDateFormatter(field.getPattern().get());
                DateTime oldStartDate = new DateTime(sdf.parse(field.getValue().get()), DateTimeZone.UTC);
                DateTime newStartDate = new DateTime(apiSdf.parse(updatedFields.get(key)), DateTimeZone.UTC);
                DateTime updatedStartDate = oldStartDate.withDate(newStartDate.year().get(), newStartDate.monthOfYear().get(), newStartDate.dayOfMonth().get());
                collection.removeField(field);
                collection.addField(MetadataField.copyMetadataFieldWithValue(field, sdf.format(updatedStartDate.toDate())));
            } else if ("startTime".equals(key)) {
                // Special handling for start time since in API v1 we expect start date and start time to be separate fields.
                MetadataField<String> field = (MetadataField<String>) collection.getOutputFields().get("startDate");
                Opt<Response> error = validateField(field, "startDate", id, type, updatedFields);
                if (error.isSome()) {
                    return error.get();
                }
                String apiPattern = "HH:mm";
                if (configuredMetadataFields.containsKey("startTime")) {
                    apiPattern = configuredMetadataFields.get("startTime").getPattern().getOr(apiPattern);
                }
                SimpleDateFormat apiSdf = MetadataField.getSimpleDateFormatter(apiPattern);
                SimpleDateFormat sdf = MetadataField.getSimpleDateFormatter(field.getPattern().get());
                DateTime oldStartDate = new DateTime(sdf.parse(field.getValue().get()), DateTimeZone.UTC);
                DateTime newStartDate = new DateTime(apiSdf.parse(updatedFields.get(key)), DateTimeZone.UTC);
                DateTime updatedStartDate = oldStartDate.withTime(newStartDate.hourOfDay().get(), newStartDate.minuteOfHour().get(), newStartDate.secondOfMinute().get(), newStartDate.millisOfSecond().get());
                collection.removeField(field);
                collection.addField(MetadataField.copyMetadataFieldWithValue(field, sdf.format(updatedStartDate.toDate())));
            } else {
                MetadataField<?> field = collection.getOutputFields().get(key);
                Opt<Response> error = validateField(field, key, id, type, updatedFields);
                if (error.isSome()) {
                    return error.get();
                }
                collection.removeField(field);
                collection.addField(MetadataField.copyMetadataFieldWithValue(field, updatedFields.get(key)));
            }
        }
        metadataList.add(adapter, collection);
        indexService.updateEventMetadata(id, metadataList, externalIndex);
        return ApiResponses.Json.noContent(ApiVersion.VERSION_1_0_0);
    }
    return ApiResponses.notFound("Cannot find an event with id '%s'.", id);
}
Also used : JSONArray(org.json.simple.JSONArray) MediaPackageElementFlavor(org.opencastproject.mediapackage.MediaPackageElementFlavor) MetadataField(org.opencastproject.metadata.dublincore.MetadataField) DateTime(org.joda.time.DateTime) MetadataList(org.opencastproject.index.service.catalog.adapter.MetadataList) RestResponse(org.opencastproject.util.doc.rest.RestResponse) Response(javax.ws.rs.core.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) Opt(com.entwinemedia.fn.data.Opt) CommonEventCatalogUIAdapter(org.opencastproject.index.service.catalog.adapter.events.CommonEventCatalogUIAdapter) EventCatalogUIAdapter(org.opencastproject.metadata.dublincore.EventCatalogUIAdapter) MediaPackage(org.opencastproject.mediapackage.MediaPackage) Event(org.opencastproject.index.service.impl.index.event.Event) JSONParser(org.json.simple.parser.JSONParser) MetadataCollection(org.opencastproject.metadata.dublincore.MetadataCollection) ParseException(org.json.simple.parser.ParseException) SimpleDateFormat(java.text.SimpleDateFormat) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) RestQuery(org.opencastproject.util.doc.rest.RestQuery) PUT(javax.ws.rs.PUT)

Example 39 with ParseException

use of org.json.simple.parser.ParseException in project opencast by opencast.

the class SeriesEndpoint method createNewSeries.

@POST
@Path("")
@Produces({ "application/json", "application/v1.0.0+json" })
@RestQuery(name = "createseries", description = "Creates a series.", returnDescription = "", restParameters = { @RestParameter(name = "metadata", isRequired = true, description = "Series metadata", type = STRING), @RestParameter(name = "acl", description = "A collection of roles with their possible action", isRequired = false, type = STRING), @RestParameter(name = "theme", description = "The theme ID to be applied to the series", isRequired = false, type = STRING) }, reponses = { @RestResponse(description = "A new series is created and its identifier is returned in the Location header.", responseCode = HttpServletResponse.SC_CREATED), @RestResponse(description = "The request is invalid or inconsistent..", responseCode = HttpServletResponse.SC_BAD_REQUEST), @RestResponse(description = "The user doesn't have the rights to create the series.", responseCode = HttpServletResponse.SC_UNAUTHORIZED) })
public Response createNewSeries(@HeaderParam("Accept") String acceptHeader, @FormParam("metadata") String metadataParam, @FormParam("acl") String aclParam, @FormParam("theme") String themeIdParam) throws UnauthorizedException, NotFoundException {
    if (isBlank(metadataParam))
        return R.badRequest("Required parameter 'metadata' is missing or invalid");
    MetadataList metadataList;
    try {
        metadataList = deserializeMetadataList(metadataParam);
    } catch (ParseException e) {
        logger.debug("Unable to parse series metadata '{}' because: {}", metadataParam, ExceptionUtils.getStackTrace(e));
        return R.badRequest(String.format("Unable to parse metadata because '%s'", e.toString()));
    } catch (NotFoundException e) {
        // One of the metadata fields could not be found in the catalogs or one of the catalogs cannot be found.
        return R.badRequest(e.getMessage());
    } catch (IllegalArgumentException e) {
        logger.debug("Unable to create series with metadata '{}' because: {}", metadataParam, ExceptionUtils.getStackTrace(e));
        return R.badRequest(e.getMessage());
    }
    Map<String, String> options = new TreeMap<>();
    Opt<Long> optThemeId = Opt.none();
    if (StringUtils.trimToNull(themeIdParam) != null) {
        try {
            Long themeId = Long.parseLong(themeIdParam);
            optThemeId = Opt.some(themeId);
        } catch (NumberFormatException e) {
            return R.badRequest(String.format("Unable to parse the theme id '%s' into a number", themeIdParam));
        }
    }
    AccessControlList acl;
    try {
        acl = AclUtils.deserializeJsonToAcl(aclParam, false);
    } catch (ParseException e) {
        logger.debug("Unable to parse acl '{}' because: '{}'", aclParam, ExceptionUtils.getStackTrace(e));
        return R.badRequest(String.format("Unable to parse acl '%s' because '%s'", aclParam, e.getMessage()));
    } catch (IllegalArgumentException e) {
        logger.debug("Unable to create new series with acl '{}' because: '{}'", aclParam, ExceptionUtils.getStackTrace(e));
        return R.badRequest(e.getMessage());
    }
    try {
        String seriesId = indexService.createSeries(metadataList, options, Opt.some(acl), optThemeId);
        return ApiResponses.Json.created(VERSION_1_0_0, URI.create(getSeriesUrl(seriesId)), obj(f("identifier", v(seriesId, BLANK))));
    } catch (IndexServiceException e) {
        logger.error("Unable to create series with metadata '{}', acl '{}', theme '{}' because: ", metadataParam, aclParam, themeIdParam, ExceptionUtils.getStackTrace(e));
        throw new WebApplicationException(e, Status.INTERNAL_SERVER_ERROR);
    }
}
Also used : AccessControlList(org.opencastproject.security.api.AccessControlList) WebApplicationException(javax.ws.rs.WebApplicationException) NotFoundException(org.opencastproject.util.NotFoundException) TreeMap(java.util.TreeMap) MetadataList(org.opencastproject.index.service.catalog.adapter.MetadataList) ParseException(org.json.simple.parser.ParseException) IndexServiceException(org.opencastproject.index.service.exception.IndexServiceException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 40 with ParseException

use of org.json.simple.parser.ParseException in project opencast by opencast.

the class SeriesEndpoint method deserializeMetadataList.

/**
 * Change the simplified fields of key values provided to the external api into a {@link MetadataList}.
 *
 * @param json
 *          The json string that contains an array of metadata field lists for the different catalogs.
 * @return A {@link MetadataList} with the fields populated with the values provided.
 * @throws ParseException
 *           Thrown if unable to parse the json string.
 * @throws NotFoundException
 *           Thrown if unable to find the catalog or field that the json refers to.
 */
protected MetadataList deserializeMetadataList(String json) throws ParseException, NotFoundException {
    MetadataList metadataList = new MetadataList();
    JSONParser parser = new JSONParser();
    JSONArray jsonCatalogs = (JSONArray) parser.parse(json);
    for (int i = 0; i < jsonCatalogs.size(); i++) {
        JSONObject catalog = (JSONObject) jsonCatalogs.get(i);
        if (catalog.get("flavor") == null || StringUtils.isBlank(catalog.get("flavor").toString())) {
            throw new IllegalArgumentException("Unable to create new series as no flavor was given for one of the metadata collections");
        }
        String flavorString = catalog.get("flavor").toString();
        MediaPackageElementFlavor flavor = MediaPackageElementFlavor.parseFlavor(flavorString);
        MetadataCollection collection = null;
        SeriesCatalogUIAdapter adapter = null;
        for (SeriesCatalogUIAdapter seriesCatalogUIAdapter : indexService.getSeriesCatalogUIAdapters()) {
            MediaPackageElementFlavor catalogFlavor = MediaPackageElementFlavor.parseFlavor(seriesCatalogUIAdapter.getFlavor());
            if (catalogFlavor.equals(flavor)) {
                adapter = seriesCatalogUIAdapter;
                collection = seriesCatalogUIAdapter.getRawFields();
            }
        }
        if (collection == null) {
            throw new IllegalArgumentException(String.format("Unable to find an SeriesCatalogUIAdapter with Flavor '%s'", flavorString));
        }
        String fieldsJson = catalog.get("fields").toString();
        if (StringUtils.trimToNull(fieldsJson) != null) {
            Map<String, String> fields = RequestUtils.getKeyValueMap(fieldsJson);
            for (String key : fields.keySet()) {
                if ("subjects".equals(key)) {
                    MetadataField<?> field = collection.getOutputFields().get("subject");
                    if (field == null) {
                        throw new NotFoundException(String.format("Cannot find a metadata field with id '%s' from Catalog with Flavor '%s'.", key, flavorString));
                    }
                    collection.removeField(field);
                    try {
                        JSONArray subjects = (JSONArray) parser.parse(fields.get(key));
                        collection.addField(MetadataField.copyMetadataFieldWithValue(field, StringUtils.join(subjects.iterator(), ",")));
                    } catch (ParseException e) {
                        throw new IllegalArgumentException(String.format("Unable to parse the 'subjects' metadata array field because: %s", e.toString()));
                    }
                } else {
                    MetadataField<?> field = collection.getOutputFields().get(key);
                    if (field == null) {
                        throw new NotFoundException(String.format("Cannot find a metadata field with id '%s' from Catalog with Flavor '%s'.", key, flavorString));
                    }
                    collection.removeField(field);
                    collection.addField(MetadataField.copyMetadataFieldWithValue(field, fields.get(key)));
                }
            }
        }
        metadataList.add(adapter, collection);
    }
    return metadataList;
}
Also used : JSONArray(org.json.simple.JSONArray) NotFoundException(org.opencastproject.util.NotFoundException) SeriesCatalogUIAdapter(org.opencastproject.metadata.dublincore.SeriesCatalogUIAdapter) MediaPackageElementFlavor(org.opencastproject.mediapackage.MediaPackageElementFlavor) MetadataList(org.opencastproject.index.service.catalog.adapter.MetadataList) JSONObject(org.json.simple.JSONObject) JSONParser(org.json.simple.parser.JSONParser) MetadataCollection(org.opencastproject.metadata.dublincore.MetadataCollection) ParseException(org.json.simple.parser.ParseException)

Aggregations

ParseException (org.json.simple.parser.ParseException)258 JSONObject (org.json.simple.JSONObject)191 JSONParser (org.json.simple.parser.JSONParser)185 JSONArray (org.json.simple.JSONArray)84 IOException (java.io.IOException)71 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)50 HashMap (java.util.HashMap)41 ArrayList (java.util.ArrayList)34 Map (java.util.Map)23 HashSet (java.util.HashSet)18 API (org.wso2.carbon.apimgt.api.model.API)18 BufferedReader (java.io.BufferedReader)13 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)13 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)13 List (java.util.List)12 File (java.io.File)11 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)11 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)11 InputStreamReader (java.io.InputStreamReader)10 URL (java.net.URL)10