<commit_before>/**
 * JBoss, Home of Professional Open Source
 * Copyright Red Hat, Inc., and individual contributors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jboss.aerogear.connectivity.rest.registry.instances;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.OPTIONS;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.Response.Status;

import org.jboss.aerogear.connectivity.api.MobileVariant;
import org.jboss.aerogear.connectivity.model.MobileVariantInstanceImpl;
import org.jboss.aerogear.connectivity.rest.security.util.HttpBasicHelper;
import org.jboss.aerogear.connectivity.service.MobileVariantInstanceService;
import org.jboss.aerogear.connectivity.service.MobileVariantService;

@Stateless
@Path("/registry/device")
@TransactionAttribute
public class MobileVariantInstanceEndpoint {
    @Inject
    private Logger logger;
    @Inject
    private MobileVariantInstanceService mobileApplicationInstanceService;
    @Inject
    private MobileVariantService mobileApplicationService;

    @OPTIONS
    public Response crossOriginForInstallations(@HeaderParam("Access-Control-Request-Headers") String requestHeaders) {
        ResponseBuilder response = Response.ok();
        
        return response.header("Access-Control-Allow-Origin", "*")
                .header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
                .header("Access-Control-Allow-Headers", requestHeaders)
                .build();
    }

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    public Response registerInstallation(
            MobileVariantInstanceImpl entity,
            @Context HttpServletRequest request) {

        // find the matching variation:
        final MobileVariant mobileVariant = loadMobileVariantWhenAuthorized(request);
        if (mobileVariant == null) {
            return Response.status(Status.UNAUTHORIZED)
                    .entity("Unauthorized Request").build();
        }

        // Poor validation: We require the Token!
        if (entity.getDeviceToken() == null) {
            return Response.status(Status.BAD_REQUEST).build();
        }

        // look up all instances for THIS variant:
        List<MobileVariantInstanceImpl> instances = findInstanceByDeviceToken(
                mobileVariant.getInstances(), entity.getDeviceToken());
        if (instances.isEmpty()) {
            // store the installation:
            entity = mobileApplicationInstanceService
                    .addMobileVariantInstance(entity);
            // add installation to the matching variant
            mobileApplicationService.addInstance(mobileVariant, entity);
        } else {
            logger.info("Updating received metadata for MobileVariantInstance");

            // should be impossible
            if (instances.size() > 1) {
                logger.severe("Too many registration for one installation");
            }

            // update the entity:
            entity = this.updateMobileApplicationInstance(instances.get(0),
                    entity);
        }

        return appendAllowOriginHeader(Response.ok());
    }

    @DELETE
    @Path("{token}")
    @Consumes(MediaType.APPLICATION_JSON)
    public Response unregisterInstallations(
            @PathParam("token") String token,
            @Context HttpServletRequest request) {

        // find the matching variation:
        final MobileVariant mobileVariant = loadMobileVariantWhenAuthorized(request);
        if (mobileVariant == null) {
            return Response.status(Status.UNAUTHORIZED)
                    .entity("Unauthorized Request").build();
        }

        // there can be multiple regs.........
        List<MobileVariantInstanceImpl> instances = mobileApplicationInstanceService
                .findMobileVariantInstancesByToken(token);
        // delete them:
        mobileApplicationInstanceService
                .removeMobileVariantInstances(instances);

        return appendAllowOriginHeader(Response.noContent());
    }

    private Response appendAllowOriginHeader(ResponseBuilder rb) {
        return rb.header("Access-Control-Allow-Origin", "*").build();
    }

    // TODO: move to JQL
    private List<MobileVariantInstanceImpl> findInstanceByDeviceToken(
            Set<MobileVariantInstanceImpl> instances, String deviceToken) {
        final List<MobileVariantInstanceImpl> instancesWithToken = new ArrayList<MobileVariantInstanceImpl>();

        for (MobileVariantInstanceImpl instance : instances) {
            if (instance.getDeviceToken().equals(deviceToken))
                instancesWithToken.add(instance);
        }

        return instancesWithToken;
    }

    private MobileVariantInstanceImpl updateMobileApplicationInstance(
            MobileVariantInstanceImpl toUpdate,
            MobileVariantInstanceImpl postedVariant) {
        toUpdate.setCategory(postedVariant.getCategory());
        toUpdate.setDeviceToken(postedVariant.getDeviceToken());
        toUpdate.setAlias(postedVariant.getAlias());
        toUpdate.setDeviceType(postedVariant.getDeviceType());
        toUpdate.setMobileOperatingSystem(postedVariant<commit_msg>Add preflight DELETE handler & return entity in POST response body<commit_after>/**
 * JBoss, Home of Professional Open Source
 * Copyright Red Hat, Inc., and individual contributors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jboss.aerogear.connectivity.rest.registry.instances;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.OPTIONS;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.Response.Status;

import org.jboss.aerogear.connectivity.api.MobileVariant;
import org.jboss.aerogear.connectivity.model.MobileVariantInstanceImpl;
import org.jboss.aerogear.connectivity.rest.security.util.HttpBasicHelper;
import org.jboss.aerogear.connectivity.service.MobileVariantInstanceService;
import org.jboss.aerogear.connectivity.service.MobileVariantService;

@Stateless
@Path("/registry/device")
@TransactionAttribute
public class MobileVariantInstanceEndpoint {
    @Inject
    private Logger logger;
    @Inject
    private MobileVariantInstanceService mobileApplicationInstanceService;
    @Inject
    private MobileVariantService mobileApplicationService;

    @OPTIONS
    @Path("{token}")
    public Response crossOriginForInstallations(
            @Context HttpHeaders headers,
            @PathParam("token") String token) {
        
        return appendPreflightResponseHeaders(headers, Response.ok()).build();
    }
    
    @OPTIONS
    public Response crossOriginForInstallations(
            @Context HttpHeaders headers) {
        
        return appendPreflightResponseHeaders(headers, Response.ok()).build();
    }

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    public Response registerInstallation(
            MobileVariantInstanceImpl entity,
            @Context HttpServletRequest request) {

        // find the matching variation:
        final MobileVariant mobileVariant = loadMobileVariantWhenAuthorized(request);
        if (mobileVariant == null) {
            return Response.status(Status.UNAUTHORIZED)
                    .entity("Unauthorized Request").build();
        }

        // Poor validation: We require the Token!
        if (entity.getDeviceToken() == null) {
            return Response.status(Status.BAD_REQUEST).build();
        }

        // look up all instances for THIS variant:
        List<MobileVariantInstanceImpl> instances = findInstanceByDeviceToken(
                mobileVariant.getInstances(), entity.getDeviceToken());
        if (instances.isEmpty()) {
            // store the installation:
            entity = mobileApplicationInstanceService
                    .addMobileVariantInstance(entity);
            // add installation to the matching variant
            mobileApplicationService.addInstance(mobileVariant, entity);
        } else {
            logger.info("Updating received metadata for MobileVariantInstance");

            // should be impossible
            if (instances.size() > 1) {
                logger.severe("Too many registration for one installation");
            }

            // update the entity:
            entity = this.updateMobileApplicationInstance(instances.get(0),
                    entity);
        }

        return appendAllowOriginHeader(Response.ok(entity), request);
    }

    @DELETE
    @Path("{token}")
    @Consumes(MediaType.APPLICATION_JSON)
    public Response unregisterInstallations(
            @PathParam("token") String token,
            @Context HttpServletRequest request) {

        // find the matching variation:
        final MobileVariant mobileVariant = loadMobileVariantWhenAuthorized(request);
        if (mobileVariant == null) {
            return Response.status(Status.UNAUTHORIZED)
                    .entity("Unauthorized Request").build();
        }

        // there can be multiple regs.........
        List<MobileVariantInstanceImpl> instances = mobileApplicationInstanceService
                .findMobileVariantInstancesByToken(token);
        // delete them:
        mobileApplicationInstanceService
                .removeMobileVariantInstances(instances);

        return appendAllowOriginHeader(Response.noContent(), request);
    }
    
    private ResponseBuilder appendPreflightResponseHeaders(@Context HttpHeaders headers, ResponseBuilder response) {
        // add response headers for the preflight request
        // required
        response.header("Access-Control-Allow-Origin", headers.getRequestHeader("Origin").get(0))
                .header("Access-Control-Allow-Methods", headers.getRequestHeader("Access-Control-Request-Method").get(0));
        // required if the request has an Access-Control-Request-Headers header
        if (headers.getRequestHeader("Access-Control-Request-Headers") != null
                && !headers.getRequestHeader("Access-Control-Request-Headers").isEmpty()) {
            response.header("Access-Control-Allow-Headers", headers.getRequestHeader("Access-Control-Request-Headers").get(0));
        }
        return response;
    }

    private Response appendAllowOriginHeader(ResponseBuilder rb, @Context HttpServletRequest request) {
        return rb.header("Access-Control-Allow-Origin", request.getHeader("Origin")).build();
    }

    // TODO: move to JQL
    private List<MobileVariantInstanceImpl> findInstanceByDeviceToken(
            Set<MobileVariantInstanceImpl> instances, String deviceToken) {
        final List<MobileVariantInstanceImpl> instancesWithToken = new ArrayList<MobileVariantInstanceImpl>();

        for (MobileVariantInstanceImpl instance : instances) {
            if (instance.getDeviceToken().equals(deviceToken))
                instancesWithToken.add(instance);
        }

        return instancesWithToken;
    }

    private MobileVariantInstanceImpl updateMobileApplicationInstance(
            MobileVariantInstanceImpl toUpdate,
            MobileVariantInstanceImpl postedVariant) {
        toUpdate.setCategory(postedVariant.getCategory());
        toUpdate.setDeviceToken(postedVariant.getDeviceToken());
        toUpdate.setAlias(postedVariant.getAlias());
        toUpdate.setDeviceType(postedVariant.getDeviceType());
        toUpdate.setMobileOperatingSystem(postedVariant
{'fraction_non_alphanumeric': 0.09028871391076115, 'fraction_numerical': 0.0011248593925759281, 'mean_word_length': 3.123685837971552, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5049435', 'n_tokens_mistral': 3312, 'n_tokens_neox': 3236, 'n_words': 766}