0

Here is REST handler.

@RestResource(urlMapping='/UpdateContact/*') global with sharing class REST_ParticipantHandler {

@HttpPost
global static void updateParticipant() {

    //rest context variable initialization.
    RestRequest req = RestContext.request;
    RestResponse res = RestContext.response;
    //utill class returns fieldmap from the custom setings
    Map<String,String> FieldMap=util.getFieldMap();
    Map<String,String> FieldTypeMap=util.getFieldTypeMap();
    Map<String, Object> jsonBodyMap = (Map<String, Object>)JSON.deserializeUntyped(req.requestBody.toString());
    Blob body = req.requestBody;
    String bodyString = body.toString();
    Wrapclass deserializedinput = (Wrapclass)JSON.deserialize(bodyString, Wrapclass.class);
    Map<String, Object> jsonBodyMapLcase = new Map<String, Object>();
    string qFields=String.join(FieldMap.values(), ', ');
    string uNum=''; 
    String sf_jsonResponse = '';
    //converting jSON body map keys into lowercase to handle casesensitity issues.
    for( string s1:jsonBodyMap.keySet()){
        jsonBodyMapLcase.put(s1.toLowerCase(),String.valueOf((String)jsonBodyMap.get(s1)));
        system.debug(LoggingLevel.error,'jsonBodyMap#'+s1+'='+String.valueOf((String)jsonBodyMap.get(s1)));
    }

    //getting the userNum from Jsonbody to instantiate corresponding participant record.
    if(!string.IsBlank((String)jsonBodyMap.get('userNum'))){
        uNum = !string.IsBlank((String)jsonBodyMap.get('userNum'))?String.valueOf((String)jsonBodyMap.get('userNum')):'';
    }

    system.debug(LoggingLevel.error,'uNum#'+uNum);
    system.debug(LoggingLevel.error,'jsonBodyMap#'+jsonBodyMap);
    // No userNum parameter was found; return status 400
    if(uNum == null) {
        res.statusCode = 400;
        sf_jsonResponse = '{"response": {"status": "Failure", "message": "MissingRequiredQueryParameter userNum"}}';
        res.responseBody = blob.valueOf(sf_jsonResponse);
        return;
    }
    //Dynamic query to query the object dynamically with all the fields.
    string query ='SELECT ' + qFields
                   + ' FROM contact'
                   + ' WHERE user_num__c = \'' + String.escapeSingleQuotes(uNum) + '\''
                   + ' LIMIT 1';
    system.debug(LoggingLevel.error,'query#'+query);
    List<Contact> parts=Database.query(query);
    // No Participants with matching userNum
    if( parts.size()<=0) {
        res.statusCode = 400;
        sf_jsonResponse = '{"response": {"status": "Failure", "message": "No matching Participant record:'+uNum+' ' +'found with this userNum"}}';
        res.responseBody = blob.valueOf(sf_jsonResponse);
        return;
    }
    //participant Instance
    contact p=parts.get(0);

    for(String pfield:FieldMap.keySet()){

        if(!string.IsBlank((String)jsonBodyMapLcase.get(pfield))){

            if('Text'==FieldTypeMap.get(pfield))    {
                p.put(FieldMap.get(pfield),String.valueOf((String)jsonBodyMapLcase.get(pfield)));}

            else if('Currency'==FieldTypeMap.get(pfield)){
                p.put(FieldMap.get(pfield),Decimal.valueOf((String)jsonBodyMapLcase.get(pfield)));}

            else if('Number'==FieldTypeMap.get(pfield))  {
                p.put(FieldMap.get(pfield),Integer.valueOf((String)jsonBodyMapLcase.get(pfield)));}

            else if('Date'==FieldTypeMap.get(pfield))    {
                system.debug(LoggingLevel.error,'Field=' + FieldMap.get(pfield));
                //Data coming as a string value with '-' seprator and salesfore wont accept the string to date field. needs to convert string to salesforce date formate.
                string sDate=string.valueOf((String)jsonBodyMapLcase.get(pfield));
                system.debug(LoggingLevel.error,'sDate**=' + sDate);
                //date d =util.getDateSfFormate(sdate);
                String[] myDateOnly = sDate.split(' ');
                String[] strDate = myDateOnly[0].split('-');
                Integer myIntYear = integer.valueOf(strDate[0]);
                Integer myIntMonth = integer.valueOf(strDate[1]);
                Integer myIntDate = integer.valueOf(strDate[2]);
                Date dt= Date.newInstance(myIntYear, myIntMonth, myIntDate);
                system.debug(LoggingLevel.error,'dt**=' + dt);
                p.put(FieldMap.get(pfield),dt);}
            else if('Checkbox'==FieldTypeMap.get(pfield)){
                if(String.valueOf((String)jsonBodyMapLcase.get(pfield))=='1'){
                    p.put(FieldMap.get(pfield),True);} 
                else {
                    p.put(FieldMap.get(pfield),False);}
            }
        }
        else{
            p.put(FieldMap.get(pfield),null);}
    }
    system.debug(LoggingLevel.error,'updated Participant=' + p);

    try {
        res.statusCode = 200;
        update p;
        sf_jsonResponse = '{"response": {"status": "Sucess", "message": "Participant record:'+uNum +' ' +'is updated in Salesforce"}}';
        res.responseBody = blob.valueOf(sf_jsonResponse);
        return;
    } catch ( Exception ex ) {
        res.statusCode = 500;
        sf_jsonResponse = '{"response": {"status": "Failure", "message": "Participant record:'+uNum +' '+ ex + '"}}';
        res.responseBody = blob.valueOf(sf_jsonResponse);
        return;
    }

}
 global class Wrapclass {
    public String status;
    public String responseBody;

}

}

