Search in sources :

Example 11 with KeyGenerator

use of org.activityinfo.model.legacy.KeyGenerator in project activityinfo by bedatadriven.

the class LocationsResource method postNewLocations.

@POST
@Path("/{typeId}")
@Timed(name = "api.rest.locations.post")
public Response postNewLocations(@InjectParam EntityManager entityManager, @PathParam("typeId") int locationTypeId, List<NewLocation> locations) {
    KeyGenerator generator = new KeyGenerator();
    entityManager.getTransaction().begin();
    LocationType locationType = entityManager.getReference(LocationType.class, locationTypeId);
    for (NewLocation newLocation : locations) {
        Location location = new Location();
        location.setId(generator.generateInt());
        System.out.println(location.getId());
        location.setName(newLocation.getName());
        location.setLocationType(locationType);
        location.setX(newLocation.getLongitude());
        location.setY(newLocation.getLatitude());
        location.setTimeEdited(new Date());
        location.setAdminEntities(new HashSet<AdminEntity>());
        for (int entityId : newLocation.getAdminEntityIds()) {
            location.getAdminEntities().add(entityManager.getReference(AdminEntity.class, entityId));
        }
        entityManager.persist(location);
    }
    entityManager.getTransaction().commit();
    return Response.ok().build();
}
Also used : AdminEntity(org.activityinfo.server.database.hibernate.entity.AdminEntity) NewLocation(org.activityinfo.server.endpoint.rest.model.NewLocation) KeyGenerator(org.activityinfo.model.legacy.KeyGenerator) LocationType(org.activityinfo.server.database.hibernate.entity.LocationType) Date(java.util.Date) NewLocation(org.activityinfo.server.endpoint.rest.model.NewLocation) Location(org.activityinfo.server.database.hibernate.entity.Location) Timed(org.activityinfo.server.util.monitoring.Timed)

Example 12 with KeyGenerator

use of org.activityinfo.model.legacy.KeyGenerator in project activityinfo by bedatadriven.

the class XFormSubmissionResource method submit.

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_XML)
public Response submit(byte[] bytes) {
    XFormInstance instance = new XFormInstanceImpl(bytes);
    AuthenticatedUser user = authenticationTokenService.authenticate(instance.getAuthenticationToken());
    FormClass formClass = locator.getFormClass(instance.getFormClassId());
    ResourceId formId = newLegacyFormInstanceId(formClass.getId());
    FormInstance formInstance = new FormInstance(formId, formClass.getId());
    String instanceId = instance.getId();
    LOGGER.log(Level.INFO, "Saving XForm " + instance.getId() + " as " + formId);
    for (FormField formField : formClass.getFields()) {
        if (formField.getType().isUpdatable()) {
            Optional<Element> element = instance.getFieldContent(formField.getId());
            if (element.isPresent()) {
                formInstance.set(formField.getId(), tryParse(formInstance, formField, element.get()));
            } else if (isLocation(formClass, formField)) {
                FieldType fieldType = formField.getType();
                Optional<Element> gpsField = instance.getFieldContent(field(formClass.getId(), GPS_FIELD));
                Optional<Element> nameField = instance.getFieldContent(field(formClass.getId(), LOCATION_NAME_FIELD));
                if (fieldType instanceof ReferenceType && gpsField.isPresent() && nameField.isPresent()) {
                    ResourceId locationFieldId = field(formClass.getId(), LOCATION_FIELD);
                    int newLocationId = new KeyGenerator().generateInt();
                    ReferenceType locationRefType = (ReferenceType) fieldType;
                    if (locationRefType.getRange().isEmpty()) {
                        throw new IllegalStateException("Location field has empty range");
                    }
                    ResourceId locationFormId = locationRefType.getRange().iterator().next();
                    int locationTypeId = getLegacyIdFromCuid(locationFormId);
                    FieldValue fieldValue = new ReferenceValue(new RecordRef(locationFormId, locationInstanceId(newLocationId)));
                    String name = OdkHelper.extractText(nameField.get());
                    if (Strings.isNullOrEmpty(name)) {
                        throw new WebApplicationException(Response.status(BAD_REQUEST).entity("Name value for location field is blank. ").build());
                    }
                    Optional<GeoPoint> geoPoint = parseLocation(gpsField);
                    formInstance.set(locationFieldId, fieldValue);
                    createLocation(newLocationId, locationTypeId, name, geoPoint);
                }
            }
        }
    }
    ensurePartnerIsSet(formClass, formInstance);
    if (!instanceIdService.exists(instanceId)) {
        for (FieldValue fieldValue : formInstance.getFieldValueMap().values()) {
            if (fieldValue instanceof AttachmentValue) {
                persist(user, instance, (AttachmentValue) fieldValue);
            }
        }
        locator.persist(formInstance);
        instanceIdService.submit(instanceId);
    }
    // Backup the original XForm in case something went wrong with processing
    submissionArchiver.backup(formClass.getId(), formId, ByteSource.wrap(bytes));
    return Response.status(CREATED).build();
}
Also used : AttachmentValue(org.activityinfo.model.type.attachment.AttachmentValue) Optional(com.google.common.base.Optional) Element(org.w3c.dom.Element) AuthenticatedUser(org.activityinfo.legacy.shared.AuthenticatedUser) ResourceId(org.activityinfo.model.resource.ResourceId) FormClass(org.activityinfo.model.form.FormClass) XFormInstanceImpl(org.activityinfo.server.endpoint.odk.xform.XFormInstanceImpl) XFormInstance(org.activityinfo.server.endpoint.odk.xform.XFormInstance) FormInstance(org.activityinfo.model.form.FormInstance) FormField(org.activityinfo.model.form.FormField) KeyGenerator(org.activityinfo.model.legacy.KeyGenerator) XFormInstance(org.activityinfo.server.endpoint.odk.xform.XFormInstance)

