/*
 *  Copyright WSO2 Inc.
 *
 *  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.wso2.carbon.apimgt.keymgt.handlers;

import org.wso2.carbon.apimgt.keymgt.ScopesIssuer;
import org.wso2.carbon.apimgt.keymgt.util.APIKeyMgtDataHolder;
import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser;
import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception;
import org.wso2.carbon.identity.oauth2.model.RequestParameter;
import org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext;
import org.wso2.carbon.identity.oauth2.token.handlers.grant.ClientCredentialsGrantHandler;

import java.util.ArrayList;
import java.util.Arrays;

public class ExtendedClientCredentialsGrantHandler extends ClientCredentialsGrantHandler {
    private static final String VALIDITY_PERIOD = "validity_period";

    @Override
    public boolean authorizeAccessDelegation(OAuthTokenReqMessageContext tokReqMsgCtx) {

        RequestParameter[] parameters = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getRequestParameters();

        long validityPeriod;

        if (parameters == null) {
            return true;
        }

        // find out validity period
        for (RequestParameter parameter : parameters) {
            if (VALIDITY_PERIOD.equals(parameter.getKey())) {
                if (parameter.getValue() != null && parameter.getValue().length > 0) {
                    validityPeriod = Long.parseLong(parameter.getValue()[0]);
                    //set validity time
                    tokReqMsgCtx.setValidityPeriod(validityPeriod);

                }
            }
        }

        return true;
    }


    @Override
    public boolean validateGrant(OAuthTokenReqMessageContext tokReqMsgCtx)
            throws IdentityOAuth2Exception {

        boolean validateResult = super.validateGrant(tokReqMsgCtx);
        AuthenticatedUser user = tokReqMsgCtx.getAuthorizedUser();
        String username = user.getUserName();
        user.setUserName(username);
        tokReqMsgCtx.setAuthorizedUser(user);

        return validateResult;
    }

    @Override
    public boolean issueRefreshToken() throws IdentityOAuth2Exception {
        return super.issueRefreshToken();
    }

    @Override
    public boolean isOfTypeApplicationUser() throws IdentityOAuth2Exception {
        return super.isOfTypeApplicationUser();
    }

    @Override
    public boolean validateScope(OAuthTokenReqMessageContext tokReqMsgCtx) {
        // Execute ScopeIssuer
        boolean state = ScopesIssuer.getInstance().setScopes(tokReqMsgCtx);

        // If ScopeIssuer returns true, then see if application scope is set.
        if (state) {
            String[] scopes = tokReqMsgCtx.getScope();

            String applicationScope = APIKeyMgtDataHolder.getApplicationTokenScope();
            if (scopes != null) {

                // Arrays.asList won't work here, because list.add cannot be called on the returned list.
                ArrayList<String> scopeList = new ArrayList<String>(scopes.length);
                scopeList.addAll(Arrays.asList(scopes));
                // Forcefully add application scope if it's not included in the list.
                if (!scopeList.contains(applicationScope)) {
                    scopeList.add(applicationScope);
                    tokReqMsgCtx.setScope(scopeList.toArray(new String[scopeList.size()]));
                }
            }
        }

        return state;
    }
}

@@ -1,14 +1,13 @@
 /*%0A *
- 
  Copyrig
@@ -13,33 +13,112 @@
 ght 
-WSO2 Inc.%0A *%0A *  Licensed
+(c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.%0A *%0A * WSO2 Inc. licenses this file to you
  und
@@ -139,16 +139,19 @@
 License,
+%0A *
  Version
@@ -171,20 +171,16 @@
 cense%22);
-%0A * 
  you may
@@ -204,16 +204,19 @@
 e except
+%0A *
  in comp
@@ -242,17 +242,16 @@
 ense.%0A *
- 
  You may
@@ -292,18 +292,16 @@
 *%0A *    
- 
- 
 http://w
@@ -340,17 +340,16 @@
 .0%0A *%0A *
- 
  Unless 
@@ -399,16 +399,19 @@
 writing,
+%0A *
  softwar
@@ -411,20 +411,16 @@
 software
-%0A * 
  distrib
@@ -462,16 +462,19 @@
 ed on an
+%0A *
  %22AS IS%22
@@ -480,20 +480,16 @@
 %22 BASIS,
-%0A * 
  WITHOUT
@@ -520,16 +520,19 @@
 S OF ANY
+%0A *
  KIND, e
@@ -556,19 +556,16 @@
 implied.
-%0A *
   See th
@@ -581,16 +581,19 @@
  for the
+%0A *
  specifi
@@ -628,20 +628,16 @@
 ions and
-%0A * 
  limitat
@@ -640,16 +640,19 @@
 itations
+%0A *
  under t
@@ -1894,19 +1894,17 @@
 etKey())
-) %7B
+ 
 %0A       
@@ -1904,36 +1904,39 @@
                 
-if (
+    && 
 parameter.getVal
@@ -2002,20 +2002,16 @@
         
-    
 validity
@@ -2076,20 +2076,16 @@
         
-    
 //set va
@@ -2104,36 +2104,32 @@
                 
-  
-  
 tokReqMsgCtx.set
@@ -2163,27 +2163,8 @@
 od);
-%0A%0A                %7D
 %0A   
@@ -2655,290 +2655,8 @@
  %7D%0A%0A
-    @Override%0A    public boolean issueRefreshToken() throws IdentityOAuth2Exception %7B%0A        return super.issueRefreshToken();%0A    %7D%0A%0A    @Override%0A    public boolean isOfTypeApplicationUser() throws IdentityOAuth2Exception %7B%0A        return super.isOfTypeApplicationUser();%0A    %7D%0A%0A
     

format and fix sonar issue for ExtendedClientCredentialsGrantHandler