Here is my Test class..

@isTest(seeAllData=false) Public class Test_RESTParticipantHandler {

public static testMethod void testdoPost() {

    System.RestContext.request = new RestRequest();
    System.RestContext.response = new RestResponse();

    Account a = new Account(Name = 'Test', RK_ID__c='106',PR_FE_Branded__c= true);
    insert a;
    String orgId=a.id;

    Contact c = new Contact();

    c.firstname = 'Wain';
    c.lastname = 'R';
    c.AccountId = orgId;
    c.email = '[email protected]';
    c.phone = '6884382997';
    c.mailingstreet = '123 Test Ave';
    c.mailingcity = 'Somewhere';
    c.mailingstate = 'MA';
    c.mailingPostalCode = '87945';
    c.mailingcountry = 'US';
    c.User_Num__c='1234567';
    insert(c);

    RestRequest req = new RestRequest(); 
    RestResponse res = new RestResponse();

    REST_ParticipantHandler.Wrapclass reqst=new REST_ParticipantHandler.Wrapclass();
    reqst.status= 'Success';
    reqst.responseBody ='{"state":"CA","riskTolerance":"Typical for your age","retirementAge":"70",alPortfolio":"65627.50","phoneContactPreference":"SEC Required Only","email":"","homePhone":"5555555555","title":"","mailingAddress":"13630 SE 231ST ST","userNum":"13328911","lastInitial":"R","city":"Sunnyvale","zip":"94086","foreignResident":"0","workPhone":"4084986934","otherPhone":"5555555555",","isFeBrand":"1","primaryAccountPlan":"Voluntary Investment Plan (VIP)","convertedFromUserNum":"","convertedToUserNum":"","countryCode":"US"}';
    String JsonMsg=JSON.serialize(reqst);

    req.requestURI ='/services/apexrest/UpdateParticipant'; 
    req.httpMethod = 'POST';
    req.requestBody = Blob.valueof(JsonMsg);
    RestContext.response= res;
    RestContext.request = req;
    REST_ParticipantHandler.UpdateParticipant();

    //System.assertEquals('true', results.success);
    //System.assertEquals(10, results.records.size());

  }

}


Im getting an error "System.QueryException: unexpected token: 'FROM'"


1 Answer 1

1

The issue is in the qFields check this line -

string qFields=String.join(FieldMap.values(), ', ');

Its adding comma after each field api name so your effective query comes like -

Select Id, Name, Email, FROM Contact 

Notice the extra comma after Email. So you may have to write a method to replace the eliminate the last comma from qFields something like below (where I add below line after the String.Join line)-

qFields = qFields.substring(0, value.length-1)

This will eliminate the current error.

1
  • Thanks for your response Amit, i was able to resolve the query issue. but still the code coverage is 40%. its skipping below lines of code, im actually setting status code and jsonpayload has the usernum but it is still skipping below if block if(uNum == null) { res.statusCode = 400; sf_jsonResponse = '{"response": {"status": "Failure", "message": "MissingRequiredQueryParameter userNum"}}';
    – KrForce
    Aug 18, 2015 at 16:06

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .