<commit_before># -*- coding: utf-8 -*-
from plone.jsonserializer.interfaces import ISerializeToJson
from plone.jsonserializer.interfaces import IDeserializeFromJson
from plone.server.api.service import Service
from plone.server.registry import ICors
from plone.server.browser import get_physical_path
from zope.component import getMultiAdapter
from plone.server.browser import Response
from plone.server.browser import ErrorResponse
from plone.server.browser import UnauthorizedResponse
from plone.server.interfaces import IAbsoluteUrl
from plone.server import _
import fnmatch
from zope.security import checkPermission
from zope.security.interfaces import Unauthorized
from plone.dexterity.utils import createContent
from zope.component import queryMultiAdapter
import traceback
from datetime import datetime
import logging
from random import randint
from plone.jsonserializer.exceptions import DeserializationError


logger = logging.getLogger(__name__)


class DefaultGET(Service):
    async def __call__(self):
        serializer = getMultiAdapter(
            (self.context, self.request),
            ISerializeToJson)
        return serializer()


class DefaultPOST(Service):
    async def __call__(self):
        """To create a content. Its a copy of plone.restapi"""
        data = await self.request.json()
        type_ = data.get('@type', None)
        id_ = data.get('id', None)
        title = data.get('title', None)

        if not type_:
            return ErrorResponse(
                'RequiredParam',
                _("Property '@type' is required"))

        # Generate a temporary id if the id is not given
        if not id_:
            now = datetime.now()
            new_id = '{}.{}.{}{:04d}'.format(
                type_.lower().replace(' ', '_'),
                now.strftime('%Y-%m-%d'),
                str(now.millis())[7:],
                randint(0, 9999))
        else:
            new_id = id_

        # It already exists
        if new_id in self.context:
            return ErrorResponse(
                'Conflict',
                _("Id already exists"))

        # Create object
        try:
            obj = createContent(type_, id=new_id, title=title)
            self.context[new_id] = obj
        except ValueError as e:
            return ErrorResponse(
                'DeserializationError',
                str(e),
                status=400)

        # Update fields
        deserializer = queryMultiAdapter((obj, self.request),
                                         IDeserializeFromJson)
        if deserializer is None:
            return ErrorResponse(
                'DeserializationError',
                'Cannot deserialize type {}'.format(obj.portal_type),
                status=501)

        try:
            deserializer(data, validate_all=True)
        except DeserializationError as e:
            return ErrorResponse(
                'DeserializationError',
                str(e),
                status=400)

        # Rename if generated id<commit_msg>Call create Content in container to have security checks on restrictions and permissions to add the content<commit_after># -*- coding: utf-8 -*-
from plone.jsonserializer.interfaces import ISerializeToJson
from plone.jsonserializer.interfaces import IDeserializeFromJson
from plone.server.api.service import Service
from plone.server.registry import ICors
from plone.server.browser import get_physical_path
from zope.component import getMultiAdapter
from plone.server.browser import Response
from plone.server.browser import ErrorResponse
from plone.server.browser import UnauthorizedResponse
from plone.server.interfaces import IAbsoluteUrl
from plone.server import _
import fnmatch
from zope.security import checkPermission
from zope.security.interfaces import Unauthorized
from plone.dexterity.utils import createContentInContainer
from zope.component import queryMultiAdapter
import traceback
from datetime import datetime
import logging
from random import randint
from plone.jsonserializer.exceptions import DeserializationError
from plone.server.utils import get_authenticated_user_id


logger = logging.getLogger(__name__)


class DefaultGET(Service):
    async def __call__(self):
        serializer = getMultiAdapter(
            (self.context, self.request),
            ISerializeToJson)
        return serializer()


class DefaultPOST(Service):
    async def __call__(self):
        """To create a content. Its a copy of plone.restapi"""
        data = await self.request.json()
        type_ = data.get('@type', None)
        id_ = data.get('id', None)
        title = data.get('title', None)

        if not type_:
            return ErrorResponse(
                'RequiredParam',
                _("Property '@type' is required"))

        # Generate a temporary id if the id is not given
        if not id_:
            now = datetime.now()
            new_id = '{}.{}.{}{:04d}'.format(
                type_.lower().replace(' ', '_'),
                now.strftime('%Y-%m-%d'),
                str(now.millis())[7:],
                randint(0, 9999))
        else:
            new_id = id_

        # It already exists
        if new_id in self.context:
            return ErrorResponse(
                'Conflict',
                _("Id already exists"))

        user = get_authenticated_user_id(self.request)
        # Create object
        try:
            obj = createContentInContainer(
                self.context, type_, id=new_id, creators=(user,),
                contributors=(user,))
        except ValueError as e:
            return ErrorResponse(
                'CreatingObject',
                str(e),
                status=400)

        # Update fields
        deserializer = queryMultiAdapter((obj, self.request),
                                         IDeserializeFromJson)
        if deserializer is None:
            return ErrorResponse(
                'DeserializationError',
                'Cannot deserialize type {}'.format(obj.portal_type),
                status=501)

        try:
            deserializer(data, validate_all=True)
        except DeserializationError as e:
            return ErrorResponse(
                'DeserializationError',
                str(e),
                status=400)

        # Rename if generated id
{'fraction_non_alphanumeric': 0.0817102137767221, 'fraction_numerical': 0.005700712589073635, 'mean_word_length': 2.178661298439859, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '667052', 'n_tokens_mistral': 1659, 'n_tokens_neox': 1579, 'n_words': 464}