コード例 #1
0
    def process(self, request, to_ws_id):

        to_ws = get_object_or_404(Workspace, id=to_ws_id)
        if not request.user.is_superuser and to_ws.creator != request.user:
            return build_error_response(request, 403, _('You are not allowed to update this workspace'))

        data = parse_json_request(request)

        mashup_id = data.get('mashup', '')
        workspace_id = data.get('workspace', '')

        if mashup_id == '' and workspace_id == '':
            return build_error_response(request, 422, _('Missing workspace or mashup parameter'))
        elif mashup_id != '' and workspace_id != '':
            return build_error_response(request, 422, _('Workspace and mashup parameters cannot be used at the same time'))

        if mashup_id != '':
            values = mashup_id.split('/', 3)
            if len(values) != 3:
                return build_error_response(request, 422, _('invalid mashup id'))

            (mashup_vendor, mashup_name, mashup_version) = values
            try:
                resource = CatalogueResource.objects.get(vendor=mashup_vendor, short_name=mashup_name, version=mashup_version)
                if not resource.is_available_for(request.user) or resource.resource_type() != 'mashup':
                    raise CatalogueResource.DoesNotExist
            except CatalogueResource.DoesNotExist:
                return build_error_response(request, 422, _('Mashup not found: %(mashup_id)s') % {'mashup_id': mashup_id})

            base_dir = catalogue.wgt_deployer.get_base_dir(mashup_vendor, mashup_name, mashup_version)
            wgt_file = WgtFile(os.path.join(base_dir, resource.template_uri))
            template = TemplateParser(wgt_file.get_template())

        else:

            from_ws = get_object_or_404(Workspace, id=workspace_id)
            if not request.user.is_superuser and from_ws.creator != request.user:
                return build_error_response(request, 403, _('You are not allowed to read from workspace %s') % workspace_id)

            options = {
                'vendor': 'api',
                'name': 'merge_op',
                'version': '1.0',
                'title': '',
                'description': 'Temporal mashup for merging operation',
                'email': '*****@*****.**',
            }

            template = TemplateParser(build_json_template_from_workspace(options, from_ws, from_ws.creator))

        try:
            check_mashup_dependencies(template, request.user)
        except MissingDependencies as e:
            details = {
                'missingDependencies': e.missing_dependencies,
            }
            return build_error_response(request, 422, e, details=details)

        fillWorkspaceUsingTemplate(to_ws, template)
        return HttpResponse(status=204)
コード例 #2
0
ファイル: views.py プロジェクト: yasuhi526/wirecloud
def undeploy_tenant_ac(request):

    result = _parse_ac_request(request)
    if isinstance(result, HttpResponse):
        return result

    id_4CaaSt, wgt_file, fileURL = result

    # Process 4CaaSt Id
    username = parse_username(id_4CaaSt)

    user = get_object_or_404(User, username=username)
    try:
        if user.tenantprofile_4CaaSt.id_4CaaSt != id_4CaaSt:
            raise Http404
    except TenantProfile.DoesNotExist:
        raise Http404

    # If the resource is a mashup, remove the assigned workspace
    template = TemplateParser(wgt_file.get_template())
    if template.get_resource_type() == 'mashup':
        Workspace.objects.filter(
            creator=user, name=template.get_resource_info()['title']).delete()

    # Uninstall de resource
    template = TemplateParser(wgt_file.get_template())
    resource = CatalogueResource.objects.get(
        vendor=template.get_resource_vendor(),
        short_name=template.get_resource_name(),
        version=template.get_resource_version())
    resource.users.remove(user)

    return HttpResponse(status=204)
コード例 #3
0
    def test_fix_dev_version(self):

        wgt_file = self.build_simple_wgt('template11.xml',
                                         b'code',
                                         other_files=('doc/index.html', ))
        original_template = wgt_file.get_template()
        original_version = TemplateParser(
            original_template).get_resource_info()['version']

        fix_dev_version(wgt_file, self.user)
        new_version = TemplateParser(
            wgt_file.get_template()).get_resource_info()['version']

        self.assertNotEqual(original_template, wgt_file.get_template())
        self.assertEqual(original_version + self.user.username, new_version)
