• KitagawaSan805
  • NEWBIE
  • 0 Points
  • Member since 2012

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 4
    Questions
  • 6
    Replies

I have a custom class that is creating a JSON file (served up by a visualforce page). 

 

Is it possible to have an API call go out and retrieve this file and save it somewhere else? 

 

I am very, very new to this, so any pointers would be highly appreciated! 

Hello, 

 

I new still new to APEX and have a class that generates some JSON, but can't figure out how to write a test class for it... I have written test classes before, but not for a page controller that just serves up JSON... 

 

Thanks!

 

public class Json_Controller {
    
    public string json {get;set;}
        
    public Json_Controller() {      
        VQ_Reference_Sheet__c[] vqr = new VQ_Reference_Sheet__c[]{};
        integer start = 0;
        integer pageSize = 100;
        
        if (ApexPages.currentPage().getParameters().get('start') != null && ApexPages.currentPage().getParameters().get('limit') != null) {
            start = integer.valueof(ApexPages.currentPage().getParameters().get('start'));
            pageSize = integer.valueof(ApexPages.currentPage().getParameters().get('limit'));
        }
        
        string jsonRecordsString = '';
        
        integer i = 1;
        integer j = 0;
        
        for (VQ_Reference_Sheet__c v : [Select 
        
        id, 
        name, 
        Times_Referenced_Used_Total__c, 
        Hardware_Platform__c
              
        
        from VQ_Reference_Sheet__c order by name limit 1000]) {
            if (j >= start) {
                if (i <= pageSize) {
                    jsonRecordsString += '{';
                //record info      
                    jsonRecordsString += '"label":' + '"'+v.name+'",';  
                    jsonRecordsString += '"use":' + '["'+v.Times_Referenced_Used_Total__c+'"],';
                    jsonRecordsString += '"hrd":' + '["'+v.Hardware_Platform__c+'"],';
                    
                //record id    
                    jsonRecordsString += '"sfdcid":' + '"'+v.id+'",';
                    jsonRecordsString += '},';
                    i++;
                }
            }
            vqr.add(v);
            j++;
        }
        
      //lets do some clean-up   
            jsonRecordsString = jsonRecordsString.replaceAll(' 00:00:00','');
            jsonRecordsString = jsonRecordsString.replaceAll(';','","');
            jsonRecordsString = jsonRecordsString.replaceAll('null','');
            jsonRecordsString = jsonRecordsString.replaceAll('"latlng":","','"latlng":""');
               
        string jsonString = 'sfdccallback({ types: {"Reference" : {pluralLabel: "References"}},"items":[' + jsonRecordsString + '], "properties" : {"rev" : {"valueType" : "number"}, "emp" : {"valueType" : "number"}}   })';
        jsonString = jsonString.replaceAll(',]',']');
        this.json = jsonString;

    }
}

 

I have started something like this just to see if I can get it to  work, but still not success: 

@isTest
private class ControllerTest {
    static testMethod void Json_Controller() {
        Json_Controller controller = new Json_Controller();
        System.assertEquals(json.substring(0, 12),'sfdccallback');
    }
}

 

Hello, 

 

I am looking to create a vf page within the account page that will show all related account records based on a field called Ultimate_Parent_ID__c. The idea being that it will show all the sites for a given company. 

 

I already have the latlng coordinates stored on the account object, and a controller to query the related accounts (see below) but I can't seem to get them to plot on a google map. I have been looking around the various tutorials, but they all seem to go over how to geocode them, or how to show only 1 point on the map. 

 

Any help would be greatly appreicated! 

 

public class mapController2 {
    public String address {get;set;}
    private List<Account> accounts;

    public void find() {
        accounts = [SELECT Id, Name, BillingStreet, BillingCity, BillingCountry, BillingLat__c, BillingLong__c FROM Account 
        WHERE Ultimate_Parent_ID__c = :ApexPages.currentPage().getParameters().get('Account.Ultimate_Parent_ID__c')];
        
    }

    public List<Account> getAccounts() {
        return accounts;
    }
}

 

I am working on a trigger that will populate longitude and latitude fields on the account object. I have a start on it, but I am getting an error:

"Error:Apex trigger AccountBeforeUpsert caused an unexpected exception, contact your administrator: AccountBeforeUpsert: System.LimitException: Too many script statements: 200001"

 

