def read(self, request):

        try:
            metricRec = metricRecorder()
            metricRec.newInstance(request, 'PICBadgeAPI', 'Libre')
            metricRec.addMetric('ServiceEndpoint', 'GetLicenses')
            metricRec.sendMetric()
        except IOError as e:
            log.debug("Error while calling the metric client")
            log.error(e)

        pic_cc_licenses = picLicenses()
        return HttpResponse(pic_cc_licenses.getLicenseClasses())
Beispiel #2
0
	def read(self, request):
		
		try:		
			metricRec= metricRecorder()
			metricRec.newInstance(request,'PICBadgeAPI','Libre')
			metricRec.addMetric('ServiceEndpoint','GetLicenses')
			metricRec.sendMetric()
		except IOError as e:
			log.debug("Error while calling the metric client")
			log.error (e)
			
		pic_cc_licenses = picLicenses()
		return HttpResponse(pic_cc_licenses.getLicenseClasses())
    def create(self, request):
        # Creative Commons licensing web Service URL
        cc_url = 'http://api.creativecommons.org/rest/staging/license/zero/issue'

        metricRec = metricRecorder()
        metricRec.newInstance(request, 'PICBadgeAPI', 'Libre')
        metricRec.addMetric('ServiceEndpoint', 'IssueLicense')
        metricRec.addMetric("LicenseType", 'pic_cc_zero')

        log.debug("Creating CC Zero Badge...")
        try:
            # get user information from the request.
            if request.content_type:
                log.debug("Received %s data..." % (request.content_type))
                answers = request.raw_post_data
            else:
                log.debug("Received form data...")
                answers = request.POST.get('answers', '')
            #remove <?xml...?> header, as it seems to have problems with encoding
            answers = re.sub('<\?.*?\?>', '', answers)
            log.debug("Answers is: %s" % answers)
            doc = lxml.etree.parse(StringIO(answers))

            #extact output type from answers
            outputType = doc.xpath('//answers/outputType')
            outputType = outputType[0].text
            metricRec.addMetric('OutputType', outputType)
            metrics_title = doc.xpath('//answers/work-info/title')[0].text
            metrics_url = doc.xpath(
                '//answers/work-info/attribution_url')[0].text
            metrics_territory = doc.xpath(
                '//answers/work-info/territory')[0].text

            metricRec.addMetric("Territory", metrics_territory)
            metricRec.addMetric("Url", metrics_url)
            metricRec.addMetric("Title", metrics_title)

            metrics_source = doc.xpath('//answers/source')
            if (not metrics_source):
                metrics_source = 'api'
            else:
                metrics_source = metrics_source[0].text
            metricRec.addMetric("Source", metrics_source)

            metricRec.sendMetric()

            root = doc.getroot()
            root.remove(root.find("outputType"))

            # Create anwers xml to request license from CC WebService.
            newAnswers = lxml.etree.Element("answers")
            newAnswersDoc = lxml.etree.ElementTree(newAnswers)
            localeNode = lxml.etree.SubElement(newAnswers, "locale")
            localeNode.text = "en"
            localeNode = lxml.etree.SubElement(newAnswers, "license-zero")
            # appending user information into the answers
            newAnswers.append(root.find("work-info"))

            newAnswers = lxml.etree.tostring(newAnswersDoc)

        except Exception as ex:
            log.debug("Exception while reading answers...")
            log.debug(ex)
            return HttpResponse(errHandler.PythonError())

        # get license from CC Webservice
        try:
            CCLicenseXML = urllib2.urlopen(cc_url,
                                           data='answers=%s' %
                                           newAnswers).read()
        except:
            return HttpResponse(errHandler.CCServerError())

        # embed PIC logo into the license
        try:
            licenseXMLProcessor = CCLicenseProcessor()
            licenseXMLProcessor.setLicenseType("zero")
            CCLicenseXMLwithPIC = licenseXMLProcessor.embeddPICLOGO(
                CCLicenseXML)
        except:
            return HttpResponse(
                CCLicenseXML
            )  #"Error occured while generating license. please verify you sent valid data.")

        if outputType == "html":
            try:
                htmlOnly = licenseXMLProcessor.extractLicenseHTML(
                    CCLicenseXMLwithPIC)
            except:
                return HttpResponse(CCLicenseXMLwithPIC)

            return HttpResponse(htmlOnly)
        else:
            return HttpResponse(CCLicenseXMLwithPIC)
