Description
Create the Address Manager application using the Spring framework. Run it connected to the SAP API Business Hub sandbox, connect it to an SAP S/4HANA Cloud system, deploy it to Cloud Foundry, and then finally create a Destination service and use it to connect the application to the back-end.
Prerequisites
For the complete execution of current exercise, you must prior execute the following other exercises:
- Create your Free Trial Account in SAP BTP
- Activating the APIs in SAP S/4HANA Cloud: this exercise activates the required API in the S/4HANA Cloud tenant.
For the full execution of this exercise, you need to have the following software installed on your laptop:
Software | Type |
---|---|
Apache Maven | application |
Cloud Foundry CLI | application |
Java Development Kit, Standard Edition, version 8 | application |
IntelliJ IDEA Community Edition | application |
Visual Studio Code | application |
Cloudfoundry Manifest YML Support | Visual Studio Code Extension |
Debugger for Java | Visual Studio Code Extension |
Project Manager for Java | Visual Studio Code Extension |
Java Extension Pack | Visual Studio Code Extension |
Java Test Runner | Visual Studio Code Extension |
Language Support for Java(TM) by Red Hat | Visual Studio Code Extension |
Some steps of this exercise depend on the https://api.sap.com website. As a consequence, they may not run properly if the website is not running 100% correctly. In this case, proceed with the exercise to reach the part that runs against the SAP S/4HANA Cloud instance.
Information for execution
The exercise comes with an archive file:
java-adman-spring-solution.zip
[download] contains the Maven project in its final status after the correct execution of the exercise. This project can be used to clarify the correct solution or to copy and paste parts of the source code.
In the case you wish to run the solution application directly without going through the exercise steps, then complete the following actions (this is not a prerequisite to exercise execution):
- Extract the archive to a folder in your local system.
- Open the Windows Powershell and change the directory to the project root folder.
- Execute the following sequence of commands (replace ">>>YOUR API KEY<<<" with your own API Key, for example,
"FDqbnElM7mgmgqbIKBFHRpS1dvpt6sHD"
. To get your API Key, open https://api.sap.com/api/API_BUSINESS_PARTNER, then log on, and choose Show API Key).Code snippetCopy code$env:S4_APIKEY=">>>YOUR API KEY<<<" $env:S4_URL="https://sandbox.api.sap.com/s4hanacloud" mvn clean install cd application mvn spring-boot:run
- Wait until the Tomcat server starts. Open the application at http://localhost:8080/address-manager.
To configure the application, complete the following exercise steps.
The application reads the following environment variables, such variables need to be properly set for the application to interact with the back-end service:
Variable | Content |
---|---|
S4_DESTINATION | The name of the destination defined within the Destination service of Cloud Foundry. Use it when running in Cloud Foundry. |
S4_URL | The URL of the backend ERP system. Use it when running locally. |
S4_USERNAME | The user name to access the backend ERP system. Use it when running locally. |
S4_PASSWORD | The user name to access the backend ERP system. Use it when running locally. |
S4_APIKEY | Your API Key identifier, required to access the SAP API Business Hub. You can get your apikey at https://api.sap.com . |
Two authentication methods are possible. Based on the method, you will provide the corresponding environment variables:
- Basic user and password authentication: used by the S/4HANA Cloud system.
- No Authentication plus API key: used by the SAP API Business Hub Sandbox system.
Task 1: Creating the Spring Boot Development Project in a Local IDE (Visual Studio Code or IntelliJ IDEA)
Steps
In a local folder (folder
D:\workspace
if you are in the SAP Training System), generate an extension application project from an archetype, using the following information: [play]Parameter Value Project folder D:\workspace\java-adman-spring archetypeGroupId com.sap.cloud.sdk.archetypes archetypeArtifactId scp-cf-spring archetypeVersion 3.62.0 (you may use RELEASE, to get the latest version) groupId com.example artifactId java-adman-spring version 1.0-SNAPSHOT Open the Windows PowerShell, and execute the following command:
cd D:\workspace
.Execute the following command (you can copy it from the
java-adman-spring-1-create-project.txt
file [download]):Code snippetCopy codemvn archetype:generate "-DarchetypeGroupId=com.sap.cloud.sdk.archetypes" "-DarchetypeArtifactId=scp-cf-spring" "-DarchetypeVersion=3.62.0" "-DgroupId=com.example" "-DartifactId=java-adman-spring" "-Dversion=1.0-SNAPSHOT"
Wait until the project is generated. When requested, enter Y to continue.
If successful, theBUILD SUCCESS
message displays.
Build and run the application from the command line. [play]
In the Windows PowerShell, run the following commands:
Wait until the application is built successfully.In the Windows PowerShell, run the following commands:
Wait until the Tomcat server starts.In your Web browser (for example, Google Chrome), open http://localhost:8080.
In the PowerShell, choose Ctrl+C and then Y and stop the Tomcat server.
Open the local project folder using your preferred local Java IDE (such as, Visual Studio Code). [play]
Open Windows File Explorer and navigate to the project folder. Right-click and execute Open with Code (in case you use IntelliJ IDEA: Open Folder as IntelliJ IDEA Community Edition Project, in case you are asked, specify it is a Maven project).
Check the status bar of your Java IDE (lower right corner of the window) until the analysis (build) of the project is complete.
Review the project content. [play]
Open
application/src/main/java/com/example/
and review the project files in the sub-folders.The
HelloWorldController
listens in the context of/hello
for incoming HTTP requests. When aGET
request is sent to this resource, it logs the string'I am running'
and returns a response based on the HelloWorldResponse class. As expected in Spring programming, the Model-View-Controller pattern is applied, so the controller object is separated from the model one.Open the
application/src/main/resources/static/index.html
file and review the code.The index file that we see here helps us to validate a fresh deployment of our app. It welcomes every visitor who sends a request to our application base URL with a generic landing page.
Open the
application/src/test/java/com/example/UnitTest.java
file and review the code.We use the unit-tests module for tests that ensure the functional correctness of small functional units of our application, typically on Java API level.
Open the
integration-tests/src/test/java/com/example/HelloWorldControllerTest.java
file and review the code.The integration test module holds tests that typically test multiple parts of the application and their interplay. These tests are often written on the level of HTTP requests and expected responses.
Open the
manifest.yml
file and review the code.The
manifest.yml
file is used to tell the Cloud foundry environment which resources our application needs to run. This is interpreted by Cloud Foundry when deploying the application. The following figure shows, for example, the memory requirements, environment variable definitions, and instances of platform services that should be bound to our app.
In your IDE (for example, Visual Studio Code), run the application in debug mode. Set a breakpoint in file
HelloWorldController.java
at line26
. Open the application in the browser and verify that the execution stops at the breakpoint. Continue the execution to the end. Remove the breakpoint. Stop the application. [play]Open the
application/src/main/java/com/example/Application.java
file.If you are using Visual Studio Code, choose the small Debug command that appears just before the
Main()
method definition.It may take a couple of minutes to display until the application build is automatically executed in background.
If you are using IntelliJ IDEA, select the little green arrow on the left side of the class definition and choose Debug Application.Main(). A run configuration is automatically created and the application is started.
Open the
application/src/main/java/com/example/controllers/HelloWorldController.java
file. Create a breakpoint by selecting aside line number 26. A red dot appears beside the number.Open the Web browser at http://localhost:8080. The welcome screen appears.
In the welcome screen, choose HelloWorldController . The controller runs and the execution stops in the debugger at the breakpoint.
In the Debugger, choose Continue (or Resume Program).
hello: 'world'
appears in the browser.In the
HelloWorldController.java
, click on the red dot to remove the breakpoint.Choose Stop (or Stop 'Application').
Deploy the application to Cloud Foundry.
Open the Windows PowerShell. In required, you can open the Cloud Foundry CLI by executing the following commands:
Enter your SAP BTP API endpoint, e-mail, and password.In the Windows PowerShell, run the following commands:
Look for the running application in the SAP BTP Cockpit and open it.
In Google Chrome, open the URL https://account.hanatrial.ondemand.com. If required, enter your e-mail and password.
In the SAP BTP Cockpit, choose Enter Your Trial account. Navigate to your trial Subaccount. Navigate to the dev space.
Choose the java-adman-spring application name.
Choose the Application Route. The application opens in the Welcome page.
Create a debug configuration to attach the remote Java application in Cloud Foundry.
If you are using Visual Studio Code, choose Run → Add Configuration → Java. The
launch.json
file is opened.In the
launch.json
file, add the following debug configuration (for simplicity, you can just copy the whole content of filejava-adman-spring-2-launch-json.txt
file [download]):Code snippetCopy code{ "type": "java", "name": "Attach Application", "request": "attach", "hostName": "localhost", "port": 5005, "sourcePaths": [ "${workspaceFolder}" ] }
If you are using IntelliJ IDEA, create a debug configuration to attach the remote Java application in Cloud Foundry.
In IntelliJ IDEA, choose Run → Edit Configurations...
You should find a configuration with name Application. Rename it to Launch Application
In the Run/Debug Configurations window, choose Add New Configuration → Remote JVM Debug. Enter the following information:
Field Value Name Attach Application Debugger mode Attach to remote JVM Host localhost Port 5005 User module classpath java-adman-spring Choose Ok.
Attach the debugger of your local IDE (for example, Visual Studio Code) to the remote application running in Cloud Foundry.
In the PowerShell, make sure that the current directory is the project root folder
D:\workspace\java-adman-spring
.To enable the remote application for debug, execute the following commands (you can find them in the
java-adman-spring_enable_cf_debug.txt
file [download]):Code snippetCopy codecf set-env java-adman-spring JBP_CONFIG_JAVA_OPTS "[java_opts: '-Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=8000,suspend=n']" cf enable-ssh java-adman-spring cf restage java-adman-spring cf ssh -N -T -L 5005:localhost:8000 java-adman-spring
In the local IDE (for example Visual Studio Code) run the Attach Application configuration in debug mode. The debugger attaches to the remote application.
In your IDE (for example, Visual Studio Code), set a breakpoint in the
HelloWorldController.java
file at line26
. Open the application in the browser and verify that the execution stops at the breakpoint. Continue the execution to the end. Remove the breakpoint. Stop the application.Open the
application/src/main/java/com/example/controllers/HelloWorldController.java
file. Create a breakpoint clicking aside the line number 26. A red dot appears aside the number.Open the Web browser in the SAP BTP Cockpit at the welcome page of the java-adman-spring application that you just deployed.
In the welcome screen, choose HelloWorldController. The controller runs and the execution stops in the debugger at the breakpoint.
In the Debugger, choose Continue (or Resume Program).
hello: 'world'
appears in the browser.In the
HelloWorldController.java
, click on the red dot to remove the breakpoint.Disconnect the debugger.
In the Powershell, chooseCtrl+C to interrupt the
cf ssh
command.
Task 2: Creating the Spring Boot Development Project in the SAP Business Application Studio
Steps
Open the SAP Business Application Studio → training development space.
In your Web browser (for example, Google Chrome), open https://account.hanatrial.ondemand.com. If requested, enter your user and password.
Choose SAP Business Application Studio.
Enter the training development space.
In the
projects
folder, generate an extension application project from an archetype, using the following information:Parameter Value archetypeGroupId com.sap.cloud.sdk.archetypes archetypeArtifactId scp-cf-spring archetypeVersion 3.62.0 (you may use RELEASE, to get the latest version) groupId com.example artifactId java-adman-spring version 1.0-SNAPSHOT Choose File → Open Workspace... (Ctrl+Alt+W), choose the
projects
folder and choose Open.Choose Terminal → New Terminal. A terminal window appears in the lower part of the screen.
In the terminal, execute the following command (you can copy it from the
java-adman-spring-1-create-project.txt
file [download]):Code snippetCopy codemvn archetype:generate "-DarchetypeGroupId=com.sap.cloud.sdk.archetypes" "-DarchetypeArtifactId=scp-cf-spring" "-DarchetypeVersion=3.62.0" "-DgroupId=com.example" "-DartifactId=java-adman-spring" "-Dversion=1.0-SNAPSHOT"
Wait until the project is generated. If requested, enter Y to continue.
If successful, aBUILD SUCCESS
message displays.
Open the
projects/java-adman-spring
folder as a workspace.Choose File → Open Workspace... (Ctrl+Alt+W), choose the
projects/java-adman-spring
folder and choose Open.
Build and run the application from the command line.
Choose Terminal → New Terminal. A terminal window appears in the lower part of the screen.
In the terminal, execute the following command:
Wait until the application is built successfully.In the terminal, execute the following commands:
Wait until the Tomcat server starts. After a few seconds a pop-up window appears with the following message:A service is listening to port 8080.
Choose Expose and Open, then press enter. The application is opened.Return to the terminal, choose Ctrl+C to stop the Tomcat server.
Review the project content.
Open
application/src/main/java/com/example/
and review the project files in the sub-folders.The
HelloWorldController
listens in the context of/hello
for incoming HTTP requests. When aGET
request is sent to this resource, it logs the string'I am running'
and returns a response based on the HelloWorldResponse class. As expected in Spring programming, the Model-View-Controller pattern is applied, so the controller object is separated from the model one.Open the
application/src/main/resources/static/index.html
file and review the code.The index file that we see here helps us to validate a fresh deployment of our app. It welcomes every visitor who sends a request to our application base URL with a generic landing page.
Open the
application/src/test/java/com/example/UnitTest.java
file and review the code.We use the unit-tests module for tests that ensure the functional correctness of small functional units of our application, typically on Java API level.
Open the
integration-tests/src/test/java/com/example/HelloWorldControllerTest.java
file and review the code.The integration test module holds tests that typically test multiple parts of the application and their interplay. These tests are often written on the level of HTTP requests and expected responses.
Open the
manifest.yml
file and review the code.The
manifest.yml
file is used to tell the Cloud foundry environment which resources our application needs to run. This is interpreted by Cloud Foundry when deploying the application. The following figure shows an example of the memory requirements, environment variable definitions, and instances of platform services that should be bound to our app.
Run the application in debug mode. Set a breakpoint in the
HelloWorldController.java
file at line26
. Open the application in the browser and verify that the execution stops at the breakpoint. Continue the execution to the end. Remove the breakpoint. Stop the application.Open the
application/src/main/java/com/example/Application.java
file.Choose the small Debug command that appears just before the
Main()
method definition.Once the application has started, a pop up window appears stating
A service is listening to port 8080.
Choose Open in New Tab. A new tab is opened showing the application welcome screen.Open the
application/src/main/java/com/example/controllers/HelloWorldController.java
file. Create a breakpoint by selecting aside line number 26. A red dot appears beside the number.In the welcome screen, choose HelloWorldController. The controller runs and the execution stops in the debugger at the breakpoint.
In the Debugger, choose Continue(in the Debug page).
hello: "world"
appears in the application page.In the
HelloWorldController.java
, click on the red dot to remove the breakpoint.Choose Stop.
Deploy the application to Cloud Foundry.
Choose Terminal → New Terminal. A terminal window appears in the lower part of the screen.
If required, login to the Cloud Foundry CLI by executing the following commands
Enter your SAP BTP API endpoint, e-mail and password.In the terminal, make sure you are in the project root folder, then run the following command:
Look for the running application in the SAP BTP Cockpit and open it.
In Google Chrome, open the URL https://account.hanatrial.ondemand.com. If required, enter your e-mail and password.
In the SAP BTP Cockpit, choose Enter Your Trial account. Navigate to your trial Subaccount. Navigate to the dev space.
Choose the java-adman-spring application name.
Choose the Application Route. The application opens in the Welcome page.
In SAP Business Application Studio, create a debug configuration to attach the remote Java application in Cloud Foundry.
Choose Run → Open Configurations. The
launch.json
file is opened.In the
launch.json
file, change the name of the existing configuration to Launch Application, then add the following debug configuration (for simplicity, you can just copy the whole content of filejava-adman-spring-2-launch-json.txt
file [download]):Code snippetCopy code{ "type": "java", "name": "Attach Application", "request": "attach", "hostName": "localhost", "port": 5005, "sourcePaths": [ "${workspaceFolder}" ] }
Attach the debugger of SAP Business Application Studio to the remote application running in Cloud Foundry.
Open a terminal, make sure that the current directory is the project root folder.
To enable the remote application for debug, execute the following commands (you can find them in the
java-adman-spring_enable_cf_debug.txt
file [download]):Ignore eventual messages proposing you to expose port 5005.Code snippetCopy codecf set-env java-adman-spring JBP_CONFIG_JAVA_OPTS "[java_opts: '-Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=8000,suspend=n']" cf enable-ssh java-adman-spring cf restage java-adman-spring cf ssh -N -T -L 5005:localhost:8000 java-adman-spring
In SAP Business Application Studio, in the Debug tab, run the Attach Application configuration. The debugger attaches to the remote application.
Set a breakpoint in the
HelloWorldController.java
file at line26
. Open the application in the browser and verify that the execution stops at the breakpoint. Continue the execution to the end. Remove the breakpoint. Stop the application.Open the
application/src/main/java/com/example/controllers/HelloWorldController.java
file. Create a breakpoint by selecting aside line number 26. A red dot appears beside the number.Open the Web browser in the SAP BTP Cockpit at the welcome page of the java-adman-spring application you just deployed.
In the welcome screen, choose
HelloWorldController
. The controller runs and the execution stops in the debugger, at the breakpoint (switch back to SAP Business Application Studio).In the Debugger, choose Continue.
hello: 'world'
appears in the browser.In the
HelloWorldController.java
, click on the red dot to remove the breakpoint.Stop the debugger.
In the Terminal, chooseCtrl+C to interrupt the
cf ssh
command.
Task 3: Create the Address Manager Application using SAP Business Application Studio
Steps
At the top of the initial application, create an Address Manager application that maintains the SAP S/4HANA Cloud business partners address information. The application is provided in the exercise files, and includes the following parts:
Part File Description Java back-end java-adman-spring-backend.zip[download] Based on SAP Cloud SDK. Realizes two rest services "/api/business-partners" and "/api/addresses". SAPUI5 front-end java-adman-spring-frontend.zip[download] A JavaScript frontend based on the SAPUI5 library. It will run in the web browser. Navigate to the
java-adman-spring\application\src\main\java\com\example
folder.Right-click on the
example
folder, choose Upload Files..., upload thejava-adman-spring-backend.zip
archive [download].Right-click on the
example
folder, choose Open in Terminal.In the terminal, execute the following commands:
Close the terminal.
Navigate to the
java-adman-spring\application\src\main\resources\static
folder.Right-click on the
static
folder, choose Upload Files..., upload thejava-adman-spring-frontend.zip
archive [download].Right-click on the
static
folder, choose Open in Terminal.In the terminal execute the following commands:
Close the terminal.
Note
If anything is unclear, you can compare your project with the one provided within thejava-adman-spring-solution.zip
file [download].Review the service definitions in
application/src/main/java/com/example/adman
.The content of
BackendConnector.java
is as follows:The content ofCode snippetCopy codepackage com.example.adman; import com.sap.cloud.sdk.cloudplatform.connectivity.DefaultDestination; import com.sap.cloud.sdk.cloudplatform.connectivity.DestinationAccessor; import com.sap.cloud.sdk.cloudplatform.connectivity.HttpDestination; public class BackendConnector { private static String destinationName; private static String system_uri; private static String username; private static String password; private static String authentication; private static String apikey; private static HttpDestination destination; static { // Get the environment variables destinationName = System.getenv("S4_DESTINATION"); system_uri = System.getenv("S4_URL"); username = System.getenv("S4_USERNAME"); password = System.getenv("S4_PASSWORD"); authentication = (username != null && password != null) ? "BasicAuthentication" : "NoAuthentication"; apikey = System.getenv("S4_APIKEY"); if (apikey==null) apikey=""; if (destinationName != null){ // Get the destination via the Destination service // of Cloud Foundry, in the SCP. destination = DestinationAccessor .getDestination(destinationName).asHttp(); } else { // Create the destination at run time, // using the URI and credentials // provided in the environment variables. destination = DefaultDestination.builder() .property("Name", "DESTINATION") .property("URL", system_uri) .property("Type", "HTTP") .property("Authentication", authentication) .property("User", username) .property("Password", password) .build().asHttp(); } } public static HttpDestination getDestination() { return destination; } public static String getApikey() { return apikey; } }
BusinessPartnerController.java
is as follows:The content ofCode snippetCopy codepackage com.example.adman; import com.google.gson.Gson; import com.sap.cloud.sdk.s4hana.datamodel.odata.namespaces.businesspartner.BusinessPartner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.server.ResponseStatusException; import java.util.List; @RestController public class BusinessPartnerController { private static final Logger logger = LoggerFactory.getLogger(BusinessPartnerController.class); @GetMapping( "/api/business-partners" ) ResponseEntity<String> doGet( @RequestParam(required = false) String id) { String jsonResult; if (id == null) { // Get all Business Partners List<BusinessPartner> list; try { list = BusinessPartnerRepository.findAll(); } catch (BusinessPartnerRepository_InternalErrorException e) { final String message = "Internal error " + "retrieving business partners."; logger.error(message, e); throw new ResponseStatusException( HttpStatus.INTERNAL_SERVER_ERROR, message, e); } // Convert to JSon and remove null values jsonResult = new Gson().toJson(list); } else { // Get Business Partner based on id BusinessPartner bp; try { bp = BusinessPartnerRepository.findById(id); } catch (BusinessPartnerRepository_InternalErrorException e) { final String message = "Internal error retrieving " + "business partner " + id; logger.error(message, e); throw new ResponseStatusException( HttpStatus.INTERNAL_SERVER_ERROR, message, e); } // Convert to JSon and remove null values jsonResult = new Gson().toJson(bp); } // Prepare response headers (optional) HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); return new ResponseEntity<>( jsonResult, headers, HttpStatus.OK); } }
BusinessPartnerRepository.java
is as follows:The content ofCode snippetCopy codepackage com.example.adman; import com.sap.cloud.sdk.datamodel.odata.client.exception.ODataResponseException; import com.sap.cloud.sdk.datamodel.odata.helper.Order; import com.sap.cloud.sdk.s4hana.datamodel.odata.namespaces.businesspartner.BusinessPartner; import com.sap.cloud.sdk.s4hana.datamodel.odata.namespaces.businesspartner.BusinessPartnerAddress; import com.sap.cloud.sdk.s4hana.datamodel.odata.services.DefaultBusinessPartnerService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; public class BusinessPartnerRepository { private static final String CATEGORY_PERSON = "1"; private static final Logger logger = LoggerFactory.getLogger(BusinessPartnerRepository.class); public static BusinessPartner findById(String id) { BusinessPartner result; try { result = new DefaultBusinessPartnerService() .getBusinessPartnerByKey(id) .select(BusinessPartner.BUSINESS_PARTNER, BusinessPartner.LAST_NAME, BusinessPartner.FIRST_NAME, BusinessPartner.IS_MALE, BusinessPartner.IS_FEMALE, BusinessPartner.CREATION_DATE, BusinessPartner.TO_BUSINESS_PARTNER_ADDRESS .select( BusinessPartnerAddress.BUSINESS_PARTNER, BusinessPartnerAddress.ADDRESS_ID, BusinessPartnerAddress.COUNTRY, BusinessPartnerAddress.POSTAL_CODE, BusinessPartnerAddress.CITY_NAME, BusinessPartnerAddress.STREET_NAME, BusinessPartnerAddress.HOUSE_NUMBER)) .withHeader("apikey", BackendConnector.getApikey()) .executeRequest(BackendConnector.getDestination()); } catch (ODataResponseException e) { final String message = "OData error retrieving " + "business partner " + id; logger.error(message, e); throw new BusinessPartnerRepository_InternalErrorException( message, e); } return result; } public static List<BusinessPartner> findAll() { List<BusinessPartner> result; try { result = new DefaultBusinessPartnerService() .getAllBusinessPartner() .select(BusinessPartner.BUSINESS_PARTNER, BusinessPartner.LAST_NAME, BusinessPartner.FIRST_NAME) .filter(BusinessPartner.BUSINESS_PARTNER_CATEGORY .eq(CATEGORY_PERSON)) .orderBy(BusinessPartner.LAST_NAME, Order.ASC) .withHeader("apikey", BackendConnector.getApikey()) .executeRequest(BackendConnector.getDestination()); } catch (ODataResponseException e) { final String message = "OData error " + "retrieving business partners."; logger.error(message, e); throw new BusinessPartnerRepository_InternalErrorException( message, e); } return result; } }
BusinessPartnerRepository_InternalErrorException.java
is as follows:The content ofCode snippetCopy codepackage com.example.adman; public class BusinessPartnerRepository_InternalErrorException extends RuntimeException { BusinessPartnerRepository_InternalErrorException( String message, Throwable cause){ super(message, cause); } }
BusinessPartnerAddressController.java
is as follows:The content ofCode snippetCopy codepackage com.example.adman; import com.sap.cloud.sdk.s4hana.datamodel.odata.namespaces.businesspartner.BusinessPartnerAddress; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import org.springframework.web.server.ResponseStatusException; @RestController public class BusinessPartnerAddressController { private static final Logger logger = LoggerFactory.getLogger(BusinessPartnerController.class); @PostMapping("/api/addresses") BusinessPartnerAddress doPost( @RequestBody BusinessPartnerAddress newAddress) { BusinessPartnerAddress bpa; try { bpa = BusinessPartnerAddressRepository.save(newAddress); } catch ( BusinessPartnerAddressRepository_InternalErrorException e) { final String message = "Internal error " + "saving the business partner address."; logger.error(message, e); throw new ResponseStatusException( HttpStatus.INTERNAL_SERVER_ERROR, message, e); } return bpa; } @PatchMapping("/api/addresses") BusinessPartnerAddress doPatch( @RequestBody BusinessPartnerAddress address) { BusinessPartnerAddress bpa; try { bpa = BusinessPartnerAddressRepository.save(address); } catch ( BusinessPartnerAddressRepository_InternalErrorException e) { final String message = "Internal error " + "updating the business partner address."; logger.error(message, e); throw new ResponseStatusException( HttpStatus.INTERNAL_SERVER_ERROR, message, e); } return bpa; } @DeleteMapping("/api/addresses") protected void doDelete( @RequestParam String businessPartnerId, @RequestParam String addressId) { try { BusinessPartnerAddressRepository .delete(businessPartnerId, addressId); } catch ( BusinessPartnerAddressRepository_InternalErrorException e) { final String message = "Internal error " + "deleting the business partner address."; logger.error(message, e); throw new ResponseStatusException( HttpStatus.INTERNAL_SERVER_ERROR, message, e); } } }
BusinessPartnerAddressRepository.java
is as follows:The content ofCode snippetCopy codepackage com.example.adman; import com.sap.cloud.sdk.datamodel.odata.client.exception.ODataResponseException; import com.sap.cloud.sdk.datamodel.odata.helper.ModificationResponse; import com.sap.cloud.sdk.s4hana.datamodel.odata.namespaces.businesspartner.BusinessPartnerAddress; import com.sap.cloud.sdk.s4hana.datamodel.odata.services.DefaultBusinessPartnerService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class BusinessPartnerAddressRepository { private static final Logger logger = LoggerFactory.getLogger(BusinessPartnerAddressRepository.class); public static BusinessPartnerAddress save( BusinessPartnerAddress address) { ModificationResponse<BusinessPartnerAddress> response; if(address.getAddressID()==null) { // Create new address try { response = new DefaultBusinessPartnerService() .createBusinessPartnerAddress(address) .withHeader("apikey", BackendConnector.getApikey()) .executeRequest(BackendConnector.getDestination()); } catch (ODataResponseException e) { final String message = "OData error " + "creating new business partner address."; logger.error(message, e); throw new BusinessPartnerAddressRepository_InternalErrorException( message, e); } } else { // Update existing address try { final BusinessPartnerAddress addressToUpdate = createAddressToUpdate(address); response = new DefaultBusinessPartnerService() .updateBusinessPartnerAddress(addressToUpdate) .withHeader("apikey", BackendConnector.getApikey()) .executeRequest(BackendConnector.getDestination()); } catch (ODataResponseException e) { final String message = "OData error " + "updating business partner address."; logger.error(message, e); throw new BusinessPartnerAddressRepository_InternalErrorException( message, e); } } return response.getModifiedEntity(); } private static BusinessPartnerAddress createAddressToUpdate( BusinessPartnerAddress addressFromBody) { final BusinessPartnerAddress addressToUpdate = BusinessPartnerAddress.builder() .businessPartner(addressFromBody.getBusinessPartner()) .addressID(addressFromBody.getAddressID()) .build(); addressToUpdate.setStreetName(addressFromBody.getStreetName()); addressToUpdate.setHouseNumber(addressFromBody.getHouseNumber()); addressToUpdate.setCityName(addressFromBody.getCityName()); addressToUpdate.setPostalCode(addressFromBody.getPostalCode()); addressToUpdate.setCountry(addressFromBody.getCountry()); return addressToUpdate; } static void delete( String businessPartnerId, String addressId) { final BusinessPartnerAddress addressToDelete = BusinessPartnerAddress.builder() .businessPartner(businessPartnerId) .addressID(addressId) .build(); try { new DefaultBusinessPartnerService() .deleteBusinessPartnerAddress(addressToDelete) .withHeader("apikey", BackendConnector.getApikey()) .executeRequest(BackendConnector.getDestination()); } catch (ODataResponseException e) { final String message = "OData error " + "deleting business partner address."; logger.error(message, e); throw new BusinessPartnerAddressRepository_InternalErrorException( message, e); } } }
BusinessPartnerAddressRepository_InternalErrorException.java
is as follows:Code snippetCopy codepackage com.example.adman; public class BusinessPartnerAddressRepository_InternalErrorException extends RuntimeException { BusinessPartnerAddressRepository_InternalErrorException( String message, Throwable cause){ super(message, cause); } }
In SAP Business Application Studio, adjust the run configuration to include the following environment variable definitions (replace >>>YOUR API KEY<<< with your own API Key):
Name Value S4_URL https://sandbox.api.sap.com/s4hanacloud S4_APIKEY >>>YOUR API KEY<<< Choose Run → Open Configurations. The
launch.json
file appears.Modify the Launch Application configuration that was created adding the environment variable definitions. The final configuration will look like the following (replace >>>YOUR API KEY<<< with your own API Key, for example,
FDqbnElM7mgmgqbIKBFHRpS1dvpt6sHD
. To get your API Key, open https://api.sap.com/api/API_BUSINESS_PARTNER, then log on, and choose Show API Key):Copy the entire content of theCode snippetCopy code{ "type": "java", "name": "Launch Application", "request": "launch", "mainClass": "com.example.Application", "projectName": "java-adman-spring-application", "env": { "S4_URL": "https://sandbox.api.sap.com/s4hanacloud", "S4_APIKEY": ">>>YOUR API KEY<<<" } }
java-adman-spring-3-launch-json.txt
file [download] to thelaunch.json
file.Save the
launch.json
file.
Build, run the application and open the Address Manager page.
Choose Terminal → New Terminal
In the terminal run the following command:
The application project is built including the latest changes.Go to the Debug tab, select the Launch Application configuration, choose Start Debugging. After a few seconds a pop-up window advises you that
A service is listening to port 8080.
Choose Open in New Tab. The application is opened on the welcome page. To access the address manager, in the Web browser, edit the application URL and add at the end the following text:
The SAP API Business hub sandbox is accessible in read-only mode, so you cannot modify addresses here.Close the application window, stop the application.
Log on to your SAP S/4HANA Cloud tenant.
In the Web browser (for example, Google Chrome), on your SAP S/4HANA Cloud tenant, access the SAP Fiori Launchpad at
[S/4HANA tenant url]/ui
, for example (https://my000000.s4hana.ondemand.com/ui
). If requested, enter your user and password.
In SAP S/4HANA Cloud, if it is not yet assigned, assign role BR_BUPA_MASTER_SPECIALIST to your user.
In the Home page, choose Search and search for the Maintain Business Users app.
In the app, search for your user and display its details by selecting the line of the list.
In the user detail screen, scroll down and check the Assigned Business Roles section.
If BR_BUPA_MASTER_SPECIALIST is missing from the list, choose Add, search for the BR_BUPA_MASTER_SPECIALIST role, select the box beside it, choose OK, and choose Save.
Select the SAP logo to navigate back to the Home page.
Refresh the Web browser page to see the additional apps provided with the new role.
In SAP S/4HANA Cloud, in the Manage Business Partner Master Data app, create a new business partner based on the following information (replace ### with your user number) if it doesn't already exist:
Field Value Grouping Internal numbering for standard use BP Role CRM000 Sold-to-party First Name John Last Name Doe ### City New York Country US Language EN In the home page, search for and open the Manage Business Partner Master Data app.
Choose Create → Person.
In the Create Person dialog, enter the information provided in the table.
Choose OK
Choose Create.
Select the SAP logo to navigate back to the Home page.
Run the application against your SAP S/4HANA Cloud tenant. Use the following environment variables to configure the connection information (replace ### with your user number):
Name Value S4_URL Your S/4HANA Client tenant URL, for example https://my000000.s4hana.ondemand.com S4_USERNAME ADDRESS_MANAGER_### S4_PASSWORD WelcomeToTheClouds1! Note
As a prerequisite, for this API to be accessible in the S/4HANA Cloud tenant, you need to execute the previous exercise: Activating the APIs in SAP S/4HANA Cloud.In your development environment, in the proper run configuration, replace the old environment variables with the new ones provided. The run configuration will display like the following example:
Code snippetCopy code{ "type": "java", "name": "Launch Application", "request": "launch", "mainClass": "com.example.Application", "projectName": "java-adman-spring-application", "env": { "S4_URL": "https://my000000.s4hana.ondemand.com", "S4_USERNAME": "ADDRESS_MANAGER_###", "S4_PASSWORD": "WelcomeToTheClouds1!" } }
Copy the entire content of the
java-adman-spring-4-launch-json.txt
file [download] to thelaunch.json
file.Go to the Debug tab, select the Launch Application configuration, choose Start Debugging. After a few seconds a pop-up window displays the following:
A service is listening to port 8080.
Choose Open in New Tab. The application is opened on the welcome page. To access the address manager, in the Web browser, edit the application URL and add the following text at the end:
The Address Manager application is opened in read-write mode. Search your John Doe ### business partner and add a new address to it.
Note
If the search feature doesn't work, try to access the business partner using the following suffix in the application URL:Replace 1000000 with your business partner ID.Stop the application.
Deploy the application to Cloud Foundry.
Choose Terminal → New Terminal. A terminal window appears in the lower part of the screen.
if Cloud Foundry CLI login is required, execute the following commands
Enter your SAP BTP API endpoint, e-mail, and password.In the Terminal, run the following commands:
In the SAP BTP Cockpit, in the application, configure the environment variables to run against the SAP API Business Hub Sandbox, then open the application.
In Google Chrome, open the URL https://account.hanatrial.ondemand.com. If required, enter your e-mail and password.
In the SAP BTP Cockpit, choose Enter Your Trial account. Navigate to your trial Subaccount. Navigate to the dev space.
Choose the java-adman-spring application name.
In the Application: java-adman-spring - Overview page, go to the User-Provided Variables tab. Add the following variables (replace >>>YOUR API KEY<<< with your own API Key, for example
FDqbnElM7mgmgqbIKBFHRpS1dvpt6sHD
.To get your API Key, open https://api.sap.com/api/API_BUSINESS_PARTNER, then log on, and choose Show API Key):
Key Value S4_URL https://sandbox.api.sap.com/s4hanacloud/ S4_APIKEY >>>YOUR API KEY<<< Go to the Overview tab.
Restart the application.
Choose the Application Route. The application opens in the Welcome page.
Add
/address-manager/index.html
at the end of the browser URL. The Address Manager application is opened, reading the data from the SAP API Business Hub Sandbox system.
In Cloud Foundry, create an instance of the Destination service named my-destinations if it doesn't exist already.
In the SAP BTP Cockpit, navigate to the trial subaccount, then to the dev space.
In the dev space, navigate to Services → Instances tab.
In the Space:dev - Service Instances screen, Choose Create. Create a new instance based on the following information:
Field Value Service Destination Service Service Plan lite Instance Name my-destinations
Bind the my-destinations service to the java-adman-spring application.
In the SAP BTP Cockpit, navigate to the dev space, then to the java-adman-spring application.
In the Application: java-adman-spring - Overview page, go to the Service Bindings page.
Choose Bind Service.
Select Service from the catalog. Choose Next.
Choose the Destination service. Choose Next.
Choose the Re-use existing instance. Select the my-destinations Instance. Choose Next.
Choose Finish.
In the my-destinations service, in case it doesn't already exist, create a destination named sandbox, referring to the SAP API Business Hub Sandbox.
Return to the main page of the dev space, navigate to Services → Instances page. Choose the my-destinations instance. Click on Manage Instance
Choose the Destinations page.
Chose New Destination create a destination based on the following information:
Field Value Name sandbox Type HTTP Description SAP API Business Hub sandbox system URL https://sandbox.api.sap.com/s4hanacloud Proxy Type Internet Authentication NoAuthentication
Adapt the environment variables of your application so that it reads the system information from the Destination Service. Restart and open the application again.
Navigate to the dev space, then to your application, then to the User-Provided Variables tab.
Delete the S4_URL variable.
Enter a new variable with the S4_DESTINATION name and sandbox value .
Go to the Overview page.
Restart the application.
Choose the Application Route. The application opens in the Welcome page.
Add
/address-manager/index.html
at the end of the browser URL. The Address Manager application is opened, reading the data from the SAP API Business Hub Sandbox system, configured via the sandbox destination in the my-destinations service.
In the my-destinations service, create a destination named s4cloud, referring to your SAP S/4HANA Cloud tenant if it doesn't already exist.
Return to the main page of the dev space, navigate to Services → Instances page. Choose the my-destinations instance. Click on Manage Instance
Choose the Destinations view.
Chose New Destination create a destination based on the following information (replace ### with your user number, replace the URL value with your own SAP S/4HANA Cloud tenant URL):
Field Value Name s4cloud Type HTTP Description SAP S/4HANA Cloud tenant URL Your S/4HANA Client tenant URL, for example https://my000000.s4hana.ondemand.com Proxy Type Internet Authentication BasicAuthentication User ADDRESS_MANAGER_### Password WelcomeToTheClouds1!
Adapt the environment variables of your application so that it reads the s4cloud system information from the Destination service. Restart and open the application again.
Navigate to the dev space, then to your application, then to the User-Provided Variables tab.
Change the value of the S4_DESTINATION variable to s4cloud.
Optionally, delete the S4_APIKEY variable.
Go to the Overview tab.
Restart the application.
Choose Application Route. The application opens on the Welcome page.
Add
/address-manager/index.html
at the end of the browser URL.The Address Manager application is opened, reading the data from your SAP S/4HANA Cloud tenant, configured via the s4cloud destination in the my-destinations service. Search your John Doe ### business partner and add a new address to it.