text:
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include "logger.h"
#include "oic_malloc.h"
#include "oic_string.h"
#include "ocprovisioningmanager.h"
#include "oxmjustworks.h"
#include "oxmrandompin.h"
#include "securevirtualresourcetypes.h"
#include "srmutility.h"
#include "pmtypes.h"

#ifdef __cplusplus
extern "C"
{
#endif //__cplusplus

// declaration(s) for provisioning client using C-level provisioning API
// user input definition for main loop on provisioning client
#define _10_DISCOV_ALL_DEVS_    10
#define _11_DISCOV_UNOWN_DEVS_  11
#define _12_DISCOV_OWN_DEVS_    12
#define _20_REGIST_DEVS_        20
#define _30_PROVIS_PAIR_DEVS_   30
#define _31_PROVIS_CRED_        31
#define _32_PROVIS_ACL_         32
#define _33_PROVIS_DP_           33
#define _34_CHECK_LINK_STATUS_  34
#define _40_UNLINK_PAIR_DEVS_   40
#define _50_REMOVE_SELEC_DEV_   50
#define _99_EXIT_PRVN_CLT_      99

#define ACL_RESRC_MAX_NUM   16
#define ACL_RESRC_MAX_LEN   128
#define ACL_PEMISN_CNT      5
#define DISCOVERY_TIMEOUT   10  // 10 sec
#define CALLBACK_TIMEOUT    60  // 1 min
#define TAG "provisioningclient"

static const char* ACL_PEMISN[5] = {"CREATE", "READ", "WRITE", "DELETE", "NOTIFY"};
static const char* SVR_DB_FILE_NAME = "oic_svr_db_client.dat";
        // '_' for separaing from the same constant variable in |srmresourcestrings.c|
static const char* PRVN_DB_FILE_NAME = "oic_prvn_mng.db";
static const OicSecPrm_t  SUPPORTED_PRMS[1] =
{
    PRM_PRE_CONFIGURED,
};

// |g_ctx| means provision manager application context and
// the following, includes |un/own_list|, could be variables, which |g_ctx| has,
// for accessing all function(s) for these, they are declared on global domain
static const char* g_ctx = "Provision Manager Client Application Context";
static char* g_svr_fname;
static char* g_prvn_fname;
static OCProvisionDev_t* g_own_list;
static OCProvisionDev_t* g_unown_list;
static int g_own_cnt;
static int g_unown_cnt;
static bool g_doneCB;

// function declaration(s) for calling them before implementing
static OicSecAcl_t* createAcl(const int);
static OicSecPdAcl_t* createPdAcl(const int);
static OCProvisionDev_t* getDevInst(const OCProvisionDev_t*, const int);
static int printDevList(const OCProvisionDev_t*);
static size_t printUuidList(const OCUuidList_t*);
static int printResultList(const OCProvisionResult_t*, const int);
static void printUuid(const OicUuid_t*);
static FILE* fopen_prvnMng(const char*, const char*);
static int waitCallbackRet(void);
static int selectTwoDiffNum(int*, int*, const int, const char*);

// callback function(s) for provisioning client using C-level provisioning API
static void ownershipTransferCB(void* ctx, int nOfRes, OCProvisionResult_t* arr, bool hasError)
{
    if(!hasError)
    {
        OIC_LOG_V(INFO, TAG, "Ownership Transfer SUCCEEDED - ctx: %s", (char*) ctx);
    }
    else
    {
        OIC_LOG_V(ERROR, TAG, "Ownership Transfer FAILED - ctx: %s", (char*) ctx);
        printResultList((const OCProvisionResult_t*) arr, nOfRes);
    }
    g_doneCB = true;
}

static void provisionPairwiseCB(void* ctx, int nOfRes, OCProvisionResult_t* arr, bool hasError)
{
    if(!hasError)
    {
        OIC_LOG_V(INFO, TAG, "Provision Pairwise SUCCEEDED - ctx: %s", (char*) ctx);
    }
    else
    {
        OIC_LOG_V(ERROR, TAG, "Provision Pairwise FAILED - ctx: %s", (char*) ctx);
        printResultList((const OCProvisionResult_t*) arr, nOfRes);
    }
    g_doneCB = true;
}

static void provisionCredCB(void* ctx, int nOfRes, OCProvisionResult_t* arr, bool hasError)
{
    if(!hasError)
    {
        OIC_LOG_V(INFO, TAG, "Provision Credential SUCCEEDED - ctx: %s", (char*) ctx);
    }
    else
    {
        OIC_LOG_V(ERROR, TAG, "Provision Credential FAILED - ctx: %s", (char*) ctx);
        printResultList((const OCProvisionResult_t*) arr, nOfRes);
    }
    g_doneCB = true;
}

static void provisionAclCB(void* ctx, int nOfRes, OCProvisionResult_t* arr, bool hasError)
{
    if(!hasError)
    {
        OIC_LOG_V(INFO, TAG, "Provision ACL SUCCEEDED - ctx: %s", (char*) ctx);
    }
    else
    {
        OIC_LOG_V(ERROR, TAG, "Provision ACL FAILED - ctx: %s", (char*) ctx);
        printResultList((const OCProvisionResult_t*) arr, nOfRes);
    }
    g_doneCB = true;
}

static void provisionDPCB(void* ctx, int nOfRes, OCProvisionResult_t* arr, bool hasError)
{
    if(!hasError)
    {
        OIC_LOG_V(INFO, TAG, "Provision Direct-Pairing SUCCEEDED - ctx: %s", (char*) ctx);
    }
    else
    {
        OIC_LOG_V(ERROR, TAG, "Provision Direct-Pairing FAILED - ctx: %s", (char*) ctx);
        printResultList((const OCProvisionResult_t*) arr, nOfRes);
    }
    g_doneCB = true;
}

static void unlinkDevicesCB(void* ctx, int nOfRes, OCProvisionResult_t* arr, bool hasError)
{
    if(!hasError)
    {
        OIC_LOG_V(INFO, TAG, "Unlink Devices SUCCEEDED - ctx: %s", (char*) ctx);
    }
    else
    {
        OIC_LOG_V(ERROR, TAG, "Unlink Devices FAILED - ctx: %s", (char*) ctx);
        printResultList((const OCProvisionResult_t*) arr, nOfRes);
    }
    g_doneCB = true;
}

static void removeDeviceCB(void* ctx, int nOfRes, OCProvisionResult_t* arr, bool hasError)
{
    if(!hasError)
    {
        OIC_LOG_V(INFO, TAG, "Remove Device SUCCEEDED - ctx: %s", (char*) ctx);
    }
    else
    {
        OIC_LOG_V(ERROR, TAG, "Remove Device FAILED - ctx: %s", (char*) ctx);
        printResultList((const OCProvisionResult_t*) arr, nOfRes);
    }
    g_doneCB = true;
}

static void inputPinCB(char* pin, size_t len)
{
    if(!pin || OXM_RANDOM_PIN_SIZE>=len)
    {
        OIC_LOG(ERROR, TAG, "inputPinCB invalid parameters");
        return;
    }

    printf("   > INPUT PIN: ");
    for(int ret=0; 1!=ret; )
    {
        ret = scanf("%8s", pin);
        for( ; 0x20<=getchar(); );  // for removing overflow garbages
                                    // '0x20<=code' is character region
    }
}

// function(s) for provisioning client using C-level provisioning API
static int initProvisionClient(void)
{
    // initialize persistent storage for SVR DB
    static OCPersistentStorage pstStr =
    {
        .open = fopen_prvnMng,
        .read = fread,
        .write = fwrite,
        .close = fclose,
        .unlink = unlink
    };
    if(OC_STACK_OK != OCRegisterPersistentStorageHandler(&pstStr))
    {
        OIC_LOG(ERROR, TAG, "OCRegisterPersistentStorageHandler error");
        return -1;
    }

    // initialize OC stack and provisioning manager
    if(OC_STACK_OK != OCInit(NULL, 0, OC_CLIENT_SERVER))
    {
        OIC_LOG(ERROR, TAG, "OCStack init error");
        return -1;
    }

    if (access(PRVN_DB_FILE_NAME, F_OK) != -1)
    {
        printf("************************************************************\n");
        printf("************Provisioning DB file already exists.************\n");
        printf("************************************************************\n");
    }
    else
    {
        printf("*************************************************************\n");
        printf("************No provisioning DB file, creating new************\n");
        printf("*************************************************************\n");
    }

    if(OC_STACK_OK != OCInitPM(PRVN_DB_FILE_NAME))
    {
        OIC_LOG(ERROR, TAG, "OC_PM init error");
        return -1;
    }

    // register callback function(s) to each OxM
    OTMCallbackData_t otmcb =
    {
        .loadSecretCB = LoadSecretJustWorksCallback,
        .createSecureSessionCB = CreateSecureSessionJustWorksCallback,
        .createSelectOxmPayloadCB = CreateJustWorksSelectOxmPayload,
        .createOwnerTransferPayloadCB = CreateJustWorksOwnerTransferPayload
    };
    if(OC_STACK_OK != OCSetOwnerTransferCallbackData(OIC_JUST_WORKS, &otmcb))
    {
        OIC_LOG(ERROR, TAG, "OCSetOwnerTransferCallbackData error: OIC_JUST_WORKS");
        return -1;
    }
    otmcb.loadSecretCB = InputPinCodeCallback;
    otmcb.createSecureSessionCB = CreateSecureSessionRandomPinCallback;
    otmcb.createSelectOxmPayloadCB = CreatePinBasedSelectOxmPayload;
    otmcb.createOwnerTransferPayloadCB = CreatePinBasedOwnerTransferPayload;
    if(OC_STACK_OK != OCSetOwnerTransferCallbackData(OIC_RANDOM_DEVICE_PIN, &otmcb))
    {
        OIC_LOG(ERROR, TAG, "OCSetOwnerTransferCallbackData error: OIC_RANDOM_DEVICE_PIN");
        return -1;
    }
    SetInputPinCB(inputPinCB);

    return 0;
}

static int discoverAllDevices(void)
{
    // delete un/owned device lists before updating them
    if(g_own_list)
    {
        OCDeleteDiscoveredDevices(g_own_list);
        g_own_list = NULL;
    }
    if(g_unown_list)
    {
        OCDeleteDiscoveredDevices(g_unown_list);
        g_unown_list = NULL;
    }

    // call |OCGetDevInfoFromNetwork| API actually
    printf("   Discovering All Un/Owned Devices on Network..\n");
    if(OC_STACK_OK != OCGetDevInfoFromNetwork(DISCOVERY_TIMEOUT, &g_own_list, &g_unown_list))
    {
        OIC_LOG(ERROR, TAG, "OCGetDevInfoFromNetwork API error");
        return -1;
    }

    // display the discovered un/owned lists
    printf("   > Discovered Owned Devices\n");
    g_own_cnt = printDevList(g_own_list);
    printf("   > Discovered Unowned Devices\n");
    g_unown_cnt = printDevList(g_unown_list);

    return 0;
}

static int discoverUnownedDevices(void)
{
    // delete unowned device list before updating it
    if(g_unown_list)
    {
        OCDeleteDiscoveredDevices(g_unown_list);
        g_unown_list = NULL;
    }

    // call |OCDiscoverUnownedDevices| API actually
    printf("   Discovering Only Unowned Devices on Network..\n");
    if(OC_STACK_OK != OCDiscoverUnownedDevices(DISCOVERY_TIMEOUT, &g_unown_list))
    {
        OIC_LOG(ERROR, TAG, "OCDiscoverUnownedDevices API error");
        return -1;
    }

    // display the discovered unowned list
    printf("   > Discovered Unowned Devices\n");
    g_unown_cnt = printDevList(g_unown_list);

    return 0;
}

static int discoverOwnedDevices(void)
{
    // delete owned device list before updating it
    if(g_own_list)
    {
        OCDeleteDiscoveredDevices(g_own_list);
        g_own_list = NULL;
    }

    // call |OCDiscoverOwnedDevices| API actually
    printf("   Discovering Only Owned Devices on Network..\n");
    if(OC_STACK_OK != OCDiscoverOwnedDevices(DISCOVERY_TIMEOUT, &g_own_list))
    {
        OIC_LOG(ERROR, TAG, "OCDiscoverOwnedDevices API error");
        return -1;
    }

    // display the discovered owned list
    printf("   > Discovered Owned Devices\n");
    g_own_cnt = printDevList(g_own_list);

    return 0;
}

static int registerDevices(void)
{
    // check |unown_list| for registering devices
    if(!g_unown_list || 0>=g_unown_cnt)
    {
        printf("   > Unowned Device List, to Register Devices, is Empty\n");
        printf("   > Please Discover Unowned Devices first, with [10|11] Menu\n");
        return 0;  // normal case
    }

    // call |OCDoOwnershipTransfer| API actually
    // calling this API with callback actually acts like blocking
    // for error checking, the return value saved and printed
    g_doneCB = false;
    printf("   Registering All Discovered Unowned Devices..\n");
    OCStackResult rst = OCDoOwnershipTransfer((void*) g_ctx, g_unown_list, ownershipTransferCB);
    if(OC_STACK_OK != rst)
    {
        OIC_LOG_V(ERROR, TAG, "OCDoOwnershipTransfer API error: %d", rst);
        return -1;
    }
    if(waitCallbackRet())  // input |g_doneCB| flag implicitly
    {
        OIC_LOG(ERROR, TAG, "OCProvisionCredentials callback error");
        return -1;
    }

    // display the registered result
    printf("   > Registered Discovered Unowned Devices\n");
    printf("   > Please Discover Owned Devices for the Registered Result, with [10|12] Menu\n");

    return 0;
}

static int provisionPairwise(void)
{
    // check |own_list| for provisioning pairwise devices
    if(!g_own_list || 2>g_own_cnt)
    {
        printf("   > Owned Device List, to Provision the Pairwise, is Empty\n");
        printf("   > Please Register Unowned Devices first, with [20] Menu\n");
        return 0;  // normal case
    }

    // select two devices for provisioning pairwise devices
    int dev_num[2] = {0};
    if(selectTwoDiffNum(&(dev_num[0]), &(dev_num[1]), g_own_cnt, "for Linking Devices"))
    {
        OIC_LOG(ERROR, TAG, "selectTwoDiffNum error return");
        return -1;  // not need to 'goto' |ERROR| before allocating |acl|
    }

    // create ACL(s) for each selected device
    OicSecAcl_t* acl[2] = {0};
    for(int i=0; 2>i; ++i)
    {
        acl[i] = createAcl(dev_num[i]);
        if(!acl[i])
        {
            OIC_LOG(ERROR, TAG, "createAcl error return");
            goto PVPWS_ERROR;
        }
    }

    // call |OCProvisionPairwiseDevices| API actually
    // calling this API with callback actually acts like blocking
    // for error checking, the return value saved and printed
    g_doneCB = false;
    printf("   Provisioning Selected Pairwise Devices..\n");
    OCStackResult rst =
            OCProvisionPairwiseDevices((void*) g_ctx,
                    SYMMETRIC_PAIR_WISE_KEY, OWNER_PSK_LENGTH_128,
                    getDevInst((const OCProvisionDev_t*) g_own_list, dev_num[0]), acl[0],
                    getDevInst((const OCProvisionDev_t*) g_own_list, dev_num[1]), acl[1],
                    provisionPairwiseCB);
    if(OC_STACK_OK != rst)
    {
        OIC_LOG_V(ERROR, TAG, "OCProvisionPairwiseDevices API error: %d", rst);
        goto PVPWS_ERROR;
    }
    if(waitCallbackRet())  // input |g_doneCB| flag implicitly
    {
        OIC_LOG(ERROR, TAG, "OCProvisionCredentials callback error");
        goto PVPWS_ERROR;
    }
    OCDeleteACLList(acl[0]);
    OCDeleteACLList(acl[1]);

    // display the pairwise-provisioned result
    printf("   > Provisioned Selected Pairwise Devices\n");
    printf("   > Please Check Device's Status for the Linked Result, with [33] Menu\n");

    return 0;

PVPWS_ERROR:
    OCDeleteACLList(acl[0]);
    OCDeleteACLList(acl[1]);
    return -1;
}

static int provisionCred(void)
{
    // check |own_list| for provisioning pairwise credentials
    if(!g_own_list || 2>g_own_cnt)
    {
        printf("   > Owned Device List, to Provision Credentials, is Empty\n");
        printf("   > Please Register Unowned Devices first, with [20] Menu\n");
        return 0;  // normal case
    }

    // select two devices for provisioning pairwise credentials
    int dev_num[2] = {0};
    if(selectTwoDiffNum(&(dev_num[0]), &(dev_num[1]), g_own_cnt, "for Linking CRED(s)"))
    {
        OIC_LOG(ERROR, TAG, "selectTwoDiffNum error return");
        return -1;
    }

    printf("   Select PSK length..\n");
    printf("   1 - 128bit(Default)\n");
    printf("   2 - 256bit\n");
    int sizeOption = 0;

    for(int ret=0; 1!=ret; )
    {
         ret = scanf("%d",&sizeOption);
         for( ; 0x20<=getchar(); );  // for removing overflow garbages
                                    // '0x20<=code' is character region
    }
    size_t size = 0;

    switch(sizeOption)
    {
        case 1:
        {
            size = OWNER_PSK_LENGTH_128;
            break;
        }
        case 2:
        {
            size = OWNER_PSK_LENGTH_256;
            break;
        }
        default:
        {
            size = OWNER_PSK_LENGTH_128;
            break;
        }
    }

    // call |OCProvisionCredentials| API actually
    // calling this API with callback actually acts like blocking
    // for error checking, the return value saved and printed
    g_doneCB = false;
    printf("   Provisioning Selected Pairwise Credentials..\n");
    OCStackResult rst =
            OCProvisionCredentials((void*) g_ctx,
                    SYMMETRIC_PAIR_WISE_KEY, size,
                    getDevInst((const OCProvisionDev_t*) g_own_list, dev_num[0]),
                    getDevInst((const OCProvisionDev_t*) g_own_list, dev_num[1]),
                    provisionCredCB);
    if(OC_STACK_OK != rst)
    {
        OIC_LOG_V(ERROR, TAG, "OCProvisionCredentials API error: %d", rst);
        return -1;
    }
    if(waitCallbackRet())  // input |g_doneCB| flag implicitly
    {
        OIC_LOG(ERROR, TAG, "OCProvisionCredentials callback error");
        return -1;
    }

    // display the CRED-provisioned result
    printf("   > Provisioned Selected Pairwise Crendentials\n");
    printf("   > Please Check Device's Status for the Linked Result, with [33] Menu\n");

    return 0;
}

static int provisionAcl(void)
{
    // check |own_list| for provisioning access control list
    if(!g_own_list || 1>g_own_cnt)
    {
        printf("   > Owned Device List, to Provision ACL, is Empty\n");
        printf("   > Please Register Unowned Devices first, with [20] Menu\n");
        return 0;  // normal case
    }

    // select device for provisioning access control list
    int dev_num = 0;
    for( ; ; )
    {
        printf("   > Enter Device Number, for Provisioning ACL: ");
        for(int ret=0; 1!=ret; )
        {
            ret = scanf("%d", &dev_num);
            for( ; 0x20<=getchar(); );  // for removing overflow garbages
                                        // '0x20<=code' is character region
        }
        if(0<dev_num && g_own_cnt>=dev_num)
        {
            break;
        }
        printf("     Entered Wrong Number. Please Enter Again\n");
    }

    // create ACL for selected device
    OicSecAcl_t* acl = NULL;
    acl = createAcl(dev_num);
    if(!acl)
    {
        OIC_LOG(ERROR, TAG, "createAcl error return");
        goto PVACL_ERROR;
    }

    // call |OCProvisionACL| API actually
    // calling this API with callback actually acts like blocking
    // for error checking, the return value saved and printed
    g_doneCB = false;
    printf("   Provisioning Selected ACL..\n");
    OCProvisionDev_t* dev = getDevInst((const OCProvisionDev_t*) g_own_list, dev_num);
    if(!dev)
    {
        OIC_LOG(ERROR, TAG, "provisionAcl: device instance empty");
        goto PVACL_ERROR;
    }
    OCStackResult rst = OCProvisionACL((void*) g_ctx, dev, acl, provisionAclCB);
    if(OC_STACK_OK != rst)
    {
        OIC_LOG_V(ERROR, TAG, "OCProvisionACL API error: %d", rst);
        goto PVACL_ERROR;
    }
    if(waitCallbackRet())  // input |g_doneCB| flag implicitly
    {
        OIC_LOG(ERROR, TAG, "OCProvisionCredentials callback error");
        goto PVACL_ERROR;
    }
    OCDeleteACLList(acl);  // after here |acl| points nothing

    // display the ACL-provisioned result
    printf("   > Provisioned Selected ACL\n");

    return 0;

PVACL_ERROR:
    OCDeleteACLList(acl);  // after here |acl| points nothing
    return -1;
}

static int provisionDirectPairing(void)
{
    // check |own_list| for provisioning direct-pairing
    if(!g_own_list || 1>g_own_cnt)
    {
        printf("   > Owned Device List, to Provision ACL, is Empty\n");
        printf("   > Please Register Unowned Devices first, with [20] Menu\n");
        return 0;  // normal case
    }

    // select device for provisioning direct-pairing
    int dev_num = 0;
    for( ; ; )
    {
        printf("   > Enter Device Number, for Provisioning Direct-Pairing: ");
        for(int ret=0; 1!=ret; )
        {
            ret = scanf("%d", &dev_num);
            for( ; 0x20<=getchar(); );  // for removing overflow garbages
                                        // '0x20<=code' is character region
        }
        if(0<dev_num && g_own_cnt>=dev_num)
        {
            break;
        }
        printf("     Entered Wrong Number. Please Enter Again\n");
    }

    // create Direct-Pairing Configuration(PIN, PDACL) for selected device
    // TODO: default acl -> input from user !
    OicSecPconf_t pconf;
    memset(&pconf, 0, sizeof(OicSecPconf_t));

    // set enable dp
    pconf.edp = true;

    // set default supported PRM types
    pconf.prmLen = sizeof(SUPPORTED_PRMS)/sizeof(OicSecPrm_t);
    pconf.prm = (OicSecPrm_t *)OICCalloc(pconf.prmLen, sizeof(OicSecPrm_t));
    if(pconf.prm)
    {
        for (size_t i=0; i<pconf.prmLen; i++)
        {
            pconf.prm[i] = SUPPORTED_PRMS[i];
        }
    }
    else
    {
        OIC_LOG(ERROR, TAG, "create prm error return");
        goto PVDP_ERROR;
    }

    // set default pin
    const char DP_DEFAULT_PIN[] = "00000000";
    memcpy(pconf.pin.val, DP_DEFAULT_PIN, DP_PIN_LENGTH);

    // set default pdacl
    pconf.pdacls = createPdAcl(dev_num);
    if(!pconf.pdacls)
    {
        OIC_LOG(ERROR, TAG, "createPdAcl error return");
        goto PVDP_ERROR;
    }

    // call |OCProvisionDirectPairing| API actually
    // calling this API with callback actually acts like blocking
    // for error checking, the return value saved and printed
    g_doneCB = false;
    printf("   Atempt Direct-Pairing Provisioning (PIN : [%s])..\n", (char*)pconf.pin.val);
    OCStackResult rst = OCProvisionDirectPairing((void*) g_ctx,
                                       getDevInst((const OCProvisionDev_t*) g_own_list, dev_num),
                                       &pconf, provisionDPCB);
    if(OC_STACK_OK != rst)
    {
        OIC_LOG_V(ERROR, TAG, "OCProvisionDirectPairing API error: %d", rst);
        if (OC_STACK_UNAUTHORIZED_REQ == rst)
        {
            OIC_LOG(ERROR, TAG, "Target Server NOT Support Direct-Pairing !!! (DPC == false)");
        }
        goto PVDP_ERROR;
    }
    if(waitCallbackRet())  // input |g_doneCB| flag implicitly
    {
        OIC_LOG(ERROR, TAG, "OCProvisionCredentials callback error");
        goto PVDP_ERROR;
    }
    OCDeletePdAclList(pconf.pdacls);

    // display the PCONF-provisioned result
    printf("   > SUCCESS to provision Direct-Pairing !!\n");

    return 0;

PVDP_ERROR:
    OCDeletePdAclList(pconf.pdacls);  // after here |acl| points nothing
    return -1;
}

static int checkLinkedStatus(void)
{
    // check |own_list| for checking selected link status on PRVN DB
    if(!g_own_list || 1>g_own_cnt)
    {
        printf("   > Owned Device List, to Check Linked Status on PRVN DB, is Empty\n");
        printf("   > Please Register Unowned Devices first, with [20] Menu\n");
        return 0;  // normal case
    }

    // select device for checking selected link status on PRVN DB
    int dev_num = 0;
    for( ; ; )
    {
        printf("   > Enter Device Number, for Checking Linked Status on PRVN DB: ");
        for(int ret=0; 1!=ret; )
        {
            ret = scanf("%d", &dev_num);
            for( ; 0x20<=getchar(); );  // for removing overflow garbages
                                        // '0x20<=code' is character region
        }
        if(0<dev_num && g_own_cnt>=dev_num)
        {
            break;
        }
        printf("     Entered Wrong Number. Please Enter Again\n");
    }

    // call |OCGetLinkedStatus| API actually
    printf("   Checking Selected Link Status on PRVN DB..\n");
    OCUuidList_t* dvid_lst = NULL;
    size_t dvid_cnt = 0;
    OCProvisionDev_t* dev = getDevInst((const OCProvisionDev_t*)g_own_list, dev_num);
    if(!dev || !dev->doxm)
    {
        OIC_LOG(ERROR, TAG, "checkLinkedStatus: device instance empty");
        goto CKLST_ERROR;
    }

    if(OC_STACK_OK !=
            OCGetLinkedStatus(
                    &dev->doxm->deviceID,
                    &dvid_lst, &dvid_cnt))  // allow empty list
    {
        OIC_LOG(ERROR, TAG, "OCGetLinkedStatus API error");
        goto CKLST_ERROR;
    }

    // display the linked status result
    printf("   > Checked Selected Link Status on PRVN DB\n");
    if(!dvid_lst || !dvid_cnt)  // |size_t| is unsigned
    {
        printf("     Linked Device List is Empty..\n");
        return 0;  // normal case
    }
    if(dvid_cnt != printUuidList((const OCUuidList_t*) dvid_lst))
    {
        OIC_LOG(ERROR, TAG, "printUuidList error return");
        goto CKLST_ERROR;
    }
    OCDeleteUuidList(dvid_lst);

    return 0;

CKLST_ERROR:
    OCDeleteUuidList(dvid_lst);
    return -1;
}

static int unlinkPairwise(void)
{
    // check |own_list| for unlinking pairwise devices
    if(!g_own_list || 2>g_own_cnt)
    {
        printf("   > Owned Device List, to Unlink the Pairwise, is Empty\n");
        printf("   > Please Register Unowned Devices first, with [20] Menu\n");
        return 0;  // normal case
    }

    // select two devices for unlinking pairwise devices
    int dev_num[2] = {0};
    if(selectTwoDiffNum(&(dev_num[0]), &(dev_num[1]), g_own_cnt, "for Unlinking Devices"))
    {
        OIC_LOG(ERROR, TAG, "selectTwoDiffNum error return");
        return -1;
    }

    // call |OCUnlinkDevices| API actually
    // calling this API with callback actually acts like blocking
    // for error checking, the return value saved and printed
    g_doneCB = false;
    printf("   Unlinking Selected Pairwise Devices..\n");
    OCStackResult rst =
            OCUnlinkDevices((void*) g_ctx,
                    getDevInst((const OCProvisionDev_t*) g_own_list, dev_num[0]),
                    getDevInst((const OCProvisionDev_t*) g_own_list, dev_num[1]),
                    unlinkDevicesCB);
    if(OC_STACK_OK != rst)
    {
        OIC_LOG_V(ERROR, TAG, "OCUnlinkDevices API error: %d", rst);
        return -1;
    }
    if(waitCallbackRet())  // input |g_doneCB| flag implicitly
    {
        OIC_LOG(ERROR, TAG, "OCProvisionCredentials callback error");
        return -1;
    }

    // display the pairwise-unlinked result
    printf("   > Unlinked Selected Pairwise Devices\n");
    printf("   > Please Check Device's Status for the Unlinked Result, with [33] Menu\n");

    return 0;
}

static int removeDevice(void)
{
    // check |own_list| for removing device
    if(!g_own_list || 1>g_own_cnt)
    {
        printf("   > Owned Device List, to Remove Device, is Empty\n");
        printf("   > Please Register Unowned Devices first, with [20] Menu\n");
        return 0;  // normal case
    }

    // select device for removing it
    int dev_num = 0;
    for( ; ; )
    {
        printf("   > Enter Device Number, for Removing Device: ");
        for(int ret=0; 1!=ret; )
        {
            ret = scanf("%d", &dev_num);
            for( ; 0x20<=getchar(); );  // for removing overflow garbages
                                        // '0x20<=code' is character region
        }
        if(0<dev_num && g_own_cnt>=dev_num)
        {
            break;
        }
        printf("     Entered Wrong Number. Please Enter Again\n");
    }

    // call |OCRemoveDevice| API actually
    // calling this API with callback actually acts like blocking
    // for error checking, the return value saved and printed
    g_doneCB = false;
    printf("   Removing Selected Owned Device..\n");
    OCStackResult rst =
            OCRemoveDevice((void*) g_ctx, DISCOVERY_TIMEOUT,
                    getDevInst((const OCProvisionDev_t*) g_own_list, dev_num), removeDeviceCB);
    if(OC_STACK_OK != rst)
    {
        OIC_LOG_V(ERROR, TAG, "OCRemoveDevice API error: %d", rst);
        return -1;
    }
    if(waitCallbackRet())  // input |g_doneCB| flag implicitly
    {
        OIC_LOG(ERROR, TAG, "OCProvisionCredentials callback error");
        return -1;
    }

    // display the removed result
    printf("   > Removed Selected Owned Device\n");
    printf("   > Please Discover Owned Devices for the Registered Result, with [10|12] Menu\n");

    return 0;
}

static OicSecAcl_t* createAcl(const int dev_num)
{
    if(0>=dev_num || g_own_cnt<dev_num)
    {
        OIC_LOG(ERROR, TAG, "createAcl invalid parameters");
        return NULL;  // not need to 'goto' |ERROR| before allocating |acl|
    }

    // allocate memory for |acl| struct
    printf("   **** Create ACL for the Selected Device[%d]\n", dev_num);
    OicSecAcl_t* acl = (OicSecAcl_t*) OICCalloc(1, sizeof(OicSecAcl_t));
    if(!acl)
    {
        OIC_LOG(ERROR, TAG, "createAcl: OICCalloc error return");
        return NULL;  // not need to 'goto' |ERROR| before allocating |acl|
    }

    // enter |subject| device number
    int num = 0;
    for( ; ; )
    {
        printf("   > [A] Enter Subject Device Number: ");
        for(int ret=0; 1!=ret; )
        {
            ret = scanf("%d", &num);
            for( ; 0x20<=getchar(); );  // for removing overflow garbages
                                        // '0x20<=code' is character region
        }
        if(0<num && g_own_cnt>=num && dev_num!=num)
        {
            break;
        }
        printf("     Entered Wrong Number. Please Enter Again\n");
    }

    OCProvisionDev_t* dev = getDevInst((const OCProvisionDev_t*)g_own_list, num);
    if(!dev || !dev->doxm)
    {
        OIC_LOG(ERROR, TAG, "createAcl: device instance empty");
        goto CRACL_ERROR;
    }
    memcpy(&acl->subject, &dev->doxm->deviceID, UUID_LENGTH);

    // enter number of |resources| in 'accessed' device
    for( ; ; )
    {
        printf("   > [B] Enter Number of Accessed Resources (under 16): ");
                // '16' is |ACL_RESRC_MAX_NUM|
        for(int ret=0; 1!=ret; )
        {
            ret = scanf("%d", &num);
            for( ; 0x20<=getchar(); );  // for removing overflow garbages
                                        // '0x20<=code' is character region
        }
        if(0<num && ACL_RESRC_MAX_NUM>=num)
        {
            break;
        }
        printf("     Entered Wrong Number. Please Enter under 16 Again\n");
                // '16' is |ACL_RESRC_MAX_NUM|
    }

    // enter actually each 'accessed' |resources| name
    printf("         Enter Each Accessed Resource Name (each under 128 char)\n");
            // '128' is ACL_RESRC_MAX_LEN
    acl->resourcesLen = (unsigned) num;
    acl->resources = (char**) OICCalloc(acl->resourcesLen, sizeof(char*));
    if(!acl->resources)
    {
        OIC_LOG(ERROR, TAG, "createAcl: OICCalloc error return");
        goto CRACL_ERROR;
    }
    char rsrc_in[ACL_RESRC_MAX_LEN+1] = {0};  // '1' for null termination
    for(int i=0; acl->resourcesLen>(unsigned)i; ++i)
    {
        printf("         Enter Accessed Resource[%d] Name: ", i+1);
        for(int ret=0; 1!=ret; )
        {
            ret = scanf("%128s", rsrc_in);  // '128' is ACL_RESRC_MAX_LEN
            for( ; 0x20<=getchar(); );  // for removing overflow garbages
                                        // '0x20<=code' is character region
        }
        size_t len = strlen(rsrc_in)+1;  // '1' for null termination
        char* rsrc = (char*) OICCalloc(len, sizeof(char));
        if(!rsrc)
        {
            OIC_LOG(ERROR, TAG, "createAcl: OICCalloc error return");
            goto CRACL_ERROR;
        }
        OICStrcpy(rsrc, len, rsrc_in);
        acl->resources[i] = rsrc;  // after here, |rsrc| points nothing
    }

    // enter |permission| for this access
    printf("   > [C] Enter Permission for This Access\n");
    uint16_t pmsn = PERMISSION_FULL_CONTROL;  // default full permission
    uint16_t pmsn_msk = PERMISSION_CREATE;  // default permission mask
    for(int i=0; ACL_PEMISN_CNT>i; ++i)
    {
        char ans = 0;
        for( ; ; )
        {
            printf("         Enter %s Permission (y/n): ", ACL_PEMISN[i]);
            for(int ret=0; 1!=ret; )
            {
                ret = scanf("%c", &ans);
                for( ; 0x20<=getchar(); );  // for removing overflow garbages
                                            // '0x20<=code' is character region
            }
            if('y'==ans || 'Y'==ans || 'n'==ans|| 'N'==ans)
            {
                ans &= ~0x20;  // for masking lower case, 'y/n'
                break;
            }
            printf("         Entered Wrong Answer. Please Enter 'y/n' Again\n");
        }
        if('N' == ans)  // masked lower case, 'n'
        {
            pmsn -= pmsn_msk;
        }
        pmsn_msk <<= 1;
    }
    acl->permission = pmsn;

    // enter |owner| device number
    int own_num = 0;
    for( ; ; )
    {
        printf("   > [D] Enter Owner Device Number: ");
        for(int ret=0; 1!=ret; )
        {
            ret = scanf("%d", &own_num);
            for( ; 0x20<=getchar(); );  // for removing overflow garbages
                                        // '0x20<=code' is character region
        }
        if(0<own_num && g_own_cnt>=own_num)
        {
            break;
        }
        printf("         Entered Wrong Number. Please Enter Again\n");
    }

    dev = getDevInst((const OCProvisionDev_t*)g_own_list, own_num);
    if(!dev || !dev->doxm)
    {
        OIC_LOG(ERROR, TAG, "createAcl: device instance empty");
        goto CRACL_ERROR;
    }
    memcpy(&acl->rownerID, &dev->doxm->deviceID, sizeof(OicUuid_t));
    printf("\n");

    return acl;

CRACL_ERROR:
    OCDeleteACLList(acl);  // after here |acl| points nothing
    return NULL;
}

static OicSecPdAcl_t* createPdAcl(const int dev_num)
{
    if(0>=dev_num || g_own_cnt<dev_num)
    {
        OIC_LOG(ERROR, TAG, "createAcl invalid parameters");
        return NULL;  // not need to 'goto' |ERROR| before allocating |acl|
    }

    // allocate memory for |pdacl| struct
    printf("   **** Create PDACL for the Selected Device[%d]\n", dev_num);
    OicSecPdAcl_t* pdAcl = (OicSecPdAcl_t*) OICCalloc(1, sizeof(OicSecPdAcl_t));
    if(!pdAcl)
    {
        OIC_LOG(ERROR, TAG, "createAcl: OICCalloc error return");
        return NULL;  // not need to 'goto' |ERROR| before allocating |acl|
    }

    // number of resources
    char rsrc_in[][ACL_RESRC_MAX_LEN+1] = {"*", "/rsrc/*"};
    pdAcl->resourcesLen = 1;

    // resource
    int num = pdAcl->resourcesLen;
    pdAcl->resources = (char**) OICCalloc(num, sizeof(char*));
    if(!pdAcl->resources)
    {
        OIC_LOG(ERROR, TAG, "createPdAcl: OICCalloc error return");
        goto CRPDACL_ERROR;
    }
    for(int i=0; num>i; ++i)
    {
        size_t len = strlen(rsrc_in[i])+1;  // '1' for null termination
        char* rsrc = (char*) OICCalloc(len, sizeof(char));
        if(!rsrc)
        {
            OIC_LOG(ERROR, TAG, "createPdAcl: OICCalloc error return");
            goto CRPDACL_ERROR;
        }
        OICStrcpy(rsrc, len, rsrc_in[i]);
        pdAcl->resources[i] = rsrc;  // after here, |rsrc| points nothing
    }

    // permission
    pdAcl->permission = PERMISSION_FULL_CONTROL;

    return pdAcl;

CRPDACL_ERROR:
    OCDeletePdAclList(pdAcl);
    return NULL;
}

static OCProvisionDev_t* getDevInst(const OCProvisionDev_t* dev_lst, const int dev_num)
{
    if(!dev_lst || 0>=dev_num)
    {
        printf("     Device List is Empty..\n");
        return NULL;
    }

    OCProvisionDev_t* lst = (OCProvisionDev_t*) dev_lst;
    for(int i=0; lst; )
    {
        if(dev_num == ++i)
        {
            return lst;
        }
        lst = lst->next;
    }

    return NULL;  // in here |lst| is always |NULL|
}

static int printDevList(const OCProvisionDev_t* dev_lst)
{
    if(!dev_lst)
    {
        printf("     Device List is Empty..\n\n");
        return 0;
    }

    OCProvisionDev_t* lst = (OCProvisionDev_t*) dev_lst;
    int lst_cnt = 0;
    for( ; lst; )
    {
        printf("     [%d] ", ++lst_cnt);
        printUuid((const OicUuid_t*) &lst->doxm->deviceID);
        printf("\n");
        lst = lst->next;
    }
    printf("\n");

    return lst_cnt;
}

static size_t printUuidList(const OCUuidList_t* uid_lst)
{
    if(!uid_lst)
    {
        printf("     Device List is Empty..\n\n");
        return 0;
    }

    OCUuidList_t* lst = (OCUuidList_t*) uid_lst;
    size_t lst_cnt = 0;
    for( ; lst; )
    {
        printf("     [%zu] ", ++lst_cnt);
        printUuid((const OicUuid_t*) &lst->dev);
        printf("\n");
        lst = lst->next;
    }
    printf("\n");

    return lst_cnt;
}

static int printResultList(const OCProvisionResult_t* rslt_lst, const int rslt_cnt)
{
    if(!rslt_lst || 0>=rslt_cnt)
    {
        printf("     Device List is Empty..\n\n");
        return 0;
    }

    int lst_cnt = 0;
    for( ; rslt_cnt>lst_cnt; ++lst_cnt)
    {
        printf("     [%d] ", lst_cnt+1);
        printUuid((const OicUuid_t*) &rslt_lst[lst_cnt].deviceId);
        printf(" - result: %d\n", rslt_lst[lst_cnt].res);
    }
    printf("\n");

    return lst_cnt;
}

static void printUuid(const OicUuid_t* uid)
{
    for(int i=0; i<UUID_LENGTH; )
    {
        printf("%02X", (*uid).id[i++]);
        if(i==4 || i==6 || i==8 || i==10)  // canonical format for UUID has '8-4-4-4-12'
        {
            printf("-");
        }
    }
}

static FILE* fopen_prvnMng(const char* path, const char* mode)
{
    (void)path;  // unused |path| parameter

    // input |g_svr_db_fname| internally by force, not using |path| parameter
    // because |OCPersistentStorage::open| is called |OCPersistentStorage| internally
    // with its own |SVR_DB_FILE_NAME|
    return fopen(SVR_DB_FILE_NAME, mode);
}

static int waitCallbackRet(void)
{
    for(int i=0; !g_doneCB && CALLBACK_TIMEOUT>i; ++i)
    {
        sleep(1);
        if(OC_STACK_OK != OCProcess())
        {
            OIC_LOG(ERROR, TAG, "OCStack process error");
            return -1;
        }
    }

    return 0;
}

static int selectTwoDiffNum(int* a, int* b, const int max, const char* str)
{
    if(!a || !b || 2>=max || !str)
    {
        return -1;
    }

    for( ; ; )
    {
        for(int i=0; 2>i; ++i)
        {
            int* num = 0==i?a:b;
            for( ; ; )
            {
                printf("   > Enter Device[%d] Number, %s: ", i+1, str);
                for(int ret=0; 1!=ret; )
                {
                    ret = scanf("%d", num);
                    for( ; 0x20<=getchar(); );  // for removing overflow garbages
                                                // '0x20<=code' is character region
                }
                if(0<*num && max>=*num)
                {
                    break;
                }
                printf("     Entered Wrong Number. Please Enter Again\n");
            }
        }
        if(*a != *b)
        {
            printf("\n");
            return 0;
        }
    }

    return -1;
}

static void printMenu(void)
{
    printf("************************************************************\n");
    printf("****** OIC Provisioning Client with using C-level API ******\n");
    printf("************************************************************\n\n");

    printf("** [A] DISCOVER DEVICES ON NETWORK\n");
    printf("** 10. Discover All Un/Owned Devices on Network\n");
    printf("** 11. Discover Only Unowned Devices on Network\n");
    printf("** 12. Discover Only Owned Devices on Network\n\n");

    printf("** [B] REGISTER/OWN ALL DISCOVERED UNOWNED DEVICES\n");
    printf("** 20. Register/Own All Discovered Unowned Devices\n\n");

    printf("** [C] PROVISION/LINK PAIRWISE THINGS\n");
    printf("** 30. Provision/Link Pairwise Things\n");
    printf("** 31. Provision Credentials for Pairwise Things\n");
    printf("** 32. Provision the Selected Access Control List(ACL)\n");
    printf("** 33. Provision Direct-Pairing Configuration\n");
    printf("** 34. Check Linked Status of the Selected Device on PRVN DB\n\n");

    printf("** [D] UNLINK PAIRWISE THINGS\n");
    printf("** 40. Unlink Pairwise Things\n\n");

    printf("** [E] REMOVE THE SELECTED DEVICE\n");
    printf("** 50. Remove the Selected Device\n\n");

    printf("** [F] EXIT PROVISIONING CLIENT\n");
    printf("** 99. Exit Provisionong Client\n\n");

    printf("************************************************************\n\n");
}

#if 0 // Code for enabling path configuration for PDB and SVR DBf
static void printUsage(void)
{
    printf("\n");
    printf("OIC Provisioning Client with using C-level API\n");
    printf("Usage: provisioningclient [option]...\n");
    printf("\n");
    printf("  -h                           print help for this provisioning client\n");
    printf("  -p=[prvn_db_file_path/name]  input PRVN DB file path and name\n");
    printf("                               if not exists, will load default DB file\n");
    printf("                               (default: |oic_prvn_mng.db| on working dir)\n");
    printf("                               (ex. -p=oic_prvn_mng.db)\n");
    printf("  -s=[svr_db_file_path/name]   input SVR DB file path and name\n");
    printf("                               if not exists, will load default DB file\n");
    printf("                               (default: |oic_svr_db_client.json| on working dir)\n");
    printf("                               (ex. -s=oic_svr_db_client.json)\n");
    printf("\n");
}
#endif

// main function for provisioning client using C-level provisioning API
int main()
{
    // initialize provisioning client
    if(initProvisionClient())
    {
        OIC_LOG(ERROR, TAG, "ProvisionClient init error");
        goto PMCLT_ERROR;
    }

    // main loop for provisioning manager
    int mn_num = 0;
    for( ; ; )
    {
        printf("\n");
        printMenu();
        printf(">> Enter Menu Number: ");
        for(int ret=0; 1!=ret; )
        {
            ret = scanf("%d", &mn_num);
            for( ; 0x20<=getchar(); );  // for removing overflow garbages
                                        // '0x20<=code' is character region
        }
        printf("\n");
        switch(mn_num)
        {
        case _10_DISCOV_ALL_DEVS_:
            if(discoverAllDevices())
            {
                OIC_LOG(ERROR, TAG, "_10_DISCOV_ALL_DEVS_: error");
            }
            break;
        case _11_DISCOV_UNOWN_DEVS_:
            if(discoverUnownedDevices())
            {
                OIC_LOG(ERROR, TAG, "_11_DISCOV_UNOWN_DEVS_: error");
            }
            break;
        case _12_DISCOV_OWN_DEVS_:
            if(discoverOwnedDevices())
            {
                OIC_LOG(ERROR, TAG, "_12_DISCOV_OWN_DEVS_: error");
            }
            break;
        case _20_REGIST_DEVS_:
            if(registerDevices())
            {
                OIC_LOG(ERROR, TAG, "_20_REGIST_DEVS_: error");
            }
            break;
        case _30_PROVIS_PAIR_DEVS_:
            if(provisionPairwise())
            {
                OIC_LOG(ERROR, TAG, "_30_PROVIS_PAIR_DEVS_: error");
            }
            break;
        case _31_PROVIS_CRED_:
            if(provisionCred())
            {
                OIC_LOG(ERROR, TAG, "_31_PROVIS_CRED_: error");
            }
            break;
        case _32_PROVIS_ACL_:
            if(provisionAcl())
            {
                OIC_LOG(ERROR, TAG, "_32_PROVIS_ACL_: error");
            }
            break;
        case _33_PROVIS_DP_:
            if(provisionDirectPairing())
            {
                OIC_LOG(ERROR, TAG, "_33_PROVIS_DP_: error");
            }
            break;
        case _34_CHECK_LINK_STATUS_:
            if(checkLinkedStatus())
            {
                OIC_LOG(ERROR, TAG, "_34_CHECK_LINK_STATUS_: error");
            }
            break;
        case _40_UNLINK_PAIR_DEVS_:
            if(unlinkPairwise())
            {
                OIC_LOG(ERROR, TAG, "_40_UNLINK_PAIR_DEVS_: error");
            }
            break;
        case _50_REMOVE_SELEC_DEV_:
            if(removeDevice())
            {
                OIC_LOG(ERROR, TAG, "_50_REMOVE_SELEC_DEV_: error");
            }
            break;
        case _99_EXIT_PRVN_CLT_:
            goto PMCLT_ERROR;
        default:
            printf(">> Entered Wrong Number. Please Enter Again\n\n");
            break;
        }
    }

PMCLT_ERROR:
    if(OC_STACK_OK != OCStop())
    {
        OIC_LOG(ERROR, TAG, "OCStack stop error");
    }
    OCDeleteDiscoveredDevices(g_own_list);  // after here |g_own_list| points nothing
    OCDeleteDiscoveredDevices(g_unown_list);  // after here |g_unown_list| points nothing

    if(g_svr_fname)
    {
        OICFree(g_svr_fname);  // after here |g_svr_fname| points nothing
    }
    if(g_prvn_fname)
    {
        OICFree(g_prvn_fname);  // after here |g_prvn_fname| points nothing
    }
    return 0;  // always return normal case
}

#ifdef __cplusplus
}
#endif //__cplusplus


