def view(request, information_uuid):
    """ """
    if request.user.is_anonymous():
        api_client = get_portal_api_client()
    else:
        api_client = request.user.agave_oauth.api_client

    try:
        information = Information(api_client=api_client, uuid=information_uuid)
        project = information.project
        processes = information.processes
    except Exception as e:
        exception_msg = 'Unable to load information entity. %s' % e
        logger.error(exception_msg)
        messages.warning(request, exception_msg)
        return HttpResponseRedirect(reverse('ids_projects:project-list-private'))

    try:
        information_types = get_information_type_keys(project)
        information_fields = get_information_fields(project, information.value['information_type'])
        information.set_fields(information_fields)
    except Exception as e:
        exception_msg = 'Unable to load config values. %s' % e
        logger.warning(exception_msg)

    context = {'information': information,
               'project': project,
               'processes': processes,
               'information_types': information_types}

    return render(request, 'ids_projects/information/detail.html', context)
def view(request, specimen_uuid):
    """ """
    if request.user.is_anonymous():
        api_client = get_portal_api_client()
    else:
        api_client = request.user.agave_oauth.api_client

    try:
        specimen = Specimen(api_client=api_client, uuid=specimen_uuid)
        project = specimen.project
        processes = specimen.processes
    except Exception as e:
        exception_msg = 'Unable to load specimen. %s' % e
        logger.error(exception_msg)
        messages.warning(request, exception_msg)
        return HttpResponseRedirect('/projects')

    try:
        process_types = get_process_type_keys(project)
        specimen_fields = get_specimen_fields(project)
        specimen.set_fields(specimen_fields)

        context = {'project': project,
                   'specimen': specimen,
                   'processes': processes,
                   'process_types': process_types}

        return render(request, 'ids_projects/specimens/detail.html', context)
    except Exception as e:
        exception_msg = 'Unable to load config values. %s' % e
        logger.warning(exception_msg)
        messages.warning(request, exception_msg)
        return HttpResponseRedirect(reverse('ids_projects:project-list-private'))
def view(request, project_uuid):
    """Queries project metadata and all associated metadata"""
    if request.user.is_anonymous():
        api_client = get_portal_api_client()
    else:
        # api_client = get_portal_api_client()
        api_client = request.user.agave_oauth.api_client

    try:
        project = Project(api_client=api_client, uuid=project_uuid)
    except Exception as e:
        exception_msg = 'Unable to load project. %s' % e
        logger.error(exception_msg)
        messages.error(request, exception_msg)
        return HttpResponseRedirect('/projects/')

    try:
        process_types = get_process_type_keys(project)
        project_fields = get_project_form_fields()
        project.set_fields(project_fields)
        investigation_type = get_investigation_type(project)

        context = {'project': project,
                   'investigation_type': investigation_type,
                   'process_types': process_types}

        return render(request, 'ids_projects/projects/detail.html', context)
    except Exception as e:
        exception_msg = 'Unable to load config values. %s' % e
        logger.warning(exception_msg)
        messages.warning(request, exception_msg)
        return HttpResponseRedirect(
                    reverse('ids_projects:project-list-private'))
    def share(self, username=None, permission='READ_WRITE'):
        """
        Grant permissions on this metadata object to other users.  This metadata object
        must have a UUID.

        :param username:    The username of the api user whose permission is to be set.
                            (Default: portal's user account)
        :param permission:  ['READ' or 'WRITE' or 'READ_WRITE' or 'ALL' or 'NONE']:
                            The permission to set. (Default: READ_WRITE)
        :return: None
        """
        if self.uuid is None:            
            raise Exception('Cannot grant permissions, objects does not have a UUID.')

        if not username:            
            username = get_portal_api_client().profiles.get().username

        perm_result = self._api_client.meta.updateMetadataPermissions(
            uuid=self.uuid,
            body={
                'username': username,
                'permission': permission
            })

        return perm_result
def bulk_probe_registration(self, probes_meta, project_uuid, username=None):

    if username:
        UserModel = get_user_model()
        user = UserModel.objects.get(username=username)
        api_client = user.agave_oauth.api_client
    else:
        api_client = get_portal_api_client()

    project = Project(api_client, uuid=project_uuid)

    ## check if the probe is already registered by the project

    for probe_info in probes_meta:
        meta = {'value': probe_info}
        probe = Probe(api_client=api_client, meta=meta)
        probe.save()

        # add_part: probe
        project.add_probe(probe)
        project.save()

        # add_container: project
        probe.add_project(project)
        probe.save()
