Create new ticket granting ticket.

@param requestBody username and password application/x-www-form-urlencoded values
@param request     raw HttpServletRequest used to call this method
@return ResponseEntity representing RESTful response
507402
@PostMapping(value = "/v1/tickets", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public ResponseEntity<String> createTicketGrantingTicket(@RequestBody(required=false) final MultiValueMap<String, String> requestBody,
                                                             final HttpServletRequest request) {
        try {
            val tgtId = createTicketGrantingTicketForRequest(requestBody, request);
            return createResponseEntityForTicket(request, tgtId);
        } catch (final AuthenticationException e) {
            return RestResourceUtils.createResponseEntityForAuthnFailure(e, request, applicationContext);
        } catch (final BadRestRequestException e) {
            LOGGER.error(e.getMessage(), e);
            return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
        } catch (final Exception e) {
            LOGGER.error(e.getMessage(), e);
            return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
712034
private String getProxyTicket(PortletRequest request) {

        final HttpServletRequest httpServletRequest =
                this.portalRequestUtils.getPortletHttpRequest(request);

        // try to determine the URL for our portlet
        String targetService = null;
        try {
            URL url = null;

            // if the server port is 80 or 443, don't include it in the URL
            int port = request.getServerPort();
            if (port == 80 || port == 443)
                url =
                        new URL(
                                request.getScheme(),
                                request.getServerName(),
                                request.getContextPath());
            else
                url =
                        new URL(
                                request.getScheme(),
                                request.getServerName(),
                                request.getServerPort(),
                                request.getContextPath());
            targetService = url.toString();

        } catch (MalformedURLException e) {
            log.error("Failed to create a URL for the target portlet", e);
            e.printStackTrace();
            return null;
        }

        // get the CasSecurityContext
        final IUserInstance userInstance = userInstanceManager.getUserInstance(httpServletRequest);
        final IPerson person = userInstance.getPerson();
        final ISecurityContext context = person.getSecurityContext();
        if (context == null) {
            log.error("no security context, no proxy ticket passed to the portlet");
            return null;
        }
        ISecurityContext casContext = getCasContext(context);
        if (casContext == null) {
            log.debug("no CAS security context, no proxy ticket passed to the portlet");
            return null;
        }
        if (!casContext.isAuthenticated()) {
            log.debug("no CAS authentication, no proxy ticket passed to the portlet");
            return null;
        }

        // get a proxy ticket for our portlet from the CasSecurityContext
        String proxyTicket = null;
        try {
            proxyTicket = ((ICasSecurityContext) casContext).getCasServiceToken(targetService);
            log.debug("Put proxy ticket in userinfo: " + proxyTicket);
        } catch (CasProxyTicketAcquisitionException e) {
            log.error("no proxy ticket passed to the portlet: " + e);
        }

        return proxyTicket;
    }
294351
@RequestMapping(path = "", method = RequestMethod.POST)
    public ResponseEntity<Customer> createCustomer(@RequestBody Customer customer){
        Customer newCustomer = customerService.createCustomer(customer);
        if(newCustomer != null){
            return new ResponseEntity<Customer>(newCustomer, HttpStatus.CREATED);
        }else{
            return new ResponseEntity<Customer>(HttpStatus.CONFLICT);
        }
    }
1153313
public static String postResponseAsString(String uri, Header header,
            HttpEntity httpEntity) {
        HttpPost httpPost = new HttpPost(uri);
        httpPost.setHeader(header);
        httpPost.setEntity(httpEntity);
        return request(httpPost);
    }
1300118
@Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
            throws IOException {
        String service = request.getURI().toASCIIString();
        String proxyTicket = proxyTicketProvider.getProxyTicket(service);
        if (!StringUtils.hasText(proxyTicket)) {
            throw new IllegalStateException(
                    String.format("Proxy ticket provider returned a null proxy ticket for service %s.", service));
        }
        URI uri = UriComponentsBuilder
                .fromUri(request.getURI())
                .replaceQueryParam(serviceProperties.getArtifactParameter(), proxyTicket)
                .build().toUri();
        return execution.execute(new HttpRequestWrapper(request) {
            @Override
            public URI getURI() {
                return uri;
            }
        }, body);
    }
13523
private UsernamePasswordToken usernamePassword(ServiceRequestContext ctx, AggregatedHttpMessage req) {
        // check the Basic HTTP authentication first (https://tools.ietf.org/html/rfc7617)
        final BasicToken basicToken = AuthTokenExtractors.BASIC.apply(req.headers());
        if (basicToken != null) {
            return new UsernamePasswordToken(basicToken.username(), basicToken.password());
        }

        final MediaType mediaType = req.headers().contentType();
        if (mediaType != MediaType.FORM_DATA) {
            return throwResponse(ctx, HttpStatus.BAD_REQUEST,
                                 "The content type of a login request must be '%s'.", MediaType.FORM_DATA);
        }

        final Map<String, List<String>> parameters = new QueryStringDecoder(req.contentUtf8(),
                                                                            false).parameters();
        // assume that the grant_type is "password"
        final List<String> usernames = parameters.get("username");
        final List<String> passwords = parameters.get("password");
        if (usernames != null && passwords != null) {
            final String username = usernames.get(0);
            final String password = passwords.get(0);
            return new UsernamePasswordToken(loginNameNormalizer.apply(username), password);
        }

        return throwResponse(ctx, HttpStatus.BAD_REQUEST,
                             "A login request must contain username and password.");
    }
284878
protected Response executeRequest(Request request)
    {
        try
        {
            com.squareup.okhttp.Request httpRequest = buildHttpRequest(request);

            if(logger.isInfoEnabled())
                logger.info("Sending request: {} {}",httpRequest.method(),httpRequest.urlString());

            if(logger.isDebugEnabled() && request.getRequestMethod().isBodyRequest())
            {
                Buffer buffer = new Buffer();
                httpRequest.body().writeTo(buffer);
                if(maxLoggedBodySize == -1 || buffer.size() <= maxLoggedBodySize )
                    logger.debug("Request body: {}", buffer.readUtf8());
                else
                    logger.debug("Request body not captured: too large. ");
            }

            if(logger.isTraceEnabled())
                logger.trace("Request headers: {}",httpRequest.headers().toString());

            Response response = client.newCall(httpRequest).execute();

            if(response.code() == HttpURLConnection.HTTP_UNAUTHORIZED && authorizationFactory != null
                    && authorizationFactory.retryOnAuthenticationError())
            {
                if(authorizationFactory instanceof ResettableAuthorizationFactory)
                    ((ResettableAuthorizationFactory) authorizationFactory).reset();

                response = client.newCall(httpRequest).execute();
            }

            logger.info("Response code: {}",response.code());

            if(logger.isTraceEnabled())
                logger.trace("Response headers: {}",response.headers().toString());

            if(logger.isDebugEnabled())
            {
                ByteArrayOutputStream copy = new ByteArrayOutputStream();
                copy(response.body().byteStream(),copy);
                response = response.newBuilder().body(ResponseBody.create(response.body().contentType(),copy.toByteArray())).build();

                if(maxLoggedBodySize == -1 || copy.size() <= maxLoggedBodySize)
                    logger.debug("Response body: {}",copy.toString());
                else
                    logger.debug("Response body not captured: too large.");
            }
            if (response.code() >= HttpURLConnection.HTTP_BAD_REQUEST)
            {
                throw readException(response);
            }

            return response;
        }
        catch (IOException e)
        {
            throw new ClientConnectionException("Error calling service.",e);
        }

    }
454854
protected Event grantServiceTicket(final RequestContext context) {
        val ticketGrantingTicketId = WebUtils.getTicketGrantingTicketId(context);
        val credential = getCredentialFromContext(context);

        try {
            val service = WebUtils.getService(context);
            val authn = getWebflowEventResolutionConfigurationContext().getTicketRegistrySupport().getAuthenticationFrom(ticketGrantingTicketId);
            val registeredService = getWebflowEventResolutionConfigurationContext().getServicesManager().findServiceBy(service);

            if (authn != null && registeredService != null) {
                LOGGER.debug("Enforcing access strategy policies for registered service [{}] and principal [{}]", registeredService, authn.getPrincipal());

                val audit = AuditableContext.builder().service(service)
                    .authentication(authn)
                    .registeredService(registeredService)
                    .retrievePrincipalAttributesFromReleasePolicy(Boolean.TRUE)
                    .build();
                val accessResult = getWebflowEventResolutionConfigurationContext().getRegisteredServiceAccessStrategyEnforcer().execute(audit);
                accessResult.throwExceptionIfNeeded();
            }

            val authenticationResult =
                getWebflowEventResolutionConfigurationContext().getAuthenticationSystemSupport()
                    .handleAndFinalizeSingleAuthenticationTransaction(service, credential);
            val serviceTicketId = getWebflowEventResolutionConfigurationContext().getCentralAuthenticationService()
                .grantServiceTicket(ticketGrantingTicketId, service, authenticationResult);
            WebUtils.putServiceTicketInRequestScope(context, serviceTicketId);
            WebUtils.putWarnCookieIfRequestParameterPresent(getWebflowEventResolutionConfigurationContext().getWarnCookieGenerator(), context);
            return newEvent(CasWebflowConstants.TRANSITION_ID_WARN);

        } catch (final AuthenticationException | AbstractTicketException e) {
            return newEvent(CasWebflowConstants.TRANSITION_ID_AUTHENTICATION_FAILURE, e);
        }
    }
231125
private HttpUriRequest makeRequest(URI uri, final String requestBody)
    {
        HttpUriRequest request;
        if (m_method == HttpMethod.GET) {
            request = new HttpGet(uri + "?" + requestBody);
        } else if (m_method == HttpMethod.POST) {
            if (m_isHdfs) {
                try {
                    uri = HDFSUtils.opAdder(uri, "APPEND");
                } catch (IllegalArgumentException e) {
                    rateLimitedLogError(m_logger, "Invalid URI %s %s", uri.toString(), Throwables.getStackTraceAsString(e));
                    return null;
                }
            }
            final HttpPost post = new HttpPost(uri);
            post.setEntity(new StringEntity(requestBody, m_contentType));
            request = post;

        } else if (m_method == HttpMethod.PUT) {
            final HttpPut put = new HttpPut(uri);
            put.setEntity(new StringEntity(requestBody, m_contentType));
            request = put;
        } else {
            // Should never reach here
            request = null;
        }

        if (m_isHdfs && request != null) {
            request.setHeader("Expect", "100-continue");
        }

        return request;
    }
841336
protected RequestEntity createStringRequestContent(HTTPRequest httpRequest)
    {
        RequestEntity requestEntity=null;
        String contentString=httpRequest.getContentAsString();
        if(contentString!=null)
        {
            try
            {
                requestEntity=new StringRequestEntity(contentString,"text/plain",null);
            }
            catch(UnsupportedEncodingException exception)
            {
                throw new FaxException("Unable to set string request entity.",exception);
            }
        }
        
        return requestEntity;
    }
1270527
protected RequestEntity createBinaryRequestContent(HTTPRequest httpRequest)
    {
        RequestEntity requestEntity=null;
        byte[] contentBinary=httpRequest.getContentAsBinary();
        if(contentBinary!=null)
        {
            requestEntity=new ByteArrayRequestEntity(contentBinary,"binary/octet-stream");
        }
        
        return requestEntity;
    }
861761
public HttpMethod createRequestMethodNew(HttpRequestHeader header, HttpBody body) throws URIException {
		HttpMethod httpMethod = null;
		
		String method = header.getMethod();
		URI uri	= header.getURI();
		String version = header.getVersion();
		
		httpMethod = new GenericMethod(method);

		httpMethod.setURI(uri);
		HttpMethodParams httpParams = httpMethod.getParams();
		// default to use HTTP 1.0
		httpParams.setVersion(HttpVersion.HTTP_1_0);
		if (version.equalsIgnoreCase(HttpHeader.HTTP11)) {
			httpParams.setVersion(HttpVersion.HTTP_1_1);
		}
		
		// set various headers
		int pos = 0;
		// ZAP: FindBugs fix - always initialise pattern
		Pattern pattern = patternCRLF;
		
		String msg = header.getHeadersAsString();
		if ((pos = msg.indexOf(CRLF)) < 0) {
			if ((pos = msg.indexOf(LF)) < 0) {
				pattern = patternLF;
			}
		} else {
			pattern = patternCRLF;
		}
	        
		String[] split = pattern.split(msg);
		String token = null;
		String name = null;
		String value = null;
		
		for (int i=0; i<split.length; i++) {
			token = split[i];
			if (token.equals("")) {
				continue;
			}
			
			if ((pos = token.indexOf(":")) < 0) {
				return null;
			}
			name  = token.substring(0, pos).trim();
			value = token.substring(pos +1).trim();			
			httpMethod.addRequestHeader(name, value);

		}

		// set body if post method or put method
		if (body != null && body.length() > 0) {
			EntityEnclosingMethod generic = (EntityEnclosingMethod) httpMethod;
            generic.setRequestEntity(new ByteArrayRequestEntity(body.getBytes()));

        }

		httpMethod.setFollowRedirects(false);
		return httpMethod;

	}
1060949
private ResponseEntity<?> handleRequestInternal(HttpMethod method, HttpEntity<?> requestEntity) {
        HttpMessage request = endpointConfiguration.getMessageConverter().convertInbound(requestEntity, endpointConfiguration, null);

        HttpServletRequest servletRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        UrlPathHelper pathHelper = new UrlPathHelper();

        Enumeration allHeaders = servletRequest.getHeaderNames();
        for (String headerName : CollectionUtils.toArray(allHeaders, new String[] {})) {
            if (request.getHeader(headerName) == null) {
                String headerValue = servletRequest.getHeader(headerName);
                request.header(headerName, headerValue != null ? headerValue : "");
            }
        }

        if (endpointConfiguration.isHandleCookies()) {
            request.setCookies(servletRequest.getCookies());
        }

        if (endpointConfiguration.isHandleAttributeHeaders()) {
            Enumeration<String> attributeNames = servletRequest.getAttributeNames();
            while (attributeNames.hasMoreElements()) {
                String attributeName = attributeNames.nextElement();
                Object attribute = servletRequest.getAttribute(attributeName);
                request.setHeader(attributeName, attribute);
            }
        }

        request.path(pathHelper.getRequestUri(servletRequest))
                .uri(pathHelper.getRequestUri(servletRequest))
                .contextPath(pathHelper.getContextPath(servletRequest))
                .queryParams(Optional.ofNullable(pathHelper.getOriginatingQueryString(servletRequest))
                                    .map(queryString -> queryString.replaceAll("&", ","))
                                    .orElse(""))
                .version(servletRequest.getProtocol())
                .method(method);

        Message response = endpointAdapter.handleMessage(request);

        ResponseEntity<?> responseEntity;
        if (response == null) {
            responseEntity = new ResponseEntity<>(HttpStatus.valueOf(endpointConfiguration.getDefaultStatusCode()));
        } else {
            HttpMessage httpResponse;
            if (response instanceof HttpMessage) {
                httpResponse = (HttpMessage) response;
            } else {
                httpResponse = new HttpMessage(response);
            }

            if (httpResponse.getStatusCode() == null) {
                httpResponse.status(HttpStatus.valueOf(endpointConfiguration.getDefaultStatusCode()));
            }

            responseEntity = (ResponseEntity<?>) endpointConfiguration.getMessageConverter().convertOutbound(httpResponse, endpointConfiguration, null);

            if (endpointConfiguration.isHandleCookies() && httpResponse.getCookies() != null) {
                HttpServletResponse servletResponse = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
                for (Cookie cookie : httpResponse.getCookies()) {
                    servletResponse.addCookie(cookie);
                }
            }
        }
        responseCache.add(responseEntity);
        
        return responseEntity;
    }
617912
public function createAction(Request $request)
    {
        $ticketManager = $this->get('hackzilla_ticket.ticket_manager');

        $ticket = $ticketManager->createTicket();
        $form   = $this->createForm(TicketType::class, $ticket);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $message = $ticket->getMessages()->current();
            $message->setStatus(TicketMessageInterface::STATUS_OPEN)
                ->setUser($this->getUserManager()->getCurrentUser());

            $ticketManager->updateTicket($ticket, $message);
            $this->dispatchTicketEvent(TicketEvents::TICKET_CREATE, $ticket);

            return $this->redirect($this->generateUrl('hackzilla_ticket_show', ['ticketId' => $ticket->getId()]));
        }

        return $this->render(
            $this->container->getParameter('hackzilla_ticket.templates')['new'],
            [
                'entity' => $ticket,
                'form'   => $form->createView(),
            ]
        );
    }
928642
public AuthenticationResult authenticate(HttpServletRequest request) {
        HttpSession session = null;
        AuthenticationResult authResult = null;
        if (!HTTP_DONT_USE_SESSION && !m_dontUseSession) {
            try {
                session = request.getSession();
                if (session != null) {
                    if (session.isNew()) {
                        session.setMaxInactiveInterval(MAX_SESSION_INACTIVITY_SECONDS);
                    }
                    authResult = (AuthenticationResult )session.getAttribute(AUTH_USER_SESSION_KEY);
                }
            } catch (Exception ex) {
                //Use no session mode meaning whatever VMC sends as hashed password is used to authenticate.
                session = null;
                m_rate_limited_log.log(EstTime.currentTimeMillis(), Level.ERROR, ex, "Failed to get or create HTTP Session. authenticating user explicitely.");
            }
        }
        if (authResult == null) {
            authResult = getAuthenticationResult(request);
            if (!authResult.isAuthenticated()) {
                if (session != null) {
                    session.removeAttribute(AUTH_USER_SESSION_KEY);
                }
                m_rate_limited_log.log("JSON interface exception: " + authResult.m_message, EstTime.currentTimeMillis());
            } else {
                if (session != null) {
                    //Cache the authResult in session so we dont authenticate again.
                    session.setAttribute(AUTH_USER_SESSION_KEY, authResult);
                }
            }
        }
        return authResult;
    }
127552
public static Session create(SessionStore sessionStore, HttpRequest<?> request) {
        Session session = sessionStore.newSession();
        request.getAttributes().put(HttpSessionFilter.SESSION_ATTRIBUTE, session);
        return session;
    }
588715
protected ResponseEntity<String> createResponseEntityForTicket(final HttpServletRequest request,
                                                                   final TicketGrantingTicket tgtId) throws Exception {
        return this.ticketGrantingTicketResourceEntityResponseFactory.build(tgtId, request);
    }