Class: 

public with sharing class GeoUtilities {

  @future(callout=true)
  public static void updateAccounts(List<Id> accountIds)
  {
  // get the custom city, state and country fields from account
    List<account> accounts = [select Id, Name, BillingStreet, BillingCity, BillingState, BillingCountry
      from Account where Id in :accountIds ];
    for(Account theAccount: accounts) { 
      List<string> address = new List<string>();
      address.add(theAccount.BillingStreet);
      address.add(theAccount.BillingCity);
      address.add(theAccount.BillingState);
      address.add(theAccount.BillingCountry);
      String[] coordinates = GeoUtilities.getCoordinates(address);
      if(coordinates != null)
      {
        Decimal pos1 = Decimal.valueOf(coordinates[0]);
        theAccount.Latitude__c = pos1;
        Decimal pos2 = Decimal.valueOf(coordinates[1]);
        theAccount.Longitude__c = pos2;
        system.debug(Logginglevel.ERROR,'GeoUtilities coordinates ' + pos1 + ' ' + pos2 );    
      }
      else
      {
        system.debug(Logginglevel.ERROR,'GeoUtilities no coordinates!!! for address' );          
      }
    }
    update accounts;  
  }

/* 
Input list of address parts: street,  city,  state,  country. 
Output: list of coordinates: latitude, longitude
*/ 
public static String[] getCoordinates(String[] addressParts)
{ 
  String[] Coordinates; 
  String address = '';
  boolean needComma = false;

  if(address.length() == 0)
  {
    system.debug(Logginglevel.ERROR,
      'GeoUtilities getCoordinates no address provided. Return null');    
    return null; 
  }
   
  String url = 'http://maps.google.com/maps/geo?';
  url += 'q=' + address; 
  url += '&output=csv'; 
  
  system.debug(Logginglevel.ERROR,'GeoUtilities getCoordinates url: ' + url);    
  
  Http h = new Http(); 
  HttpRequest req = new HttpRequest();
  
  req.setHeader('Content-type', 'application/x-www-form-urlencoded'); 
  req.setHeader('Content-length', '0'); 
  req.setEndpoint(url); 
  req.setMethod('POST');
  String responseBody;
  if (!Test.isRunningTest()){ 
  // Methods defined as TestMethod do not support Web service callouts
    HttpResponse res = h.send(req); 
    responseBody = res.getBody();
  }
  else {
    // dummy data
    responseBody = '200,4,48.5,-123.67';
  } 
  String[] responseParts = responseBody.split(',',0); 
  // the response has four parts: 
  // status code, quality code, latitude and longitude
  Coordinates = new String[2];
  Coordinates[0] = responseParts[2];
  Coordinates[1] = responseParts[3];
    
  return Coordinates; 
}   
  
  static testMethod void  testGetGeo()
  {
    String[] addressParts;
    String[] coordinates;
    
    addressParts = new List<string>();
    addressParts.add('');
    addressParts.add('San Diego');
    addressParts.add('CA');
    addressParts.add('USA');
    
    coordinates = GeoUtilities.getCoordinates(addressParts);
    System.assert(coordinates != null);
    System.assertEquals(2, coordinates.size()); 
  }
}

 

Trigger: 

trigger AccountBeforeUpsert on Account (before insert, before update) {
  system.debug(Logginglevel.ERROR,'AccountBeforeUpsert  geo updates');    

  List<Id> accountsToUpdate = new List<Id>();
  for(Account theAccount: trigger.new)
  {
    boolean needsUpdate = false;
    if(Trigger.isInsert)
    {
      needsUpdate = true;
    }
    else {
    Account beforeUpdate = System.Trigger.oldMap.get(theAccount.Id);
    needsUpdate = (
      (beforeUpdate.BillingStreet != theAccount.BillingStreet) ||
      (beforeUpdate.BillingCity != theAccount.BillingCity) ||
      (beforeUpdate.BillingState != theAccount.BillingState) ||
      (beforeUpdate.BillingCountry != theAccount.BillingCountry)
      );
    }
    if(needsUpdate)
    {
      accountsToUpdate.add(theAccount.Id);
    }
  }
  if(accountsToUpdate.size() >0 )
  {
    Integer cnt = 0;
    Integer i = 0;
    Integer x = accountsToUpdate.size();
    x = (x>100? 100: x);
    while(i < x){
      List<account> smallList = new List<account>();
      for(Integer k = 0; k == x;)
          break;
      }
      GeoUtilities.updateAccounts(accountsToUpdate);
    }
  }

 Any help with this would be greatly appreciated. Credit for much of the code goes to Bryan at https://bryandf11.wordpress.com/2011/08/22/geocoding-in-apex-triggers-callouts-and-future-methods/

 

