Search in sources :

Example 11 with AuthenticatedUser

use of org.activityinfo.legacy.shared.AuthenticatedUser in project activityinfo by bedatadriven.

the class JobResourceTest method startJob.

@Test
public void startJob() {
    final org.activityinfo.json.JsonParser parser = new org.activityinfo.json.JsonParser();
    final Queue queue = QueueFactory.getDefaultQueue();
    final AuthenticatedUser user = new AuthenticatedUser("XYZ", 1, "akbertram@gmail.com");
    final JobResource resource = new JobResource(Providers.of(user), queue);
    // First request starts the job
    final String jobId = ObjectifyService.run(new Work<String>() {

        @Override
        public String run() {
            TableModel tableModel = ImmutableTableModel.builder().formId(ResourceId.valueOf("FORM1")).build();
            ExportFormJob exportForm = new ExportFormJob(tableModel);
            JobRequest request = new JobRequest(exportForm, "en");
            Response response = resource.start(request.toJsonObject().toJson());
            JsonValue resultObject = parser.parse((String) response.getEntity());
            JobStatus result = JobStatus.fromJson(resultObject);
            assertThat(result.getState(), equalTo(JobState.STARTED));
            return result.getId();
        }
    });
    // Second request retrieves status
    ObjectifyService.run(new VoidWork() {

        @Override
        public void vrun() {
            Response statusResponse = resource.get(jobId);
            JsonValue statusObject = parser.parse(((String) statusResponse.getEntity()));
            JobStatus status = JobStatus.fromJson(statusObject);
            assertThat(status.getState(), equalTo(JobState.STARTED));
        }
    });
}
Also used : JsonValue(org.activityinfo.json.JsonValue) AuthenticatedUser(org.activityinfo.legacy.shared.AuthenticatedUser) ExportFormJob(org.activityinfo.model.job.ExportFormJob) Response(javax.ws.rs.core.Response) JobStatus(org.activityinfo.model.job.JobStatus) JobRequest(org.activityinfo.model.job.JobRequest) VoidWork(com.googlecode.objectify.VoidWork) Queue(com.google.appengine.api.taskqueue.Queue) TableModel(org.activityinfo.model.analysis.TableModel) ImmutableTableModel(org.activityinfo.model.analysis.ImmutableTableModel) Test(org.junit.Test)

Example 12 with AuthenticatedUser

use of org.activityinfo.legacy.shared.AuthenticatedUser in project activityinfo by bedatadriven.

the class PivotTestResource method get.

@GET
@Path("report")
@Produces(MediaType.APPLICATION_JSON)
public List<PivotSites.PivotResult> get(@QueryParam("reportId") int reportId, @QueryParam("userId") int userId, @QueryParam("new") boolean newEngine, @QueryParam("details") boolean showDetails) {
    assertRunningInLocalDevelopmentEnvironment();
    authProvider.set(new AuthenticatedUser("XYZ", userId, "user@user.org"));
    ReportDTO report = dispatcher.execute(new GetReportModel(reportId));
    Report model = report.getReport();
    List<PivotSites.PivotResult> results = Lists.newArrayList();
    for (ReportElement element : model.getElements()) {
        if (element instanceof PivotReportElement) {
            PivotSites command = command(model, (PivotReportElement) element, newEngine, showDetails);
            if (!command.isTooBroad()) {
                results.add(dispatcher.execute(command));
            } else {
                results.add(new PivotSites.PivotResult());
            }
        }
    }
    return results;
}
Also used : Report(org.activityinfo.legacy.shared.reports.model.Report) PivotReportElement(org.activityinfo.legacy.shared.reports.model.PivotReportElement) ReportDTO(org.activityinfo.legacy.shared.model.ReportDTO) PivotReportElement(org.activityinfo.legacy.shared.reports.model.PivotReportElement) ReportElement(org.activityinfo.legacy.shared.reports.model.ReportElement) AuthenticatedUser(org.activityinfo.legacy.shared.AuthenticatedUser)

