<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package com.haulmont.cuba.core.sys.restapi;

import com.haulmont.chile.core.model.MetaClass;
import com.haulmont.chile.core.model.MetaProperty;
import com.haulmont.cuba.core.entity.BaseUuidEntity;
import com.haulmont.cuba.core.entity.Entity;
import com.haulmont.cuba.core.global.EntityLoadInfo;
import com.haulmont.cuba.core.global.MetadataHelper;
import com.haulmont.cuba.core.global.MetadataProvider;
import com.haulmont.cuba.core.global.UserSessionProvider;
import com.haulmont.cuba.security.entity.EntityAttrAccess;
import com.haulmont.cuba.security.entity.EntityOp;
import com.haulmont.cuba.security.global.UserSession;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import javax.activation.MimeType;
import javax.activation.MimeTypeParseException;
import javax.persistence.Id;
import javax.servlet.http.HttpServletResponse;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.util.*;

/**
 *
 * @version $Id$
 */
public class JSONConvertor implements Convertor {
    public static final String MIME_STR = "application/json;charset=UTF-8";
    public static final MimeType MIME_TYPE_JSON;

    static {
        try {
            MIME_TYPE_JSON = new MimeType(MIME_STR);
        } catch (MimeTypeParseException e) {
            throw new RuntimeException(e);
        }
    }

    public MimeType getMimeType() {
        return MIME_TYPE_JSON;
    }

    public MyJSONObject process(Entity entity, MetaClass metaclass, String requestURI)
            throws InvocationTargetException, NoSuchMethodException, IllegalAccessException {
        return encodeInstance(entity, new HashSet<Entity>(), metaclass);
    }

    public MyJSONObject.Array process(List<Entity> entities, MetaClass metaClass, String requestURI)
            throws InvocationTargetException, NoSuchMethodException, IllegalAccessException {
        MyJSONObject.Array result = new MyJSONObject.Array();
        for (Entity entity : entities) {
            MyJSON item = encodeInstance(entity, new HashSet<Entity>(), metaClass);
            result.add(item);
        }
        return result;
    }

    public MyJSONObject.Array process(Map<Entity, Entity> entityMap, String requestURI)
            throws InvocationTargetException, NoSuchMethodException, IllegalAccessException {
        MyJSONObject.Array result = new MyJSONObject.Array();
        for (Map.Entry<Entity, Entity> entry : entityMap.entrySet()) {
            Entity key = entry.getKey();
            Entity value = entry.getValue();
            MyJSONObject keyJson = encodeInstance(key, new HashSet<Entity>(), getMetaClass(key));
            MyJSONObject valueJson = encodeInstance(value, new HashSet<Entity>(), getMetaClass(value));

            MyJSONObject.Array mapping = new MyJSONObject.Array();
            mapping.add(keyJson);
            mapping.add(valueJson);
            result.add(mapping);
        }
        return result;
    }

    private MetaClass getMetaClass(Entity entity) {
        return MetadataProvider.getSession().getClass(entity.getClass());
    }

