text:
package com.amazonaws.services.directconnect.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * Information about an Direct Connect location.
 *

 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class Location implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * The code for the location.
     *

     */
    private String locationCode;
    /**
     *

     * The name of the location. This includes the name of the colocation partner and the physical site of the building.
     *

     */
    private String locationName;
    /**
     *

     * The Amazon Web Services Region for the location.
     *

     */
    private String region;
    /**
     *

     * The available port speeds for the location.
     *

     */
    private com.amazonaws.internal.SdkInternalList<String> availablePortSpeeds;
    /**
     *

     * The name of the service provider for the location.
     *

     */
    private com.amazonaws.internal.SdkInternalList<String> availableProviders;
    /**
     *

     * The available MAC Security (MACsec) port speeds for the location.
     *

     */
    private com.amazonaws.internal.SdkInternalList<String> availableMacSecPortSpeeds;

    /**
     *

     * The code for the location.
     *

     *
     * @param locationCode
     *        The code for the location.
     */

    public void setLocationCode(String locationCode) {
        this.locationCode = locationCode;
    }

    /**
     *

     * The code for the location.
     *

     *
     * @return The code for the location.
     */

    public String getLocationCode() {
        return this.locationCode;
    }

    /**
     *

     * The code for the location.
     *

     *
     * @param locationCode
     *        The code for the location.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public Location withLocationCode(String locationCode) {
        setLocationCode(locationCode);
        return this;
    }

    /**
     *

     * The name of the location. This includes the name of the colocation partner and the physical site of the building.
     *

     *
     * @param locationName
     *        The name of the location. This includes the name of the colocation partner and the physical site of the
     *        building.
     */

    public void setLocationName(String locationName) {
        this.locationName = locationName;
    }

    /**
     *

     * The name of the location. This includes the name of the colocation partner and the physical site of the building.
     *

     *
     * @return The name of the location. This includes the name of the colocation partner and the physical site of the
     *         building.
     */

    public String getLocationName() {
        return this.locationName;
    }

    /**
     *

     * The name of the location. This includes the name of the colocation partner and the physical site of the building.
     *

     *
     * @param locationName
     *        The name of the location. This includes the name of the colocation partner and the physical site of the
     *        building.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public Location withLocationName(String locationName) {
        setLocationName(locationName);
        return this;
    }

    /**
     *

     * The Amazon Web Services Region for the location.
     *

     *
     * @param region
     *        The Amazon Web Services Region for the location.
     */

    public void setRegion(String region) {
        this.region = region;
    }

    /**
     *

     * The Amazon Web Services Region for the location.
     *

     *
     * @return The Amazon Web Services Region for the location.
     */

    public String getRegion() {
        return this.region;
    }

    /**
     *

     * The Amazon Web Services Region for the location.
     *

     *
     * @param region
     *        The Amazon Web Services Region for the location.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public Location withRegion(String region) {
        setRegion(region);
        return this;
    }

    /**
     *

     * The available port speeds for the location.
     *

     *
     * @return The available port speeds for the location.
     */

    public java.util.List<String> getAvailablePortSpeeds() {
        if (availablePortSpeeds == null) {
            availablePortSpeeds = new com.amazonaws.internal.SdkInternalList<String>();
        }
        return availablePortSpeeds;
    }

    /**
     *

     * The available port speeds for the location.
     *

     *
     * @param availablePortSpeeds
     *        The available port speeds for the location.
     */

    public void setAvailablePortSpeeds(java.util.Collection<String> availablePortSpeeds) {
        if (availablePortSpeeds == null) {
            this.availablePortSpeeds = null;
            return;
        }

        this.availablePortSpeeds = new com.amazonaws.internal.SdkInternalList<String>(availablePortSpeeds);
    }

    /**
     *

     * The available port speeds for the location.
     *

     *

     * NOTE: This method appends the values to the existing list (if any). Use
     * {@link #setAvailablePortSpeeds(java.util.Collection)} or {@link #withAvailablePortSpeeds(java.util.Collection)}
     * if you want to override the existing values.
     *

     *
     * @param availablePortSpeeds
     *        The available port speeds for the location.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public Location withAvailablePortSpeeds(String... availablePortSpeeds) {
        if (this.availablePortSpeeds == null) {
            setAvailablePortSpeeds(new com.amazonaws.internal.SdkInternalList<String>(availablePortSpeeds.length));
        }
        for (String ele : availablePortSpeeds) {
            this.availablePortSpeeds.add(ele);
        }
        return this;
    }

    /**
     *

     * The available port speeds for the location.
     *

     *
     * @param availablePortSpeeds
     *        The available port speeds for the location.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public Location withAvailablePortSpeeds(java.util.Collection<String> availablePortSpeeds) {
        setAvailablePortSpeeds(availablePortSpeeds);
        return this;
    }

    /**
     *

     * The name of the service provider for the location.
     *

     *
     * @return The name of the service provider for the location.
     */

    public java.util.List<String> getAvailableProviders() {
        if (availableProviders == null) {
            availableProviders = new com.amazonaws.internal.SdkInternalList<String>();
        }
        return availableProviders;
    }

    /**
     *

     * The name of the service provider for the location.
     *

     *
     * @param availableProviders
     *        The name of the service provider for the location.
     */

    public void setAvailableProviders(java.util.Collection<String> availableProviders) {
        if (availableProviders == null) {
            this.availableProviders = null;
            return;
        }

        this.availableProviders = new com.amazonaws.internal.SdkInternalList<String>(availableProviders);
    }

    /**
     *

     * The name of the service provider for the location.
     *

     *

     * NOTE: This method appends the values to the existing list (if any). Use
     * {@link #setAvailableProviders(java.util.Collection)} or {@link #withAvailableProviders(java.util.Collection)} if
     * you want to override the existing values.
     *

     *
     * @param availableProviders
     *        The name of the service provider for the location.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public Location withAvailableProviders(String... availableProviders) {
        if (this.availableProviders == null) {
            setAvailableProviders(new com.amazonaws.internal.SdkInternalList<String>(availableProviders.length));
        }
        for (String ele : availableProviders) {
            this.availableProviders.add(ele);
        }
        return this;
    }

    /**
     *

     * The name of the service provider for the location.
     *

     *
     * @param availableProviders
     *        The name of the service provider for the location.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public Location withAvailableProviders(java.util.Collection<String> availableProviders) {
        setAvailableProviders(availableProviders);
        return this;
    }

    /**
     *

     * The available MAC Security (MACsec) port speeds for the location.
     *

     *
     * @return The available MAC Security (MACsec) port speeds for the location.
     */

    public java.util.List<String> getAvailableMacSecPortSpeeds() {
        if (availableMacSecPortSpeeds == null) {
            availableMacSecPortSpeeds = new com.amazonaws.internal.SdkInternalList<String>();
        }
        return availableMacSecPortSpeeds;
    }

    /**
     *

     * The available MAC Security (MACsec) port speeds for the location.
     *

     *
     * @param availableMacSecPortSpeeds
     *        The available MAC Security (MACsec) port speeds for the location.
     */

    public void setAvailableMacSecPortSpeeds(java.util.Collection<String> availableMacSecPortSpeeds) {
        if (availableMacSecPortSpeeds == null) {
            this.availableMacSecPortSpeeds = null;
            return;
        }

        this.availableMacSecPortSpeeds = new com.amazonaws.internal.SdkInternalList<String>(availableMacSecPortSpeeds);
    }

    /**
     *

     * The available MAC Security (MACsec) port speeds for the location.
     *

     *

     * NOTE: This method appends the values to the existing list (if any). Use
     * {@link #setAvailableMacSecPortSpeeds(java.util.Collection)} or
     * {@link #withAvailableMacSecPortSpeeds(java.util.Collection)} if you want to override the existing values.
     *

     *
     * @param availableMacSecPortSpeeds
     *        The available MAC Security (MACsec) port speeds for the location.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public Location withAvailableMacSecPortSpeeds(String... availableMacSecPortSpeeds) {
        if (this.availableMacSecPortSpeeds == null) {
            setAvailableMacSecPortSpeeds(new com.amazonaws.internal.SdkInternalList<String>(availableMacSecPortSpeeds.length));
        }
        for (String ele : availableMacSecPortSpeeds) {
            this.availableMacSecPortSpeeds.add(ele);
        }
        return this;
    }

    /**
     *

     * The available MAC Security (MACsec) port speeds for the location.
     *

     *
     * @param availableMacSecPortSpeeds
     *        The available MAC Security (MACsec) port speeds for the location.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public Location withAvailableMacSecPortSpeeds(java.util.Collection<String> availableMacSecPortSpeeds) {
        setAvailableMacSecPortSpeeds(availableMacSecPortSpeeds);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getLocationCode() != null)
            sb.append("LocationCode: ").append(getLocationCode()).append(",");
        if (getLocationName() != null)
            sb.append("LocationName: ").append(getLocationName()).append(",");
        if (getRegion() != null)
            sb.append("Region: ").append(getRegion()).append(",");
        if (getAvailablePortSpeeds() != null)
            sb.append("AvailablePortSpeeds: ").append(getAvailablePortSpeeds()).append(",");
        if (getAvailableProviders() != null)
            sb.append("AvailableProviders: ").append(getAvailableProviders()).append(",");
        if (getAvailableMacSecPortSpeeds() != null)
            sb.append("AvailableMacSecPortSpeeds: ").append(getAvailableMacSecPortSpeeds());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof Location == false)
            return false;
        Location other = (Location) obj;
        if (other.getLocationCode() == null ^ this.getLocationCode() == null)
            return false;
        if (other.getLocationCode() != null && other.getLocationCode().equals(this.getLocationCode()) == false)
            return false;
        if (other.getLocationName() == null ^ this.getLocationName() == null)
            return false;
        if (other.getLocationName() != null && other.getLocationName().equals(this.getLocationName()) == false)
            return false;
        if (other.getRegion() == null ^ this.getRegion() == null)
            return false;
        if (other.getRegion() != null && other.getRegion().equals(this.getRegion()) == false)
            return false;
        if (other.getAvailablePortSpeeds() == null ^ this.getAvailablePortSpeeds() == null)
            return false;
        if (other.getAvailablePortSpeeds() != null && other.getAvailablePortSpeeds().equals(this.getAvailablePortSpeeds()) == false)
            return false;
        if (other.getAvailableProviders() == null ^ this.getAvailableProviders() == null)
            return false;
        if (other.getAvailableProviders() != null && other.getAvailableProviders().equals(this.getAvailableProviders()) == false)
            return false;
        if (other.getAvailableMacSecPortSpeeds() == null ^ this.getAvailableMacSecPortSpeeds() == null)
            return false;
        if (other.getAvailableMacSecPortSpeeds() != null && other.getAvailableMacSecPortSpeeds().equals(this.getAvailableMacSecPortSpeeds()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getLocationCode() == null) ? 0 : getLocationCode().hashCode());
        hashCode = prime * hashCode + ((getLocationName() == null) ? 0 : getLocationName().hashCode());
        hashCode = prime * hashCode + ((getRegion() == null) ? 0 : getRegion().hashCode());
        hashCode = prime * hashCode + ((getAvailablePortSpeeds() == null) ? 0 : getAvailablePortSpeeds().hashCode());
        hashCode = prime * hashCode + ((getAvailableProviders() == null) ? 0 : getAvailableProviders().hashCode());
        hashCode = prime * hashCode + ((getAvailableMacSecPortSpeeds() == null) ? 0 : getAvailableMacSecPortSpeeds().hashCode());
        return hashCode;
    }

    @Override
    public Location clone() {
        try {
            return (Location) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.directconnect.model.transform.LocationMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}

redpajama_set_name: RedPajamaGithub


text:
//go:build test_unit

package iguazio

import (
	"bytes"
	"io/ioutil"
	"net/http"
	"testing"

	"github.com/nuclio/nuclio/pkg/auth"
	"github.com/nuclio/nuclio/pkg/common/testutils"

	"github.com/nuclio/logger"
	nucliozap "github.com/nuclio/zap"
	"github.com/stretchr/testify/suite"
)

type AuthTestSuite struct {
	suite.Suite
	logger logger.Logger
}

func (suite *AuthTestSuite) SetupSuite() {
	var err error
	suite.logger, err = nucliozap.NewNuclioZapTest("iguazio-auth")
	suite.Require().NoError(err)
}

func (suite *AuthTestSuite) TestAuthenticateIguazioCaching() {
	// mocks IguazioConfig session verification endpoint
	mockedHTTPClient := testutils.CreateDummyHTTPClient(func(r *http.Request) *http.Response {
		authorization := r.Header.Get("Authorization")
		cookie := r.Header.Get("Cookie")
		if authorization != "Basic YWJjOmVmZwo=" || cookie != "session=some-session" {
			return &http.Response{
				StatusCode: http.StatusUnauthorized,
			}
		}
		return &http.Response{
			StatusCode: http.StatusOK,
			Header: map[string][]string{
				"X-Remote-User":      {"admin"},
				"X-User-Group-Ids":   {"1,2", "3"},
				"X-User-Id":          {"some-user-id"},
				"X-V3io-Session-Key": {"some-password"},
			},
			Body: ioutil.NopCloser(bytes.NewBufferString(`
{
    "data": {
        "type": "session_verification",
        "attributes": {
            "username": "some-username",
            "context": {
                "id": "1234",
                "authentication": {
                    "user_id": "some-user-id",
                    "tenant_id": "some-tenant-id",
                    "group_ids": [
                        "1,2",
                        "3"
                    ],
                    "mode": "normal"
                }
            }
        }
    },
    "meta": {
        "ctx": "1234"
    }
}`)),
		}
	})

	newAuth := NewAuth(suite.logger, func() *auth.Config {
		authConfig := auth.NewConfig(auth.KindIguazio)
		authConfig.Iguazio.VerificationURL = "http://somewhere.local"
		return authConfig
	}())
	authInstance := newAuth.(*Auth)
	authInstance.httpClient = mockedHTTPClient
	authOptions := auth.Options{}
	incomingRequest := &http.Request{
		Header: map[string][]string{
			"Authorization": {"Basic YWJjOmVmZwo="},
			"Cookie":        {"session=some-session"},
		}}

	// step A. successfully authenticate, let it to be cached
	_, err := authInstance.Authenticate(incomingRequest, &authOptions)
	suite.Require().NoError(err)
	suite.Require().NotEmpty(authInstance.cache.Keys())

	// step B. re-authenticate, read from cache
	// nil the http client in order to force it to panic if it was used to make an HTTP request
	authInstance.httpClient = nil
	session, err := authInstance.Authenticate(incomingRequest, &authOptions)
	suite.Require().NoError(err)
	suite.Require().Equal("some-user-id", session.GetUserID())
	suite.Require().Equal([]string{"1", "2", "3"}, session.GetGroupIDs())
	suite.Require().Equal("admin", session.GetUsername())
	suite.Require().Equal("some-password", session.GetPassword())

	authInstance.cache.Remove(authInstance.cache.Keys()[0])

	// step C. bad authentication + cache remains empty
	authInstance.httpClient = testutils.CreateDummyHTTPClient(func(r *http.Request) *http.Response {
		return &http.Response{
			StatusCode: http.StatusUnauthorized,
		}
	})
	_, err = authInstance.Authenticate(incomingRequest, &authOptions)
	suite.Require().Error(err)
	suite.Require().Empty(authInstance.cache.Keys())
}

func (suite *AuthTestSuite) TestAuthenticate() {

	for _, testCase := range []struct {
		name                string
		auth                auth.Auth
		authOptions         auth.Options
		incomingRequest     *http.Request
		invalidRequest      bool
		includeResponseBody bool
	}{
		{
			name: "sanity",
			auth: NewAuth(suite.logger, func() *auth.Config {
				authConfig := auth.NewConfig(auth.KindIguazio)
				authConfig.Iguazio.VerificationURL = "http://somewhere.local"
				return authConfig
			}()),
			authOptions: auth.Options{},
			incomingRequest: &http.Request{
				Header: map[string][]string{
					"Authorization": {"Basic YWJjOmVmZwo="},
					"Cookie":        {"session=some-session"},
				},
			},
			includeResponseBody: true,
		},
		{
			name: "backwardsCompatibilitySanity",
			auth: NewAuth(suite.logger, func() *auth.Config {
				authConfig := auth.NewConfig(auth.KindIguazio)
				authConfig.Iguazio.VerificationURL = "http://somewhere.local"
				return authConfig
			}()),
			authOptions: auth.Options{},
			incomingRequest: &http.Request{
				Header: map[string][]string{
					"Authorization": {"Basic YWJjOmVmZwo="},
					"Cookie":        {"session=some-session"},
				},
			},
			includeResponseBody: true,
		},
		{
			name: "enrichmentSanity",
			auth: NewAuth(suite.logger, func() *auth.Config {
				authConfig := auth.NewConfig(auth.KindIguazio)
				authConfig.Iguazio.VerificationURL = "http://somewhere.local"
				return authConfig
			}()),
			authOptions: auth.Options{
				EnrichDataPlane: true,
			},
			incomingRequest: &http.Request{
				Header: map[string][]string{
					"Authorization": {"Basic YWJjOmVmZwo="},
					"Cookie":        {"session=some-session"},
				},
			},
			includeResponseBody: true,
		},
		{
			name: "missingCookie",
			auth: NewAuth(suite.logger, func() *auth.Config {
				authConfig := auth.NewConfig(auth.KindIguazio)
				authConfig.Iguazio.VerificationURL = "http://somewhere.local"
				return authConfig
			}()),
			authOptions: auth.Options{},
			incomingRequest: &http.Request{
				Header: map[string][]string{
					"Authorization": {"Basic YWJjOmVmZwo="},
				},
			},
			invalidRequest:      true,
			includeResponseBody: true,
		},
		{
			name: "missingAuthorizationHeader",
			auth: NewAuth(suite.logger, func() *auth.Config {
				authConfig := auth.NewConfig(auth.KindIguazio)
				authConfig.Iguazio.VerificationURL = "http://somewhere.local"
				return authConfig
			}()),
			authOptions: auth.Options{},
			incomingRequest: &http.Request{
				Header: map[string][]string{
					"Cookie": {"session=some-session"},
				},
			},
			invalidRequest:      true,
			includeResponseBody: false,
		},
	} {
		suite.Run(testCase.name, func() {
			testCase.auth.(*Auth).httpClient = testutils.CreateDummyHTTPClient(suite.resolveMockHttpClientHandler(testCase.includeResponseBody))
			authInfo, err := testCase.auth.Authenticate(testCase.incomingRequest, &testCase.authOptions)
			if testCase.invalidRequest {
				suite.Require().Error(err)
				return
			}
			suite.Require().NoError(err)
			suite.Require().Equal("admin", authInfo.GetUsername())
			suite.Require().Equal([]string{"1", "2"}, authInfo.GetGroupIDs())
			suite.Require().Equal("3", authInfo.GetUserID())
			suite.Require().Equal("4", authInfo.GetPassword())
		})
	}
}

func (suite *AuthTestSuite) resolveMockHttpClientHandler(includeResponseBody bool) func(r *http.Request) *http.Response {

	response := &http.Response{
		StatusCode: http.StatusOK,
		Header: map[string][]string{
			"X-Remote-User":      {"admin"},
			"X-User-Group-Ids":   {"1", "2"},
			"X-User-Id":          {"3"},
			"X-V3io-Session-Key": {"4"},
		},
	}

	if includeResponseBody {
		response.Body = ioutil.NopCloser(bytes.NewBufferString(`
{
    "data": {
        "type": "session_verification",
        "attributes": {
            "username": "some-username",
            "context": {
                "id": "1234",
                "authentication": {
                    "user_id": "3",
                    "tenant_id": "some-tenant-id",
                    "group_ids": [
                        "1",
                        "2"
                    ],
                    "mode": "normal"
                }
            }
        }
    },
    "meta": {
        "ctx": "1234"
    }
}`))
	}

	return func(r *http.Request) *http.Response {
		authorization := r.Header.Get("Authorization")
		cookie := r.Header.Get("Cookie")
		if authorization != "Basic YWJjOmVmZwo=" || cookie != "session=some-session" {
			return &http.Response{
				StatusCode: http.StatusUnauthorized,
			}
		}
		return response
	}
}
func TestAuthTestSuite(t *testing.T) {
	suite.Run(t, new(AuthTestSuite))
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>Scheduler: src/scheduler/tests/taskSchedulerTest.cpp File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Scheduler

Main Page

Related Pages

Namespaces

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

File List

File Members

src

scheduler

tests

Functions

taskSchedulerTest.cpp File Reference

#include <scheduler/taskScheduler.h>

#include <scheduler/queue.h>

#include <scheduler/events/event.h>

#include <gtest/gtest.h>

Go to the source code of this file.

Functions

 	TEST (taskSchedulerTest, DISABLED_scheduleTask)

 	TEST (taskSchedulerTest, DISABLED_clearRunningTask)

 	TEST (taskSchedulerTest, DISABLED_dealWithMissedDeadlines)

 	TEST (taskSchedulerTest, DISABLED_scheduleEndOfBurst)

Function Documentation

          TEST
          (
          taskSchedulerTest
          ,

          DISABLED_scheduleTask

          )

Copyright 2017 Jacques Florence All rights reserved. See License.txt file

Definition at line 20 of file taskSchedulerTest.cpp.

          TEST
          (
          taskSchedulerTest
          ,

          DISABLED_clearRunningTask

          )

Definition at line 25 of file taskSchedulerTest.cpp.

          TEST
          (
          taskSchedulerTest
          ,

          DISABLED_dealWithMissedDeadlines

          )

Definition at line 29 of file taskSchedulerTest.cpp.

          TEST
          (
          taskSchedulerTest
          ,

          DISABLED_scheduleEndOfBurst

          )

Definition at line 40 of file taskSchedulerTest.cpp.

<address class="footer">
Generated on Sun Nov 26 2017 17:01:37 for Scheduler by

 1.8.11
</address>


text:
package de.tum.in.www1.artemis.domain;

import java.time.ZonedDateTime;
import java.util.Optional;

import javax.persistence.*;
import javax.validation.constraints.Size;

import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;

import de.tum.in.www1.artemis.domain.enumeration.ComplaintType;
import de.tum.in.www1.artemis.domain.participation.Participant;

/**
 * A Complaint.
 */