コード例 #4
0
def check_packaged_resource(wgt_file, resource_info=None):

    if resource_info is None:
        template_contents = wgt_file.get_template()
        template = TemplateParser(template_contents)
        resource_info = template.get_resource_info()

    if resource_info['type'] == 'widget':
        code_url = resource_info['contents']['src']
        if not code_url.startswith(('http://', 'https://')):

            try:
                code = wgt_file.read(code_url)
            except KeyError:
                msg = _('Missing contents file: %(file_name)s.')
                raise InvalidContents(msg % {'file_name': code_url})

            try:
                code.decode(resource_info['contents']['charset'])
            except UnicodeDecodeError:
                msg = _(
                    '%(file_name)s was not encoded using the specified charset (%(charset)s according to the widget descriptor file).'
                )
                raise InvalidContents(
                    msg % {
                        'file_name': code_url,
                        'charset': resource_info['contents']['charset']
                    })

    check_invalid_doc_content(wgt_file, resource_info, 'longdescription')
    check_invalid_doc_content(wgt_file, resource_info, 'doc')
    check_invalid_doc_content(wgt_file, resource_info, 'changelog')
    check_invalid_embedded_resources(wgt_file, resource_info)
コード例 #5
0
def buildWorkspaceFromTemplate(template,
                               user,
                               allow_renaming=False,
                               new_name=None):

    if not isinstance(template, TemplateParser):
        template = TemplateParser(template)

    if template.get_resource_type() != 'mashup':
        raise TypeError('Unsupported resource type: %s' %
                        template.get_resource_type())

    if new_name is not None:
        name = new_name
    else:
        name = template.get_resource_processed_info(
            process_urls=False)['title']

    # Workspace creation
    workspace = Workspace(name=name, creator=user)
    if allow_renaming:
        save_alternative(Workspace, 'name', workspace)
    else:
        workspace.save()

    # Adding user reference to workspace in the many to many relationship
    user_workspace = UserWorkspace(user=user,
                                   workspace=workspace,
                                   active=False)
    user_workspace.save()

    fillWorkspaceUsingTemplate(workspace, template)

    return (workspace, user_workspace)
コード例 #6
0
    def test_basic_operator_creation_from_rdf(self):
        template = self.read_file('operatorTemplate1.rdf')
        parser = TemplateParser(template)
        data = parser.get_resource_info()

        self.assertEqual(data['vendor'], 'Wirecloud')
        self.assertEqual(data['name'], 'test operator')
        self.assertEqual(data['type'], 'operator')
        self.assertEqual(data['version'], '0.1')
        self.assertEqual(data['email'], '*****@*****.**')
        self.assertEqual(data['wiring']['inputs'][0]['label'], 'slot')
        self.assertEqual(data['wiring']['inputs'][0]['type'], 'text')
        self.assertEqual(data['wiring']['inputs'][0]['friendcode'],
                         'test_friend_code')
        self.assertEqual(data['wiring']['outputs'][0]['label'], 'event')
        self.assertEqual(data['wiring']['outputs'][0]['type'], 'text')
        self.assertEqual(data['wiring']['outputs'][0]['friendcode'],
                         'test_friend_code')
        self.assertEqual(data['preferences'][0]['label'], 'Preference label')
        self.assertEqual(data['preferences'][0]['description'],
                         'Preference description')
        self.assertEqual(data['preferences'][0]['default'], 'value')
        self.assertEqual(len(data['js_files']), 5)

        self.assertEqual(data['js_files'][0], '/examplecode1.js')
        self.assertEqual(data['js_files'][1], '/examplecode2.js')
        self.assertEqual(data['js_files'][2], '/examplecode3.js')
        self.assertEqual(data['js_files'][3], '/examplecode4.js')
        self.assertEqual(data['js_files'][4], '/examplecode5.js')
コード例 #7
0
def install_resource(wgt_file, executor_user):

    if not isinstance(wgt_file, WgtFile):
        raise TypeError('wgt_file must be a WgtFile')

    file_contents = wgt_file.get_underlying_file()
    template_contents = wgt_file.get_template()

    template = TemplateParser(template_contents)
    resources = CatalogueResource.objects.filter(
        vendor=template.get_resource_vendor(),
        short_name=template.get_resource_name(),
        version=template.get_resource_version())[:1]

    # Create/recreate/recover catalogue resource
    if '-dev' in template.get_resource_version() and len(resources) == 1:
        # TODO: Update widget visually
        resources[0].delete()
        resource = add_packaged_resource(file_contents,
                                         executor_user,
                                         wgt_file=wgt_file)
    elif len(resources) == 1:
        resource = resources[0]
    else:
        resource = add_packaged_resource(file_contents,
                                         executor_user,
                                         wgt_file=wgt_file)

    return resource