def view(request, dataset_uuid):
    """View a specific dataset"""
    if request.user.is_anonymous():
        api_client = get_portal_api_client()
    else:
        api_client = request.user.agave_oauth.api_client

    try:
        dataset = Dataset(api_client=api_client, uuid=dataset_uuid)
        project = dataset.project
        data = dataset.data
    except Exception as e:
        exception_msg = 'Unable to load process. %s' % e
        logger.error(exception_msg)
        messages.warning(request, exception_msg)
        return HttpResponseRedirect(reverse('ids_projects:project-list-private'))

    try:
        process_types = get_process_type_keys(project)
        dataset_fields = get_dataset_fields(project)
        dataset.set_fields(dataset_fields)
    except Exception as e:
        exception_msg = 'Unable to load config values. %s' % e
        logger.warning(exception_msg)

    context = { 'project': project,
                'dataset': dataset,
                'datas': data,
                'process_types': process_types }

    return render(request, 'ids_projects/datasets/detail.html', context)
def bulk_specimen_registration(self, specimens_meta, project_uuid, username=None):

    if username:
        UserModel = get_user_model()
        user = UserModel.objects.get(username=username)
        api_client = user.agave_oauth.api_client
    else:
        api_client = get_portal_api_client()

    project = Project(api_client=api_client, uuid=project_uuid)

    # ## check if the specimen is already registered by the project
    # for specimen_info in specimens_meta:
    #     specimen_id = specimen_info['specimen_id']
    #     specimen = project.query_specimens_by_id([specimen_id]) # taking a list as input

    #     # already exists a speicmen
    #     if len(specimen) > 0:
    #         raise Exception('Specimen ID of %s already exists in this project.' % specimen_id)

    ## registering bulk specimens
    for specimen_info in specimens_meta:
        meta = {'value': specimen_info}
        specimen = Specimen(api_client=api_client, meta=meta)
        specimen.save()

        # logger.debug("Specimen UUID: {}".format(specimen.uuid))

        # add_part: specimen
        project.add_specimen(specimen)
        project.save()

        # add_container: project
        specimen.add_project(project)
        specimen.save()
def view(request, material_uuid):
    """ """
    if request.user.is_anonymous():
        api_client = get_portal_api_client()
    else:
        api_client = request.user.agave_oauth.api_client

    try:
        material = Material(api_client=api_client, uuid=material_uuid)
        project = material.project
        processes = material.processes
    except Exception as e:
        exception_msg = 'Unable to load material entity. %s' % e
        logger.error(exception_msg)
        messages.warning(request, exception_msg)
        return HttpResponseRedirect(reverse('ids_projects:project-list-private'))

    try:
        material_types = get_material_type_keys(project)
        material_fields = get_material_fields(project, material.value['material_type'])
        material.set_fields(material_fields)
    except Exception as e:
        exception_msg = 'Unable to load config values. %s' % e
        logger.warning(exception_msg)

    context = {'material': material,
               'project': project,
               'processes': processes,
               'material_types': material_types}

    return render(request, 'ids_projects/material/detail.html', context)
def entity_detail_api(request, uuid):		
	if request.user.is_anonymous():
		api_client = get_portal_api_client()
	else:
		api_client = request.user.agave_oauth.api_client	

   	base = BaseMetadata(api_client=api_client, uuid=uuid)
   	return HttpResponse(json.dumps(base.meta, cls=DjangoJSONEncoder),
   												content_type='application/json')