text:
require 'rspec'
require_relative '../lib/ehrmagerd'

Ehrmagerd.api_token = ENV['API_TOKEN']

require 'vcr'

VCR.configure do |c|
  c.cassette_library_dir = 'spec/cassettes'
  c.hook_into :webmock
  c.configure_rspec_metadata!
  c.default_cassette_options = { :record => :new_episodes }
  c.filter_sensitive_data('<EHRMAGERD API TOKEN>') { Ehrmagerd.api_token }
end

RSpec.configure do |c|
  c.treat_symbols_as_metadata_keys_with_true_values = true
end

redpajama_set_name: RedPajamaGithub


text:
[![Maven Central](https://img.shields.io/maven-central/v/io.airlift/airlift.svg?label=Maven%20Central)](https://search.maven.org/#search%7Cga%7C1%7Cg%3A%22io.airlift%22)
[![Build Status](https://github.com/airlift/airlift/workflows/CI/badge.svg)](https://github.com/airlift/airlift/actions?query=workflow%3ACI+event%3Apush+branch%3Amaster)

Airlift is a framework for building REST services in Java.

This project is used as the foundation for distributed systems like [Trino (formerly PrestoSQL)](https://trino.io).

Airlift pulls together stable, mature libraries from the Java ecosystem into a simple, light-weight package that lets you focus on getting things done and includes built-in support for configuration, metrics, logging, dependency injection, and much more, enabling you and your team to ship a production-quality web service in the shortest time possible.

Airlift takes the best-of-breed libraries from the Java ecosystem and glues them together based on years of experience in building high performance Java services without getting in your way and without forcing you into a large, proprietary framework.

## Getting Started

- [Overview](docs/overview.md)
- [Getting Started](docs/getting_started.md)
  - Then see [Next Steps](docs/next_steps.md)

## Reference

- [Configuration](docs/ref_configuration.md)
- [Lifecycle/Bootstrapping](docs/ref_lifecycle.md)
- TBD - Concurrency
- TBD - Database Pooling
- TBD - Discovery
- TBD - Events
- TBD - HTTP server
- [HTTP client](http-client/README.md)
- TBD - Packaging
- TBD - Logging
- TBD - Tracing
- TBD - Maven BOM
- TBD - Jackson/JSON

## Recipes

- How do I ... [do conditional binding based on config](docs/recipes.md#how-do-i-do-conditional-binding-based-on-a-config-value)
- How do I ... [serve static HTML files](docs/recipes.md#how-do-i-serve-static-html-files)
- How do I ... [package my service](docs/recipes.md#how-do-i-package-my-service)
- TBD - How do I do ... ?


text:
import Page from './Page';

class SideNav extends Page {
	// New channel
	get channelType() { return browser.element('.create-channel__content .rc-switch__button'); }
	get channelReadOnly() { return browser.elements('.create-channel__switches .rc-switch__button').value[1]; }
	get channelName() { return browser.element('.create-channel__content input[name="name"]'); }
	get saveChannelBtn() { return browser.element('.create-channel__content [data-button="create"]'); }

	// Account box
	getPopOverContent() { return browser.element('.rc-popover__content'); }
	get accountBoxUserName() { return browser.element('.sidebar__account-username'); }
	get accountBoxUserAvatar() { return browser.element('.sidebar__account .avatar-image'); }
	get accountMenu() { return browser.element('.sidebar__account'); }
	get sidebarHeader() { return browser.element('.sidebar__header'); }
	get sidebarUserMenu() { return browser.element('.sidebar__header .avatar'); }
	get sidebarMenu() { return browser.element('.sidebar__toolbar-button-icon--menu'); }
	get popOverContent() { return browser.element('.rc-popover__content'); }
	get statusOnline() { return browser.element('.rc-popover__item--online'); }
	get statusAway() { return browser.element('.rc-popover__item--away'); }
	get statusBusy() { return browser.element('.rc-popover__item--busy'); }
	get statusOffline() { return browser.element('.rc-popover__item--offline'); }
	get account() { return browser.element('[data-id="account"][data-type="open"]'); }
	get admin() { return browser.element('[data-id="administration"][data-type="open"]'); }
	get logout() { return browser.element('[data-id="logout"][data-type="open"]'); }
	get sideNavBar() { return browser.element('.sidebar'); }

	// Toolbar
	get spotlightSearchIcon() { return browser.element('.sidebar__toolbar-button-icon--magnifier'); }
	get spotlightSearch() { return browser.element('.toolbar__search input'); }
	get spotlightSearchPopUp() { return browser.element('.rooms-list__toolbar-search'); }
	get newChannelBtn() { return browser.element('.sidebar__toolbar-button-icon--edit-rounded'); }
	get newChannelIcon() { return browser.element('.toolbar__icon.toolbar__search-create-channel'); }

	// Rooms List
	get general() { return this.getChannelFromList('general'); }
	get channelLeave() { return browser.element('.leave-room'); }
	get channelHoverIcon() { return browser.element('.rooms-list > .wrapper > ul [title="general"] .icon-eye-off'); }
	get moreChannels() { return browser.element('.rooms-list .more-channels'); }

	// Account
	get preferences() { return browser.element('[href="/account/preferences"]'); }
	get profile() { return browser.element('[href="/account/profile"]'); }
	get avatar() { return browser.element('[href="/changeavatar"]'); }
	get preferencesClose() { return browser.element('.sidebar-flex__close-button[data-action="close"]'); }

	get burgerBtn() { return browser.element('.burger'); }

	// Opens a channel via rooms list
	openChannel(channelName) {
		browser.waitForVisible(`.sidebar-item__name=${ channelName }`, 5000);
		browser.click(`.sidebar-item__name=${ channelName }`);
		browser.waitForVisible('.rc-message-box__container textarea', 5000);
		browser.waitForVisible('.rc-header', 5000);
		browser.waitUntil(function() {
			browser.waitForVisible('.rc-header__name', 8000);
			return browser.getText('.rc-header__name') === channelName;
		}, 10000);
	}

	// Opens a channel via spotlight search
	searchChannel(channelName) {
		let currentRoom;
		browser.waitForVisible('.rc-header', 15000);
		if (browser.isVisible('.rc-header__name')) {
			currentRoom = browser.element('.rc-header__name').getText();
		}
		if (currentRoom !== channelName) {
			this.spotlightSearch.waitForVisible(5000);
			this.spotlightSearch.click();
			this.spotlightSearch.setValue(channelName);
			browser.waitForVisible(`[aria-label='${ channelName }']`, 5000);
			browser.click(`[aria-label='${ channelName }']`);
			browser.waitForVisible('.rc-header__name', 8000);
			browser.waitUntil(function() {
				return browser.getText('.rc-header__name') === channelName;
			}, 10000);

		}
	}

	// Gets a channel from the spotlight search
	getChannelFromSpotlight(channelName) {
		let currentRoom;
		browser.waitForVisible('.rc-header', 15000);
		if (browser.isVisible('.rc-header__name')) {
			currentRoom = browser.element('.rc-header__name').getText();
		}
		currentRoom = browser.element('.rc-header__name').getText();
		console.log(currentRoom, channelName);
		if (currentRoom !== channelName) {
			this.spotlightSearch.waitForVisible(5000);
			this.spotlightSearch.click();
			this.spotlightSearch.setValue(channelName);
			browser.waitForVisible(`.sidebar-item__name=${ channelName }`, 5000);
			return browser.element(`.sidebar-item__name=${ channelName }`);
		}
	}

	// Gets a channel from the rooms list
	getChannelFromList(channelName, reverse) {
		if (reverse == null) {
			browser.waitForVisible(`.sidebar-item__name=${ channelName }`, 5000);
		}
		return browser.element(`.sidebar-item__name=${ channelName }`);
	}

	createChannel(channelName, isPrivate, /* isReadOnly*/) {
		this.newChannelBtn.waitForVisible(10000);
		this.newChannelBtn.click();
		this.channelName.waitForVisible(10000);

		// workaround for incomplete setvalue bug
		this.channelName.setValue(channelName);

		browser.waitUntil(function() {
			return browser.isEnabled('.create-channel__content [data-button="create"]');
		}, 5000);

		this.channelType.waitForVisible(10000);
		if (isPrivate) {
			this.channelType.click();
		}
		// if (isReadOnly) {
		// 	this.channelReadOnly.click();
		// }
		browser.pause(500);
		this.saveChannelBtn.click();
		// this.channelType.waitForVisible(5000, true);
		browser.pause(500);
	}
}

module.exports = new SideNav();


text:
import { safeGet } from '../../utils';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import React, { Component } from 'react';
import { withRouter } from 'react-router';
import Form from '../../components/form/form';
import { bindActionCreators } from 'redux';
import I18NInjector from '../../decorator/i18nInjector';
import * as ProfilesActions from '../../actionCreators/profilesAction';
import { Button, ControlLabel, FormControl, FormGroup, HelpBlock, Table } from 'react-bootstrap';
import PropTypes from 'prop-types';

const columns = [{key: '_id', name: 'ID'},
  {key: 'name.first', name: 'First'},
  {key: 'name.last', name: 'Last'},
  {key: 'email', name: 'Email'}];

@I18NInjector()
export class UserProfiles extends Component {

  constructor (props) {
    super(props);
    this.displayName = 'containers/userProfiles';
    this.onSubmit = this.onSubmit.bind(this);
    this.renderRow = this.renderRow.bind(this);
    this.renderCol = this.renderCol.bind(this);
    this.onChange = this.onChange.bind(this);
    this.getValidationState = this.getValidationState.bind(this);
  }

  onSubmit () {
    this.props.profilesActionDispatcher.requestProfiles();
  }

  onChange () {

  }

  getValidationState () {
    // valid values are ["success","warning","error",null]
    return null;
  }

  /**
   * Well this might not be be the best method of determining the column
   * with the router link (eg  col.key === '_id' ) but it will do for now.
   */
  renderCol (row) {
    return (col, ii) => {
      return (

          { col.key === '_id' ? (
            <Link to={{pathname: `/userProfiles/${row._id}`}}>{safeGet(row, col.key)}</Link>
          ) : (

{safeGet(row, col.key)}

          )}

      );
    };
  }

  renderRow (row, i) {
    return (

{columns.map(this.renderCol(row))}

    );
  }

  render () {
    return (

{this.props.i18n.translate('Profiles Search')}

        <Form>
          <FormGroup controlId="formBasicText" validationState={this.getValidationState()}>
            <ControlLabel>{this.props.i18n.translate('Search Name')}</ControlLabel>
            <FormControl type="text" placeholder={this.props.i18n.translate('Enter search name')} onChange={this.onChange} />
            <FormControl.Feedback />
            <HelpBlock>{this.props.i18n.translate('Enter a name to search')}</HelpBlock>
          </FormGroup>
          <Button bsStyle="primary" onClick={this.onSubmit}>{this.props.i18n.translate('Submit')}</Button>
        </Form>

              {columns.map((row, i) => {
                return ({row.name}	);
              })}

            {this.props.profiles.map(this.renderRow)}

    );
  }
}

/**
 * Map a specific store's state to the props.
 *
 * @param {*} state - the state of the store/reducer
 * @returns {{profiles: (*|Array)}}
 */
let mapStateToProps = (state /*, ownProps */) => {
  return {
    profiles: state.profilesReducer.profiles
  };
};

/**
 * Map the Action(s)'s Dispatcher(s) to the props. The way this is written all the action's dispatch functions are
 * mapped to the given name space.
 *
 * @param dispatch
 * @returns {{profilesActionDispatcher: (A|B|M|N)}}
 */
let mapDispatchToProps = (dispatch) => {
  return {
    profilesActionDispatcher: bindActionCreators(ProfilesActions, dispatch)
  };
};

/**
 * If you are using withRouter to prevent updates from being blocked by shouldComponentUpdate,
 * it is important that withRouter wraps the component that implements shouldComponentUpate.
 * For example, when using Redux:
 * https://reacttraining.com/react-router/web/api/matchPath
 */
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(UserProfiles));

UserProfiles.propTypes = {
  i18n: PropTypes.object.isRequired,
  profilesActionDispatcher: PropTypes.object,
  profiles: PropTypes.array
};


text:
NSString * const ELBaseNetworkingService_JSESSIONID = @"jsessionid";
NSString * const ELBaseNetworkingService_HEADER = @"smthit-api-header";
NSString * const ELBaseNetworkingService_AGENT= @"agent";

@interface ELBaseNetworkingService ()
@property (nonatomic,strong)AFURLSessionManager * sessionManager;
@property (nonatomic,strong)NSURLSessionConfiguration * sessionConfig;
@end

@implementation ELBaseNetworkingService
static ELBaseNetworkingService * _sharedService;
+(instancetype)sharedService{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedService = [[ELBaseNetworkingService alloc]init];
    });
    return _sharedService;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
        self.sessionManager = [[AFURLSessionManager alloc]initWithSessionConfiguration:self.sessionConfig];
        AFJSONResponseSerializer * jsonSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
        jsonSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/plain", nil];
        jsonSerializer.removesKeysWithNullValues = YES;

        self.sessionManager.responseSerializer = jsonSerializer;
//        NSString * cerPath = [[NSBundle mainBundle]pathForResource:@"ticai.cn" ofType:@"crt"];
//        NSData * cerData = [NSData dataWithContentsOfFile:cerPath];
#if DEBUG
        AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey];
        policy.allowInvalidCertificates = YES;//是否允许使用自签名证书
        policy.validatesDomainName = NO;
        self.sessionManager.securityPolicy = policy;
        __weak typeof(self) weakSelf = self;
        [self.sessionManager setSessionDidBecomeInvalidBlock:^(NSURLSession * _Nonnull session, NSError * _Nonnull error) {
            NSLog(@"setSessionDidBecomeInvalidBlock");
        }];

        [self.sessionManager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession*session, NSURLAuthenticationChallenge *challenge, NSURLCredential *__autoreleasing*_credential) {
            NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
            __autoreleasing NSURLCredential *credential =nil;
            if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
                if([weakSelf.sessionManager.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) {
                    credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
                    if(credential) {
                        disposition =NSURLSessionAuthChallengeUseCredential;
                    } else {
                        disposition =NSURLSessionAuthChallengePerformDefaultHandling;
                    }
                } else {
                    disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
                }
            } else {
                // client authentication
                SecIdentityRef identity = NULL;
                SecTrustRef trust = NULL;
                NSString *p12 = [[NSBundle mainBundle] pathForResource:@"ticai.cn"ofType:@"crt"];
                NSFileManager *fileManager =[NSFileManager defaultManager];

                if(![fileManager fileExistsAtPath:p12])
                {
                    NSLog(@"client.p12:not exist");
                }
                else
                {
                    NSData *PKCS12Data = [NSData dataWithContentsOfFile:p12];

                    if ([[weakSelf class]extractIdentity:&identity andTrust:&trust fromPKCS12Data:PKCS12Data])
                    {
                        SecCertificateRef certificate = NULL;
                        SecIdentityCopyCertificate(identity, &certificate);
                        const void*certs[] = {certificate};
                        CFArrayRef certArray =CFArrayCreate(kCFAllocatorDefault, certs,1,NULL);
                        credential =[NSURLCredential credentialWithIdentity:identity certificates:(__bridge  NSArray*)certArray persistence:NSURLCredentialPersistencePermanent];
                        disposition =NSURLSessionAuthChallengeUseCredential;
                    }
                }
            }
            *_credential = credential;
            return disposition;
        }];

#endif
    }
    return self;
}
+(BOOL)extractIdentity:(SecIdentityRef*)outIdentity andTrust:(SecTrustRef *)outTrust fromPKCS12Data:(NSData *)inPKCS12Data {
    OSStatus securityError = errSecSuccess;
    //client certificate password
    NSDictionary*optionsDictionary = [NSDictionary dictionaryWithObject:@"ticai"
                                                                 forKey:(__bridge id)kSecImportExportPassphrase];

    CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);
    securityError = SecPKCS12Import((__bridge CFDataRef)inPKCS12Data,(__bridge CFDictionaryRef)optionsDictionary,&items);

    if(securityError == 0) {
        CFDictionaryRef myIdentityAndTrust =CFArrayGetValueAtIndex(items,0);
        const void*tempIdentity =NULL;
        tempIdentity= CFDictionaryGetValue (myIdentityAndTrust,kSecImportItemIdentity);
        *outIdentity = (SecIdentityRef)tempIdentity;
        const void*tempTrust =NULL;
        tempTrust = CFDictionaryGetValue(myIdentityAndTrust,kSecImportItemTrust);
        *outTrust = (SecTrustRef)tempTrust;
    } else {
        NSLog(@"Failedwith error code %d",(int)securityError);
        return NO;
    }
    return YES;
}

-   (void)request:(ELReturnRequestBlock)requestBlock
    withUserToken:(ELReturnStringBlock)token
         didStart:(ELNormalBlock)startBlock
   uploadProgress:(ELProgressBlock)uploadProgressBlock
 downloadProgress:(ELProgressBlock)downloadProgressBlock
        didFinish:(ELResponseBlock)responseBlock{
    id<ELRequestProtocol> req = requestBlock();
    //用户唯一标识
    NSString * tokenStr = token();
    NSURLRequest * request = [self URLRequestWithRequest:req andToken:tokenStr];
    //如果该请求需要登陆权限 同时用户表示为空时  不进行网络请求 并返回error
    if ([req needTokenAuth] && (tokenStr == nil || tokenStr.length == 0)) {
        NSError * error = [NSError errorWithDomain:EL_PRECHECK_DOMAIN
                                              code:501
                                          userInfo:@{NSLocalizedFailureReasonErrorKey:@"请登录"}];
        responseBlock(nil,error);
        return;
    }

    NSURLSessionDataTask * dataTask = [self.sessionManager dataTaskWithRequest:request
                                                                uploadProgress:^(NSProgress * _Nonnull uploadProgress) {
                                                                    dispatch_async(dispatch_get_main_queue(), ^{
                                                                        uploadProgressBlock(uploadProgress);
                                                                    });
                                                                }
                                                              downloadProgress:^(NSProgress * _Nonnull downloadProgress) {
                                                                  dispatch_async(dispatch_get_main_queue(), ^{
                                                                      downloadProgressBlock(downloadProgress);
                                                                  });
                                                              }
                                                             completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {

                                                                 if (error) {
                                                                     responseBlock(nil,error);
                                                                 }
                                                                 else{
                                                                     id<ELResponseProtocol> resp = [self responseWithResponseObj:responseObject andRequest:req];
                                                                     if (resp.status == 200) {

                                                                     }
                                                                     else if(resp.status == 500){
                                                                         error = [NSError errorWithDomain:EL_API_DOMAIN code:500 userInfo:@{NSLocalizedFailureReasonErrorKey:resp.memo}];
                                                                     }
                                                                     else if (resp.status == 501) {
                                                                         error = [NSError errorWithDomain:EL_API_DOMAIN code:501 userInfo:@{NSLocalizedFailureReasonErrorKey:resp.memo}];
                                                                     }
                                                                     else{
                                                                         error = [NSError errorWithDomain:EL_API_DOMAIN code:resp.status userInfo:@{NSLocalizedFailureReasonErrorKey:resp.memo}];
                                                                     }
                                                                     responseBlock(resp,error);
                                                                 }
                                                             }];
    startBlock();
    [dataTask resume];
}

-(NSURLRequest *)URLRequestWithRequest:(id<ELRequestProtocol>)request andToken:(NSString *)token{

    NSData  * requestData = nil;
    if ([request respondsToSelector:@selector(isFileData)]&&[request isFileData]) {
        requestData = [request fileData];
    }
    else{
        requestData = [[request toJSONString] dataUsingEncoding:NSUTF8StringEncoding];
    }

    //组装请求
    NSMutableURLRequest * URLRequest = nil;
    NSString * URLStr = [NSString stringWithFormat:@"%@",self.defaultConfig.HOST];
    URLRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URLStr] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:40];

    [URLRequest setHTTPMethod:@"POST"];
    if (token) {
        [URLRequest setValue:token forHTTPHeaderField:ELBaseNetworkingService_JSESSIONID];
    }
    [URLRequest setValue:[self wokeHeaderWithProtocolId:[request protocolId]] forHTTPHeaderField:ELBaseNetworkingService_HEADER];
    [URLRequest setValue:[self agent] forHTTPHeaderField:ELBaseNetworkingService_AGENT];
    [URLRequest setHTTPBody:requestData];
    return URLRequest;
}

-(id<ELResponseProtocol>)responseWithResponseObj:(id)responseObj andRequest:(id<ELRequestProtocol>)req{
    return [[req responseClass]responseWithDictionary:responseObj];
}

-(NSString *)wokeHeaderWithProtocolId:(NSString *)protocolId{
    NSString * woke = [NSString stringWithFormat:@"client-version:%@;protocol-id:%@;c-time=%ld;",
                       self.defaultConfig.clientVersion,
                       protocolId,
                       (long)[NSDate timeIntervalSinceReferenceDate]];
    return woke;
}

-(NSString *)agent{
    return  [NSString stringWithFormat:@"%@-%@",[UIDevice currentDevice].systemName,[UIDevice currentDevice].systemVersion];
}

@end


text:
require 'opennorth/represent/models/representatives'

module Opennorth
  class Represent
    class PostalCode < Fog::Model
      identity  :code,     type: :string
      attribute :province, type: :string
      attribute :city,     type: :string

      attribute :representatives, type: :array, aliases: %w(representatives_centroid)

      def representatives=(representative_set)
        attributes[:representatives] ||= Opennorth::Represent::Representatives.new(service: service)

        self.representatives.clear
        self.representatives.load(representative_set)
      end
    end
  end
end


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package controle;

import acao.Acao;
import dao.PessoaDAO;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import modelo.Pessoa;
import webAcoes.PesquisarPessoa;

/**
 *
 * @author Luis
 */
@WebServlet(name = "controlador", urlPatterns = {"controlador"})
public class ControladorServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP GET and POST
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        String acaoP = request.getParameter("acao");
        try {
            Class classe = Class.forName("acao."+acaoP+"Acao");
            Object obj = classe.newInstance();
            Acao acao = (Acao)obj;
            String destino = acao.executar(request, response);
            RequestDispatcher d = request.getRequestDispatcher(destino);
            d.forward(request, response);
        } catch (Exception e) {
        }

        /*
            switch(acao){
                case "PesquisarPessoa":
                    /*
                    System.out.println("Entrei no case");
                    PessoaDAO dao = new PessoaDAO();
                    Pessoa p = new Pessoa(request.getParameter("nome"));
                    List<Pessoa> pessoas = dao.pesquisar(p);
                    System.out.println("LISTA DE PESSOAS: " + pessoas);
                    request.setAttribute("pessoas", pessoas);
                    RequestDispatcher direcionador = request.getRequestDispatcher("/PesquisarPessoa.jsp");
                    System.out.println("Sai do case");
                    direcionador.forward(request, response);

                    PesquisarPessoa action = new PesquisarPessoa();
                    action.executar(request, response);
                    break;
                default:
                    System.out.println("ERROS");
            }*/

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP GET method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP POST method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}