コード例 #8
0
def buildWorkspaceFromTemplate(template, user, allow_renaming=False, new_name=None, new_title=None, searchable=True, public=False):

    if not isinstance(template, TemplateParser):
        template = TemplateParser(template)

    if template.get_resource_type() != 'mashup':
        raise TypeError('Unsupported resource type: %s' % template.get_resource_type())

    if (new_name is None or new_name.strip() == '') and (new_title is None or new_title.strip() == ''):
        processed_info = template.get_resource_processed_info(process_urls=False)
        new_name = processed_info['name']
        new_title = processed_info['title']
    elif new_title is None or new_title.strip() == '':
        new_title = new_name
    elif new_name is None or new_name.strip() == '':
        new_name = URLify(new_title)

    # Workspace creation
    workspace = Workspace(title=new_title, name=new_name, creator=user, searchable=searchable, public=public)
    if allow_renaming:
        save_alternative(Workspace, 'name', workspace)
    else:
        workspace.save()

    # Adding user reference to workspace in the many to many relationship
    user_workspace = UserWorkspace(user=user, workspace=workspace)
    user_workspace.save()

    fillWorkspaceUsingTemplate(workspace, template)

    return (workspace, user_workspace)
コード例 #9
0
ファイル: views.py プロジェクト: yasuhi526/wirecloud
def _parse_ac_request(request):

    fileURL = None
    file_contents = None
    content_type = get_content_type(request)[0]

    data = parse_json_request(request)

    if 'url' not in data:
        return build_error_response(request, 400, _('Missing widget URL'))

    fileURL = data.get('url')
    id_4CaaSt = data.get('4CaaStID')

    if id_4CaaSt is None:
        return build_error_response(request, 400, _('Missing 4CaaStID'))

    if not isinstance(id_4CaaSt, string_types) or id_4CaaSt.strip() == '':
        return build_error_response(request, 400, _('Invalid 4CaaStID'))

    try:
        downloaded_file = download_http_content(fileURL)
    except:
        return build_error_response(
            request, 409,
            _('Mashable application component could not be downloaded'))

    downloaded_file = StringIO(downloaded_file)
    file_contents = WgtFile(downloaded_file)

    # Create a custom version of the resource
    template = TemplateParser(file_contents.get_template())
    template_info = template.get_resource_info()
    template_info['name'] += '@' + id_4CaaSt

    for pref_name, pref_value in six.iteritems(data.get('preferences', {})):
        for widget_pref_index, widget_pref in enumerate(
                template_info['preferences']):
            if widget_pref['name'] == pref_name:
                template_info['preferences'][widget_pref_index][
                    'readonly'] = True
                template_info['preferences'][widget_pref_index][
                    'value'] = pref_value
                break

    # Write a new Wgt file
    new_file = StringIO()
    zin = zipfile.ZipFile(downloaded_file, 'r')
    zout = zipfile.ZipFile(new_file, 'w')
    zout.writestr('config.xml', write_rdf_description(template_info))
    for item in zin.infolist():
        if item.filename == 'config.xml':
            continue
        zout.writestr(item, zin.read(item.filename))
    zin.close()
    zout.close()

    file_contents = WgtFile(new_file)

    return id_4CaaSt, file_contents, fileURL
コード例 #10
0
def install_resource(wgt_file, executor_user, restricted=False):

    if not isinstance(wgt_file, WgtFile):
        raise TypeError('wgt_file must be a WgtFile')

    file_contents = wgt_file.get_underlying_file()
    template_contents = wgt_file.get_template()

    template = TemplateParser(template_contents)
    resource_version = template.get_resource_version()
    if restricted:
        if '-dev' in resource_version:
            raise PermissionDenied("dev versions cannot be published")
        vendor = template.get_resource_vendor()
        if check_vendor_permissions(executor_user, vendor) is False:
            raise PermissionDenied("You don't have persmissions to publish in name of {}".format(vendor))

    resources = CatalogueResource.objects.filter(vendor=template.get_resource_vendor(), short_name=template.get_resource_name(), version=template.get_resource_version())[:1]

    # Create/recreate/recover catalogue resource
    if '-dev' in resource_version and len(resources) == 1:
        # dev version are automatically overwritten
        resources[0].delete()
        resource = add_packaged_resource(file_contents, executor_user, wgt_file=wgt_file)
    elif len(resources) == 1:
        resource = resources[0]
    else:
        resource = add_packaged_resource(file_contents, executor_user, wgt_file=wgt_file)

    return resource