Thanks!

Hello, 

 

I new still new to APEX and have a class that generates some JSON, but can't figure out how to write a test class for it... I have written test classes before, but not for a page controller that just serves up JSON... 

 

Thanks!

 

public class Json_Controller {
    
    public string json {get;set;}
        
    public Json_Controller() {      
        VQ_Reference_Sheet__c[] vqr = new VQ_Reference_Sheet__c[]{};
        integer start = 0;
        integer pageSize = 100;
        
        if (ApexPages.currentPage().getParameters().get('start') != null && ApexPages.currentPage().getParameters().get('limit') != null) {
            start = integer.valueof(ApexPages.currentPage().getParameters().get('start'));
            pageSize = integer.valueof(ApexPages.currentPage().getParameters().get('limit'));
        }
        
        string jsonRecordsString = '';
        
        integer i = 1;
        integer j = 0;
        
        for (VQ_Reference_Sheet__c v : [Select 
        
        id, 
        name, 
        Times_Referenced_Used_Total__c, 
        Hardware_Platform__c
              
        
        from VQ_Reference_Sheet__c order by name limit 1000]) {
            if (j >= start) {
                if (i <= pageSize) {
                    jsonRecordsString += '{';
                //record info      
                    jsonRecordsString += '"label":' + '"'+v.name+'",';  
                    jsonRecordsString += '"use":' + '["'+v.Times_Referenced_Used_Total__c+'"],';
                    jsonRecordsString += '"hrd":' + '["'+v.Hardware_Platform__c+'"],';
                    
                //record id    
                    jsonRecordsString += '"sfdcid":' + '"'+v.id+'",';
                    jsonRecordsString += '},';
                    i++;
                }
            }
            vqr.add(v);
            j++;
        }
        
      //lets do some clean-up   
            jsonRecordsString = jsonRecordsString.replaceAll(' 00:00:00','');
            jsonRecordsString = jsonRecordsString.replaceAll(';','","');
            jsonRecordsString = jsonRecordsString.replaceAll('null','');
            jsonRecordsString = jsonRecordsString.replaceAll('"latlng":","','"latlng":""');
               
        string jsonString = 'sfdccallback({ types: {"Reference" : {pluralLabel: "References"}},"items":[' + jsonRecordsString + '], "properties" : {"rev" : {"valueType" : "number"}, "emp" : {"valueType" : "number"}}   })';
        jsonString = jsonString.replaceAll(',]',']');
        this.json = jsonString;

    }
}

 

I have started something like this just to see if I can get it to  work, but still not success: 

@isTest
private class ControllerTest {
    static testMethod void Json_Controller() {
        Json_Controller controller = new Json_Controller();
        System.assertEquals(json.substring(0, 12),'sfdccallback');
    }
}

 

I am working on a trigger that will populate longitude and latitude fields on the account object. I have a start on it, but I am getting an error:

"Error:Apex trigger AccountBeforeUpsert caused an unexpected exception, contact your administrator: AccountBeforeUpsert: System.LimitException: Too many script statements: 200001"

 

Class: 

