/* JWTBearerInterface
540614
public function getClientKey($client_id, $subject)
    {
        $result = $this->client->getItem(array(
            "TableName"=> $this->config['jwt_table'],
            "Key" => array('client_id'   => array('S' => $client_id), 'subject' => array('S' => $subject))
        ));
        if ($result->count()==0) {
            return false ;
        }
        $token = $this->dynamo2array($result);

        return $token['public_key'];
    }
1196231
@Override
    public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
        long timer = System.nanoTime();
        long random = (long) (Math.random() * Integer.MAX_VALUE);
        long token = timer ^ random;
        NGSecureUtilities.setSecurityToken(String.valueOf(token), component.getClientId());
        super.encodeBegin(context, component);

        NGSecurityFilter filter = findAndVerifySecurityFilter(context, component);
        showLegalDisclaimer(context, filter);
    }
1060669
@Override
    public void filter(ClientRequestContext requestContext) {
        //
        if (requestContext == null || jwt == null || requestContext.getHeaders().containsKey("Authorization")) {
            return;
        }
        if (header == null || header.equals("")) {
            header = "Authorization";
        }
        final String headerValue;
        if ("Authorization".equals(header)) {
            headerValue = "Bearer " + jwt;
        } else {
            headerValue = jwt;
        }

        requestContext.getHeaders().add(header, headerValue);
    }
857684
@Override
	public void encodeBegin(FacesContext context) throws IOException {

		// Initialize attributes
		String src = (String) getAttributes().get("src");

		// src is mandatory
		if (null == src)
			throw new IllegalStateException("The src attribute is mandatory for the Jawr image path tag. ");

		HttpServletRequest request = ((HttpServletRequest) context.getExternalContext().getRequest());
		BinaryResourcesHandler imgRsHandler = getBinaryResourcesHandler(context);

		// Refresh the config if needed
		RendererRequestUtils.refreshConfigIfNeeded(request, imgRsHandler.getConfig());

		render(context);

		super.encodeBegin(context);

		// Reset the Thread local for the Jawr context
		ThreadLocalJawrContext.reset();
	}
305722
@Override
    public Builder claimFrom(String jsonOrJwt) throws InvalidTokenException {
        isValidToken(jsonOrJwt);
        String decoded = jsonOrJwt;
        if (JwtUtils.isBase64Encoded(jsonOrJwt)) {
            decoded = JwtUtils.decodeFromBase64String(jsonOrJwt);
        }
        boolean isJson = JwtUtils.isJson(decoded);

        if (!isJson) {
            String jwtPayload = JwtUtils.getPayload(jsonOrJwt);
            decoded = JwtUtils.decodeFromBase64String(jwtPayload);
        }

        // boolean isJwt = JwtUtils.isJwtToken(jsonOrJwt);
        // String decoded = jsonOrJwt;
        // if (isJwt) {
        // String jwtPayload = JwtUtils.getPayload(jsonOrJwt);
        // decoded = JwtUtils.decodeFromBase64String(jwtPayload);
        //
        // } else {
        // // either decoded payload from jwt or encoded/decoded json string
        // if (JwtUtils.isBase64Encoded(jsonOrJwt)) {
        // decoded = JwtUtils.decodeFromBase64String(jsonOrJwt);
        // }
        // }

        // String formattedString = JwtUtils.fromBase64ToJsonString(jsonOrJwt);
        if (decoded != null) {
            Map claimsFromAnother = null;
            try {
                claimsFromAnother = JwtUtils.claimsFromJsonObject(decoded);
            } catch (JoseException e) {
                String err = Tr.formatMessage(tc, "JWT_INVALID_TOKEN_ERR");
                throw new InvalidTokenException(err);
            }
            if (claimsFromAnother != null && !claimsFromAnother.isEmpty()) {
                claims.putAll(claimsFromAnother);
            }
        }
        return this;
    }
1039253
@Remoted
    public IPromise<Object[]> login(String user, String pw, String jwt) {
        Promise res = new Promise();
        ConnectionRegistry remoteConnection = connection.get();
        getCredentials(user,pw,jwt).then( (authres, err) -> {
            if ( err != null ) {
                res.reject(err);
            } else {
                String sessionId = remoteConnection != null ? remoteConnection.getSocketRef().getConnectionIdentifier() : null;
                getSession(user,sessionId, authres ).then( (sess,serr) -> {
                    if ( sess != null ) {
                        if ( sessionId != null && sessionStorage != null ) {
                            sessionStorage.putUserAtSessionId(sessionId,user);
                        }
                        res.resolve(new Object[]{sess,authres});
                    } else
                        res.complete(sess,serr);
                });
            }
        });
        return res;
    }
301057
void checkForReusedJwt(JwtTokenConsumerImpl jwt, JwtConsumerConfig config) throws InvalidTokenException {
		// Only throw an error if tokens are not allowed to be reused
		if (!config.getTokenReuse()) {
			throwExceptionIfJwtReused(jwt);
		}
	}
493658
private void processJWKRequest(HttpServletResponse response, JwtConfig jwtConfig) throws IOException {

		/*
		 * if (!jwtConfig.isJwkEnabled()) { String errorMsg =
		 * Tr.formatMessage(tc, "JWK_ENDPOINT_JWK_NOT_ENABLED", new Object[] {
		 * jwtConfig.getId() }); Tr.error(tc, errorMsg);
		 * response.sendError(HttpServletResponse.SC_BAD_REQUEST, errorMsg);
		 * return; }
		 */

		String signatureAlg = jwtConfig.getSignatureAlgorithm();
		if (!Constants.SIGNATURE_ALG_RS256.equals(signatureAlg)) {
			String errorMsg = Tr.formatMessage(tc, "JWK_ENDPOINT_WRONG_ALGORITHM",
					new Object[] { jwtConfig.getId(), signatureAlg, Constants.SIGNATURE_ALG_RS256 });
			Tr.error(tc, errorMsg);
			response.sendError(HttpServletResponse.SC_BAD_REQUEST, errorMsg);
			return;
		}

		String jwkString = jwtConfig.getJwkJsonString();

		addNoCacheHeaders(response);
		response.setStatus(200);

		if (jwkString == null) {
			return;
		}
		try {
			PrintWriter pw = response.getWriter();
			response.setHeader(WebConstants.HTTP_HEADER_CONTENT_TYPE, WebConstants.HTTP_CONTENT_TYPE_JSON);
			pw.write(jwkString);
			pw.flush();
			pw.close();
		} catch (IOException e) {
			if (tc.isDebugEnabled()) {
				Tr.debug(tc, "Caught an exception attempting to get the response writer: " + e.getLocalizedMessage());
			}
		}
	}