Beispiel #4
0
def createBadge(request):
    errHandler = ErrorHandler()
    # what license to generate?
    licenseType = request.POST['licenseType']
    formID = request.POST['formID']

    # PIC RESTful webservice URL = http://testservername.org/picbadgeapi...
    # creating pic client api object.
    picserver = picAPIClient(settings.PICBADGEAPI_URL +
                             settings.PICBADGEAPI_PATH)

    # We've got a pic_CCBy license application.
    if licenseType == "pic_cc_by":
        form = ccByUserInfoForm(request.POST)

    # We've got a pic_zero license application.
    elif licenseType == 'pic_cc_zero':
        form = cc0UserInfoForm(request.POST)

    # Invalid call
    else:
        response = {
            "status": "error",
            "response": errHandler.InvalidInputError()
        }

    # checks if the form data is valid w.r.t. CC by form specification.
    if form.is_valid():
        try:
            cd = form.cleaned_data
            userInfo = cd.copy()
            # removing the form element that are not required for licensing.
            del userInfo['agreementconfirm']
        except:
            errMsg = errHandler.PythonError()
            response = {"status": "error", "response": errMsg}

        try:
            # this module of the client api forms the answers xml and calls PIC Licensing webservice
            licenseOutput = picserver.getLicense(licenseType, userInfo)
            response = {"status": "license", "response": licenseOutput}

        except:
            errMsg = errHandler.PICAPIError()
            response = {"status": "error", "response": errMsg}

    else:
        t = get_template('form_template.html')
        formHtml = t.render(Context({'formID': formID, 'dataForm': form}))
        response = {"status": "validationError", "response": formHtml}

    #Notify the metrics services

    log.debug("Notifying metrics service.")
    try:
        metricRec = metricRecorder()
        metricRec.newInstance(request, 'PICBadgeGUI', 'Libre')

        # We've got a pic_CCBy license application.
        if licenseType == "pic_cc_by":
            metrics_url = request.POST['workurl']

        # We've got a pic_zero license application.
        elif licenseType == 'pic_cc_zero':
            metrics_url = request.POST['attribution_url']
            metricRec.addMetric("Territory", request.POST['territory'])

        metrics_title = request.POST['title']
        metrics_api_HttpCodeResponse = picserver.getHttpResponse()
        if metrics_api_HttpCodeResponse == 200:
            metrics_success = "True"
        else:
            metrics_success = "False"

        metricRec.addMetric("LicenseType", licenseType)
        metricRec.addMetric("Url", metrics_url)
        metricRec.addMetric("Title", metrics_title)
        metricRec.addMetric("Success", metrics_success)
        metricRec.sendMetric()

    except IOError as e:
        log.error("Error occurred sending metrics to service.")
        log.error(e)

    jsonOutput = simplejson.dumps(response)
    log.debug(jsonOutput)

    return HttpResponse(jsonOutput, mimetype='application/json')
Beispiel #5
0
	def create(self, request):
		# Creative Commons licensing web Service URL
		cc_url = 'http://api.creativecommons.org/rest/staging/license/zero/issue'	
	
		metricRec= metricRecorder()
		metricRec.newInstance(request,'PICBadgeAPI','Libre')
		metricRec.addMetric('ServiceEndpoint','IssueLicense')
		metricRec.addMetric("LicenseType",'pic_cc_zero')
		
		log.debug("Creating CC Zero Badge...")
		try:
			# get user information from the request.
			if request.content_type:
				log.debug("Received %s data..." % (request.content_type))
				answers = request.raw_post_data
			else:
				log.debug("Received form data...")
				answers = request.POST.get('answers','')
			#remove <?xml...?> header, as it seems to have problems with encoding
			answers = re.sub('<\?.*?\?>','',answers)
			log.debug("Answers is: %s" % answers)
			doc = lxml.etree.parse(StringIO(answers))
			
			#extact output type from answers
			outputType = doc.xpath('//answers/outputType')	
			outputType = outputType[0].text		
			metricRec.addMetric('OutputType',outputType)
			metrics_title=doc.xpath('//answers/work-info/title')[0].text
			metrics_url=doc.xpath('//answers/work-info/attribution_url')[0].text
			metrics_territory=doc.xpath('//answers/work-info/territory')[0].text
			
			metricRec.addMetric("Territory",metrics_territory)
			metricRec.addMetric("Url",metrics_url)
			metricRec.addMetric("Title",metrics_title)
			
			metrics_source=doc.xpath('//answers/source')
			if (not metrics_source):
				metrics_source='api'
			else:
				metrics_source=metrics_source[0].text
			metricRec.addMetric("Source", metrics_source)
			
			metricRec.sendMetric()
			
			
			root = doc.getroot()
			root.remove(root.find("outputType"))
			
			# Create anwers xml to request license from CC WebService.
			newAnswers = lxml.etree.Element("answers")
			newAnswersDoc = lxml.etree.ElementTree(newAnswers)
			localeNode = lxml.etree.SubElement(newAnswers, "locale")
			localeNode.text = "en"
			localeNode = lxml.etree.SubElement(newAnswers, "license-zero")
			# appending user information into the answers
			newAnswers.append(root.find("work-info"))	
			
			
			
			
			newAnswers = lxml.etree.tostring(newAnswersDoc)	
			
		except Exception as ex:
			log.debug("Exception while reading answers...")
			log.debug(ex)
			return HttpResponse(errHandler.PythonError())			
		
		# get license from CC Webservice
		try:
			CCLicenseXML = urllib2.urlopen(cc_url, data='answers=%s' % newAnswers).read()					
		except:
			return HttpResponse(errHandler.CCServerError())
		
		# embed PIC logo into the license
		try:
			licenseXMLProcessor = CCLicenseProcessor()	
			licenseXMLProcessor.setLicenseType("zero")		
			CCLicenseXMLwithPIC = licenseXMLProcessor.embeddPICLOGO(CCLicenseXML)
		except:
			return HttpResponse(CCLicenseXML)#"Error occured while generating license. please verify you sent valid data.")
		
		if outputType == "html":
			try:
				htmlOnly = licenseXMLProcessor.extractLicenseHTML(CCLicenseXMLwithPIC)
			except:
				return HttpResponse(CCLicenseXMLwithPIC)
				
			return HttpResponse(htmlOnly)			
		else:
			return HttpResponse(CCLicenseXMLwithPIC)		