def upload_option(request):
    project_uuid = request.GET.get('project_uuid', False)

    if not project_uuid:
        messages.warning(request, 'Missing project UUID, cannot create specimen.')
        return HttpResponseRedirect(reverse('ids_projects:project-list-private'))

    if request.user.is_anonymous():
        api_client = get_portal_api_client()
    else:
        api_client = request.user.agave_oauth.api_client

    project = Project(api_client=api_client, uuid=project_uuid)

    # POST
    if request.method == 'POST':
        context = {'project': project}

        if request.POST.get('upload_option', None) == 'Single':
            # Single Specimen
            url = "%s?project_uuid=%s" % (reverse('ids_projects:specimen-create'), project_uuid)
            return HttpResponseRedirect(url)


        elif request.POST.get('upload_option', None) == 'Bulk':

            try:
                specimens_meta = _validate_specimens(request.FILES['file'], project)
                bulk_specimen_registration.apply_async(args=(specimens_meta,
                                                             project_uuid,
                                                             request.user.username), serilizer='json')

                success_msg = 'Your %d specimens have been in the registration queue.' % len(specimens_meta)
                logger.info(success_msg)
                messages.success(request, success_msg)
                return HttpResponseRedirect(
                                reverse('ids_projects:project-view',
                                        kwargs={'project_uuid': project.uuid}))

            except Exception as e:
                traceback.print_exc()
                exception_msg = repr(e)
                logger.error(exception_msg)
                messages.warning(request, exception_msg)

                return HttpResponseRedirect(
                                reverse('ids_projects:project-view',
                                        kwargs={'project_uuid': project.uuid}))

    # GET
    else:
        context = {'project': project}
        context['form_upload_file'] = UploadFileForm()
        context['form_upload_option'] = UploadOptionForm()
        return render(request, 'ids_projects/specimens/upload_option.html', context)
def list_public(request):
    """List all public datasets in a project"""
    api_client = get_portal_api_client()

    try:
        public_datasets = Dataset.list(api_client=api_client)
    except Exception as e:
        exception_msg = 'Unable to load datasets. %s' % e
        logger.error(exception_msg)
        messages.warning(request, exception_msg)
        return HttpResponseRedirect(reverse('ids_projects:project-list-private'))

    context = { 'public_datasets': public_datasets }

    return render(request, 'ids_projects/datasets/index.html', context)
def get_outputs_of_api(request, uuid, offset):
	if request.user.is_anonymous():
		api_client = get_portal_api_client()
	else:
		api_client = request.user.agave_oauth.api_client

	try:
		query = {'value._relationships': {'$elemMatch': {'@id': uuid, '@rel:type': 'HasOutput'}}}
		response = api_client.meta.listMetadata(q=json.dumps(query), offset=offset)
		return HttpResponse(json.dumps(response, cls=DjangoJSONEncoder), 
												content_type='application/json')

	except Exception as e:
		exception_msg = 'Unable to load related objects. %s' % e
        logger.error(exception_msg)
        messages.error(request, exception_msg)
        return HttpResponseRedirect('/projects/')
    def calculate_checksum(self):
        """ """
        name = "checksum"
        app_id = "idsvc_checksum-0.1"
        archive = True

        portal_client = get_portal_api_client()

        if self.sra_id:
            parameters = {'UUID': self.uuid, 'SRA': self.sra_id}
            body = {'name': name, 'appId': app_id, 'parameters': parameters}
        else:
            agave_url = "agave://%s/%s" % (self.system_id, self.path)
            inputs = { 'AGAVE_URL': agave_url }
            parameters = { 'UUID': self.uuid }
            body={'name': name, 'appId': app_id, 'inputs': inputs, 'parameters': parameters, 'archive': archive}

        try:
            self.meta['value'].update(
                 {'checksum': None,
                  'lastChecksumUpdated': None,
                  'checksumConflict': None,
                  'checkStatus': None})
            self.save()
        except Exception as e:
            exception_msg = 'Unable to initiate job. %s' % e
            logger.error(exception_msg)
            raise Exception(exception_msg)

        try:
            logger.debug("Job submission body: %s" % body)

            import pprint
            pprint.pprint(body)

            # response = self._api_client.jobs.submit(body=body)
            response = portal_client.jobs.submit(body=body)

            logger.debug("Job submission response: %s" % response['id'])
        except Exception as e:
            exception_msg = 'Unable to initiate job. %s' % e
            logger.error(exception_msg)
            raise Exception(exception_msg)

        return response
def list(request):
    """ """
    project_uuid = request.GET.get('project_uuid', None)
    specimen_uuid = request.GET.get('specimen_uuid', None)
    process_uuid = request.GET.get('process_uuid', None)

    if request.user.is_anonymous():
        api_client = get_portal_api_client()
    else:
        api_client = request.user.agave_oauth.api_client

    project = None
    specimen = None
    process = None
    data = None

    try:
        if project_uuid:
            project = Project(api_client=api_client, uuid=project_uuid)
            data = project.data
        elif specimen_uuid:
            specimen = Specimen(api_client=api_client, uuid=specimen_uuid)
            data = specimen.data
            project = specimen.project
        elif process_uuid:
            process = Process(api_client=api_client, uuid=process_uuid)
            data = process.data
            specimen = process.specimen
            project = process.project
        else:
            data = Data.list(api_client=api_client)
    except Exception as e:
        exception_msg = 'Unable to load data. %s' % e
        logger.error(exception_msg)
        messages.warning(request, exception_msg)
        return HttpResponseRedirect(reverse('ids_projects:project-list-private'))

    context = { 'project' : project,
                'specimen': specimen,
                'process' : process,
                'data'    : data }

    return render(request, 'ids_projects/data/index.html', context)