399853
@Override
	public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
	    if (!component.isRendered()) {
	        return;
	    }
		Slider2 slider = (Slider2) component;
		ResponseWriter rw = context.getResponseWriter();
		encodeHTML(slider, context, rw);
	}
340388
@Override
	public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
		if (!component.isRendered()) {
			return;
		}
		Slider slider = (Slider) component;
		ResponseWriter rw = context.getResponseWriter();
		encodeHTML(slider, context, rw);

		Tooltip.activateTooltips(context, slider);
	}
452061
@Test
    public void MPJwtNoMpJwtConfig_mpJwtInWebXML_basicInApp() throws Exception {
        genericLoginConfigVariationTest(
                                        MpJwtFatConstants.LOGINCONFIG_MP_JWT_IN_WEB_XML_SERVLET_BASIC_IN_APP_ROOT_CONTEXT,
                                        MpJwtFatConstants.LOGINCONFIG_MP_JWT_IN_WEB_XML_SERVLET_BASIC_IN_APP,
                                        MpJwtFatConstants.MPJWT_APP_CLASS_LOGIN_CONFIG_MPJWTINWEBXML_BASICINAPP,
                                        ExpectedResult.BAD);

    }
1342528
protected void renderInputBegin(FacesContext facesContext,
            UIComponent uiComponent) throws IOException
    {
        ResponseWriter writer = facesContext.getResponseWriter();
        
        writer.startElement(HTML.INPUT_ELEM, uiComponent);
        writer.writeAttribute(HTML.TYPE_ATTR, org.apache.myfaces.shared.renderkit.html.HTML.INPUT_TYPE_PASSWORD, null);

        if (uiComponent instanceof ClientBehaviorHolder
                && !((ClientBehaviorHolder) uiComponent).getClientBehaviors().isEmpty())
        {
            writer.writeAttribute(HTML.ID_ATTR, 
                                  uiComponent.getClientId(facesContext), null);
        }
        else
        {
            HtmlRendererUtils.writeIdIfNecessary(writer, uiComponent, facesContext);
        }
        writer.writeAttribute(HTML.NAME_ATTR,
                              uiComponent.getClientId(facesContext), null);

        boolean isRedisplay;
        if (uiComponent instanceof HtmlInputSecret)
        {
            isRedisplay = ((HtmlInputSecret)uiComponent).isRedisplay();
        }
        else
        {
            isRedisplay = org.apache.myfaces.shared.renderkit.RendererUtils.getBooleanAttribute(uiComponent, 
                    JSFAttr.REDISPLAY_ATTR, false);
        }
        if (isRedisplay)
        {
            String strValue = RendererUtils.getStringValue(facesContext, uiComponent);
            writer.writeAttribute(HTML.VALUE_ATTR, strValue, JSFAttr.VALUE_ATTR);
        }

        Map<String, List<ClientBehavior>> behaviors = null;
        if (uiComponent instanceof ClientBehaviorHolder)
        {
            behaviors = ((ClientBehaviorHolder) uiComponent).getClientBehaviors();
            
            long commonPropertiesMarked = 0L;
            if (isCommonPropertiesOptimizationEnabled(facesContext))
            {
                commonPropertiesMarked = CommonPropertyUtils.getCommonPropertiesMarked(uiComponent);
            }
            if (behaviors.isEmpty() && isCommonPropertiesOptimizationEnabled(facesContext))
            {
                CommonPropertyUtils.renderChangeEventProperty(writer, 
                        commonPropertiesMarked, uiComponent);
                CommonPropertyUtils.renderEventProperties(writer, 
                        commonPropertiesMarked, uiComponent);
                CommonPropertyUtils.renderFieldEventPropertiesWithoutOnchange(writer, 
                        commonPropertiesMarked, uiComponent);
            }
            else
            {
                HtmlRendererUtils.renderBehaviorizedOnchangeEventHandler(facesContext, writer, uiComponent, behaviors);
                if (isCommonEventsOptimizationEnabled(facesContext))
                {
                    Long commonEventsMarked = CommonEventUtils.getCommonEventsMarked(uiComponent);
                    CommonEventUtils.renderBehaviorizedEventHandlers(facesContext, writer, 
                            commonPropertiesMarked, commonEventsMarked, uiComponent, behaviors);
                    CommonEventUtils.renderBehaviorizedFieldEventHandlersWithoutOnchange(
                        facesContext, writer, commonPropertiesMarked, commonEventsMarked, uiComponent, behaviors);
                }
                else
                {
                    HtmlRendererUtils.renderBehaviorizedEventHandlers(facesContext, writer, uiComponent, behaviors);
                    HtmlRendererUtils.renderBehaviorizedFieldEventHandlersWithoutOnchange(
                            facesContext, writer, uiComponent, behaviors);
                }
            }
            if (isCommonPropertiesOptimizationEnabled(facesContext))
            {
                CommonPropertyUtils.renderInputPassthroughPropertiesWithoutDisabledAndEvents(writer, 
                        commonPropertiesMarked, uiComponent);
            }
            else
            {
                HtmlRendererUtils.renderHTMLAttributes(writer, uiComponent, 
                        HTML.INPUT_PASSTHROUGH_ATTRIBUTES_WITHOUT_DISABLED_AND_EVENTS);
            }
        }
        else
        {
            if (isCommonPropertiesOptimizationEnabled(facesContext))
            {
                CommonPropertyUtils.renderInputPassthroughPropertiesWithoutDisabled(writer, 
                        CommonPropertyUtils.getCommonPropertiesMarked(uiComponent), uiComponent);
            }
            else
            {
                HtmlRendererUtils.renderHTMLAttributes(writer, uiComponent, 
                        HTML.INPUT_PASSTHROUGH_ATTRIBUTES_WITHOUT_DISABLED);
            }
        }

        if (isDisabled(facesContext, uiComponent))
        {
            writer.writeAttribute(HTML.DISABLED_ATTR, Boolean.TRUE, null);
        }

        if (isAutocompleteOff(facesContext, uiComponent))
        {
            writer.writeAttribute(HTML.AUTOCOMPLETE_ATTR, AUTOCOMPLETE_VALUE_OFF, HTML.AUTOCOMPLETE_ATTR);
        }
    }