@Entity
@Table(name = "complaint")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Complaint extends DomainObject {

    @Column(name = "complaint_text", length = 2000)
    @Size(max = 2000)
    private String complaintText;

    @Column(name = "accepted")
    private Boolean accepted;

    @Column(name = "submitted_time")
    private ZonedDateTime submittedTime;

    @Enumerated(EnumType.STRING)
    @Column(name = "complaint_type")
    private ComplaintType complaintType;

    // TODO: delete in the next major release
    @Deprecated
    @Column(name = "result_before_complaint")
    @Lob
    @JsonIgnore
    private String resultBeforeComplaint;

    @OneToOne(mappedBy = "complaint")
    @JsonIgnoreProperties(value = "complaint", allowGetters = true)
    private ComplaintResponse complaintResponse;

    @OneToOne
    @JoinColumn(unique = true)
    private Result result;

    @ManyToOne
    private User student;

    @ManyToOne
    private Team team;

    public String getComplaintText() {
        return complaintText;
    }

    public Complaint complaintText(String complaintText) {
        this.complaintText = complaintText;
        return this;
    }

    public void setComplaintText(String complaintText) {
        this.complaintText = complaintText;
    }

    public Boolean isAccepted() {
        return accepted;
    }

    public Complaint accepted(Boolean accepted) {
        this.accepted = accepted;
        return this;
    }

    public void setAccepted(Boolean accepted) {
        this.accepted = accepted;
    }

    public ZonedDateTime getSubmittedTime() {
        return submittedTime;
    }

    public void setSubmittedTime(ZonedDateTime submittedTime) {
        this.submittedTime = submittedTime;
    }

    public ComplaintType getComplaintType() {
        return complaintType;
    }

    public Complaint complaintType(ComplaintType complaintType) {
        this.complaintType = complaintType;
        return this;
    }

    public void setComplaintType(ComplaintType complaintType) {
        this.complaintType = complaintType;
    }

    public Result getResult() {
        return result;
    }

    public Complaint result(Result result) {
        this.result = result;
        return this;
    }

    public void setResult(Result result) {
        this.result = result;
    }

    public User getStudent() {
        return student;
    }

    public Team getTeam() {
        return team;
    }

    @JsonIgnore
    public Participant getParticipant() {
        return Optional.ofNullable((Participant) student).orElse(team);
    }

    public Complaint participant(Participant participant) {
        setParticipant(participant);
        return this;
    }

    public ComplaintResponse getComplaintResponse() {
        return complaintResponse;
    }

    public void setComplaintResponse(ComplaintResponse complaintResponse) {
        this.complaintResponse = complaintResponse;
    }

    /**
     * allows to set the participant independent whether it is a team or user
     * @param participant either a team or user
     */
    public void setParticipant(Participant participant) {
        if (participant instanceof User) {
            this.student = (User) participant;
        }
        else if (participant instanceof Team) {
            this.team = (Team) participant;
        }
        else if (participant == null) {
            this.student = null;
            this.team = null;
        }
        else {
            throw new Error("Unknown participant type");
        }
    }
    // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove

    /**
     * Removes the participant from the complaint, can be invoked to make sure that sensitive information is not sent to the client. E.g. tutors should not see information about
     * the participant.
     */
    public void filterSensitiveInformation() {
        setParticipant(null);
    }

    @Override
    public String toString() {
        return "Complaint{" + "id=" + getId() + ", complaintText='" + getComplaintText() + "'" + ", accepted='" + isAccepted() + "'" + ", submittedTime='" + getSubmittedTime()
                + "'}";
    }
}