<commit_before>/*
 * JBoss, Home of Professional Open Source
 * Copyright 2012 Red Hat Inc. and/or its affiliates and other contributors
 * as indicated by the @authors tag. All rights reserved.
 */
package org.searchisko.api.rest;

import org.elasticsearch.action.get.GetResponse;
import org.searchisko.api.ContentObjectFields;
import org.searchisko.api.rest.exception.RequiredFieldException;
import org.searchisko.api.rest.security.AuthenticationUtilService;
import org.searchisko.api.security.Role;
import org.searchisko.api.service.ProviderService;
import org.searchisko.api.service.ProviderService.ProviderContentTypeInfo;
import org.searchisko.api.service.SearchClientService;
import org.searchisko.api.service.SearchIndexMissingException;
import org.searchisko.api.util.SearchUtils;
import org.searchisko.persistence.jpa.model.Rating;
import org.searchisko.persistence.service.RatingPersistenceService;
import org.searchisko.persistence.service.RatingPersistenceService.RatingStats;

import javax.annotation.security.RolesAllowed;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import javax.ws.rs.core.Response.Status;
import java.util.*;
import java.util.logging.Logger;

/**
 * REST API endpoint for 'Personalized Content Rating API'.
 * 
 * @author <NAME> (velias at redhat dot com)
 */
@RequestScoped
@Path("/rating")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@RolesAllowed({Role.ADMIN, Role.CONTRIBUTOR})
public class RatingRestService extends RestServiceBase {

	public static final String QUERY_PARAM_ID = "id";
	public static final String DATA_FIELD_RATING = "rating";

	@Inject
	protected Logger log;

	@Inject
	protected ProviderService providerService;

	@Inject
	protected SearchClientService searchClientService;

	@Inject
	protected RatingPersistenceService ratingPersistenceService;

	@Inject
	protected AuthenticationUtilService authenticationUtilService;

	@Context
	protected SecurityContext securityContext;

	@GET
	@Path("/{id}")
	@Produces(MediaType.APPLICATION_JSON)
	public Object getRating(@PathParam(QUERY_PARAM_ID) String contentSysId) {

		contentSysId = SearchUtils.trimToNull(contentSysId);

		// validation
		if (contentSysId == null) {
			throw new RequiredFieldException(QUERY_PARAM_ID);
		}

		String currentContributorId = authenticationUtilService.getAuthenticatedContributor(securityContext, false);
		if (currentContributorId != null) {
			List<Rating> rl = ratingPersistenceService.getRatings(currentContributorId, contentSysId);
			if (rl != null && !rl.isEmpty()) {
				Map<String, Object> ret = ratingToJSON(rl.get(0));
				return ret;
			} else {
				return Response.status(Status.NOT_FOUND).build();
			}
		} else {
			return Response.status(Status.NOT_FOUND).build();
		}

	}

	/**
	 * Convert {@link Rating} object into JSON map.
	 * 
	 * @param rating to convert
	 * @return JSON map with rating informations
	 */
	protected Map<String, Object> ratingToJSON(Rating rating) {
		Map<String, Object> ret = new HashMap<>();
		ret.put(DATA_FIELD_RATING, rating.getRating());
		return ret;
	}

	@GET
	@Path("/")
	@Produces(MediaType.APPLICATION_JSON)
	public Map<String, Object> getRatings(@Context UriInfo uriInfo) {

		Map<String, Object> ret = new HashMap<>();

		String currentContributorId = authenticationUtilService.getAuthenticatedContributor(securityContext, false);
		if (currentContributorId == null || uriInfo == null) {
			return ret;
		}

		Set<String> contentSysIds = new LinkedHashSet<>();
		List<String> rawids = uriInfo.getQueryParameters().get(QUERY_PARAM_ID);
		if (rawids != null) {
			for (String rid : rawids) {
				rid = SearchUtils.trimToNull(rid);
				if (rid != null) {
					contentSysIds.add(rid);
				}
			}
		}

		if (!contentSysIds.isEmpty()) {
			List<Rating> rl = ratingPersistenceService.getRatings(currentContributorId,
					contentSysIds.toArray(new String[contentSysIds.size()]));
			if (rl != null && !rl.isEmpty()) {
				for (Rating r : rl) {
					ret.put(r.getContentId(), ratingToJSON(r));
				}
			}
		} else {
			throw new RequiredFieldException(QUERY_PARAM_ID);
		}
		return ret;
	}