276458
@Override
	public Map<String, String> convert(String token) {
		Map<String, String> headers;

		int headerEndIndex = token.indexOf('.');
		if (headerEndIndex == -1) {
			throw new InvalidTokenException("Invalid JWT. Missing JOSE Header.");
		}

		byte[] decodedHeader;

		try {
			decodedHeader = Codecs.b64UrlDecode(token.substring(0, headerEndIndex));
		} catch (IllegalArgumentException ex) {
			throw new InvalidTokenException("Invalid JWT. Malformed JOSE Header.", ex);
		}

		JsonParser parser = null;

		try {
			parser = this.factory.createParser(decodedHeader);
			headers = new HashMap<String, String>();
			if (parser.nextToken() == JsonToken.START_OBJECT) {
				while (parser.nextToken() == JsonToken.FIELD_NAME) {
					String headerName = parser.getCurrentName();
					parser.nextToken();
					String headerValue = parser.getValueAsString();
					headers.put(headerName, headerValue);
				}
			}

		} catch (IOException ex) {
			throw new InvalidTokenException("An I/O error occurred while reading the JWT: " + ex.getMessage(), ex);
		} finally {
			try {
				if (parser != null) parser.close();
			} catch (IOException ex) { }
		}

		return headers;
	}
987396
@Override
    public IPortletRenderExecutionWorker createRenderHeaderWorker(
            HttpServletRequest request,
            HttpServletResponse response,
            IPortletWindowId portletWindowId) {
        final IPortletWindow portletWindow =
                this.portletWindowRegistry.getPortletWindow(request, portletWindowId);
        return new PortletRenderHeaderExecutionWorker(
                portletThreadPool,
                executionInterceptors,
                portletRenderer,
                request,
                response,
                portletWindow);
    }