Example 13 with KeyGenerator

use of org.activityinfo.model.legacy.KeyGenerator in project activityinfo by bedatadriven.

the class AttachmentFieldTemplate method create.

@Override
public FormField create() {
    AttachmentType type = (AttachmentType) AttachmentType.TYPE_CLASS.createType();
    type.setKind(kind);
    FormField formField = new FormField(CuidAdapter.indicatorField(new KeyGenerator().generateInt()));
    formField.setType(type);
    formField.setLabel(label);
    return formField;
}
Also used : AttachmentType(org.activityinfo.model.type.attachment.AttachmentType) FormField(org.activityinfo.model.form.FormField) KeyGenerator(org.activityinfo.model.legacy.KeyGenerator)

Example 14 with KeyGenerator

use of org.activityinfo.model.legacy.KeyGenerator in project activityinfo by bedatadriven.

the class SiteDialog method saveNewSite.

private void saveNewSite() {
    final SiteDTO newSite = new SiteDTO();
    keyGenerator = new KeyGenerator();
    newSite.setId(keyGenerator.generateInt());
    newSite.setActivityId(activity.getId());
    if (activity.getReportingFrequency() == ActivityFormDTO.REPORT_ONCE) {
        newSite.setReportingPeriodId(new KeyGenerator().generateInt());
    }
    updateModel(newSite);
    dispatcher.execute(new CreateSite(newSite), new AsyncCallback<CreateResult>() {

        @Override
        public void onFailure(Throwable caught) {
            showError(caught);
        }

        @Override
        public void onSuccess(CreateResult result) {
            hide();
            callback.onSaved();
        }
    });
}
Also used : CreateResult(org.activityinfo.legacy.shared.command.result.CreateResult) SiteDTO(org.activityinfo.legacy.shared.model.SiteDTO) KeyGenerator(org.activityinfo.model.legacy.KeyGenerator) CreateSite(org.activityinfo.legacy.shared.command.CreateSite)

Example 15 with KeyGenerator

use of org.activityinfo.model.legacy.KeyGenerator in project activityinfo by bedatadriven.

the class ResourceLocatorAdaptorTest method persistSiteWithCalculatedIndicators.

