PUT Vehicle - JAVA

The PUT Vehicle method within the Customer Meta Data – Vehicles API enables integrated users to edit the vehicle object details within the referenced REVEAL account.

Before attempting to retrieve vehicle location information it is important to know if the REVEAL account has been updated with valid VEHICLE NUMBERS for each vehicle to be pulled via the API. The VEHICLE NUMBER and VEHICLE NAME fields are different fields within REVEAL and the VEHICLE NUMBER field is not automatically populated upon account creation.

Main Method

public class Program{
  public static void main(String[] args){
    
    // Token call goes here, see TokenGenerator example 
    
    // App Id from Fleetmatics Integration Manager (FIM) 
    String appId = "companyname-p-us-4654sdf4fa351af65dsf1d";        
        
    // Local variables that correspond to Vehicle object in PUT
    String vehicleNum = "0112358";
    String vehicleName = "TESTER";
    String registrationNumber = "GA23423";
    String vin = "1GNDX03E5YD117167";
    String make = "Ford";
    Integer year = 2012;
    String model =  "F150";
    Double tankCapacity = 20.5;	
    Double highwayMPG = 14.5;
    Double cityMPG = 11.5;	
    Integer vehicleSize = 1;
    
    // Put Vehicle URI; vehicle number is appended to the end of the string to complete the URI	
    String putVehicleUri = String.format("https://fim.api.ENV.fleetmatics.com/cmd/v1/vehicles/%s", vehicleNum);  
	
    // Create new PUT_Vehicle object
    PUT_Vehicle rest_put = new PUT_Vehicle();
    
    // Pass in local variables to create a Vehicle object
    rest_put.CreateNewPutVehicle(vehicleName, vehicleNum, registrationNumber, vin, make, model, year, tankCapacity, highwayMPG, cityMPG, vehicleSize);
    
    // Call method to execute the API call
    rest_put.PutVehicle(/* token auth string passed here */, putVehicleUri, appId);
  }  
}

PUT_Vehicle Class

import java.io.IOException;
import java.io.OutputStream;
import javax.net.ssl.HttpsURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.lang.reflect.*;

public class PUT_Vehicle
{
  private Vehicle _vehicle;
  
  public void PutVehicle(String authString, String putVehicleUri, String appId)
  {   
    try{
      // Construct authentication header for FIM   
      String authHeader = String.format("Atmosphere atmosphere_app_id=%s, Bearer %s", appId, authString);             
      
      // Serialize workorder object into JSON for POST request body     
      String json = DummySerializer(_vehicle);           
      
      URL url = new URL(putVehicleUri);                                        // Create URL object from uri parameter   
      HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();     // Begin new Https connection       
      conn.setRequestMethod("PUT");                                            // Set REST method to PUT  
      conn.setRequestProperty("Authorization", authHeader);                    // Set Authorization Header   
      conn.setRequestProperty("Content-Type", "application/json");             // Set Content-Type to json 
      conn.setDoOutput(true);                                                  // Allow output to come back in response 
      
      OutputStream os = conn.getOutputStream();   // Create new output stream for body from connection   
      os.write(json.getBytes());                  // Transmit the json workorder object       
      os.close();                                 // Flush and close stream  
      
      // Read response, 204 "no content" evaluation for "success", if not throw exception 
      if (conn.getResponseCode() != HttpsURLConnection.HTTP_NO_CONTENT) {
        throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
      }
      else {
        System.out.println("Vehicle Updated Successfully!");
        _vehicle = null                          // Clear object 
      }
 
      conn.disconnect();                         // End connection to free resources 
      
    } catch (MalformedURLException e) {          // Required Exception 
      e.printStackTrace();
    } catch (IOException e) {                    // Required Exception 
      e.printStackTrace();
    }
  } 
  
  // Public method used to create the Vehicle object which contains.
  // After serialization, this will be used as the body for the PUT command
  public void CreateNewPutVehicle(String name, String number, String registrationNumber, String vin, String make, String model,
                                  Integer year, Double tankCapacity, Double highwayMpg, Double cityMpg, Integer vehicleSize)
  {
    _vehicle = new Vehicle();
    _vehicle.Name = name;
    _vehicle.VehicleNumber = number;
    _vehicle.RegistrationNumber = registrationNumber;
    _vehicle.VIN = vin;
    _vehicle.Make = make;
    _vehicle.Model = model;
    _vehicle.Year = year;
    _vehicle.TankCapacity = tankCapacity;
    _vehicle.HighwayMPG = highwayMpg;
    _vehicle.CityMPG = cityMpg;
    _vehicle.VehicleSize = vehicleSize;
  }
  
  // Serializer - "object to JSON" for Vehicle object
  private String DummySerializer(Object object)
  {    
    try{
      StringBuilder sb = new StringBuilder();
      sb.append("{");                                             // Open parentheses
      
      for (Field field : object.getClass().getDeclaredFields())   // Loop through object
      {
        field.setAccessible(true);                                // Override
        if (field != null && field.getName() != "this$0")         // Skip "this$0" - outer class
        {
          sb.append("\"" + field.getName() + "\" : ");
          sb.append(field.get(object) != null ? ("\"" + field.get(object) + "\"") : "null");   
          sb.append(", ");
        }
      }
      
      sb.setLength(sb.length() - 2);                              // Remove last ", "
      sb.append("}");                                             // Close parentheses
      
      return sb.toString
      
    } catch (IllegalAccessException e) {                          // Required exception
      throw new RuntimeException("Error accessing object value!");
    }
  }
  
  public class Vehicle
  {
    public String VehicleNumber;
    public String Name;
    public String RegistrationNumber;
    public String VIN;
    public String Make;
    public Integer Year;
    public String Model;
    public Double TankCapacity;
    public Double HighwayMPG;
    public Double CityMPG;
    public Integer VehicleSize;
  }
}

To download the source code .zip for this example, click HERE.

DISCLAIMER

All sample code is provided by Fleetmatics, A Verizon Company, for illustrative purposes only. These examples have not been thoroughly tested under all conditions. Fleetmatics, therefore, cannot guarantee or imply reliability, serviceability, or function of these programs. All programs contained herein are provided to you “AS IS” without any warranties of any kind.