def add_images(request):
    print "In the add images"
    project_uuid = request.GET.get('project_uuid', False)

    if not project_uuid:
        messages.warning(request, 'Missing project UUID, cannot create specimen.')
        return HttpResponseRedirect(reverse('ids_projects:project-list-private'))

    if request.user.is_anonymous():
        api_client = get_portal_api_client()
    else:
        api_client = request.user.agave_oauth.api_client

    project = Project(api_client=api_client, uuid=project_uuid)

    if request.method == 'POST':

        if request.FILES['file'] != None:
            try:
                images_meta = _image_process(request.FILES['file'], project)
                bulk_images_registration.apply_async(args=(images_meta, project_uuid, request.user.username), serilizer = 'json')
                return HttpResponseRedirect(
                                    reverse('ids_projects:project-view',
                                            kwargs={'project_uuid': project.uuid}))


            except Exception as e:
                traceback.print_exc()
                exception_msg = repr(e)
                logger.error(exception_msg)
                messages.warning(request, exception_msg)

                return HttpResponseRedirect(
                                    reverse('ids_projects:project-view',
                                            kwargs={'project_uuid': project.uuid}))

    # GET
    else:
        print "GET request"
        context = {'project': project}
        context['form_upload_file'] = UploadFileForm()
        return render(request, 'ids_projects/data/add_images.html', context)
def view(request, process_uuid):
    """ """
    if request.user.is_anonymous():
        api_client = get_portal_api_client()
    else:
        api_client = request.user.agave_oauth.api_client

    try:
        process = Process(api_client=api_client, uuid=process_uuid)
        project = process.project
        specimen = process.specimen
        data = process.data
        inputs = process.inputs
        outputs = process.outputs
    except Exception as e:
        exception_msg = "Unable to load process. %s" % e
        logger.error(exception_msg)
        messages.warning(request, exception_msg)
        return HttpResponseRedirect(reverse("ids_projects:project-list-private"))

    try:
        process_types = get_process_type_keys(project)
        process_fields = get_process_fields(project, process.value["process_type"])
        process.set_fields(process_fields)
    except Exception as e:
        exception_msg = "Unable to load config values. %s" % e
        logger.warning(exception_msg)

    context = {
        "process": process,
        "project": project,
        "specimen": specimen,
        "datas": data,
        "inputs": inputs,
        "outputs": outputs,
        "process_types": process_types,
    }

    return render(request, "ids_projects/processes/detail.html", context)
def bulk_images_registration(self, images_meta, project_uuid, username=None):

    if username:
        UserModel = get_user_model()
        user = UserModel.objects.get(username=username)
        api_client = user.agave_oauth.api_client
    else:
        api_client = get_portal_api_client()

    project = Project(api_client, uuid=project_uuid)

    for image_meta in images_meta:
        meta = {'value': image_meta}
        # create new data object
        data = Data(api_client=api_client, meta=meta)
        data.save()
        # data.calculate_checksum()

        project.add_data(data)
        project.save()

        data.add_project(project)
        data.save()
def list(request):
    """List all specimens related to a project"""
    project_uuid = request.GET.get('project_uuid', None)

    if not project_uuid:
        messages.warning(request, 'Missing project UUID, cannot find specimens.')
        return HttpResponseRedirect(reverse('ids_projects:project-list-private'))

    if request.user.is_anonymous():
        api_client = get_portal_api_client()
    else:
        api_client = request.user.agave_oauth.api_client

    try:
        project = Project(api_client=api_client, uuid=project_uuid)
    except Exception as e:
        exception_msg = 'Unable to load project. %s' % e
        logger.error(exception_msg)
        messages.warning(request, exception_msg)
        return HttpResponseRedirect('/projects/')

    context = {'project': project, 'specimens': project.specimens}
    return render(request, 'ids_projects/specimens/index.html', context)
