Search in sources :

Example 31 with ParseException

use of org.json.simple.parser.ParseException in project Brino by BrinoOficial.

the class BrppCompilerMain method main.

public static void main(String[] args) {
    BrppCompilerMain.init();
    final String[] getArgs = args;
    // cria o diretorio do Brino
    logger.log(Level.CONFIG, "Criando o diretorio do Brino");
    File dir = new File(FileUtils.getBrinodirectory());
    dir.mkdirs();
    // cria o diretorio do Brino
    logger.log(Level.CONFIG, "Criando o diretorio de bibliotecas do Brino");
    File libDir = new File(Paths.get(FileUtils.getBrinodirectory(), "bibliotecas").toAbsolutePath().toString());
    libDir.mkdirs();
    // salva o diretorio do brino
    logger.log(Level.INFO, "Path set to: " + currentRelativePath);
    setPath(currentRelativePath);
    try {
        logger.log(Level.CONFIG, "Configurando preferências");
        PrefManager.setPrefs();
        logger.log(Level.CONFIG, "Configurando lingua");
        JSONUtils.config(currentRelativePath);
        logger.log(Level.CONFIG, "Configurando bibliotecas");
        FileUtils.copyFolder(libDir, destDir);
        logger.log(Level.CONFIG, "Processando bibliotecas para highlight");
        KeywordManagerUtils.processLibraries();
        logger.log(Level.CONFIG, "Atualizando lingua");
        LanguageVersionUtils.updateLanguages();
        logger.log(Level.CONFIG, "Verificando versao");
        VersionUtils.checkVersion();
    } catch (FileNotFoundException fnfe) {
        logger.log(Level.SEVERE, "Erro ao configurar o programa! Arquivo não encontrado : \n", fnfe);
    } catch (UnknownHostException uhe) {
        logger.log(Level.CONFIG, "Nao ha internet. Nao foi possivel atualizar a lingua!\n", uhe);
    } catch (MalformedURLException mue) {
        logger.log(Level.SEVERE, "Erro ao acessar a URL da lingua!\n", mue);
    } catch (IOException ioe) {
        logger.log(Level.SEVERE, "Erro ao configurar o programa!\n", ioe);
    } catch (ParseException pe) {
        logger.log(Level.SEVERE, "Erro ao fazer o parse da lingua!\n", pe);
    } catch (NullPointerException npe) {
        logger.log(Level.SEVERE, "Erro ao mover bibliotecas!\n", npe);
    } catch (URISyntaxException e) {
        logger.log(Level.SEVERE, "Erro ao abrir página de downloads!\n", e);
    }
    SwingUtilities.invokeLater(new Runnable() {

        public void run() {
            frame = new BrppIDEFrame("Brino " + BrppCompiler.version);
            frame.setSize(500, 600);
            frame.setLocation(100, 30);
            logger.log(Level.CONFIG, "Inicializando frame");
            frame.setVisible(true);
            if (getArgs.length > 0) {
                String filePath = getArgs[0];
                FileUtils.abrirFile(filePath, BrppIDEFrame.getTextArea(), true);
            }
        }
    });
}
Also used : MalformedURLException(java.net.MalformedURLException) BrppIDEFrame(cc.brino.Brpp.IDEui.BrppIDEFrame) UnknownHostException(java.net.UnknownHostException) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) ParseException(org.json.simple.parser.ParseException) URISyntaxException(java.net.URISyntaxException) File(java.io.File)

Example 32 with ParseException

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

the class FFmpegAnalyzer method analyze.