	@POST
	@Path("/{id}")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public Object postRating(@PathParam(QUERY_PARAM_ID) String contentSysId, Map<String, Object> requestContent) {

		String currentContributorId = authenticationUtilService.getAuthenticatedContributor(securityContext, true);

		contentSysId = SearchUtils.trimToNull(contentSysId);

		// validation
		if (contentSysId == null) {
			throw new RequiredFieldException(QUERY_PARAM_ID);
		}

		Integer rating = null;
		try {
			rating = SearchUtils.getIntegerFromJsonMap(requestContent, DATA_FIELD_RATING);
		} catch (NumberFormatException e) {
			return Response.status(Status.BAD_REQUEST).entity(DATA_FIELD_RATING + " field must be number").build();
		}
		if (rating == null) {
			throw new RequiredFieldException(DATA_FIELD_RATING);
		}<commit_msg>Fixed RatingRestService roles. Used custom check and return 403 (throw exception). #76<commit_after>/*
 * JBoss, Home of Professional Open Source
 * Copyright 2012 Red Hat Inc. and/or its affiliates and other contributors
 * as indicated by the @authors tag. All rights reserved.
 */
package org.searchisko.api.rest;

import org.elasticsearch.action.get.GetResponse;
import org.searchisko.api.ContentObjectFields;
import org.searchisko.api.rest.exception.NotAuthorizedException;
import org.searchisko.api.rest.exception.RequiredFieldException;
import org.searchisko.api.rest.security.AuthenticationUtilService;
import org.searchisko.api.security.Role;
import org.searchisko.api.service.ProviderService;
import org.searchisko.api.service.ProviderService.ProviderContentTypeInfo;
import org.searchisko.api.service.SearchClientService;
import org.searchisko.api.service.SearchIndexMissingException;
import org.searchisko.api.util.SearchUtils;
import org.searchisko.persistence.jpa.model.Rating;
import org.searchisko.persistence.service.RatingPersistenceService;
import org.searchisko.persistence.service.RatingPersistenceService.RatingStats;

import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import javax.ws.rs.core.Response.Status;
import java.util.*;
import java.util.logging.Logger;

/**
 * REST API endpoint for 'Personalized Content Rating API'.
 *
 * @author <NAME> (velias at redhat dot com)
 */
@RequestScoped
@Path("/rating")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
// Standard Roles are not used because it's designed to return 403 if user is not authenticated.
//@RolesAllowed({Role.ADMIN, Role.CONTRIBUTOR})
public class RatingRestService extends RestServiceBase {

	public static final String QUERY_PARAM_ID = "id";
	public static final String DATA_FIELD_RATING = "rating";

	@Inject
	protected Logger log;

	@Inject
	protected ProviderService providerService;

	@Inject
	protected SearchClientService searchClientService;

	@Inject
	protected RatingPersistenceService ratingPersistenceService;

	@Inject
	protected AuthenticationUtilService authenticationUtilService;

	@Context
	protected SecurityContext securityContext;

	/**
	 * Custom authentication check if user is in role ${@link org.searchisko.api.security.Role#CONTRIBUTOR}
	 * or ${@link org.searchisko.api.security.Role#CONTRIBUTOR}
	 *
	 * @throws NotAuthorizedException if user doesn't have role
	 */
	protected void checkIfUserAuthenticated() throws NotAuthorizedException {
		if (!securityContext.isUserInRole(Role.CONTRIBUTOR) || !securityContext.isUserInRole(Role.ADMIN)) {
			throw new NotAuthorizedException("User Not Authorized for Content Rating API");
		}
	}

	@GET
	@Path("/{id}")
	@Produces(MediaType.APPLICATION_JSON)
	public Object getRating(@PathParam(QUERY_PARAM_ID) String contentSysId) {
		checkIfUserAuthenticated();

		contentSysId = SearchUtils.trimToNull(contentSysId);

		// validation
		if (contentSysId == null) {
			throw new RequiredFieldException(QUERY_PARAM_ID);
		}

		String currentContributorId = authenticationUtilService.getAuthenticatedContributor(securityContext, false);
		if (currentContributorId != null) {
			List<Rating> rl = ratingPersistenceService.getRatings(currentContributorId, contentSysId);
			if (rl != null && !rl.isEmpty()) {
				Map<String, Object> ret = ratingToJSON(rl.get(0));
				return ret;
			} else {
				return Response.status(Status.NOT_FOUND).build();
			}
		} else {
			return Response.status(Status.NOT_FOUND).build();
		}

	}

	/**
	 * Convert {@link Rating} object into JSON map.
	 *
	 * @param rating to convert
	 * @return JSON map with rating informations
	 */
	protected Map<String, Object> ratingToJSON(Rating rating) {
		Map<String, Object> ret = new HashMap<>();
		ret.put(DATA_FIELD_RATING, rating.getRating());
		return ret;
	}

	@GET
	@Path("/")
	@Produces(MediaType.APPLICATION_JSON)
	public Map<String, Object> getRatings(@Context UriInfo uriInfo) {
		checkIfUserAuthenticated();

		Map<String, Object> ret = new HashMap<>();

		String currentContributorId = authenticationUtilService.getAuthenticatedContributor(securityContext, false);
		if (currentContributorId == null || uriInfo == null) {
			return ret;
		}

		Set<String> contentSysIds = new LinkedHashSet<>();
		List<String> rawids = uriInfo.getQueryParameters().get(QUERY_PARAM_ID);
		if (rawids != null) {
			for (String rid : rawids) {
				rid = SearchUtils.trimToNull(rid);
				if (rid != null) {
					contentSysIds.add(rid);
				}
			}
		}

		if (!contentSysIds.isEmpty()) {
			List<Rating> rl = ratingPersistenceService.getRatings(currentContributorId,
					contentSysIds.toArray(new String[contentSysIds.size()]));
			if (rl != null && !rl.isEmpty()) {
				for (Rating r : rl) {
					ret.put(r.getContentId(), ratingToJSON(r));
				}
			}
		} else {
			throw new RequiredFieldException(QUERY_PARAM_ID);
		}
		return ret;
	}

	@POST
	@Path("/{id}")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public Object postRating(@PathParam(QUERY_PARAM_ID) String contentSysId, Map<String, Object> requestContent) {
		checkIfUserAuthenticated();

		String currentContributorId = authenticationUtilService.getAuthenticatedContributor(securityContext, true);

		contentSysId = SearchUtils.trimToNull(contentSysId);

		// validation
		if (contentSysId == null) {
			throw new RequiredFieldException(QUERY_PARAM_ID);
		}

		Integer rating = null;
		try {
			rating = SearchUtils.getIntegerFromJsonMap(requestContent, DATA_FIELD_RATING);
		} catch (NumberFormatException e) {
			return Response.status(Status.BAD_REQUEST).entity(DATA_FIELD_RATING + " field must be number").build();
		}
		if (rating == null) {
			throw new RequiredFieldException(DATA_FIELD_RATING);
		}
{'fraction_non_alphanumeric': 0.1095233705171937, 'fraction_numerical': 0.0016594450078362682, 'mean_word_length': 5.256055363321799, 'pattern_counts': {'":': 0, '<': 31, '<?xml version=': 0, '>': 31, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '5395406', 'n_tokens_mistral': 3622, 'n_tokens_neox': 3273, 'n_words': 713}