def request_ark(request, dataset_uuid):
    if request.method == 'GET':
        context = {}
        if request.user.is_anonymous():
            api_client = get_portal_api_client()
        else:
            api_client = request.user.agave_oauth.api_client

        try:
            dataset = Dataset(api_client=api_client, uuid=dataset_uuid)
            associated_ids = dataset.identifiers
            if _has_identifier(associated_ids, 'ark'):
                messages.warning(request, "Dataset alread has an ARK identifier.")
                return HttpResponseRedirect(reverse('ids_projects:project-list-private'))

            metadata = meta_for_ark(dataset)
            client = ezidClient('apitest', 'apitest')
            response = client.Mint('ark:/99999/fk4', metadata)

            if "success" in response.keys():
                ark = response['success']

                identifier = Identifier(api_client=api_client, type='ark', uid=ark, dataset=dataset)
                identifier.save()
                dataset = _add_identifier_to_dataset(dataset, identifier)
            else:
                logger.error("Failed to mint an ARK identifier!")
                messages.warning(request, "Error in requesting ARK!")
                return HttpResponseRedirect(reverse('ids_projects:project-list-private'))

            return render(request, 'ids_projects/datasets/request_doi.html', context)

        except Exception as e:
            exception_msg = 'Unable to load process. %s' % e
            logger.error(exception_msg)
            messages.warning(request, exception_msg)
            return HttpResponseRedirect(reverse('ids_projects:project-list-private'))
def view(request, identifier_uuid):
    """View a specific identifier"""
    if request.user.is_anonymous():
        api_client = get_portal_api_client()
    else:
        api_client = request.user.agave_oauth.api_client

    try:
        identifier = Identifier(api_client=api_client, uuid=identifier_uuid)
    except Exception as e:
        exception_msg = 'Unable to load process. %s' % e
        logger.error(exception_msg)
        messages.warning(request, exception_msg)
        return HttpResponseRedirect(reverse('ids_projects:project-list-private'))

    try:
        uid = identifier.uid
    except Exception as e:
        exception_msg = 'Unable to load config values. %s' % e
        logger.warning(exception_msg)

    url = "http://ezid.cdlib.org/id/" + uid

    return HttpResponseRedirect(url)
def request_doi(request, dataset_uuid):
    if request.method == 'GET':
        context = {}
        if request.user.is_anonymous():
            api_client = get_portal_api_client()
        else:
            api_client = request.user.agave_oauth.api_client

        try:
            dataset = Dataset(api_client=api_client, uuid=dataset_uuid)
            associated_ids = dataset.identifiers
            if _has_identifier(associated_ids, 'doi'):
                messages.warning(request, "Dataset alread has a DOI identifier.")
                return HttpResponseRedirect(reverse('ids_projects:project-list-private'))

            essential = meta_for_doi(dataset)

            builder = identifierBuilder()
            builder.buildXML(essential)
            xmlObject = builder.getXML()

            # requesting doi
            client = ezidClient('apitest', 'apitest')
            metadata = {}
            metadata["datacite"] = ET.tostring(xmlObject, encoding = "UTF-8", method = "xml")
            response = client.Mint('doi:10.5072/FK2', metadata)
            if "success" in response.keys():
                res = response['success']
                doi = res.split('|')[0].strip()
                ark = res.split('|')[1].strip()

                # update generated ARK as alternative identifier
                essential_new = update_alternateIdentifier(essential, ark)
                builder.setAlternateIdentifiers(essential_new)
                xmlObject = builder.getXML()
                metadata["datacite"] = ET.tostring(xmlObject, encoding = "UTF-8", method = "xml")
                response = client.Update(doi, metadata)

                # save identifier objects
                identifier = Identifier(api_client=api_client, type='doi', uid=doi, dataset=dataset)
                identifier.save()
                dataset = _add_identifier_to_dataset(dataset, identifier)

                # NOTES:
                # It seems due to network delay, results are not printed immediately.
                # However, the metadata were successfully updated in agave
                # for elem in dataset.identifiers:
                #     print elem.title, elem.uid

            else:
                logger.error("Failed to mint a DOI identifier!")
                messages.warning(request, "Error in requesting DOI!")
                return HttpResponseRedirect(reverse('ids_projects:project-list-private'))


            return render(request, 'ids_projects/datasets/request_doi.html', context)

        except Exception as e:
            exception_msg = 'Unable to load process. %s' % e
            logger.error(exception_msg)
            messages.warning(request, exception_msg)
            return HttpResponseRedirect(reverse('ids_projects:project-list-private'))
