001    /**
002     * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.json;
016    
017    import com.fasterxml.jackson.databind.JsonNode;
018    
019    import com.github.fge.jackson.JsonLoader;
020    import com.github.fge.jsonschema.core.report.ProcessingReport;
021    import com.github.fge.jsonschema.main.JsonSchema;
022    import com.github.fge.jsonschema.main.JsonSchemaFactory;
023    
024    import com.liferay.portal.kernel.json.JSONException;
025    import com.liferay.portal.kernel.json.JSONValidator;
026    
027    /**
028     * @author Pablo Carvalho
029     */
030    public class JSONValidatorImpl implements JSONValidator {
031    
032            public JSONValidatorImpl(String json) throws JSONException {
033                    try {
034                            JsonSchemaFactory jsonSchemaFactory = JsonSchemaFactory.byDefault();
035    
036                            JsonNode jsonNode = JsonLoader.fromString(json);
037    
038                            _jsonSchema = jsonSchemaFactory.getJsonSchema(jsonNode);
039                    }
040                    catch (Exception e) {
041                            throw new JSONException(e);
042                    }
043            }
044    
045            @Override
046            public boolean isValid(String json) throws JSONException {
047                    try {
048                            JsonNode jsonNode = JsonLoader.fromString(json);
049    
050                            ProcessingReport processingReport = _jsonSchema.validate(jsonNode);
051    
052                            return processingReport.isSuccess();
053                    }
054                    catch (Exception e) {
055                            throw new JSONException(e);
056                    }
057            }
058    
059            private final JsonSchema _jsonSchema;
060    
061    }