@Override
public MediaContainerMetadata analyze(File media) throws MediaAnalyzerException {
    if (binary == null)
        throw new IllegalStateException("Binary is not set");
    List<String> command = new ArrayList<>();
    command.add("-show_format");
    command.add("-show_streams");
    if (accurateFrameCount)
        command.add("-count_frames");
    command.add("-of");
    command.add("json");
    command.add(media.getAbsolutePath().replaceAll(" ", "\\ "));
    String commandline = StringUtils.join(command, " ");
    /* Execute ffprobe and obtain the result */
    logger.debug("Running {} {}", binary, commandline);
    MediaContainerMetadata metadata = new MediaContainerMetadata();
    final StringBuilder sb = new StringBuilder();
    try {
        ProcessInfo info = ProcessRunner.mk(binary, command.toArray(new String[command.size()]));
        int exitCode = ProcessRunner.run(info, new Pred<String>() {

            @Override
            public Boolean apply(String s) {
                logger.debug(s);
                sb.append(s);
                sb.append(System.getProperty("line.separator"));
                return true;
            }
        }, fnLogError);
        // Windows binary will return -1 when queried for options
        if (exitCode != -1 && exitCode != 0 && exitCode != 255)
            throw new MediaAnalyzerException("Frame analyzer " + binary + " exited with code " + exitCode);
    } catch (IOException e) {
        logger.error("Error executing ffprobe: {}", ExceptionUtils.getStackTrace(e));
        throw new MediaAnalyzerException("Error while running ffprobe " + binary, e);
    }
    JSONParser parser = new JSONParser();
    try {
        JSONObject jsonObject = (JSONObject) parser.parse(sb.toString());
        Object obj;
        Double duration;
        /* Get format specific stuff */
        JSONObject jsonFormat = (JSONObject) jsonObject.get("format");
        /* File Name */
        obj = jsonFormat.get("filename");
        if (obj != null) {
            metadata.setFileName((String) obj);
        }
        /* Format */
        obj = jsonFormat.get("format_long_name");
        if (obj != null) {
            metadata.setFormat((String) obj);
        }
        /*
       * Mediainfo does not return a duration if there is no stream but FFprobe will return 0. For compatibility
       * reasons, check if there are any streams before reading the duration:
       */
        obj = jsonFormat.get("nb_streams");
        if (obj != null && (Long) obj > 0) {
            obj = jsonFormat.get("duration");
            if (obj != null) {
                duration = new Double((String) obj) * 1000;
                metadata.setDuration(duration.longValue());
            }
        }
        /* File Size */
        obj = jsonFormat.get("size");
        if (obj != null) {
            metadata.setSize(new Long((String) obj));
        }
        /* Bitrate */
        obj = jsonFormat.get("bit_rate");
        if (obj != null) {
            metadata.setBitRate(new Float((String) obj));
        }
        /* Loop through streams */
        /*
       * FFprobe will return an empty stream array if there are no streams. Thus we do not need to check.
       */
        JSONArray streams = (JSONArray) jsonObject.get("streams");
        Iterator<JSONObject> iterator = streams.iterator();
        while (iterator.hasNext()) {
            JSONObject stream = iterator.next();
            /* Check type of string */
            String codecType = (String) stream.get("codec_type");
            if ("audio".equals(codecType)) {
                /* Extract audio stream metadata */
                AudioStreamMetadata aMetadata = new AudioStreamMetadata();
                /* Codec */
                obj = stream.get("codec_long_name");
                if (obj != null) {
                    aMetadata.setFormat((String) obj);
                }
                /* Duration */
                obj = stream.get("duration");
                if (obj != null) {
                    duration = new Double((String) obj) * 1000;
                    aMetadata.setDuration(duration.longValue());
                } else {
                    /*
             * If no duration for this stream is specified assume the duration of the file for this as well.
             */
                    aMetadata.setDuration(metadata.getDuration());
                }
                /* Bitrate */
                obj = stream.get("bit_rate");
                if (obj != null) {
                    aMetadata.setBitRate(new Float((String) obj));
                }
                /* Channels */
                obj = stream.get("channels");
                if (obj != null) {
                    aMetadata.setChannels(((Long) obj).intValue());
                }
                /* Sample Rate */
                obj = stream.get("sample_rate");
                if (obj != null) {
                    aMetadata.setSamplingRate(Integer.parseInt((String) obj));
                }
                /* Frame Count */
                obj = stream.get("nb_read_frames");
                if (obj != null) {
                    aMetadata.setFrames(Long.parseLong((String) obj));
                } else {
                    /* alternate JSON element if accurate frame count is not requested from ffmpeg */
                    obj = stream.get("nb_frames");
                    if (obj != null) {
                        aMetadata.setFrames(Long.parseLong((String) obj));
                    }
                }
                /* Add video stream metadata to overall metadata */
                metadata.getAudioStreamMetadata().add(aMetadata);
            /* Handle video streams ----------------------------- */
            } else if ("video".equals(codecType)) {
                /* Extract video stream metadata */
                VideoStreamMetadata vMetadata = new VideoStreamMetadata();
                /* Codec */
                obj = stream.get("codec_long_name");
                if (obj != null) {
                    vMetadata.setFormat((String) obj);
                }
                /* Duration */
                obj = stream.get("duration");
                if (obj != null) {
                    duration = new Double((String) obj) * 1000;
                    vMetadata.setDuration(duration.longValue());
                } else {
                    /*
             * If no duration for this stream is specified assume the duration of the file for this as well.
             */
                    vMetadata.setDuration(metadata.getDuration());
                }
                /* Bitrate */
                obj = stream.get("bit_rate");
                if (obj != null) {
                    vMetadata.setBitRate(new Float((String) obj));
                }
                /* Width */
                obj = stream.get("width");
                if (obj != null) {
                    vMetadata.setFrameWidth(((Long) obj).intValue());
                }
                /* Height */
                obj = stream.get("height");
                if (obj != null) {
                    vMetadata.setFrameHeight(((Long) obj).intValue());
                }
                /* Profile */
                obj = stream.get("profile");
                if (obj != null) {
                    vMetadata.setFormatProfile((String) obj);
                }
                /* Aspect Ratio */
                obj = stream.get("sample_aspect_ratio");
                if (obj != null) {
                    vMetadata.setPixelAspectRatio(parseFloat((String) obj));
                }
                /* Frame Rate */
                obj = stream.get("avg_frame_rate");
                if (obj != null) {
                    vMetadata.setFrameRate(parseFloat((String) obj));
                }
                /* Frame Count */
                obj = stream.get("nb_read_frames");
                if (obj != null) {
                    vMetadata.setFrames(Long.parseLong((String) obj));
                } else {
                    /* alternate JSON element if accurate frame count is not requested from ffmpeg */
                    obj = stream.get("nb_frames");
                    if (obj != null) {
                        vMetadata.setFrames(Long.parseLong((String) obj));
                    }
                }
                /* Add video stream metadata to overall metadata */
                metadata.getVideoStreamMetadata().add(vMetadata);
            }
        }
    } catch (ParseException e) {
        logger.error("Error parsing ffprobe output: {}", e.getMessage());
    }
    return metadata;
}
Also used : MediaContainerMetadata(org.opencastproject.inspection.ffmpeg.api.MediaContainerMetadata) ArrayList(java.util.ArrayList) JSONArray(org.json.simple.JSONArray) ProcessInfo(org.opencastproject.util.ProcessRunner.ProcessInfo) IOException(java.io.IOException) VideoStreamMetadata(org.opencastproject.inspection.ffmpeg.api.VideoStreamMetadata) JSONObject(org.json.simple.JSONObject) MediaAnalyzerException(org.opencastproject.inspection.ffmpeg.api.MediaAnalyzerException) AudioStreamMetadata(org.opencastproject.inspection.ffmpeg.api.AudioStreamMetadata) JSONParser(org.json.simple.parser.JSONParser) JSONObject(org.json.simple.JSONObject) ParseException(org.json.simple.parser.ParseException)