def bulk_ISH_registration(self, ISH_meta, process_meta, project_uuid, username=None):

    if username:
        UserModel = get_user_model()
        user = UserModel.objects.get(username=username)
        api_client = user.agave_oauth.api_client
    else:
        api_client = get_portal_api_client()

    project = Project(api_client, uuid=project_uuid)

    for ISH_link in ISH_meta:
        # create a new process
        process = Process(api_client=api_client, meta=process_meta)
        process.save()

        # two-way binding
        project.add_process(process)
        project.save()
        process.add_project(project)
        process.save()

        # Query probes with given probe ids
        # TO DO: What if some probes are not registered in the system
        probe_ids = ISH_link['probe_id'].split(',')

        logger.debug("Probe IDs: {}".format(probe_ids))

        probes = project.query_probes_by_id(probe_ids)

        # Query specimens with given specimen ids
        specimen_ids = ISH_link['specimen_id'].split(',')
        specimens = project.query_specimens_by_id(specimen_ids)

        # Query data with given image uri
        image_urls = ISH_link['image_url'].split(',')
        images = project.query_images_by_url(image_urls)
        print "number of images returned %d" % len(images)

        for probe in probes:
            process.add_input(probe)
            probe.add_is_input_to(process)
            process.save()
            probe.save()
            # print probe.value

        # Query specimens with given specimen ids
        specimen_ids = ISH_link['specimen_id'].split(',')

        logger.debug("Specimen IDs: {}".format(specimen_ids))
        specimens = project.query_specimens_by_id(specimen_ids)

        for specimen in specimens:
            process.add_input(specimen)
            specimen.add_is_input_to(process)
            process.save()
            specimen.save()

        for image in images:
            process.add_output(image)
            image.add_is_output_of(process)
            process.save()
            image.save()
def type_select(request):
    """ """
    project_uuid = request.GET.get('project_uuid', None)
    specimen_uuid = request.GET.get('specimen_uuid', None)
    process_uuid = request.GET.get('process_uuid', None)
    relationship = request.GET.get('relationship', None)

    # check to make sure we have at least one parent uuid (project or specimen)

    if not process_uuid and not specimen_uuid and not project_uuid:
        messages.warning(request, 'Missing parent UUID, cannot add data.')
        return HttpResponseRedirect(reverse('ids_projects:project-list-private'))

    data_type_choices = [('', 'Choose one'), ('SRA', 'SRA'), ('File','File')]

    if request.user.is_anonymous():
        api_client = get_portal_api_client()
    else:
        api_client = request.user.agave_oauth.api_client

    #######
    # GET #
    #######
    if request.method == 'GET':
        project = None
        specimen = None
        process = None
        try:
            if process_uuid is not None:
                process = Process(api_client=api_client, uuid=process_uuid)
                specimen = process.specimen
                project = process.project
            elif specimen_uuid is not None:
                process = None
                specimen = Specimen(api_client=api_client, uuid=specimen_uuid)
                project = specimen.project
            elif project_uuid is not None:
                process = None
                specimen = None
                project = Project(api_client=api_client, uuid=project_uuid)
        except Exception as e:
            exception_msg = 'Unable to load parent object. %s' % e
            logger.error(exception_msg)
            messages.warning(request, exception_msg)
            return HttpResponseRedirect(reverse('ids_projects:project-list-private'))

        form_data_type = DataTypeForm(data_type_choices)

        context = {
            'project': project,
            'specimen': specimen,
            'process': process,
            'form_data_type': form_data_type,
            'cancel_url': _get_cancel_url(request)
        }

        return render(request, 'ids_projects/data/type_select.html', context)

    ########
    # POST #
    ########
    elif request.method == 'POST':

        form_data_type = DataTypeForm(data_type_choices, request.POST)

        if form_data_type.is_valid():

            data = form_data_type.cleaned_data
            data_type = data.get('data_type')

            if data_type == 'SRA':
                if process_uuid is not None:
                    return HttpResponseRedirect('%s?process_uuid=%s' %
                        (reverse('ids_projects:add-sra', kwargs={'relationship': relationship}), process_uuid)
                    )
                elif specimen_uuid is not None:
                    return HttpResponseRedirect('%s?specimen_uuid=%s' %
                        (reverse('ids_projects:add-sra', kwargs={'relationship': relationship}), specimen_uuid)
                    )
                elif project_uuid is not None:
                    return HttpResponseRedirect('%s?project_uuid=%s' %
                        (reverse('ids_projects:add-sra', kwargs={'relationship': relationship}), project_uuid)
                    )

            elif data_type == 'File':
                if process_uuid is not None:
                    return HttpResponseRedirect('%s?process_uuid=%s' %
                        (reverse('ids_projects:file-select', kwargs={'relationship': relationship}), process_uuid)
                    )
                elif specimen_uuid is not None:
                    return HttpResponseRedirect('%s?specimen_uuid=%s' %
                        (reverse('ids_projects:file-select', kwargs={'relationship': relationship}), specimen_uuid)
                    )
                elif project_uuid is not None:
                    return HttpResponseRedirect('%s?project_uuid=%s' %
                        (reverse('ids_projects:file-select', kwargs={'relationship': relationship}), project_uuid)
                    )