text:
package org.xsystem.sql2.http.impl;

import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import org.xsystem.sql2.http.ConnectionManager;

/**
 *
 * @author Andrey Timofeev
 */
public class JNDIConnectionManager implements ConnectionManager{
    @Override
    public Connection create(String dsName) {
        try {
            InitialContext cxt = new InitialContext();

            DataSource ds = (DataSource) cxt.lookup(dsName);
            Connection ret = ds.getConnection();
            return ret;
        } catch (NamingException | SQLException ex) {
            throw new RuntimeException(ex);
        }
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    >

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="200dp"
        android:adjustViewBounds="true"
        android:contentDescription="@null"
        android:scaleType="centerCrop"
        android:layout_gravity="center"
        tools:srcCompat="@drawable/community"
        />

</FrameLayout>


text:
#ifndef _GETOPT_H
#define _GETOPT_H

#include "zarray.h"
#include "string_util.h"

#ifdef __cplusplus
extern "C" {
#endif

typedef struct getopt getopt_t;

getopt_t *getopt_create();
void getopt_destroy(getopt_t *gopt);

// Parse args. Returns 1 on success
int getopt_parse(getopt_t *gopt, int argc, char *argv[], int showErrors);
void getopt_do_usage(getopt_t *gopt);

// Returns a string containing the usage. Must be freed by caller
char * getopt_get_usage(getopt_t *gopt);

void getopt_add_spacer(getopt_t *gopt, const char *s);
void getopt_add_bool(getopt_t *gopt, char sopt, const char *lname, int def, const char *help);
void getopt_add_int(getopt_t *gopt, char sopt, const char *lname, const char *def, const char *help);
void getopt_add_string(getopt_t *gopt, char sopt, const char *lname, const char *def, const char *help);
void getopt_add_double(getopt_t *gopt, char sopt, const char *lname, const char *def, const char *help);

const char *getopt_get_string(getopt_t *gopt, const char *lname);
int getopt_get_int(getopt_t *getopt, const char *lname);
int getopt_get_bool(getopt_t *getopt, const char *lname);
double getopt_get_double(getopt_t *getopt, const char *lname);
int getopt_was_specified(getopt_t *gopt, const char *lname);
const zarray_t *getopt_get_extra_args(getopt_t *gopt);

#ifdef __cplusplus
}
#endif

#endif


text:
class AuditTrailSweeper < ActionController::Caching::Sweeper
  observe AuditTrail

  def before_create(audit_trail)
    audit_trail.user ||= current_user
    audit_trail.remote_address = controller.try(:request).try(:ip)
  end

  def current_user
    controller.send :current_user if controller.respond_to?(:current_user, true)
  end
end


text:
/**
 * Module dependencies.
 */
const express = require('express');
const compression = require('compression');
const session = require('express-session');
const bodyParser = require('body-parser');
const logger = require('morgan');
const errorHandler = require('errorhandler');
const lusca = require('lusca');
const dotenv = require('dotenv');
const MongoStore = require('connect-mongo')(session);
const flash = require('express-flash');
const path = require('path');
const mongoose = require('mongoose');
const passport = require('passport');
const expressValidator = require('express-validator');
const sass = require('node-sass-middleware');
const multer = require('multer');
const upload = multer({ dest: path.join(__dirname, 'uploads') });

/**
 * Load environment variables from .env file, where API keys and passwords are configured.
 */
dotenv.load({ path: '.env.example' });

/**
 * Controllers (route handlers).
 */
const homeController = require('./controllers/home');
const userController = require('./controllers/user');
const apiController = require('./controllers/api');
const contactController = require('./controllers/contact');
const questionController = require('./controllers/questions');
const wishController = require('./controllers/wish');

/**
 * API keys and Passport configuration.
 */
const passportConfig = require('./config/passport');

/**
 * Create Express server.
 */
const app = express();

/**
 * Connect to MongoDB.
 */
mongoose.connect(process.env.MONGODB_URI || process.env.MONGOLAB_URI);
mongoose.connection.on('error', () => {
  console.error('MongoDB Connection Error. Please make sure that MongoDB is running.');
  process.exit(1);
});

/**
 * Express configuration.
 */
app.set('port', process.env.PORT || 80);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(compression());
app.use(express.static(path.join(__dirname, 'public')));
app.use(sass({
  src: path.join(__dirname, 'public'),
  dest: path.join(__dirname, 'public')
}));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressValidator());
app.use(session({
  resave: true,
  saveUninitialized: true,
  secret: process.env.SESSION_SECRET,
  store: new MongoStore({
    url: process.env.MONGODB_URI || process.env.MONGOLAB_URI,
    autoReconnect: true
  })
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use((req, res, next) => {
  if (req.path === '/api/upload') {
    next();
  } else {
    lusca.csrf()(req, res, next);
  }
});
app.use(lusca.xframe('SAMEORIGIN'));
app.use(lusca.xssProtection(true));
app.use((req, res, next) => {
  res.locals.user = req.user;
  next();
});
app.use((req, res, next) => {
  // After successful login, redirect back to /api, /contact or /
  if (/(api)|(contact)|(^\/$)/i.test(req.path)) {
    req.session.returnTo = req.path;
  }
  next();
});
app.use(express.static(path.join(__dirname, 'public'), { maxAge: 31557600000 }));

/**
 * Primary app routes.
 */
app.get('/', homeController.index);
app.get('/login', userController.getLogin);
app.post('/login', userController.postLogin);
app.get('/logout', userController.logout);
app.get('/forgot', userController.getForgot);
app.post('/forgot', userController.postForgot);
app.get('/reset/:token', userController.getReset);
app.post('/reset/:token', userController.postReset);
app.get('/signup', userController.getSignup);
app.post('/signup', userController.postSignup);
app.get('/contact', contactController.getContact);
app.post('/contact', contactController.postContact);
app.get('/account', passportConfig.isAuthenticated, userController.getAccount);
app.post('/account/profile', passportConfig.isAuthenticated, userController.postUpdateProfile);
app.post('/account/password', passportConfig.isAuthenticated, userController.postUpdatePassword);
app.post('/account/delete', passportConfig.isAuthenticated, userController.postDeleteAccount);
app.get('/account/unlink/:provider', passportConfig.isAuthenticated, userController.getOauthUnlink);
app.post('/account/bank', passportConfig.isAuthenticated, userController.bank);
app.get('/adminpage', passportConfig.isAuthenticated, homeController.adminpage);
app.get('/addfavorite/:id', passportConfig.isAuthenticated, userController.addfavorite);
app.get('/delfavorite/:id', passportConfig.isAuthenticated, userController.delfavorite);

app.post('/instaquery', passportConfig.isAuthenticated, apiController.instaquery)
app.get('/star/:id', passportConfig.isAuthenticated, apiController.findstarr)
app.post('/postquestion', questionController.postquestion)
app.post('/postresponse/:id', questionController.postresponse)
app.get('/chargeone/:id', questionController.chargeone)
app.get('/refillmoney', passportConfig.isAuthenticated, questionController.refillmoney)
app.post('/refill', passportConfig.isAuthenticated, questionController.refill)
app.get('/notenoughmoney', questionController.notenough)
app.post('/setinfo', passportConfig.isAuthenticated, userController.setinfo)
app.post('/rejected/:id', passportConfig.isAuthenticated, questionController.rejected)

app.get('/api/instagram', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.getInstagram);

/**
 * OAuth authentication routes. (Sign in)
 */
app.get('/auth/instagram', passport.authenticate('instagram'));
app.get('/auth/facebook', passport.authenticate('facebook'));
app.get('/auth/facebook/callback', passport.authenticate('facebook', { failureRedirect: '/' }), (req, res) => {
  res.redirect(req.session.returnTo || '/');
  });

app.get('/auth/instagram/callback', passport.authenticate('instagram', { failureRedirect: '/login' }), (req, res) => {
  res.redirect(req.session.returnTo || '/');
});

app.post('/input_wish', wishController.inputwish);
app.post('/input_comment', wishController.inputcomment);
app.post('/commentlike', wishController.commentlike);
app.post('/commentdislike', wishController.commentdislike);
// app.post('/del_comment', wishController.delcomment);
app.post('/deletewish', wishController.deletewish);
app.post('/makelive', wishController.makelive);
app.get('/idea/:id', wishController.oneidea);
app.get('/oneuser/:id', wishController.oneuser);
app.post('/likewish', wishController.likewish);
app.post('/likewishidea', wishController.likewishidea);

/**
 * Error Handler.
 */
app.use(errorHandler());

/**
 * Start Express server.
 */
app.listen(app.get('port'), () => {
  console.log('Express server listening on port %d in %s mode', app.get('port'), app.get('env'));
});

module.exports = app;


text:
var RequireFixture = {
  foo : 'bar'
};


text:
package com.cinemattson.festical.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.cinemattson.festical.R;
import com.cinemattson.festical.activity.BrowseActivity;
import com.cinemattson.festical.adapter.ImageItemAdapter;

/**
 * Created by cinemattson on 18/12/14.
 */
public class ExploreFragment extends Fragment {
    private GridView gridView;
    private Activity mActivity;
    private FragmentActivity myContext;

    public static ExploreFragment newInstance() {
        return new ExploreFragment();
    }

    private View mViewFragment3;

    @Override
    public void onAttach(Activity activity) {
        myContext = (FragmentActivity) activity;
        super.onAttach(activity);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mViewFragment3 = inflater.inflate(R.layout.fragment_explore, container, false);

        mActivity = (Activity) getActivity();

        gridView = (GridView) mViewFragment3.findViewById(R.id.gridView1);
        gridView.setAdapter(new ImageItemAdapter(mActivity, getResources().getStringArray(R.array.genre_title)));

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v,
                                    int position, long id) {
                Toast.makeText(
                        mActivity,
                        ((TextView) v.findViewById(R.id.grid_item_label))
                                .getText(), Toast.LENGTH_SHORT).show();
                /*Intent intent = new Intent(mActivity, BrowseFragment.class);
                intent.putExtra("GENRE_NUMBER", position);
                mActivity.startActivity(intent);*/

                Bundle data = new Bundle();
                data.putInt("GENRE_NUMBER", position);

                /*Fragment fragment = new BrowseFragment();

                if (fragment != null) {
                    fragment.setArguments(data);
                    myContext.getSupportFragmentManager().beginTransaction()
                            .replace(R.id.screen_default_container, fragment)
                            .addToBackStack(null)
                            .commit();
                }*/

                Intent intent = new Intent(mActivity, BrowseActivity.class);
                intent.putExtra("GENRE_NUMBER", position);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                mActivity.startActivity(intent);

            }
        });

        return mViewFragment3;
    }
}


text:
package org.boazglean.kathab.api.summarization;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;

import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import org.h2.jdbcx.JdbcDataSource;
import static org.mockito.Mockito.*;
import org.slf4j.LoggerFactory;
import static org.testng.Assert.*;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

/**
 *
 * @author mpower
 */
public class SchemaTest {