Beispiel #6
0
def createBadge(request):	
	errHandler = ErrorHandler()
	# what license to generate?	
	licenseType = request.POST['licenseType']
	formID = request.POST['formID']
	

	# PIC RESTful webservice URL = http://testservername.org/picbadgeapi...
	# creating pic client api object.
	picserver = picAPIClient(settings.PICBADGEAPI_URL + settings.PICBADGEAPI_PATH) 
	
	# We've got a pic_CCBy license application.
	if licenseType == "pic_cc_by":
		form = ccByUserInfoForm(request.POST)
		
	# We've got a pic_zero license application.
	elif licenseType == 'pic_cc_zero':
		form = cc0UserInfoForm(request.POST)
		
	# Invalid call
	else:
		response = {"status": "error", "response": errHandler.InvalidInputError()}
	
	# checks if the form data is valid w.r.t. CC by form specification.
	if form.is_valid():			
		try:				
			cd = form.cleaned_data							
			userInfo = cd.copy()			
			# removing the form element that are not required for licensing.
			del userInfo['agreementconfirm']
		except:
			errMsg = errHandler.PythonError()
			response = {"status": "error", "response": errMsg}
		
		try:
			# this module of the client api forms the answers xml and calls PIC Licensing webservice
			licenseOutput = picserver.getLicense(licenseType, userInfo)
			response = {"status": "license", "response": licenseOutput}
			
			
		except:
			errMsg = errHandler.PICAPIError()
			response = {"status": "error", "response": errMsg}
		
	else:				
		t = get_template('form_template.html')
		formHtml = t.render(Context({'formID' : formID, 'dataForm' : form}))
		response = {"status": "validationError", "response": formHtml}
	
	#Notify the metrics services
	
	log.debug("Notifying metrics service.")	
	try:
		metricRec= metricRecorder()
		metricRec.newInstance(request,'PICBadgeGUI','Libre')

		# We've got a pic_CCBy license application.
		if licenseType == "pic_cc_by":
			metrics_url = request.POST['workurl']
					
		# We've got a pic_zero license application.
		elif licenseType == 'pic_cc_zero':
			metrics_url = request.POST['attribution_url']
			metricRec.addMetric("Territory",request.POST['territory'])
					
		metrics_title = request.POST['title']		
		metrics_api_HttpCodeResponse= picserver.getHttpResponse()
		if metrics_api_HttpCodeResponse==200:
			metrics_success="True"
		else:
			metrics_success="False"
		
		
		metricRec.addMetric("LicenseType",licenseType)			
		metricRec.addMetric("Url",metrics_url)
		metricRec.addMetric("Title",metrics_title)		
		metricRec.addMetric("Success",metrics_success)		
		metricRec.sendMetric()
		
		

		
	except IOError as e:
		log.error("Error occurred sending metrics to service.")
		log.error (e)
		
	jsonOutput = simplejson.dumps(response)
	log.debug( jsonOutput )
	
	return HttpResponse(jsonOutput, mimetype='application/json')