コード例 #11
0
def add_packaged_resource(file,
                          user,
                          wgt_file=None,
                          template=None,
                          deploy_only=False):

    close_wgt = False
    if wgt_file is None:
        wgt_file = WgtFile(file)
        close_wgt = True

    if template is None:
        template_contents = wgt_file.get_template()
        template = TemplateParser(template_contents)

    resource_info = template.get_resource_info()

    resource_id = (
        resource_info['vendor'],
        resource_info['name'],
        resource_info['version'],
    )
    file_name = '_'.join(resource_id) + '.wgt'

    check_packaged_resource(wgt_file, resource_info)

    local_dir = wgt_deployer.get_base_dir(*resource_id)
    local_wgt = os.path.join(local_dir, file_name)

    if not os.path.exists(local_dir):
        os.makedirs(local_dir)

    overrides = extract_resource_media_from_package(template, wgt_file,
                                                    local_dir)
    if close_wgt:
        wgt_file.close()

    f = open(local_wgt, "wb")
    file.seek(0)
    f.write(file.read())
    f.close()

    if not deploy_only:
        resource_info.update(overrides)

        resource = CatalogueResource.objects.create(
            short_name=resource_info['name'],
            vendor=resource_info['vendor'],
            version=resource_info['version'],
            type=CatalogueResource.RESOURCE_TYPES.index(resource_info['type']),
            creator=user,
            template_uri=file_name,
            creation_date=now(),
            popularity='0.0',
            json_description=json.dumps(resource_info))

        return resource
コード例 #12
0
    def publish(self, endpoint, wgt_file, user, request=None, template=None):

        if template is None:
            template = TemplateParser(wgt_file.get_template())

        resource_info = template.get_resource_processed_info(lang='en')

        mimetypes = {
            'widget': 'application/x-widget+mashable-application-component',
            'operator':
            'application/x-operator+mashable-application-component',
            'mashup': 'application/x-mashup+mashable-application-component',
        }

        store = endpoint['store']
        adaptor = get_market_adaptor(self._user, self._name)
        user_data = get_market_user_data(user, self._user, self._name)
        storeclient = adaptor.get_store(store)

        store_token_key = store + '/token'
        if store_token_key in user_data:
            token = user_data[store_token_key]
        else:
            token = user_data['idm_token']

        wirecloud_plugin_supported = False
        try:
            supported_plugins = storeclient.get_supported_plugins(token)
            for plugin in supported_plugins:
                if plugin.get('name', '').lower() == 'wirecloud component':
                    wirecloud_plugin_supported = True
        except UnexpectedResponse as e:
            if e.status != 404:
                raise e

        if wirecloud_plugin_supported:
            storeclient.upload_resource(
                resource_info['title'],
                resource_info['version'],
                "_".join((resource_info['vendor'], resource_info['name'],
                          resource_info['version'])) + '.wgt',
                resource_info['description'],
                "Mashable application component",
                wgt_file.get_underlying_file(),
                token,
                resource_type="Wirecloud component")
        else:
            storeclient.upload_resource(
                resource_info['title'], resource_info['version'], "_".join(
                    (resource_info['vendor'], resource_info['name'],
                     resource_info['version'])) + '.wgt',
                resource_info['description'], mimetypes[resource_info['type']],
                wgt_file.get_underlying_file(), token)
コード例 #13
0
    def publish(self, endpoint, wgt_file, user, request=None, template=None):

        if self._name == 'local':

            if template is None:
                template = TemplateParser(wgt_file.get_template())

            added, resource = install_resource_to_user(user, file_contents=wgt_file, packaged=True, raise_conflicts=True)
            if not added:
                raise Exception(_('Resource already exists %(resource_id)s') % {'resource_id': resource.local_uri_part})

            return resource
        else:
            raise Exception('TODO')