def handle_webhook(request, hook_type, *args, **kwargs):
    """
    Required parameters:
        hook_type           ['update_checksum'|'test_job']
        UUID                Unique IDS identifier for the data object to modify
        checksum            Calculated checksum value

    Testing from command line:
        curl -k --data 'UUID=2483901498122179046-242ac1111-0001-012&checksum=060a735c8f6240949ae7ac9fd8d22129' http://localhost:8000/webhook/update_checksum/
    """

    if hook_type == 'update_checksum':
        api_client = get_portal_api_client()

        try:
            logger.debug('profile: {}'.format(api_client.profiles.get()))
        except Exception as e:
            logger.error('bad client: %s', repr(e))

        logger.debug('Webhook request type: %s, body: %s' % (hook_type, request.body))

        if request.GET:
            print "GET"
            uuid = request.GET.get('UUID', None)
            checksum = request.GET.get('checksum', None)
            # last_checksum_update = request.GET.get('lastChecksumUpdated', None)
        elif request.POST:
            print "POST"
            logger.debug(request.POST)
            uuid = request.POST.get('UUID', None)
            checksum = request.POST.get('checksum', None)
            # last_checksum_update = request.POST.get('lastChecksumUpdated', None)

        if uuid is None:
            logger.exception('Missing UUID.')
            return HttpResponse("Error\n")

        if checksum is None:
            logger.exception('Missing checksum.')
            return HttpResponse("Error\n")

        try:
            data = Data(api_client=api_client, uuid=uuid)
            logger.debug('Metadata for UUID %s: %s' % (uuid, data.value))
        except Exception as e:
            logger.exception('Invalid UUID ( %s ), Agave object not found. %s' % (uuid, repr(e)))
            return HttpResponse("Error")

        updated_time = datetime.datetime.now()
        previous_checksum = data.value.get('checksum', None)

        time_template = "%Y-%m-%dT%H:%M:%S"

        if previous_checksum is None:
            try:
                data.value['checksum'] = checksum
                data.value['lastChecksumUpdated'] = updated_time.strftime(time_template)
                data.value['checkStatus'] = True
                data.save()
                logger.debug('New checksum saved for UUID: %s!' % uuid)
            except Exception as e:
                logger.exception('Checksum was not saved successfully. %s' % e)
                return HttpResponse("Error")
        elif previous_checksum == checksum:
            try:
                data.value['checksum'] = checksum
                data.value['lastChecksumUpdated'] = updated_time.strftime(time_template)
                data.value['checkStatus'] = True
                data.save()
                logger.debug('Checksum is identical, timestamp updated for UUID: %s!' % uuid)
            except Exception as e:
                logger.exception('Checksum was not saved successfully. %s' % e)
                return HttpResponse("Error")
        else:
            try:
                data.value['checksumConflict'] = checksum
                data.value['lastChecksumUpdated'] = updated_time.strftime(time_template)
                data.value['checkStatus'] = False
                data.save()
                logger.warning('Checksum is NOT consistent with previous for UUID: %s!' % uuid)
            except Exception as e:
                logger.exception('Checksum was not saved successfully. %s' % e)
                return HttpResponse("Error")

        return HttpResponse(uuid + ' ' + checksum + '\n')

    # testing for calling job
    elif hook_type == 'test_job':
        uuid = '4544798190901268966-242ac1111-0001-012'
        data = Data(uuid=uuid)
        data.calculate_checksum()
        return HttpResponse('Job submitted for uuid = %s!' % uuid)
    else:
        return HttpResponse('OK')