    public void write(HttpServletResponse response, Object o) {
        response.setContentType(MIME_STR);
        try {
            PrintWriter writer = response.getWriter();
            writer.write(o.toString());
            writer.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public CommitRequest parseCommitRequest(String content) {
        try {
            JSONObject jsonContent = new JSONObject(content);
            CommitRequest result = new CommitRequest();

            if (jsonContent.has("commitInstances")) {
                JSONArray entitiesNodeList = jsonContent.getJSONArray("commitInstances");
                result.setCommitInstances(parseIntoList(result, entitiesNodeList));
            }

            if (jsonContent.has("removeInstances")) {
                JSONArray entitiesNodeList = jsonContent.getJSONArray("removeInstances");
                result.setRemoveInstances(parseIntoList(result, entitiesNodeList));
            }

            if (jsonContent.has("softDeletion")) {
                result.setSoftDeletion(jsonContent.getBoolean("softDeletion"));
            }
            return result;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private List<BaseUuidEntity> parseIntoList(CommitRequest commitRequest, JSONArray nodeList)
            throws JSONException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, IntrospectionException, ParseException {
        List<BaseUuidEntity> result = new ArrayList<BaseUuidEntity>(nodeList.length());

        for (int j = 0; j < nodeList.length(); j++) {
            JSONObject jsonObject = nodeList.getJSONObject(j);
            InstanceRef ref = commitRequest.parseInstanceRefAndRegister(jsonObject.getString("id"));
            MetaClass metaClass = ref.getMetaClass();
            BaseUuidEntity instance = ref.getInstance();
            asJavaTree(commitRequest, instance, metaClass, jsonObject);
            result.add(instance);
        }
        return result;
    }

    private void asJavaTree(CommitRequest commitRequest, Object bean, MetaClass metaClass, JSONObject json)
            throws JSONException, InvocationTargetException, IllegalAccessException, NoSuchMethodException, InstantiationException, IntrospectionException, ParseException {
        Iterator iter = json.keys();
        while (iter.hasNext()) {
            String key = (String) iter.next();
            MetaProperty property = metaClass.getProperty(key);

            if (!attrModifyPermitted(metaClass, property.getName()))
                continue;

            if (json.get(key) == null) {
                setField(bean, key, new Object[]{null});
                continue;
            }

            if ("id".equals(key)) {
                // id was parsed already
                continue;
            }

            switch (property.getType()) {
                case DATATYPE:
                    setField(bean, key, property.getRange().<Object>asDatatype().parse(json.getString(key)));
                    break;
                case ENUM:
                    setField(bean, key, property.getRange().asEnumeration().parse(json.getString(key)));
                    break;
                case AGGREGATION:
                case ASSOCIATION:
                    MetaClass propertyMetaClass = propertyMetaClass(property);
                    //checks if the user permitted to read and update a property
                    if (!updatePermitted(propertyMetaClass) && !readPermitted(propertyMetaClass))
                        break;

                    if (!property.getRange().getCardinality().isMany()) {
                        JSONObject jsonChild = json.getJSONObject(key);
                        Object child;
                        MetaClass childMetaClass;

                        if (jsonChild.has("id")) {
                            InstanceRef ref = commitRequest.parseInstanceRefAndRegister(jsonChild.getString("id"));
                            childMetaClass = ref.getMetaClass();
                            child = ref.getInstance();<commit_msg>Fixed bug with "null" values in JSON object properties (REST Api). Now "null" text identified as null for all datatypes except StringDatatype.<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package com.haulmont.cuba.core.sys.restapi;

import com.haulmont.chile.core.datatypes.impl.StringDatatype;
import com.haulmont.chile.core.model.MetaClass;
import com.haulmont.chile.core.model.MetaProperty;
import com.haulmont.cuba.core.entity.BaseUuidEntity;
import com.haulmont.cuba.core.entity.Entity;
import com.haulmont.cuba.core.global.EntityLoadInfo;
import com.haulmont.cuba.core.global.MetadataHelper;
import com.haulmont.cuba.core.global.MetadataProvider;
import com.haulmont.cuba.core.global.UserSessionProvider;
import com.haulmont.cuba.security.entity.EntityAttrAccess;
import com.haulmont.cuba.security.entity.EntityOp;
import com.haulmont.cuba.security.global.UserSession;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import javax.activation.MimeType;
import javax.activation.MimeTypeParseException;
import javax.persistence.Id;
import javax.servlet.http.HttpServletResponse;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.util.*;

/**
 *
 * @version $Id$
 */
public class JSONConvertor implements Convertor {
    public static final String MIME_STR = "application/json;charset=UTF-8";
    public static final MimeType MIME_TYPE_JSON;

    static {
        try {
            MIME_TYPE_JSON = new MimeType(MIME_STR);
        } catch (MimeTypeParseException e) {
            throw new RuntimeException(e);
        }
    }

    public MimeType getMimeType() {
        return MIME_TYPE_JSON;
    }

    public MyJSONObject process(Entity entity, MetaClass metaclass, String requestURI)
            throws InvocationTargetException, NoSuchMethodException, IllegalAccessException {
        return encodeInstance(entity, new HashSet<Entity>(), metaclass);
    }

    public MyJSONObject.Array process(List<Entity> entities, MetaClass metaClass, String requestURI)
            throws InvocationTargetException, NoSuchMethodException, IllegalAccessException {
        MyJSONObject.Array result = new MyJSONObject.Array();
        for (Entity entity : entities) {
            MyJSON item = encodeInstance(entity, new HashSet<Entity>(), metaClass);
            result.add(item);
        }
        return result;
    }

    public MyJSONObject.Array process(Map<Entity, Entity> entityMap, String requestURI)
            throws InvocationTargetException, NoSuchMethodException, IllegalAccessException {
        MyJSONObject.Array result = new MyJSONObject.Array();
        for (Map.Entry<Entity, Entity> entry : entityMap.entrySet()) {
            Entity key = entry.getKey();
            Entity value = entry.getValue();
            MyJSONObject keyJson = encodeInstance(key, new HashSet<Entity>(), getMetaClass(key));
            MyJSONObject valueJson = encodeInstance(value, new HashSet<Entity>(), getMetaClass(value));

            MyJSONObject.Array mapping = new MyJSONObject.Array();
            mapping.add(keyJson);
            mapping.add(valueJson);
            result.add(mapping);
        }
        return result;
    }

    private MetaClass getMetaClass(Entity entity) {
        return MetadataProvider.getSession().getClass(entity.getClass());
    }

    public void write(HttpServletResponse response, Object o) {
        response.setContentType(MIME_STR);
        try {
            PrintWriter writer = response.getWriter();
            writer.write(o.toString());
            writer.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public CommitRequest parseCommitRequest(String content) {
        try {
            JSONObject jsonContent = new JSONObject(content);
            CommitRequest result = new CommitRequest();

            if (jsonContent.has("commitInstances")) {
                JSONArray entitiesNodeList = jsonContent.getJSONArray("commitInstances");
                result.setCommitInstances(parseIntoList(result, entitiesNodeList));
            }

            if (jsonContent.has("removeInstances")) {
                JSONArray entitiesNodeList = jsonContent.getJSONArray("removeInstances");
                result.setRemoveInstances(parseIntoList(result, entitiesNodeList));
            }

            if (jsonContent.has("softDeletion")) {
                result.setSoftDeletion(jsonContent.getBoolean("softDeletion"));
            }
            return result;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private List<BaseUuidEntity> parseIntoList(CommitRequest commitRequest, JSONArray nodeList)
            throws JSONException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, IntrospectionException, ParseException {
        List<BaseUuidEntity> result = new ArrayList<BaseUuidEntity>(nodeList.length());

        for (int j = 0; j < nodeList.length(); j++) {
            JSONObject jsonObject = nodeList.getJSONObject(j);
            InstanceRef ref = commitRequest.parseInstanceRefAndRegister(jsonObject.getString("id"));
            MetaClass metaClass = ref.getMetaClass();
            BaseUuidEntity instance = ref.getInstance();
            asJavaTree(commitRequest, instance, metaClass, jsonObject);
            result.add(instance);
        }
        return result;
    }

    private void asJavaTree(CommitRequest commitRequest, Object bean, MetaClass metaClass, JSONObject json)
            throws JSONException, InvocationTargetException, IllegalAccessException, NoSuchMethodException, InstantiationException, IntrospectionException, ParseException {
        Iterator iter = json.keys();
        while (iter.hasNext()) {
            String key = (String) iter.next();
            MetaProperty property = metaClass.getProperty(key);

            if (!attrModifyPermitted(metaClass, property.getName()))
                continue;

            if (json.get(key) == null) {
                setField(bean, key, new Object[]{null});
                continue;
            }

            if ("id".equals(key)) {
                // id was parsed already
                continue;
            }

            switch (property.getType()) {
                case DATATYPE:
                    String value = json.getString(key);
                    String typeName = property.getRange().asDatatype().getName();
                    if (!StringDatatype.NAME.equals(typeName))
                        if ("null".equals(value))
                            value = null;
                    setField(bean, key, property.getRange().<Object>asDatatype().parse(value));
                    break;
                case ENUM:
                    setField(bean, key, property.getRange().asEnumeration().parse(json.getString(key)));
                    break;
                case AGGREGATION:
                case ASSOCIATION:
                    MetaClass propertyMetaClass = propertyMetaClass(property);
                    //checks if the user permitted to read and update a property
                    if (!updatePermitted(propertyMetaClass) && !readPermitted(propertyMetaClass))
                        break;

                    if (!property.getRange().getCardinality().isMany()) {
                        JSONObject jsonChild = json.getJSONObject(key);
                        Object child;
                        MetaClass childMetaClass;

                        if (jsonChild.has("id")) {
                            InstanceRef ref = commitRequest.parseInstanceRefAndRegister(jsonChild.getString("id"));
                            childMetaClass = ref.getMetaClass();
                            child = ref.getInstance();
{'fraction_non_alphanumeric': 0.08981612446958982, 'fraction_numerical': 0.0007072135785007072, 'mean_word_length': 2.6127315307643175, 'pattern_counts': {'":': 0, '<': 27, '<?xml version=': 0, '>': 25, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6988676', 'n_tokens_mistral': 4288, 'n_tokens_neox': 4164, 'n_words': 1038}