def test_normalize_boolean_param_invalid_string(self): request = self._prepare_request_mock() try: normalize_boolean_param(request, 'param', 'invalid') self.fail('ErrorResponse not raised by normalize_boolean_param') except ErrorResponse as e: self.assertEqual(e.response.status_code, 422)
def test_normalize_boolean_param_boolean(self): request = self._prepare_request_mock() normalize_boolean_param(request, 'param', True)
def test_normalize_boolean_param_string(self): request = self._prepare_request_mock() normalize_boolean_param(request, 'param', 'true')
def create(self, request): status_code = 201 force_create = False install_embedded_resources = False templateURL = None file_contents = None if request.mimetype == 'multipart/form-data': force_create = request.POST.get('force_create', 'false').strip().lower() == 'true' public = request.POST.get('public', 'false').strip().lower() == 'true' user_list = set( user.strip() for user in request.POST.get('users', '').split(',') if user != "") group_list = set( group.strip() for group in request.POST.get('groups', '').split(',') if group != "") install_embedded_resources = request.POST.get( 'install_embedded_resources', 'false').strip().lower() == 'true' if 'file' not in request.FILES: return build_error_response( request, 400, _('Missing component file in the request')) downloaded_file = request.FILES['file'] try: file_contents = WgtFile(downloaded_file) except zipfile.BadZipfile: return build_error_response( request, 400, _('The uploaded file is not a zip file')) elif request.mimetype == 'application/octet-stream': downloaded_file = BytesIO(request.body) try: file_contents = WgtFile(downloaded_file) except zipfile.BadZipfile: return build_error_response( request, 400, _('The uploaded file is not a zip file')) force_create = request.GET.get('force_create', 'false').strip().lower() == 'true' public = request.GET.get('public', 'false').strip().lower() == 'true' user_list = set(user.strip() for user in request.GET.get('users', '').split(',') if user != "") group_list = set( group.strip() for group in request.GET.get('groups', '').split(',') if group != "") install_embedded_resources = request.GET.get( 'install_embedded_resources', 'false').strip().lower() == 'true' else: # if request.mimetype == 'application/json' market_endpoint = None data = parse_json_request(request) install_embedded_resources = normalize_boolean_param( request, 'install_embedded_resources', data.get('install_embedded_resources', False)) force_create = data.get('force_create', False) public = request.GET.get('public', 'false').strip().lower() == 'true' user_list = set( user.strip() for user in request.GET.get('user_list', '').split(',') if user != "") group_list = set( group.strip() for group in request.GET.get('group_list', '').split(',') if group != "") templateURL = data.get('url') market_endpoint = data.get('market_endpoint', None) headers = data.get('headers', {}) headers['Accept-Encoding'] = 'identity' if market_endpoint is not None: if 'name' not in market_endpoint: msg = _('Missing market name') return build_error_response(request, 400, msg) market_id = market_endpoint['name'] market_managers = get_market_managers(request.user) if market_id not in market_managers: return build_error_response( request, 409, _('Unknown market: %s') % market_id) market_manager = market_managers[market_id] downloaded_file = market_manager.download_resource( request.user, templateURL, market_endpoint) else: try: context = parse_context_from_referer(request) except Exception: context = {} try: context["headers"] = CaseInsensitiveDict(headers) response = WIRECLOUD_PROXY.do_request( request, templateURL, "GET", context) if response.status_code >= 300 or response.status_code < 200: raise Exception() downloaded_file = b''.join(response) except Exception: return build_error_response( request, 409, _('Content cannot be downloaded from the specified url' )) try: downloaded_file = BytesIO(downloaded_file) file_contents = WgtFile(downloaded_file) except zipfile.BadZipfile: return build_error_response( request, 400, _('The file downloaded from the marketplace is not a zip file' )) if public is False and len(user_list) == 0 and len(group_list) == 0: users = (request.user, ) else: users = User.objects.filter(username__in=user_list) groups = Group.objects.filter(name__in=group_list) if not request.user.is_superuser: if public: return build_error_response( request, 403, _('You are not allowed to make resources publicly available to all users' )) elif len(users) > 0 and tuple(users) != (request.user, ): return build_error_response( request, 403, _('You are not allowed allow to install components to other users' )) elif len(groups) > 0: for group in groups: try: owners = group.organization.team_set.get(name="owners") except ObjectDoesNotExist: fail = True else: fail = owners.users.filter( id=request.user.id).exists() is False if fail: return build_error_response( request, 403, _('You are not allowed to install components to non-owned organizations' )) try: fix_dev_version(file_contents, request.user) added, resource = install_component(file_contents, executor_user=request.user, public=public, users=users, groups=groups) if not added and force_create: return build_error_response(request, 409, _('Resource already exists')) elif not added: status_code = 200 except zipfile.BadZipfile as e: return build_error_response( request, 400, _('The uploaded file is not a valid zip file'), details="{}".format(e)) except OSError as e: if e.errno == errno.EACCES: return build_error_response( request, 500, _('Error writing the resource into the filesystem. Please, contact the server administrator.' )) else: raise except TemplateParseException as e: msg = "Error parsing config.xml descriptor file: %s" % e details = "%s" % e return build_error_response(request, 400, msg, details=details) except (InvalidContents, UnsupportedFeature) as e: details = e.details if hasattr(e, 'details') else None return build_error_response(request, 400, e, details=str(details)) if install_embedded_resources: info = { 'resource_details': resource.get_processed_info( request, url_pattern_name="wirecloud.showcase_media"), 'extra_resources': [] } if resource.resource_type() == 'mashup': resource_info = resource.get_processed_info(process_urls=False) for embedded_resource in resource_info['embedded']: resource_file = BytesIO( file_contents.read(embedded_resource['src'])) extra_resource_contents = WgtFile(resource_file) extra_resource_added, extra_resource = install_component( extra_resource_contents, executor_user=request.user, public=public, users=users, groups=groups) if extra_resource_added: info['extra_resources'].append( extra_resource.get_processed_info( request, url_pattern_name="wirecloud.showcase_media")) response = HttpResponse( json.dumps(info, sort_keys=True), status=status_code, content_type='application/json; charset=UTF-8') else: response = HttpResponse( json.dumps(resource.get_processed_info( request, url_pattern_name="wirecloud.showcase_media"), sort_keys=True), status=status_code, content_type='application/json; charset=UTF-8') response['Location'] = resource.get_template_url() return response
def create(self, request): force_create = False install_embedded_resources = False templateURL = None file_contents = None content_type = get_content_type(request)[0] if content_type == "multipart/form-data": force_create = request.POST.get("force_create", "false").strip().lower() == "true" install_embedded_resources = ( request.POST.get("install_embedded_resources", "false").strip().lower() == "true" ) if not "file" in request.FILES: return build_error_response(request, 400, _("Missing component file in the request")) downloaded_file = request.FILES["file"] try: file_contents = WgtFile(downloaded_file) except zipfile.BadZipfile: return build_error_response(request, 400, _("The uploaded file is not a zip file")) elif content_type == "application/octet-stream": downloaded_file = BytesIO(request.body) try: file_contents = WgtFile(downloaded_file) except zipfile.BadZipfile: return build_error_response(request, 400, _("The uploaded file is not a zip file")) force_create = request.GET.get("force_create", "false").strip().lower() == "true" install_embedded_resources = ( request.GET.get("install_embedded_resources", "false").strip().lower() == "true" ) else: market_endpoint = None if content_type == "application/json": try: data = json.loads(request.body) except ValueError as e: msg = _("malformed json data: %s") % unicode(e) return build_error_response(request, 400, msg) install_embedded_resources = normalize_boolean_param( "install_embedded_resources", data.get("install_embedded_resources", False) ) force_create = data.get("force_create", False) templateURL = data.get("template_uri") market_endpoint = data.get("market_endpoint", None) else: force_create = request.POST.get("force_create", False) == "true" if "url" in request.POST: templateURL = request.POST["url"] if market_endpoint is not None: if "name" not in market_endpoint: msg = _("Missing market name") return build_error_response(request, 400, msg) market_id = market_endpoint["name"] market_managers = get_market_managers(request.user) if market_id not in market_managers: return build_error_response(request, 409, _("Unknown market: %s") % market_id) market_manager = market_managers[market_id] downloaded_file = market_manager.download_resource(request.user, templateURL, market_endpoint) else: try: downloaded_file = download_http_content(templateURL) except: return build_error_response(request, 409, _("Content cannot be downloaded from the marketplace")) try: downloaded_file = BytesIO(downloaded_file) file_contents = WgtFile(downloaded_file) except zipfile.BadZipfile: return build_error_response( request, 400, _("The file downloaded from the marketplace is not a zip file") ) try: resource = install_resource_to_user( request.user, file_contents=file_contents, templateURL=templateURL, raise_conflicts=force_create ) except OSError as e: if e.errno == errno.EACCES: return build_error_response( request, 500, _("Error writing the resource into the filesystem. Please, contact the server administrator."), ) else: raise except TemplateParseException as e: msg = "Error parsing config.xml descriptor file: %s" % e details = "%s" % e return build_error_response(request, 400, msg, details=details) except (InvalidContents, UnsupportedFeature) as e: return build_error_response(request, 400, unicode(e)) except IntegrityError: return build_error_response(request, 409, _("Resource already exists")) if install_embedded_resources: info = {"resource_details": resource.get_processed_info(request), "extra_resources": []} if resource.resource_type() == "mashup": resource_info = resource.get_processed_info(process_urls=False) for embedded_resource in resource_info["embedded"]: if embedded_resource["src"].startswith("https://"): resource_file = download_http_content(embedded_resource["src"]) else: resource_file = BytesIO(file_contents.read(embedded_resource["src"])) extra_resource_contents = WgtFile(resource_file) extra_resource = install_resource_to_user( request.user, file_contents=extra_resource_contents, raise_conflicts=False ) info["extra_resources"].append(extra_resource.get_processed_info(request)) return HttpResponse(json.dumps(info), status=201, content_type="application/json; charset=UTF-8") else: return HttpResponse( json.dumps(resource.get_processed_info(request)), status=201, content_type="application/json; charset=UTF-8", )
def create(self, request): data = parse_json_request(request) workspace_name = data.get('name', '').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 == '': return build_error_response(request, 422, _('Missing name 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 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_name, request.user, 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': '', '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) if workspace_name == '': workspace_name = None try: workspace, _junk = buildWorkspaceFromTemplate(template, request.user, allow_renaming=allow_renaming, new_name=workspace_name) 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)
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)
def create(self, request): status_code = 201 force_create = False install_embedded_resources = False templateURL = None file_contents = None content_type = get_content_type(request)[0] if content_type == 'multipart/form-data': force_create = request.POST.get('force_create', 'false').strip().lower() == 'true' public = request.POST.get('public', 'false').strip().lower() == 'true' install_embedded_resources = request.POST.get( 'install_embedded_resources', 'false').strip().lower() == 'true' if 'file' not in request.FILES: return build_error_response( request, 400, _('Missing component file in the request')) downloaded_file = request.FILES['file'] try: file_contents = WgtFile(downloaded_file) except zipfile.BadZipfile: return build_error_response( request, 400, _('The uploaded file is not a zip file')) elif content_type == 'application/octet-stream': downloaded_file = BytesIO(request.body) try: file_contents = WgtFile(downloaded_file) except zipfile.BadZipfile: return build_error_response( request, 400, _('The uploaded file is not a zip file')) force_create = request.GET.get('force_create', 'false').strip().lower() == 'true' public = request.GET.get('public', 'false').strip().lower() == 'true' install_embedded_resources = request.GET.get( 'install_embedded_resources', 'false').strip().lower() == 'true' else: # if content_type == 'application/json' market_endpoint = None data = parse_json_request(request) install_embedded_resources = normalize_boolean_param( request, 'install_embedded_resources', data.get('install_embedded_resources', False)) force_create = data.get('force_create', False) public = request.GET.get('public', 'false').strip().lower() == 'true' templateURL = data.get('url') market_endpoint = data.get('market_endpoint', None) headers = data.get('headers', {}) if market_endpoint is not None: if 'name' not in market_endpoint: msg = _('Missing market name') return build_error_response(request, 400, msg) market_id = market_endpoint['name'] market_managers = get_market_managers(request.user) if market_id not in market_managers: return build_error_response( request, 409, _('Unknown market: %s') % market_id) market_manager = market_managers[market_id] downloaded_file = market_manager.download_resource( request.user, templateURL, market_endpoint) else: try: context = parse_context_from_referer(request) except: context = {} try: context["headers"] = CaseInsensitiveDict(headers) response = WIRECLOUD_PROXY.do_request( request, templateURL, "GET", context) if response.status_code >= 300 or response.status_code < 200: raise Exception() downloaded_file = b''.join(response) except: return build_error_response( request, 409, _('Content cannot be downloaded from the specified url' )) try: downloaded_file = BytesIO(downloaded_file) file_contents = WgtFile(downloaded_file) except zipfile.BadZipfile: return build_error_response( request, 400, _('The file downloaded from the marketplace is not a zip file' )) if public and not request.user.is_superuser: return build_error_response( request, 403, _('You are not allowed to make resources publicly available to all users' )) try: fix_dev_version(file_contents, request.user) added, resource = install_resource_to_user( request.user, file_contents=file_contents, templateURL=templateURL) if not added and force_create: return build_error_response(request, 409, _('Resource already exists')) elif not added: status_code = 200 if public: install_resource_to_all_users(executor_user=request.user, file_contents=file_contents) except zipfile.BadZipfile as e: return build_error_response( request, 400, _('The uploaded file is not a valid zip file'), details="{}".format(e)) except OSError as e: if e.errno == errno.EACCES: return build_error_response( request, 500, _('Error writing the resource into the filesystem. Please, contact the server administrator.' )) else: raise except TemplateParseException as e: msg = "Error parsing config.xml descriptor file: %s" % e details = "%s" % e return build_error_response(request, 400, msg, details=details) except (InvalidContents, UnsupportedFeature) as e: details = e.details if hasattr(e, 'details') else None return build_error_response(request, 400, e, details=six.text_type(details)) if install_embedded_resources: info = { 'resource_details': resource.get_processed_info( request, url_pattern_name="wirecloud.showcase_media"), 'extra_resources': [] } if resource.resource_type() == 'mashup': resource_info = resource.get_processed_info(process_urls=False) for embedded_resource in resource_info['embedded']: resource_file = BytesIO( file_contents.read(embedded_resource['src'])) extra_resource_contents = WgtFile(resource_file) if public: extra_resource_added, extra_resource = install_resource_to_user( request.user, file_contents=extra_resource_contents, raise_conflicts=False) else: extra_resource_added, extra_resource = install_resource_to_user( request.user, file_contents=extra_resource_contents, raise_conflicts=False) if extra_resource_added: info['extra_resources'].append( extra_resource.get_processed_info( request, url_pattern_name="wirecloud.showcase_media")) return HttpResponse(json.dumps(info, sort_keys=True), status=status_code, content_type='application/json; charset=UTF-8') else: return HttpResponse(json.dumps(resource.get_processed_info( request, url_pattern_name="wirecloud.showcase_media"), sort_keys=True), status=status_code, content_type='application/json; charset=UTF-8')
def create(self, request): status_code = 201 force_create = False install_embedded_resources = False templateURL = None file_contents = None content_type = get_content_type(request)[0] if content_type == 'multipart/form-data': force_create = request.POST.get('force_create', 'false').strip().lower() == 'true' public = request.POST.get('public', 'false').strip().lower() == 'true' install_embedded_resources = request.POST.get('install_embedded_resources', 'false').strip().lower() == 'true' if 'file' not in request.FILES: return build_error_response(request, 400, _('Missing component file in the request')) downloaded_file = request.FILES['file'] try: file_contents = WgtFile(downloaded_file) except zipfile.BadZipfile: return build_error_response(request, 400, _('The uploaded file is not a zip file')) elif content_type == 'application/octet-stream': downloaded_file = BytesIO(request.body) try: file_contents = WgtFile(downloaded_file) except zipfile.BadZipfile: return build_error_response(request, 400, _('The uploaded file is not a zip file')) force_create = request.GET.get('force_create', 'false').strip().lower() == 'true' public = request.GET.get('public', 'false').strip().lower() == 'true' install_embedded_resources = request.GET.get('install_embedded_resources', 'false').strip().lower() == 'true' else: # if content_type == 'application/json' market_endpoint = None data = parse_json_request(request) install_embedded_resources = normalize_boolean_param(request, 'install_embedded_resources', data.get('install_embedded_resources', False)) force_create = data.get('force_create', False) public = request.GET.get('public', 'false').strip().lower() == 'true' templateURL = data.get('url') market_endpoint = data.get('market_endpoint', None) headers = data.get('headers', {}) if market_endpoint is not None: if 'name' not in market_endpoint: msg = _('Missing market name') return build_error_response(request, 400, msg) market_id = market_endpoint['name'] market_managers = get_market_managers(request.user) if market_id not in market_managers: return build_error_response(request, 409, _('Unknown market: %s') % market_id) market_manager = market_managers[market_id] downloaded_file = market_manager.download_resource(request.user, templateURL, market_endpoint) else: try: context = parse_context_from_referer(request) except: context = {} try: context["headers"] = CaseInsensitiveDict(headers) response = WIRECLOUD_PROXY.do_request(request, templateURL, "GET", context) if response.status_code >= 300 or response.status_code < 200: raise Exception() downloaded_file = b''.join(response) except: return build_error_response(request, 409, _('Content cannot be downloaded from the specified url')) try: downloaded_file = BytesIO(downloaded_file) file_contents = WgtFile(downloaded_file) except zipfile.BadZipfile: return build_error_response(request, 400, _('The file downloaded from the marketplace is not a zip file')) if public and not request.user.is_superuser: return build_error_response(request, 403, _('You are not allowed to make resources publicly available to all users')) try: fix_dev_version(file_contents, request.user) added, resource = install_resource_to_user(request.user, file_contents=file_contents, templateURL=templateURL) if not added and force_create: return build_error_response(request, 409, _('Resource already exists')) elif not added: status_code = 200 if public: install_resource_to_all_users(executor_user=request.user, file_contents=file_contents) except zipfile.BadZipfile as e: return build_error_response(request, 400, _('The uploaded file is not a valid zip file'), details="{}".format(e)) except OSError as e: if e.errno == errno.EACCES: return build_error_response(request, 500, _('Error writing the resource into the filesystem. Please, contact the server administrator.')) else: raise except TemplateParseException as e: msg = "Error parsing config.xml descriptor file: %s" % e details = "%s" % e return build_error_response(request, 400, msg, details=details) except (InvalidContents, UnsupportedFeature) as e: details = e.details if hasattr(e, 'details') else None return build_error_response(request, 400, e, details=six.text_type(details)) if install_embedded_resources: info = { 'resource_details': resource.get_processed_info(request, url_pattern_name="wirecloud.showcase_media"), 'extra_resources': [] } if resource.resource_type() == 'mashup': resource_info = resource.get_processed_info(process_urls=False) for embedded_resource in resource_info['embedded']: resource_file = BytesIO(file_contents.read(embedded_resource['src'])) extra_resource_contents = WgtFile(resource_file) if public: extra_resource_added, extra_resource = install_resource_to_user(request.user, file_contents=extra_resource_contents, raise_conflicts=False) else: extra_resource_added, extra_resource = install_resource_to_user(request.user, file_contents=extra_resource_contents, raise_conflicts=False) if extra_resource_added: info['extra_resources'].append(extra_resource.get_processed_info(request, url_pattern_name="wirecloud.showcase_media")) return HttpResponse(json.dumps(info, sort_keys=True), status=status_code, content_type='application/json; charset=UTF-8') else: return HttpResponse(json.dumps(resource.get_processed_info(request, url_pattern_name="wirecloud.showcase_media"), sort_keys=True), status=status_code, content_type='application/json; charset=UTF-8')
def create(self, request): status_code = 201 force_create = False install_embedded_resources = False templateURL = None file_contents = None content_type = get_content_type(request)[0] if content_type == 'multipart/form-data': force_create = request.POST.get('force_create', 'false').strip().lower() == 'true' install_embedded_resources = request.POST.get('install_embedded_resources', 'false').strip().lower() == 'true' if not 'file' in request.FILES: return build_error_response(request, 400, _('Missing component file in the request')) downloaded_file = request.FILES['file'] try: file_contents = WgtFile(downloaded_file) except zipfile.BadZipfile: return build_error_response(request, 400, _('The uploaded file is not a zip file')) elif content_type == 'application/octet-stream': downloaded_file = BytesIO(request.body) try: file_contents = WgtFile(downloaded_file) except zipfile.BadZipfile: return build_error_response(request, 400, _('The uploaded file is not a zip file')) force_create = request.GET.get('force_create', 'false').strip().lower() == 'true' install_embedded_resources = request.GET.get('install_embedded_resources', 'false').strip().lower() == 'true' else: # if content_type == 'application/json' market_endpoint = None data = parse_json_request(request) install_embedded_resources = normalize_boolean_param(request, 'install_embedded_resources', data.get('install_embedded_resources', False)) force_create = data.get('force_create', False) templateURL = data.get('url') market_endpoint = data.get('market_endpoint', None) if market_endpoint is not None: if 'name' not in market_endpoint: msg = _('Missing market name') return build_error_response(request, 400, msg) market_id = market_endpoint['name'] market_managers = get_market_managers(request.user) if market_id not in market_managers: return build_error_response(request, 409, _('Unknown market: %s') % market_id) market_manager = market_managers[market_id] downloaded_file = market_manager.download_resource(request.user, templateURL, market_endpoint) else: try: downloaded_file = download_http_content(templateURL) except: return build_error_response(request, 409, _('Content cannot be downloaded from the specified url')) try: downloaded_file = BytesIO(downloaded_file) file_contents = WgtFile(downloaded_file) except zipfile.BadZipfile: return build_error_response(request, 400, _('The file downloaded from the marketplace is not a zip file')) try: added, resource = install_resource_to_user(request.user, file_contents=file_contents, templateURL=templateURL) if not added and force_create: return build_error_response(request, 409, _('Resource already exists')) elif not added: status_code = 200 except zipfile.BadZipfile as e: return build_error_response(request, 400, _('The uploaded file is not a valid zip file'), details="{}".format(e)) except OSError as e: if e.errno == errno.EACCES: return build_error_response(request, 500, _('Error writing the resource into the filesystem. Please, contact the server administrator.')) else: raise except TemplateParseException as e: msg = "Error parsing config.xml descriptor file: %s" % e details = "%s" % e return build_error_response(request, 400, msg, details=details) except (InvalidContents, UnsupportedFeature) as e: details = e.details if hasattr(e, 'details') else None return build_error_response(request, 400, e, details=six.text_type(details)) if install_embedded_resources: info = { 'resource_details': resource.get_processed_info(request), 'extra_resources': [] } if resource.resource_type() == 'mashup': resource_info = resource.get_processed_info(process_urls=False) for embedded_resource in resource_info['embedded']: resource_file = BytesIO(file_contents.read(embedded_resource['src'])) extra_resource_contents = WgtFile(resource_file) extra_resource_added, extra_resource = install_resource_to_user(request.user, file_contents=extra_resource_contents, raise_conflicts=False) if extra_resource_added: info['extra_resources'].append(extra_resource.get_processed_info(request)) return HttpResponse(json.dumps(info), status=status_code, content_type='application/json; charset=UTF-8') else: return HttpResponse(json.dumps(resource.get_processed_info(request)), status=status_code, content_type='application/json; charset=UTF-8')