    private Connection connection;

    @BeforeMethod
    public void setup() throws Exception {
        connection = DriverManager.getConnection("jdbc:h2:mem:" + this.getClass().getSimpleName());
    }

    @AfterMethod
    public void teardown() throws Exception {
        try {
            connection.close();
        }
        catch(Throwable ex) {};
    }

    @Test
    public void initSchema() {
        Schema schema = new Schema();
        schema.initSchema(connection);
    }

    @Test
    public void initSchemaFail() throws Exception {
        Connection mockConnection = mock(Connection.class);
        Schema schema = new Schema();
        when(mockConnection.createStatement()).thenThrow(new SQLException("Generated for testing"));
        schema.initSchema(mockConnection);
    }

    @Test
    public void testAccessors() {
        Schema schema = new Schema();
        String trivialSelect = "select 1";
        ClassLoader loader = mock(ClassLoader.class);

        assertTrue(schema.getDdl().indexOf("logging_event") != -1);

        schema.setDdl(trivialSelect);
        assertEquals(schema.getDdl(), trivialSelect);

    }

    @Test
    public void testEquals() {
        String trivialSelect = "select 1";
        ClassLoader loader = mock(ClassLoader.class);
        Schema schema = new Schema();
        Schema other = new Schema();
        Schema mocked = mock(Schema.class);

        assertTrue(schema.equals(schema));
        assertTrue(schema.equals(other));

        other.setDdl(null);
        assertFalse(schema.equals(other));
        schema.setDdl(null);
        assertTrue(schema.equals(other));
        other.setDdl(trivialSelect);
        assertFalse(schema.equals(other));
        schema.setDdl("");
        assertFalse(schema.equals(other));
        schema.setDdl(trivialSelect);
        assertTrue(schema.equals(other));

        assertFalse((schema.equals(new Object())));

        when(mocked.canEqual(schema)).thenReturn(false);

        assertFalse(schema.equals(mocked));

    }