コード例 #14
0
ファイル: utils.py プロジェクト: ngpJason/wirecloud
def update_resource_catalogue_cache(orm=None):

    if orm is not None:
        resources = orm.CatalogueResource.objects.all()
    else:
        resources = CatalogueResource.objects.all()

    resources_to_remove = []
    for resource in resources:

        try:

            if getattr(resource, 'fromWGT', True):
                base_dir = wgt_deployer.get_base_dir(resource.vendor,
                                                     resource.short_name,
                                                     resource.version)
                wgt_file = WgtFile(
                    os.path.join(base_dir, resource.template_uri))
                template = wgt_file.get_template()
                wgt_file.close()
            else:
                # fromWGT attribute support was removed from Wirecloud in version 0.7.0
                template = download_http_content(resource.template_uri)

            template_parser = TemplateParser(template)
            resource.json_description = json.dumps(
                template_parser.get_resource_info())
            resource.save()

        except (IOError, TemplateParseException) as e:

            if isinstance(e, IOError) and e.errno != errno.ENOENT:
                raise e

            resources_to_remove.append(resource)

    if len(resources_to_remove) > 0 and getattr(
            settings, 'WIRECLOUD_REMOVE_UNSUPPORTED_RESOURCES_MIGRATION',
            False) is False:
        raise Exception(
            'There are some mashable application components that are not supported anymore (use WIRECLOUD_REMOVE_UNSUPPORTED_RESOURCES_MIGRATION for removing automatically them in the migration process'
        )

    for resource in resources_to_remove:
        print('    Removing %s' %
              (resource.vendor + '/' + resource.short_name + '/' +
               resource.version))
        resource.delete()
コード例 #15
0
    def publish(self, endpoint, wgt_file, user, request=None, template=None):

        if self._name == 'local':

            if template is None:
                template = TemplateParser(wgt_file.get_template())

            added, resource = install_component(wgt_file, users=[user])
            if not added:
                raise Exception(
                    _('Resource already exists %(resource_id)s') %
                    {'resource_id': resource.local_uri_part})

            return resource
        else:
            raise Exception('TODO')
コード例 #16
0
def fix_dev_version(wgt_file, user):

    template_contents = wgt_file.get_template()
    template = TemplateParser(template_contents)

    resource_info = template.get_resource_info()

    # Add user name to the version if the component is in development
    if '-dev' in resource_info['version']:

        # User name added this way to prevent users to upload a version
        # *.*-devAnotherUser that would be accepted but might collide with
        # AnotherUser's development version
        resource_info['version'] = re.sub('-dev.*$', '-dev' + user.username, resource_info['version'])
        template_string = write_json_description(resource_info)
        wgt_file.update_config(template_string)
コード例 #17
0
ファイル: wgt.py プロジェクト: ngpJason/wirecloud
    def deploy(self, wgt_file):

        template_content = wgt_file.get_template()
        template_parser = TemplateParser(template_content)

        widget_rel_dir = os.path.join(
            template_parser.get_resource_vendor(),
            template_parser.get_resource_name(),
            template_parser.get_resource_version(),
        )
        widget_dir = os.path.join(self._root_dir, widget_rel_dir)
        template_parser.set_base(pathname2url(widget_rel_dir) + '/')

        self._create_folders(widget_dir)
        wgt_file.extract(widget_dir)

        return template_parser