public with sharing class GeoUtilities {

  @future(callout=true)
  public static void updateAccounts(List<Id> accountIds)
  {
  // get the custom city, state and country fields from account
    List<account> accounts = [select Id, Name, BillingStreet, BillingCity, BillingState, BillingCountry
      from Account where Id in :accountIds ];
    for(Account theAccount: accounts) { 
      List<string> address = new List<string>();
      address.add(theAccount.BillingStreet);
      address.add(theAccount.BillingCity);
      address.add(theAccount.BillingState);
      address.add(theAccount.BillingCountry);
      String[] coordinates = GeoUtilities.getCoordinates(address);
      if(coordinates != null)
      {
        Decimal pos1 = Decimal.valueOf(coordinates[0]);
        theAccount.Latitude__c = pos1;
        Decimal pos2 = Decimal.valueOf(coordinates[1]);
        theAccount.Longitude__c = pos2;
        system.debug(Logginglevel.ERROR,'GeoUtilities coordinates ' + pos1 + ' ' + pos2 );    
      }
      else
      {
        system.debug(Logginglevel.ERROR,'GeoUtilities no coordinates!!! for address' );          
      }
    }
    update accounts;  
  }

/* 
Input list of address parts: street,  city,  state,  country. 
Output: list of coordinates: latitude, longitude
*/ 
public static String[] getCoordinates(String[] addressParts)
{ 
  String[] Coordinates; 
  String address = '';
  boolean needComma = false;

  if(address.length() == 0)
  {
    system.debug(Logginglevel.ERROR,
      'GeoUtilities getCoordinates no address provided. Return null');    
    return null; 
  }
   
  String url = 'http://maps.google.com/maps/geo?';
  url += 'q=' + address; 
  url += '&output=csv'; 
  
  system.debug(Logginglevel.ERROR,'GeoUtilities getCoordinates url: ' + url);    
  
  Http h = new Http(); 
  HttpRequest req = new HttpRequest();
  
  req.setHeader('Content-type', 'application/x-www-form-urlencoded'); 
  req.setHeader('Content-length', '0'); 
  req.setEndpoint(url); 
  req.setMethod('POST');
  String responseBody;
  if (!Test.isRunningTest()){ 
  // Methods defined as TestMethod do not support Web service callouts
    HttpResponse res = h.send(req); 
    responseBody = res.getBody();
  }
  else {
    // dummy data
    responseBody = '200,4,48.5,-123.67';
  } 
  String[] responseParts = responseBody.split(',',0); 
  // the response has four parts: 
  // status code, quality code, latitude and longitude
  Coordinates = new String[2];
  Coordinates[0] = responseParts[2];
  Coordinates[1] = responseParts[3];
    
  return Coordinates; 
}   
  
  static testMethod void  testGetGeo()
  {
    String[] addressParts;
    String[] coordinates;
    
    addressParts = new List<string>();
    addressParts.add('');
    addressParts.add('San Diego');
    addressParts.add('CA');
    addressParts.add('USA');
    
    coordinates = GeoUtilities.getCoordinates(addressParts);
    System.assert(coordinates != null);
    System.assertEquals(2, coordinates.size()); 
  }
}

 

Trigger: 

trigger AccountBeforeUpsert on Account (before insert, before update) {
  system.debug(Logginglevel.ERROR,'AccountBeforeUpsert  geo updates');    

  List<Id> accountsToUpdate = new List<Id>();
  for(Account theAccount: trigger.new)
  {
    boolean needsUpdate = false;
    if(Trigger.isInsert)
    {
      needsUpdate = true;
    }
    else {
    Account beforeUpdate = System.Trigger.oldMap.get(theAccount.Id);
    needsUpdate = (
      (beforeUpdate.BillingStreet != theAccount.BillingStreet) ||
      (beforeUpdate.BillingCity != theAccount.BillingCity) ||
      (beforeUpdate.BillingState != theAccount.BillingState) ||
      (beforeUpdate.BillingCountry != theAccount.BillingCountry)
      );
    }
    if(needsUpdate)
    {
      accountsToUpdate.add(theAccount.Id);
    }
  }
  if(accountsToUpdate.size() >0 )
  {
    Integer cnt = 0;
    Integer i = 0;
    Integer x = accountsToUpdate.size();
    x = (x>100? 100: x);
    while(i < x){
      List<account> smallList = new List<account>();
      for(Integer k = 0; k == x;)
          break;
      }
      GeoUtilities.updateAccounts(accountsToUpdate);
    }
  }

 Any help with this would be greatly appreciated. Credit for much of the code goes to Bryan at https://bryandf11.wordpress.com/2011/08/22/geocoding-in-apex-triggers-callouts-and-future-methods/

 

Thanks!

I have embed a google maps in one of my custom objects. Based on the customer's address, the map is being displayed on the page. But how can I generate geocode (latitude and longitude) for the address? Any suggestions please.

Thank you in advance!

  • April 24, 2012
  • Like
  • 0

i want to read values from the text box on visual force page is it possible  to read from visual force using java api. if yes then how can i do that??