Example 13 with AuthenticatedUser

use of org.activityinfo.legacy.shared.AuthenticatedUser in project activityinfo by bedatadriven.

the class XFormResources method manifest.

@GET
@Path("{id}/manifest")
@Produces(MediaType.TEXT_XML)
public Response manifest(@Context UriInfo uri, @PathParam("id") int id) {
    AuthenticatedUser user = authProvider.get();
    LOGGER.finer("ODK manifest for " + id + " requested by " + user.getEmail() + " (" + user.getId() + ")");
    MediaFile itemSet = new MediaFile();
    itemSet.setFilename("itemsets.csv");
    itemSet.setHash("md5:00000000000000000000000000000000");
    itemSet.setDownloadUrl(uri.getBaseUriBuilder().path(XFormResources.class).path(Integer.toString(id)).path("itemsets.csv").build());
    XFormManifest manifest = new XFormManifest();
    return OpenRosaResponse.build(manifest);
}
Also used : MediaFile(org.activityinfo.io.xform.manifest.MediaFile) XFormManifest(org.activityinfo.io.xform.manifest.XFormManifest) AuthenticatedUser(org.activityinfo.legacy.shared.AuthenticatedUser)

Example 14 with AuthenticatedUser

use of org.activityinfo.legacy.shared.AuthenticatedUser 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 15 with AuthenticatedUser

use of org.activityinfo.legacy.shared.AuthenticatedUser in project activityinfo by bedatadriven.

the class AuthenticationFilter method doFilter.

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
    allowCrossOriginRequests((HttpServletResponse) response);
    contentSecurityPolicy.applyTo((HttpServletResponse) response);
    authProvider.clear();
    String authToken = ((HttpServletRequest) request).getHeader("Authorization");
    if (Strings.isNullOrEmpty(authToken)) {
        authToken = authTokenFromCookie();
    }
    if (authToken != null) {
        try {
            AuthenticatedUser currentUser = authTokenCache.get(authToken);
            authProvider.set(currentUser);
            if (currentUser != null) {
                LOGGER.info("Request authenticated as " + currentUser.getEmail());
            }
        } catch (Exception e) {
            authProvider.clear();
        }
    }
    // Unless overridden by the Application page or command handler,
    // we'll keep the default to English. Otherwise you end up with unexpected
    // behavior when the content of a page changes when a cookie is / is not present
    // https://bedatadriven.atlassian.net/browse/AI-753
    ThreadLocalLocaleProvider.pushLocale(Locale.ENGLISH);
    try {
        filterChain.doFilter(request, response);
    } finally {
        ThreadLocalLocaleProvider.popLocale();
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) AuthenticatedUser(org.activityinfo.legacy.shared.AuthenticatedUser) IOException(java.io.IOException)

Aggregations

AuthenticatedUser (org.activityinfo.legacy.shared.AuthenticatedUser)22 WebApplicationException (javax.ws.rs.WebApplicationException)3 Before (org.junit.Before)3 EntityManager (javax.persistence.EntityManager)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 Response (javax.ws.rs.core.Response)2 FormClass (org.activityinfo.model.form.FormClass)2 ResourceId (org.activityinfo.model.resource.ResourceId)2 User (org.activityinfo.server.database.hibernate.entity.User)2 Test (org.junit.Test)2 Queue (com.google.appengine.api.taskqueue.Queue)1 GcsFileMetadata (com.google.appengine.tools.cloudstorage.GcsFileMetadata)1 GcsFilename (com.google.appengine.tools.cloudstorage.GcsFilename)1 Optional (com.google.common.base.Optional)1 VoidWork (com.googlecode.objectify.VoidWork)1 Viewable (com.sun.jersey.api.view.Viewable)1 IOException (java.io.IOException)1 OutputStream (java.io.OutputStream)1 Properties (java.util.Properties)1 XForm (org.activityinfo.io.xform.form.XForm)1