コード例 #18
0
def fillWorkspaceUsingTemplate(workspace, template):

    if not isinstance(template, TemplateParser):
        template = TemplateParser(template)

    if template.get_resource_type() != 'mashup':
        raise TypeError('Unsupported resource type: %s' % template.get_resource_type())

    user = workspace.creator

    context_values = get_context_values(workspace, workspace.creator)
    processor = TemplateValueProcessor({'user': user, 'context': context_values})

    mashup_description = template.get_resource_info()

    new_values = {}
    id_mapping = {
        'operator': {},
        'widget': {},
    }
    for preference_name in mashup_description['preferences']:
        # Filter public and sharelist preferences
        if preference_name in ("public", "sharelist"):
            continue

        new_values[preference_name] = {
            'inherit': False,
            'value': mashup_description['preferences'][preference_name],
        }

    if len(new_values) > 0:
        update_workspace_preferences(workspace, new_values)

    new_forced_values = {
        'extra_prefs': [],
        'iwidget': {},
        'ioperator': {},
    }
    for param in mashup_description['params']:
        new_forced_values['extra_prefs'].append({
            'name': param['name'],
            'inheritable': False,
            'label': param.get('label'),
            'type': param.get('type'),
            'description': param.get('description'),
            'required': param.get('required'),
        })

    for tab_entry in mashup_description['tabs']:
        tab = createTab(tab_entry.get('title'), workspace, name=tab_entry['name'], allow_renaming=True)

        new_values = {}
        for preference_name in tab_entry['preferences']:
            new_values[preference_name] = {
                'inherit': False,
                'value': tab_entry['preferences'][preference_name],
            }

        if len(new_values) > 0:
            update_tab_preferences(tab, new_values)

        for resource in tab_entry['resources']:

            position = resource['position']
            rendering = resource['rendering']

            widget = get_or_add_widget_from_catalogue(resource.get('vendor'), resource.get('name'), resource.get('version'), user)

            iwidget_data = {
                "widget": widget.uri,
                "title": resource.get('title'),
                "left": float(position.get('x')),
                "top": float(position.get('y')),
                "icon_left": 0,
                "icon_top": 0,
                "zIndex": int(position.get('z')),
                "width": float(rendering.get('width')),
                "height": float(rendering.get('height')),
                "layout": int(rendering.get('layout')),
                "minimized": rendering['minimized'],
                "fulldragboard": rendering['fulldragboard'],
                "titlevisible": rendering['titlevisible'],
            }

            iwidget = SaveIWidget(iwidget_data, user, tab, commit=False)
            if resource.get('readonly'):
                iwidget.readOnly = True

            initial_variable_values = {}
            iwidget_forced_values = {}
            iwidget_info = widget.resource.get_processed_info(process_variables=True)
            for prop_name in resource['properties']:
                prop = resource['properties'][prop_name]
                read_only = prop.get('readonly')
                if prop.get('value', None) is not None:
                    value = prop['value']
                else:
                    value = iwidget_info['variables']['properties'][prop_name]['default']
                if read_only:
                    iwidget_forced_values[prop_name] = {'value': value}
                else:
                    initial_variable_values[prop_name] = processor.process(value)

            for pref_name in resource['preferences']:
                pref = resource['preferences'][pref_name]
                read_only = pref.get('readonly')
                if pref.get('value', None) is not None:
                    value = pref['value']
                    if isinstance(value, dict):
                        value = value["users"].get("%s" % workspace.creator.id, iwidget_info['variables']['preferences'][pref_name]['default'])
                else:
                    value = iwidget_info['variables']['preferences'][pref_name]['default']

                # Build multiuser structure
                if read_only:
                    iwidget_forced_values[pref_name] = {'value': value, 'hidden': pref.get('hidden', False)}
                else:
                    initial_variable_values[pref_name] = processor.process(value)
            set_initial_values(iwidget, initial_variable_values, iwidget_info, workspace.creator)
            iwidget.save()

            if len(iwidget_forced_values) > 0:
                new_forced_values['iwidget'][str(iwidget.id)] = iwidget_forced_values

            id_mapping['widget'][resource.get('id')] = {
                'id': iwidget.id,
                'name': resource.get('vendor') + "/" + resource.get('name') + "/" + resource.get('version')
            }

    # wiring
    if len(workspace.wiringStatus) == 0:
        workspace.wiringStatus = get_wiring_skeleton()

    max_id = 0

    for id_ in workspace.wiringStatus['operators'].keys():
        if int(id_) > max_id:
            max_id = int(id_)

    # Process operators info
    for operator_id, operator in mashup_description['wiring']['operators'].items():
        max_id += 1
        new_id = "%s" % max_id
        id_mapping['operator'][operator_id] = {
            'id': new_id
        }
        workspace.wiringStatus['operators'][new_id] = {
            'id': new_id,
            'name': operator['name'],
            'preferences': operator['preferences'],
            'properties': {}
        }

        ioperator_forced_values = {}
        for pref_id, pref in operator['preferences'].items():
            if pref.get('readonly', False):
                ioperator_forced_values[pref_id] = {'value': pref.get('value'), 'hidden': pref.get('hidden', False)}

            workspace.wiringStatus['operators'][new_id]["preferences"][pref_id]["value"] = {'users': {"%s" % workspace.creator.id: pref["value"]}}

        if len(ioperator_forced_values) > 0:
            new_forced_values['ioperator'][new_id] = ioperator_forced_values

    # Remap connection ids
    source_mapping = {}
    target_mapping = {}

    for connection in mashup_description['wiring']['connections']:

        if not is_valid_connection(connection, id_mapping):
            continue

        old_source_name = get_endpoint_name(connection['source'])
        old_target_name = get_endpoint_name(connection['target'])

        connection['source']['id'] = map_id(connection['source'], id_mapping)
        connection['target']['id'] = map_id(connection['target'], id_mapping)

        source_mapping[old_source_name] = get_endpoint_name(connection['source'])
        target_mapping[old_target_name] = get_endpoint_name(connection['target'])

        # Add new connection
        workspace.wiringStatus['connections'].append(connection)

    # Merging visual description...
    _remap_component_ids(id_mapping, mashup_description['wiring']['visualdescription']['components'], isGlobal=True)
    _remap_connection_endpoints(source_mapping, target_mapping, mashup_description['wiring']['visualdescription'])

    # Remap mashup description behaviours' ids
    if len(mashup_description['wiring']['visualdescription']['behaviours']) != 0:
        for behaviour in mashup_description['wiring']['visualdescription']['behaviours']:
            _remap_component_ids(id_mapping, behaviour['components'])
            _remap_connection_endpoints(source_mapping, target_mapping, behaviour)

    if len(workspace.wiringStatus['visualdescription']['behaviours']) != 0 or len(mashup_description['wiring']['visualdescription']['behaviours']) != 0:
        if len(workspace.wiringStatus['visualdescription']['behaviours']) == 0 and not is_empty_wiring(workspace.wiringStatus['visualdescription']):
            # *TODO* flag to check if the user really want to merge both workspaces.
            _create_new_behaviour(workspace.wiringStatus['visualdescription'], _("Original wiring"), _("This is the wiring description of the original workspace"))

        if len(mashup_description['wiring']['visualdescription']['behaviours']) == 0:
            _create_new_behaviour(mashup_description['wiring']['visualdescription'], _("Merged wiring"), _("This is the wiring description of the merged mashup."))

        workspace.wiringStatus['visualdescription']['behaviours'] += mashup_description['wiring']['visualdescription']['behaviours']

    # Merge global behaviour components and connections
    workspace.wiringStatus['visualdescription']['components']['operator'].update(mashup_description['wiring']['visualdescription']['components']['operator'])
    workspace.wiringStatus['visualdescription']['components']['widget'].update(mashup_description['wiring']['visualdescription']['components']['widget'])
    workspace.wiringStatus['visualdescription']['connections'] += mashup_description['wiring']['visualdescription']['connections']

    # Forced values
    normalize_forced_values(workspace)

    workspace.forcedValues['extra_prefs'] += new_forced_values['extra_prefs']
    workspace.forcedValues['iwidget'].update(new_forced_values['iwidget'])
    workspace.forcedValues['ioperator'].update(new_forced_values['ioperator'])

    workspace.save()