@Test
@OnDataSet("/dbunit/sites-calculated-indicators.db.xml")
public void persistSiteWithCalculatedIndicators() {
    int siteId = new KeyGenerator().generateInt();
    FormInstance instance = new FormInstance(CuidAdapter.cuid(SITE_DOMAIN, siteId), NFI_DIST_FORM_CLASS);
    instance.set(indicatorField(1), 1);
    instance.set(indicatorField(2), 2);
    instance.set(locationField(NFI_DIST_ID), locationRef(VILLAGE_CLASS, 1));
    instance.set(partnerField(NFI_DIST_ID), partnerRef(PEAR_DATABASE_ID, 1));
    instance.set(projectField(NFI_DIST_ID), projectRef(PEAR_DATABASE_ID, 1));
    instance.set(field(NFI_DIST_FORM_CLASS, START_DATE_FIELD), new LocalDate(2014, 1, 1));
    instance.set(field(NFI_DIST_FORM_CLASS, END_DATE_FIELD), new LocalDate(2014, 1, 1));
    instance.set(field(NFI_DIST_FORM_CLASS, COMMENT_FIELD), NarrativeValue.valueOf("My comment"));
    assertResolves(locator.persist(instance));
    FormInstance firstRead = assertResolves(locator.getFormInstance(NFI_DIST_FORM_CLASS, instance.getId()));
    assertThat(firstRead.get(indicatorField(1)), equalTo((FieldValue) new Quantity(1)));
    assertThat(firstRead.get(indicatorField(2)), equalTo((FieldValue) new Quantity(2)));
    // set indicators to null
    instance.set(indicatorField(1).asString(), null);
    instance.set(indicatorField(2).asString(), null);
    // persist it
    assertResolves(locator.persist(instance));
    // read from server
    FormInstance secondRead = assertResolves(locator.getFormInstance(NFI_DIST_FORM_CLASS, instance.getId()));
    // BENE
    assertThat(secondRead.get(indicatorField(1)), nullValue());
    // BACHE
    assertThat(secondRead.get(indicatorField(2)), nullValue());
// // Both BENE+BACHE and BENE/BACHE should be missing, because both
// // BENE and BACHE are missing
// assertEquals(null, secondRead.getValue(path(indicatorField(11))));
// assertEquals(null, secondRead.getValue(path(indicatorField(12))));
}
Also used : Quantity(org.activityinfo.model.type.number.Quantity) FieldValue(org.activityinfo.model.type.FieldValue) FormInstance(org.activityinfo.model.form.FormInstance) KeyGenerator(org.activityinfo.model.legacy.KeyGenerator) LocalDate(org.activityinfo.model.type.time.LocalDate) GeoPoint(org.activityinfo.model.type.geo.GeoPoint) OnDataSet(org.activityinfo.server.database.OnDataSet) Test(org.junit.Test)

Aggregations

KeyGenerator (org.activityinfo.model.legacy.KeyGenerator)18 Test (org.junit.Test)9 FormClass (org.activityinfo.model.form.FormClass)6 FormField (org.activityinfo.model.form.FormField)6 GeoPoint (org.activityinfo.model.type.geo.GeoPoint)6 FormInstance (org.activityinfo.model.form.FormInstance)5 ResourceId (org.activityinfo.model.resource.ResourceId)4 GregorianCalendar (java.util.GregorianCalendar)3 CreateSite (org.activityinfo.legacy.shared.command.CreateSite)3 CreateResult (org.activityinfo.legacy.shared.command.result.CreateResult)3 RecordUpdate (org.activityinfo.model.resource.RecordUpdate)3 FieldValue (org.activityinfo.model.type.FieldValue)3 LocalDate (org.activityinfo.model.type.time.LocalDate)3 OnDataSet (org.activityinfo.server.database.OnDataSet)3 SiteDTO (org.activityinfo.legacy.shared.model.SiteDTO)2 RecordTransactionBuilder (org.activityinfo.model.resource.RecordTransactionBuilder)2 AttachmentValue (org.activityinfo.model.type.attachment.AttachmentValue)2 Quantity (org.activityinfo.model.type.number.Quantity)2 TypedRecordUpdate (org.activityinfo.store.spi.TypedRecordUpdate)2 Optional (com.google.common.base.Optional)1