Search in sources :

Example 96 with Resource

use of org.wso2.carbon.registry.core.Resource in project airavata by apache.

the class SecureClient method main.

public static void main(String[] args) throws Exception {
    Scanner scanner = new Scanner(System.in);
    // register client or use existing client
    System.out.println("");
    System.out.println("Please select from the following options:");
    System.out.println("1. Register the client as an OAuth application.");
    System.out.println("2. Client is already registered. Use the existing credentials.");
    String opInput = scanner.next();
    int option = Integer.valueOf(opInput.trim());
    String consumerId = null;
    String consumerSecret = null;
    if (option == 1) {
        // register OAuth application - this happens once during initialization of the gateway.
        /**
         **********************Start obtaining input from user****************************
         */
        System.out.println("");
        System.out.println("Registering an OAuth application representing the client....");
        System.out.println("Please enter following information as you prefer, or use defaults.");
        System.out.println("OAuth application name: (default:" + Properties.appName + ", press 'd' to use default value.)");
        String appNameInput = scanner.next();
        String appName = null;
        if (appNameInput.trim().equals("d")) {
            appName = Properties.appName;
        } else {
            appName = appNameInput.trim();
        }
        System.out.println("Consumer Id: (default:" + Properties.consumerID + ", press 'd' to use default value.)");
        String consumerIdInput = scanner.next();
        if (consumerIdInput.trim().equals("d")) {
            consumerId = Properties.consumerID;
        } else {
            consumerId = consumerIdInput.trim();
        }
        System.out.println("Consumer Secret: (default:" + Properties.consumerSecret + ", press 'd' to use default value.)");
        String consumerSecInput = scanner.next();
        if (consumerSecInput.trim().equals("d")) {
            consumerSecret = Properties.consumerSecret;
        } else {
            consumerSecret = consumerSecInput.trim();
        }
        /**
         ********************* Perform registration of the client as an OAuth app**************************
         */
        try {
            ConfigurationContext configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(null, null);
            OAuthAppRegisteringClient authAppRegisteringClient = new OAuthAppRegisteringClient(Properties.oauthAuthzServerURL, Properties.adminUserName, Properties.adminPassword, configContext);
            OAuthConsumerAppDTO appDTO = authAppRegisteringClient.registerApplication(appName, consumerId, consumerSecret);
            /**
             ******************* Complete registering the client **********************************************
             */
            System.out.println("");
            System.out.println("Registered OAuth app successfully. Following is app's details:");
            System.out.println("App Name: " + appDTO.getApplicationName());
            System.out.println("Consumer ID: " + appDTO.getOauthConsumerKey());
            System.out.println("Consumer Secret: " + appDTO.getOauthConsumerSecret());
            System.out.println("");
        } catch (AiravataSecurityException e) {
            e.printStackTrace();
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    } else if (option == 2) {
        System.out.println("");
        System.out.println("Enter Consumer Id: ");
        consumerId = scanner.next().trim();
        System.out.println("Enter Consumer Secret: ");
        consumerSecret = scanner.next().trim();
    }
    // obtain OAuth access token
    /**
     **********************Start obtaining input from user****************************
     */
    System.out.println("");
    System.out.println("Please select the preferred grant type: (or press d to use the default option" + Properties.grantType + ")");
    System.out.println("1. Resource Owner Password Credential.");
    System.out.println("2. Client Credential.");
    String grantTypeInput = scanner.next().trim();
    int grantType = 0;
    if (grantTypeInput.equals("d")) {
        grantType = Properties.grantType;
    } else {
        grantType = Integer.valueOf(grantTypeInput);
    }
    String userName = null;
    String password = null;
    if (grantType == 1) {
        System.out.println("Obtaining OAuth access token via 'Resource Owner Password' grant type....");
        System.out.println("Please enter following information as you prefer, or use defaults.");
        System.out.println("End user's name: (default:" + Properties.userName + ", press 'd' to use default value.)");
        String userNameInput = scanner.next();
        if (userNameInput.trim().equals("d")) {
            userName = Properties.userName;
        } else {
            userName = userNameInput.trim();
        }
        System.out.println("End user's password: (default:" + Properties.password + ", press 'd' to use default value.)");
        String passwordInput = scanner.next();
        if (passwordInput.trim().equals("d")) {
            password = Properties.password;
        } else {
            password = passwordInput.trim();
        }
    } else if (grantType == 2) {
        System.out.println("");
        System.out.println("Please enter the user name to be passed: ");
        String userNameInput = scanner.next();
        userName = userNameInput.trim();
        System.out.println("");
        System.out.println("Obtaining OAuth access token via 'Client Credential' grant type...' grant type....");
    }
    /**
     *************************** Finish obtaining input from user******************************************
     */
    try {
        // obtain the OAuth token for the specified end user.
        String accessToken = new OAuthTokenRetrievalClient().retrieveAccessToken(consumerId, consumerSecret, userName, password, grantType);
        System.out.println("");
        System.out.println("OAuth access token is: " + accessToken);
        // invoke Airavata API by the SecureClient, on behalf of the user.
        System.out.println("");
        System.out.println("Invoking Airavata API...");
        System.out.println("Enter the access token to be used: (default:" + accessToken + ", press 'd' to use default value.)");
        String accessTokenInput = scanner.next();
        String acTk = null;
        if (accessTokenInput.trim().equals("d")) {
            acTk = accessToken;
        } else {
            acTk = accessTokenInput.trim();
        }
        // obtain as input, the method to be invoked
        System.out.println("");
        System.out.println("Enter the number corresponding to the method to be invoked: ");
        System.out.println("1. getAPIVersion");
        System.out.println("2. getAllAppModules");
        System.out.println("3. addGateway");
        String methodNumberString = scanner.next();
        int methodNumber = Integer.valueOf(methodNumberString.trim());
        Airavata.Client client = createAiravataClient(Properties.SERVER_HOST, Properties.SERVER_PORT);
        AuthzToken authzToken = new AuthzToken();
        authzToken.setAccessToken(acTk);
        Map<String, String> claimsMap = new HashMap<>();
        claimsMap.put("userName", userName);
        claimsMap.put("email", "hasini@gmail.com");
        authzToken.setClaimsMap(claimsMap);
        if (methodNumber == 1) {
            String version = client.getAPIVersion(authzToken);
            System.out.println("");
            System.out.println("Airavata API version: " + version);
            System.out.println("");
        } else if (methodNumber == 2) {
            System.out.println("");
            System.out.println("Enter the gateway id: ");
            String gatewayId = scanner.next().trim();
            List<ApplicationModule> appModules = client.getAllAppModules(authzToken, gatewayId);
            System.out.println("Output of getAllAppModuels: ");
            for (ApplicationModule appModule : appModules) {
                System.out.println(appModule.getAppModuleName());
            }
            System.out.println("");
            System.out.println("");
        } else if (methodNumber == 3) {
            System.out.println("");
            System.out.println("Enter the gateway id: ");
            String gatewayId = scanner.next().trim();
            Gateway gateway = new Gateway(gatewayId, GatewayApprovalStatus.REQUESTED);
            gateway.setDomain("airavata.org");
            gateway.setEmailAddress("airavata@apache.org");
            gateway.setGatewayName("airavataGW");
            String output = client.addGateway(authzToken, gateway);
            System.out.println("");
            System.out.println("Output of addGateway: " + output);
            System.out.println("");
        }
    } catch (InvalidRequestException e) {
        e.printStackTrace();
    } catch (TException e) {
        e.printStackTrace();
    } catch (AiravataSecurityException e) {
        e.printStackTrace();
    }
}
Also used : TException(org.apache.thrift.TException) Scanner(java.util.Scanner) ConfigurationContext(org.apache.axis2.context.ConfigurationContext) HashMap(java.util.HashMap) OAuthConsumerAppDTO(org.wso2.carbon.identity.oauth.stub.dto.OAuthConsumerAppDTO) TException(org.apache.thrift.TException) InvalidRequestException(org.apache.airavata.model.error.InvalidRequestException) AiravataClientException(org.apache.airavata.model.error.AiravataClientException) AiravataSecurityException(org.apache.airavata.security.AiravataSecurityException) ApplicationModule(org.apache.airavata.model.appcatalog.appdeployment.ApplicationModule) Gateway(org.apache.airavata.model.workspace.Gateway) AuthzToken(org.apache.airavata.model.security.AuthzToken) List(java.util.List) InvalidRequestException(org.apache.airavata.model.error.InvalidRequestException) AiravataSecurityException(org.apache.airavata.security.AiravataSecurityException) Airavata(org.apache.airavata.api.Airavata)

Example 97 with Resource

use of org.wso2.carbon.registry.core.Resource in project ballerina by ballerina-lang.

the class CommandExecutor method getDocumentEditForNode.

/**
 * Get the document edit attachment info for a given particular node.
 * @param node      Node given
 * @return          Doc Attachment Info
 */
private static CommandUtil.DocAttachmentInfo getDocumentEditForNode(Node node) {
    CommandUtil.DocAttachmentInfo docAttachmentInfo = null;
    int replaceFrom;
    switch(node.getKind()) {
        case FUNCTION:
            if (((BLangFunction) node).docAttachments.isEmpty()) {
                replaceFrom = CommonUtil.toZeroBasedPosition(((BLangFunction) node).getPosition()).getStartLine();
                docAttachmentInfo = CommandUtil.getFunctionNodeDocumentation((BLangFunction) node, replaceFrom);
            }
            break;
        case STRUCT:
            if (((BLangStruct) node).docAttachments.isEmpty()) {
                replaceFrom = CommonUtil.toZeroBasedPosition(((BLangStruct) node).getPosition()).getStartLine();
                docAttachmentInfo = CommandUtil.getStructNodeDocumentation((BLangStruct) node, replaceFrom);
            }
            break;
        case ENUM:
            if (((BLangEnum) node).docAttachments.isEmpty()) {
                replaceFrom = CommonUtil.toZeroBasedPosition(((BLangEnum) node).getPosition()).getStartLine();
                docAttachmentInfo = CommandUtil.getEnumNodeDocumentation((BLangEnum) node, replaceFrom);
            }
            break;
        case TRANSFORMER:
            if (((BLangTransformer) node).docAttachments.isEmpty()) {
                replaceFrom = CommonUtil.toZeroBasedPosition(((BLangTransformer) node).getPosition()).getStartLine();
                docAttachmentInfo = CommandUtil.getTransformerNodeDocumentation((BLangTransformer) node, replaceFrom);
            }
            break;
        case RESOURCE:
            if (((BLangResource) node).docAttachments.isEmpty()) {
                BLangResource bLangResource = (BLangResource) node;
                replaceFrom = getReplaceFromForServiceOrResource(bLangResource, bLangResource.getAnnotationAttachments());
                docAttachmentInfo = CommandUtil.getResourceNodeDocumentation(bLangResource, replaceFrom);
            }
            break;
        case SERVICE:
            if (((BLangService) node).docAttachments.isEmpty()) {
                BLangService bLangService = (BLangService) node;
                replaceFrom = getReplaceFromForServiceOrResource(bLangService, bLangService.getAnnotationAttachments());
                docAttachmentInfo = CommandUtil.getServiceNodeDocumentation(bLangService, replaceFrom);
            }
            break;
        default:
            break;
    }
    return docAttachmentInfo;
}
Also used : BLangTransformer(org.wso2.ballerinalang.compiler.tree.BLangTransformer) BLangFunction(org.wso2.ballerinalang.compiler.tree.BLangFunction) BLangResource(org.wso2.ballerinalang.compiler.tree.BLangResource) BLangService(org.wso2.ballerinalang.compiler.tree.BLangService) BLangStruct(org.wso2.ballerinalang.compiler.tree.BLangStruct) BLangEnum(org.wso2.ballerinalang.compiler.tree.BLangEnum)

Example 98 with Resource

use of org.wso2.carbon.registry.core.Resource in project ballerina by ballerina-lang.

the class CommandUtil method getServiceDocumentationByPosition.

/**
 * Get the Documentation attachment for the service.
 * @param bLangPackage      BLangPackage built
 * @param line              Start line of the service in the source
 * @return {@link String}   Documentation attachment for the service
 */
static DocAttachmentInfo getServiceDocumentationByPosition(BLangPackage bLangPackage, int line) {
    // TODO: Currently resource position is invalid and we use the annotation attachment positions.
    for (TopLevelNode topLevelNode : bLangPackage.topLevelNodes) {
        if (topLevelNode instanceof BLangService) {
            BLangService serviceNode = (BLangService) topLevelNode;
            DiagnosticPos servicePos = CommonUtil.toZeroBasedPosition(serviceNode.getPosition());
            List<BLangAnnotationAttachment> annotationAttachments = serviceNode.getAnnotationAttachments();
            if (!annotationAttachments.isEmpty()) {
                DiagnosticPos lastAttachmentPos = CommonUtil.toZeroBasedPosition(annotationAttachments.get(annotationAttachments.size() - 1).getPosition());
                if (lastAttachmentPos.getEndLine() < line && line < servicePos.getEndLine()) {
                    return getServiceNodeDocumentation(serviceNode, lastAttachmentPos.getEndLine() + 1);
                }
            } else if (servicePos.getStartLine() == line) {
                return getServiceNodeDocumentation(serviceNode, line);
            }
        }
    }
    return null;
}
Also used : DiagnosticPos(org.wso2.ballerinalang.compiler.util.diagnotic.DiagnosticPos) BLangAnnotationAttachment(org.wso2.ballerinalang.compiler.tree.BLangAnnotationAttachment) BLangService(org.wso2.ballerinalang.compiler.tree.BLangService) TopLevelNode(org.ballerinalang.model.tree.TopLevelNode)

Example 99 with Resource

use of org.wso2.carbon.registry.core.Resource in project ballerina by ballerina-lang.

the class SymbolEnter method visit.

// Visitor methods
@Override
public void visit(BLangPackage pkgNode) {
    if (pkgNode.completedPhases.contains(CompilerPhase.DEFINE)) {
        return;
    }
    // Create PackageSymbol.
    BPackageSymbol pSymbol = createPackageSymbol(pkgNode);
    SymbolEnv builtinEnv = this.symTable.pkgEnvMap.get(symTable.builtInPackageSymbol);
    SymbolEnv pkgEnv = SymbolEnv.createPkgEnv(pkgNode, pSymbol.scope, builtinEnv);
    this.symTable.pkgEnvMap.put(pSymbol, pkgEnv);
    createPackageInitFunctions(pkgNode);
    // visit the package node recursively and define all package level symbols.
    // And maintain a list of created package symbols.
    pkgNode.imports.forEach(importNode -> defineNode(importNode, pkgEnv));
    // Define struct nodes.
    pkgNode.enums.forEach(enumNode -> defineNode(enumNode, pkgEnv));
    // Define struct nodes.
    pkgNode.structs.forEach(struct -> defineNode(struct, pkgEnv));
    // Define object nodes
    pkgNode.objects.forEach(object -> defineNode(object, pkgEnv));
    // Define connector nodes.
    pkgNode.connectors.forEach(con -> defineNode(con, pkgEnv));
    // Define connector params and type.
    defineConnectorParams(pkgNode.connectors, pkgEnv);
    // Define transformer nodes.
    pkgNode.transformers.forEach(tansformer -> defineNode(tansformer, pkgEnv));
    // Define service and resource nodes.
    pkgNode.services.forEach(service -> defineNode(service, pkgEnv));
    // Define struct field nodes.
    defineStructFields(pkgNode.structs, pkgEnv);
    // Define object field nodes.
    defineObjectFields(pkgNode.objects, pkgEnv);
    // Define connector action nodes.
    defineConnectorMembers(pkgNode.connectors, pkgEnv);
    // Define object functions
    defineObjectMembers(pkgNode.objects, pkgEnv);
    // Define function nodes.
    pkgNode.functions.forEach(func -> defineNode(func, pkgEnv));
    // Define transformer params
    defineTransformerMembers(pkgNode.transformers, pkgEnv);
    // Define service resource nodes.
    defineServiceMembers(pkgNode.services, pkgEnv);
    // Define annotation nodes.
    pkgNode.annotations.forEach(annot -> defineNode(annot, pkgEnv));
    resolveAnnotationAttributeTypes(pkgNode.annotations, pkgEnv);
    pkgNode.globalVars.forEach(var -> defineNode(var, pkgEnv));
    pkgNode.globalEndpoints.forEach(ep -> defineNode(ep, pkgEnv));
    definePackageInitFunctions(pkgNode, pkgEnv);
    pkgNode.completedPhases.add(CompilerPhase.DEFINE);
}
Also used : BPackageSymbol(org.wso2.ballerinalang.compiler.semantics.model.symbols.BPackageSymbol) SymbolEnv(org.wso2.ballerinalang.compiler.semantics.model.SymbolEnv)

Example 100 with Resource

use of org.wso2.carbon.registry.core.Resource in project ballerina by ballerina-lang.

the class CodeGenerator method createServiceInfoEntry.

private void createServiceInfoEntry(BLangService serviceNode) {
    // Add service name as an UTFCPEntry to the constant pool
    int serviceNameCPIndex = addUTF8CPEntry(currentPkgInfo, serviceNode.name.value);
    // Create service info
    if (serviceNode.endpointType != null) {
        String endPointQName = serviceNode.endpointType.tsymbol.toString();
        // TODO: bvmAlias needed?
        int epNameCPIndex = addUTF8CPEntry(currentPkgInfo, endPointQName);
        ServiceInfo serviceInfo = new ServiceInfo(currentPackageRefCPIndex, serviceNameCPIndex, serviceNode.symbol.flags, epNameCPIndex);
        // Add service level variables
        int localVarAttNameIndex = addUTF8CPEntry(currentPkgInfo, AttributeInfo.Kind.LOCAL_VARIABLES_ATTRIBUTE.value());
        LocalVariableAttributeInfo localVarAttributeInfo = new LocalVariableAttributeInfo(localVarAttNameIndex);
        serviceNode.vars.forEach(var -> visitVarSymbol(var.var.symbol, pvIndexes, localVarAttributeInfo));
        serviceInfo.addAttributeInfo(AttributeInfo.Kind.LOCAL_VARIABLES_ATTRIBUTE, localVarAttributeInfo);
        // Create the init function info
        BLangFunction serviceInitFunction = (BLangFunction) serviceNode.getInitFunction();
        createFunctionInfoEntry(serviceInitFunction);
        serviceInfo.initFuncInfo = currentPkgInfo.functionInfoMap.get(serviceInitFunction.name.toString());
        currentPkgInfo.addServiceInfo(serviceNode.name.value, serviceInfo);
        // Create resource info entries for all resources
        serviceNode.resources.forEach(res -> createResourceInfoEntry(res, serviceInfo));
    }
}
Also used : ServiceInfo(org.wso2.ballerinalang.programfile.ServiceInfo) LocalVariableAttributeInfo(org.wso2.ballerinalang.programfile.attributes.LocalVariableAttributeInfo) BLangFunction(org.wso2.ballerinalang.compiler.tree.BLangFunction) BLangXMLQuotedString(org.wso2.ballerinalang.compiler.tree.expressions.BLangXMLQuotedString) BLangEndpoint(org.wso2.ballerinalang.compiler.tree.BLangEndpoint)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)111 ErrorDTO (org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO)102 HashMap (java.util.HashMap)91 Test (org.testng.annotations.Test)64 HTTPCarbonMessage (org.wso2.transport.http.netty.message.HTTPCarbonMessage)59 HTTPTestRequest (org.ballerinalang.test.services.testutils.HTTPTestRequest)56 HttpMessageDataStreamer (org.wso2.transport.http.netty.message.HttpMessageDataStreamer)53 BJSON (org.ballerinalang.model.values.BJSON)46 APIPublisher (org.wso2.carbon.apimgt.core.api.APIPublisher)38 APIStore (org.wso2.carbon.apimgt.core.api.APIStore)29 BadRequestException (org.wso2.charon3.core.exceptions.BadRequestException)27 APIMgtAdminService (org.wso2.carbon.apimgt.core.api.APIMgtAdminService)24 CharonException (org.wso2.charon3.core.exceptions.CharonException)24 IOException (java.io.IOException)23 Map (java.util.Map)20 SCIMResponse (org.wso2.charon3.core.protocol.SCIMResponse)20 NotFoundException (org.wso2.charon3.core.exceptions.NotFoundException)17 SCIMResourceTypeSchema (org.wso2.charon3.core.schema.SCIMResourceTypeSchema)17 ArrayList (java.util.ArrayList)15 InternalErrorException (org.wso2.charon3.core.exceptions.InternalErrorException)15