コード例 #19
0
    def _handle(self, *args, **options):

        self.verbosity = int(options.get('verbosity', 1))

        users = []
        groups = []
        redeploy = options['redeploy']
        public = options['public']
        users_string = options['users'].strip()
        groups_string = options['groups'].strip()

        if redeploy is False and public is False and users_string == '' and groups_string == '':
            raise CommandError(
                _('You must use at least one of the following flags: --redeploy, --users, --groups or --public'
                  ))

        if not options['redeploy']:

            if users_string != '':
                for username in users_string.split(','):
                    users.append(User.objects.get(username=username))

            if groups_string != '':
                for groupname in groups_string.split(','):
                    groups.append(Group.objects.get(name=groupname))

        for file_name in options['files']:
            try:
                f = open(file_name, 'rb')
                wgt_file = WgtFile(f)
            except:
                self.log(_('Failed to read from %(file_name)s') %
                         {'file_name': file_name},
                         level=1)
                continue

            try:
                template_contents = wgt_file.get_template()
                template = TemplateParser(template_contents)
                if options['redeploy']:
                    add_packaged_resource(f,
                                          None,
                                          wgt_file=wgt_file,
                                          template=template,
                                          deploy_only=True)
                else:
                    install_component(wgt_file,
                                      public=public,
                                      users=users,
                                      groups=groups)

                wgt_file.close()
                f.close()
                self.log(_(
                    'Successfully imported \"%(name)s\" from \"%(file_name)s\"'
                ) % {
                    'name':
                    template.get_resource_processed_info()['title'],
                    'file_name':
                    file_name
                },
                         level=1)
            except:
                self.log(_(
                    'Failed to import the mashable application component from %(file_name)s'
                ) % {'file_name': file_name},
                         level=1)