895415
@Override
    public JwtToken buildJwt() throws JwtException, InvalidBuilderException {
        // Create JWT here
        // TODO check for default claims?
        JwtConfig config = getConfig(configId);
        JwtToken jwt = new TokenImpl(this, config);

        return jwt;
    }
301224
@Override
	public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
		SelectOneMenu menu = (SelectOneMenu) component;

		if (!menu.isRendered()) {
			return;
		}
		ResponseWriter rw = context.getResponseWriter();
		String outerClientId = menu.getClientId(context);
		boolean clientIdHasBeenRendered = false;
		String clientId = outerClientId + "Inner";
		String span = null;
		if (!isHorizontalForm(component)) {
			span = startColSpanDiv(rw, menu, outerClientId);
			if (null != span) {
				Tooltip.generateTooltip(context, menu, rw);
				clientIdHasBeenRendered = true;
			}
		}
		rw.startElement("div", menu);

		rw.writeAttribute("class", getWithFeedback(getInputMode(menu.isInline()), component), "class");
		if (!clientIdHasBeenRendered) {
			rw.writeAttribute("id", outerClientId, "id");
			Tooltip.generateTooltip(context, menu, rw);
		}
		writeAttribute(rw, "dir", menu.getDir(), "dir");

		addLabel(rw, clientId, menu, outerClientId);
		if (isHorizontalForm(component)) {
			span = startColSpanDiv(rw, menu, null);
		}

		UIComponent prependingAddOnFacet = menu.getFacet("prepend");
		UIComponent appendingAddOnFacet = menu.getFacet("append");
		final boolean hasAddon = startInputGroupForAddOn(rw, (prependingAddOnFacet != null),
				(appendingAddOnFacet != null), menu);

		addPrependingAddOnToInputGroup(context, rw, prependingAddOnFacet, (prependingAddOnFacet != null), menu);
		renderSelectTag(context, rw, clientId, menu, outerClientId);
		addAppendingAddOnToInputGroup(context, rw, appendingAddOnFacet, (appendingAddOnFacet != null), menu);

		closeInputGroupForAddOn(rw, hasAddon);
		rw.endElement("div"); // form-group
		closeColSpanDiv(rw, span);
		Tooltip.activateTooltips(context, menu);
	}
545441
@Override
	public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
	    if (!component.isRendered()) {
	        return;
	    }
		Video video = (Video) component;
		ResponseWriter rw = context.getResponseWriter();
		String clientId = video.getClientId();
		boolean idHasBeenRendered=false;
		rw.startElement("div", video);
		String responsiveStyle = Responsive.getResponsiveStyleClass(video, false);
		if (null != responsiveStyle && responsiveStyle.trim().length()>0) {
			rw.writeAttribute("class", responsiveStyle, null);
			rw.writeAttribute("id", clientId, null);
			idHasBeenRendered=true;
		}
	
		rw.startElement("video", video);
		Tooltip.generateTooltip(context, video, rw);
		rw.writeAttribute("src", video.getSrc(), null);
		rw.writeAttribute("autoplay", video.isAutoplay(), null);
		rw.writeAttribute("controls", video.isControls(), null);
		rw.writeAttribute("loop", video.isLoop(), null);
		String videoId = clientId;
		if (idHasBeenRendered) {
			videoId = clientId + "_video";
		}
		rw.writeAttribute("id", videoId, null);
		String style = video.getStyle();
		if (null != style) {
			rw.writeAttribute("style", style, null);
		}
		String styleClass = video.getStyleClass();
		if (null == styleClass)
			styleClass = "";
		else
			styleClass = " " + styleClass;
		
		Tooltip.generateTooltip(context, video, rw);

		rw.writeAttribute("class", styleClass, "class");
		
		// Render Ajax Capabilities
		AJAXRenderer.generateBootsFacesAJAXAndJavaScript(FacesContext.getCurrentInstance(), video, rw, false);
	
		rw.endElement("video");
		if (null != responsiveStyle && responsiveStyle.trim().length()>0) {
			rw.endElement("div");
		}		
		Tooltip.activateTooltips(context, video, videoId);	
	}