    @Test
    public void testNegativeSchemaConstruction() {
        Schema schema = new Schema("test shouldn't find this");
        assertEquals(schema.getDdl(), "");
    }

    @Test
    public void testSchemaConstructionException() throws Exception{
        ClassLoader loader = mock(ClassLoader.class);

        when(loader.getResource(anyString())).thenReturn(new URL("file:///doesnotexit/"));
        Schema schema = new Schema("resource name does not matter", loader);

        assertEquals(schema.getDdl(), "");

    }

    @Test
    public void testInitSchemaException() throws Exception {
        Schema schema = new Schema();
        Connection connection = mock(Connection.class);

        when(connection.createStatement()).thenThrow(new SQLException("Generated for tests"));

        schema.initSchema(connection);
    }

    @Test
    public void testInitSchemaExecuteException() throws Exception {
        Schema schema = new Schema();
        Connection connection = mock(Connection.class);
        Statement statement = mock(Statement.class);

        when(connection.createStatement()).thenReturn(statement);
        when(statement.execute(anyString())).thenThrow(new SQLException("Generated for tests"));

        schema.initSchema(connection);

        verify(statement).close();

    }

    @Test
    public void testInitSchemaNoStatement() throws Exception {
        boolean exception = false;
        Schema schema = new Schema();
        Connection connection = mock(Connection.class);

        when(connection.createStatement()).thenReturn(null);

        try {
            schema.initSchema(connection);
        }
        catch (NullPointerException e) {
            exception = true;
        }
        assertTrue(exception);

    }