コード例 #20
0
    def create(self, request):

        data = parse_json_request(request)

        workspace_name = data.get('name', '').strip()
        workspace_title = data.get('title', '').strip()
        workspace_id = data.get('workspace', '')
        mashup_id = data.get('mashup', '')
        initial_pref_values = data.get('preferences', {})
        allow_renaming = normalize_boolean_param(
            request, 'allow_renaming', data.get('allow_renaming', False))
        dry_run = normalize_boolean_param(request, 'dry_run',
                                          data.get('dry_run', False))

        if mashup_id == '' and workspace_id == '' and (workspace_name == '' and
                                                       workspace_title == ''):
            return build_error_response(request, 422,
                                        _('Missing name or title parameter'))
        elif mashup_id != '' and workspace_id != '':
            return build_error_response(
                request, 422,
                _('Workspace and mashup parameters cannot be used at the same time'
                  ))

        if mashup_id == '' and workspace_id == '':

            if workspace_title == '':
                workspace_title = workspace_name

            if workspace_name != '' and not is_valid_name(workspace_name):
                return build_error_response(request, 422,
                                            _('invalid workspace name'))

            if dry_run:
                return HttpResponse(status=204)

            try:
                workspace = createEmptyWorkspace(workspace_title,
                                                 request.user,
                                                 name=workspace_name,
                                                 allow_renaming=allow_renaming)
            except IntegrityError:
                msg = _('A workspace with the given name already exists')
                return build_error_response(request, 409, msg)
        else:

            if mashup_id != '':
                values = mashup_id.split('/', 3)
                if len(values) != 3:
                    return build_error_response(request, 422,
                                                _('invalid mashup id'))

                (mashup_vendor, mashup_name, mashup_version) = values
                try:
                    resource = CatalogueResource.objects.get(
                        vendor=mashup_vendor,
                        short_name=mashup_name,
                        version=mashup_version)
                    if not resource.is_available_for(
                            request.user
                    ) or resource.resource_type() != 'mashup':
                        raise CatalogueResource.DoesNotExist
                except CatalogueResource.DoesNotExist:
                    return build_error_response(
                        request, 422,
                        _('Mashup not found: %(mashup_id)s') %
                        {'mashup_id': mashup_id})

                base_dir = catalogue.wgt_deployer.get_base_dir(
                    mashup_vendor, mashup_name, mashup_version)
                wgt_file = WgtFile(
                    os.path.join(base_dir, resource.template_uri))
                template = TemplateParser(wgt_file.get_template())

            else:

                from_ws = get_object_or_404(Workspace, id=workspace_id)
                if from_ws.public is False and not request.user.is_superuser and from_ws.creator != request.user:
                    return build_error_response(
                        request, 403,
                        _('You are not allowed to read from workspace %s') %
                        workspace_id)

                options = {
                    'vendor':
                    'api',
                    'name':
                    from_ws.name,
                    'version':
                    '1.0',
                    'title':
                    from_ws.title if from_ws.title is not None
                    and from_ws.title.strip() != "" else from_ws.name,
                    'description':
                    'Temporal mashup for the workspace copy operation',
                    'email':
                    '*****@*****.**',
                }

                template = TemplateParser(
                    build_json_template_from_workspace(options, from_ws,
                                                       from_ws.creator))

            try:
                check_mashup_dependencies(template, request.user)
            except MissingDependencies as e:
                details = {
                    'missingDependencies': e.missing_dependencies,
                }
                return build_error_response(request, 422, e, details=details)

            if dry_run:
                return HttpResponse(status=204)

            try:
                workspace, _junk = buildWorkspaceFromTemplate(
                    template,
                    request.user,
                    allow_renaming=allow_renaming,
                    new_name=workspace_name,
                    new_title=workspace_title)
            except IntegrityError:
                msg = _('A workspace with the given name already exists')
                return build_error_response(request, 409, msg)

        if len(initial_pref_values) > 0:
            update_workspace_preferences(workspace,
                                         initial_pref_values,
                                         invalidate_cache=False)

        workspace_data = get_global_workspace_data(workspace, request.user)

        return workspace_data.get_response(status_code=201, cacheable=False)