Example 33 with ParseException

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

the class MetadataList method fromJSON.

private void fromJSON(MetadataCollection 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;
    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));
    }
}
Also used : MetadataParsingException(org.opencastproject.metadata.dublincore.MetadataParsingException) JSONObject(org.json.simple.JSONObject) JSONArray(org.json.simple.JSONArray) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException)

Example 34 with ParseException

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

the class EventHttpServletRequest 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.
 * @param startDatePattern
 *          The pattern to use to parse the start date from the json payload.
 * @param startTimePattern
 *          The pattern to use to parse the start time from the json payload.
 * @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 static MetadataList deserializeMetadataList(String json, List<EventCatalogUIAdapter> catalogAdapters, Opt<String> startDatePattern, Opt<String> startTimePattern) throws ParseException, NotFoundException, java.text.ParseException {
    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 event 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;
        EventCatalogUIAdapter adapter = null;
        for (EventCatalogUIAdapter eventCatalogUIAdapter : catalogAdapters) {
            if (eventCatalogUIAdapter.getFlavor().equals(flavor)) {
                adapter = eventCatalogUIAdapter;
                collection = eventCatalogUIAdapter.getRawFields();
            }
        }
        if (collection == null) {
            throw new IllegalArgumentException(String.format("Unable to find an EventCatalogUIAdapter 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)) {
                    // Handle the special case of allowing subjects to be an array.
                    MetadataField<?> field = collection.getOutputFields().get(DublinCore.PROPERTY_SUBJECT.getLocalName());
                    if (field == null) {
                        throw new NotFoundException(String.format("Cannot find a metadata field with id 'subject' from Catalog with Flavor '%s'.", 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 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);
                    if (field == null) {
                        throw new NotFoundException(String.format("Cannot find a metadata field with id '%s' from Catalog with Flavor '%s'.", key, flavorString));
                    }
                    SimpleDateFormat apiSdf = MetadataField.getSimpleDateFormatter(startDatePattern.getOr(field.getPattern().get()));
                    SimpleDateFormat sdf = MetadataField.getSimpleDateFormatter(field.getPattern().get());
                    DateTime newStartDate = new DateTime(apiSdf.parse(fields.get(key)), DateTimeZone.UTC);
                    if (field.getValue().isSome()) {
                        DateTime oldStartDate = new DateTime(sdf.parse(field.getValue().get()), DateTimeZone.UTC);
                        newStartDate = oldStartDate.withDate(newStartDate.year().get(), newStartDate.monthOfYear().get(), newStartDate.dayOfMonth().get());
                    }
                    collection.removeField(field);
                    collection.addField(MetadataField.copyMetadataFieldWithValue(field, sdf.format(newStartDate.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");
                    if (field == null) {
                        throw new NotFoundException(String.format("Cannot find a metadata field with id '%s' from Catalog with Flavor '%s'.", "startDate", flavorString));
                    }
                    SimpleDateFormat apiSdf = MetadataField.getSimpleDateFormatter(startTimePattern.getOr("HH:mm"));
                    SimpleDateFormat sdf = MetadataField.getSimpleDateFormatter(field.getPattern().get());
                    DateTime newStartDate = new DateTime(apiSdf.parse(fields.get(key)), DateTimeZone.UTC);
                    if (field.getValue().isSome()) {
                        DateTime oldStartDate = new DateTime(sdf.parse(field.getValue().get()), DateTimeZone.UTC);
                        newStartDate = oldStartDate.withTime(newStartDate.hourOfDay().get(), newStartDate.minuteOfHour().get(), newStartDate.secondOfMinute().get(), newStartDate.millisOfSecond().get());
                    }
                    collection.removeField(field);
                    collection.addField(MetadataField.copyMetadataFieldWithValue(field, sdf.format(newStartDate.toDate())));
                } 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);
    }
    setStartDateAndTimeIfUnset(metadataList);
    return metadataList;
}
Also used : JSONArray(org.json.simple.JSONArray) NotFoundException(org.opencastproject.util.NotFoundException) MediaPackageElementFlavor(org.opencastproject.mediapackage.MediaPackageElementFlavor) MetadataField(org.opencastproject.metadata.dublincore.MetadataField) DateTime(org.joda.time.DateTime) MetadataList(org.opencastproject.index.service.catalog.adapter.MetadataList) JSONObject(org.json.simple.JSONObject) EventCatalogUIAdapter(org.opencastproject.metadata.dublincore.EventCatalogUIAdapter) JSONParser(org.json.simple.parser.JSONParser) MetadataCollection(org.opencastproject.metadata.dublincore.MetadataCollection) ParseException(org.json.simple.parser.ParseException) SimpleDateFormat(java.text.SimpleDateFormat)

Example 35 with ParseException

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

the class EventHttpServletRequest method setFormField.

/**
 * Set a value for creating a new event from a form field.
 *
 * @param eventCatalogUIAdapters
 *          The list of event catalog ui adapters used for loading the metadata for the new event.
 * @param eventHttpServletRequest
 *          The current details of the request that have been loaded.
 * @param item
 *          The content of the field.
 * @param fieldName
 *          The key of the field.
 * @param startDatePattern
 *          The pattern to use to parse the start date from the request.
 * @param startTimePattern
 *          The pattern to use to parse the start time from the request.
 * @throws IOException
 *           Thrown if unable to laod the content of the field.
 * @throws NotFoundException
 *           Thrown if unable to find a metadata catalog or field that matches an input catalog or field.
 */
private static void setFormField(List<EventCatalogUIAdapter> eventCatalogUIAdapters, EventHttpServletRequest eventHttpServletRequest, FileItemStream item, String fieldName, Opt<String> startDatePattern, Opt<String> startTimePattern) throws IOException, NotFoundException {
    if (METADATA_JSON_KEY.equals(fieldName)) {
        String metadata = Streams.asString(item.openStream());
        try {
            MetadataList metadataList = deserializeMetadataList(metadata, eventCatalogUIAdapters, startDatePattern, startTimePattern);
            eventHttpServletRequest.setMetadataList(metadataList);
        } catch (IllegalArgumentException e) {
            throw e;
        } catch (ParseException e) {
            throw new IllegalArgumentException(String.format("Unable to parse event metadata because: '%s'", e.toString()));
        } catch (NotFoundException e) {
            throw e;
        } catch (java.text.ParseException e) {
            throw new IllegalArgumentException(String.format("Unable to parse event metadata because: '%s'", e.toString()));
        }
    } else if ("acl".equals(item.getFieldName())) {
        String access = Streams.asString(item.openStream());
        try {
            AccessControlList acl = deserializeJsonToAcl(access, true);
            eventHttpServletRequest.setAcl(acl);
        } catch (Exception e) {
            logger.warn("Unable to parse acl {}", access);
            throw new IllegalArgumentException("Unable to parse acl");
        }
    } else if ("processing".equals(item.getFieldName())) {
        String processing = Streams.asString(item.openStream());
        JSONParser parser = new JSONParser();
        try {
            eventHttpServletRequest.setProcessing((JSONObject) parser.parse(processing));
        } catch (Exception e) {
            logger.warn("Unable to parse processing configuration {}", processing);
            throw new IllegalArgumentException("Unable to parse processing configuration");
        }
    }
}
Also used : MetadataList(org.opencastproject.index.service.catalog.adapter.MetadataList) AccessControlList(org.opencastproject.security.api.AccessControlList) NotFoundException(org.opencastproject.util.NotFoundException) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException) ParseException(org.json.simple.parser.ParseException) NotFoundException(org.opencastproject.util.NotFoundException) IOException(java.io.IOException) MediaPackageException(org.opencastproject.mediapackage.MediaPackageException) IngestException(org.opencastproject.ingest.api.IngestException) IndexServiceException(org.opencastproject.index.service.exception.IndexServiceException) FileUploadException(org.apache.commons.fileupload.FileUploadException)

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