    @Test
    public void testToString() {
        Schema schema = new Schema();

        assertNotNull(schema.toString());

        schema.setDdl(null);

        assertNotNull(schema.toString());
    }

    @Test
    public void testHashcode() {
        Schema schema = new Schema();

        schema.hashCode();

        schema.setDdl(null);

        schema.hashCode();
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/tv_question"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="15sp"
        android:textColor="#ffffff"/>
</FrameLayout><!-- From: file:/Users/lizeng/Work/pro_android/GfanSDK/SDK/src/main/res/layout/gfan_nomal_questions_item.xml -->


text:
#include "modules/video_coding/codecs/test/packet_manipulator.h"

#include <stdio.h>

#include "rtc_base/checks.h"
#include "rtc_base/format_macros.h"

namespace webrtc {
namespace test {

PacketManipulatorImpl::PacketManipulatorImpl(PacketReader* packet_reader,
                                             const NetworkingConfig& config,
                                             bool verbose)
    : packet_reader_(packet_reader),
      config_(config),
      verbose_(verbose),
      active_burst_packets_(0),
      random_seed_(1) {
  RTC_DCHECK(packet_reader);
}

int PacketManipulatorImpl::ManipulatePackets(
    webrtc::EncodedImage* encoded_image) {
  int nbr_packets_dropped = 0;
  // There's no need to build a copy of the image data since viewing an
  // EncodedImage object, setting the length to a new lower value represents
  // that everything is dropped after that position in the byte array.
  // EncodedImage._size is the allocated bytes.
  // EncodedImage._length is how many that are filled with data.
  int new_length = 0;
  packet_reader_->InitializeReading(encoded_image->_buffer,
                                    encoded_image->_length,
                                    config_.packet_size_in_bytes);
  uint8_t* packet = nullptr;
  int nbr_bytes_to_read;
  // keep track of if we've lost any packets, since then we shall loose
  // the remains of the current frame:
  bool packet_loss_has_occurred = false;
  while ((nbr_bytes_to_read = packet_reader_->NextPacket(&packet)) > 0) {
    // Check if we're currently in a packet loss burst that is not completed:
    if (active_burst_packets_ > 0) {
      active_burst_packets_--;
      nbr_packets_dropped++;
    } else if (RandomUniform() < config_.packet_loss_probability ||
               packet_loss_has_occurred) {
      packet_loss_has_occurred = true;
      nbr_packets_dropped++;
      if (config_.packet_loss_mode == kBurst) {
        // Initiate a new burst
        active_burst_packets_ = config_.packet_loss_burst_length - 1;
      }
    } else {
      new_length += nbr_bytes_to_read;
    }
  }
  encoded_image->_length = new_length;
  if (nbr_packets_dropped > 0) {
    // Must set completeFrame to false to inform the decoder about this:
    encoded_image->_completeFrame = false;
    if (verbose_) {
      printf("Dropped %d packets for frame %d (frame length: %" PRIuS ")\n",
             nbr_packets_dropped, encoded_image->_timeStamp,
             encoded_image->_length);
    }
  }
  return nbr_packets_dropped;
}

void PacketManipulatorImpl::InitializeRandomSeed(unsigned int seed) {
  random_seed_ = seed;
}

inline double PacketManipulatorImpl::RandomUniform() {
  // Use the previous result as new seed before each rand() call. Doing this
  // it doesn't matter if other threads are calling rand() since we'll always
  // get the same behavior as long as we're using a fixed initial seed.
  critsect_.Enter();
  srand(random_seed_);
  random_seed_ = rand();  // NOLINT (rand_r instead of rand)
  critsect_.Leave();
  return (random_seed_ + 1.0) / (RAND_MAX + 1.0);
}

}  // namespace test
}  // namespace webrtc