7

Query Create And Delete Document From BTP Document Management Service In SAPUI5

 1 year ago
source link: https://blogs.sap.com/2022/12/23/query-create-and-delete-document-from-btp-document-management-service-in-sapui5/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
December 23, 2022 5 minute read

Query Create And Delete Document From BTP Document Management Service In SAPUI5

In my blog Download And View PDF document From BTP Document Management Service In SAPUI5.   I have demo how to view PDF document from BTP Document Management Service(BTP CMIS) . But customers need to realize other requirements like query, create and delete documents in BTP CMIS in SAPUI5.  To query documents, we can use cmis query.( Text search base on file content is not supported in BTP CMIS currently) . I will demo the steps to realize these 3 requirements, the readers can realize others requirements like query, create, delete folder also base on CMIS api in API Hub .

Prerequisite:

1, You have installed CF Client .

2, You have installed Nodejs .

3,  You have installed  Cloud MTA Build Tool .

4, You have finished  Initial Setup for Document Management Service, Integration Option.

5, You have finished Onboarding Repository.

6, Destination for CMIS service key has been created as step 1 in  blog .

7, You have installed VSCode (optional).

Steps :

Step 1:  Generate SAPUI5 project with easy-ui5 .

Q01.jpg

Use the following commands to open the project with visual code .

q2.jpg

Step 2:  Change the view MainView.view as the following code:

<mvc:View controllerName="com.sap.cmissearch4.controller.MainView" xmlns:u="sap.ui.unified" xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m">
	<Page id="page" title="{i18n>title}">
		<customHeader>
			<Bar id="bar1">
				<contentLeft>
					<Image id="image1" src="https://unpkg.com/[email protected]/dist/images/sap-logo.png" />
					<Label id="label1" text="BTP CMIS Search" />
				</contentLeft>
			</Bar>
		</customHeader>
		<content>
			<Table id="table1" inset="true" items="{/results}" busy="{viewModel>/isBusy}">
				<columns>
					<Column id="headcolumn1">
						<header>
							<Label id="tablelabel" text="FileName">
							</Label>
						</header>
					</Column>
					<Column id="headcolumn7">
						<header>
							<Label id="tablelabe7" text="objectId">
							</Label>
						</header>
					</Column>
					<Column id="headcolumn2">
						<header>
							<Label id="tablelabel2" text="createdBy">
							</Label>
						</header>
					</Column>
					<Column id="headcolumn3">
						<header>
							<Label id="tablelabel3" text="ObjectTypeId">
							</Label>
						</header>
					</Column>
					<Column id="headcolumn4">
						<header>
							<Label id="tablelabel4" text="Actions">
							</Label>
						</header>
					</Column>
				</columns>
				<items>
					<ColumnListItem id="items">
						<cells>
							<Text id="text1" text="{succinctProperties/cmis:name}" />
							<Text id="text4" text="{succinctProperties/cmis:objectId}" />
							<Text id="text2" text="{succinctProperties/cmis:createdBy}" />
							<Text id="text3" text="{succinctProperties/cmis:objectTypeId}" />
							<HBox id="actionhbox">
								<Button id="buttondelte" icon="sap-icon://delete" press="pressDelete" />
							</HBox>
						</cells>
					</ColumnListItem>
				</items>
				<headerToolbar>
					<Toolbar id="toolbar1">
						<content>
							<Title id="toolbartitle" text="Ducuments" width="25%" />
							<ToolbarSpacer id="toolspace">
							</ToolbarSpacer>
							<Label id="filenamelabel" width="5%" text="FileName" />
							<Input id="filename" width="40%" />
							<Button id="button1" icon="sap-icon://search" width="15%" text="Search" press="pressQuery" />
							<Button id="button2" icon="sap-icon://add" width="15%" text="UploadFile" press="pressCreate" />
						</content>
					</Toolbar>
				</headerToolbar>
			</Table>
		</content>
	</Page>
</mvc:View>

Step 3:  Change the controller MainView.controller.js as the following code:

Note:

4c0973e8-a785-4789-a048-067d42f97873 is the created repository id in prerequisite 5 .
// @ts-nocheck
sap.ui.define(
    ["./BaseController", "sap/m/MessageBox", "sap/ui/model/json/JSONModel", "sap/m/upload/Uploader"],
    /**
     * @param {typeof sap.ui.core.mvc.Controller} Controller
     */
    function (Controller, MessageBox, JSONModel, Uploader) {
        "use strict";

        return Controller.extend("com.sap.cmissearch4.controller.MainView", {
            onInit: function () {
            },
            pressCreate: function (oEvent) {

                this.fileselector().then(file => {
                    var myHeaders = new Headers();
                    var formdata = new FormData();
                    formdata.append("cmisaction", "createDocument");
                    formdata.append("propertyId[0]", "cmis:name");
                    formdata.append("propertyValue[0]", file.name);
                    formdata.append("propertyId[1]", "cmis:objectTypeId");
                    formdata.append("propertyValue[1]", "cmis:document");
                    formdata.append("filename", file.name);
                    formdata.append("_charset", "UTF-8");
                    formdata.append("includeAllowableActions", "False");
                    formdata.append("succinct", "true");
                    formdata.append("media", file, file.name);

                    var requestOptions = {
                        method: 'POST',
                        headers: myHeaders,
                        body: formdata,
                        redirect: 'follow'
                    };

                    fetch("/sdi/browser/4c0973e8-a785-4789-a048-067d42f97873/root", requestOptions)
                        .then(response => response.text())
                        .then(result => {
                            MessageBox.information("File uploaded successfully!");
                            console.log(result);
                            this.pressQuery();

                        }).catch(error => {
                            MessageBox.information(JSON.stringify(error));

                            console.log('error', error)
                        });

                });

            },

            pressQuery: function () {
                var querystate = "";
                var filename = this.byId("filename").getValue();
                if (filename) {
                    querystate = "select * from cmis:document".concat(" where cmis:name = \'").concat(filename).concat("\'");
                } else { querystate = "select * from cmis:document"; }

                var myHeaders = new Headers();
                myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
                var urlencoded = new URLSearchParams();
                urlencoded.append("cmisaction", "query");
                urlencoded.append("succinct", "true");
                urlencoded.append("statement", querystate);
                var requestOptions = {
                    method: 'POST',
                    headers: myHeaders,
                    body: urlencoded,
                    redirect: 'follow'
                };
                fetch("/sdi/browser/4c0973e8-a785-4789-a048-067d42f97873", requestOptions)
                    .then(response => response.json())
                    .then(result => {
                        this.byId("table1").setModel(new JSONModel(result));
                    })
                    .catch(error => console.log('error', error));
            },
            pressDelete: function (oEvent) {
                var oModel = this.byId("table1").getModel();
                // console.log(oModel);
                var filePath = oEvent.getSource().getBindingContext().getPath();

                var objId = oModel.getProperty(filePath).succinctProperties['cmis:objectId'];
                console.log(objId);
                var myHeaders = new Headers();
                myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
                var urlencoded = new URLSearchParams();
                urlencoded.append("cmisaction", "delete");
                urlencoded.append("objectId", objId);
                urlencoded.append("allVersions", "true");

                var requestOptions = {
                    method: 'POST',
                    headers: myHeaders,
                    body: urlencoded,
                    redirect: 'follow'
                };

                fetch("/sdi/browser/4c0973e8-a785-4789-a048-067d42f97873/root", requestOptions)
                    .then(response => response.text())
                    .then(result => {
                        MessageBox.information("Object ".concat(result.trim()).concat(" deleted"));
                        console.log(typeof (result));

                    })
                    .catch(error => console.log('error', error));

            },
            fileselector: function popFileSelector() {
                return new Promise((resolve, reject) => {
                    let input = document.createElement('input');
                    input.value = 'Please select file';
                    input.type = 'file';
                    input.onchange = event => {
                        let file = event.target.files[0];
                        resolve(file);
                    };
                    input.click();
                });
            }
        });
    }
);

Step 4:  Add router in xs-app.json under folder approuter .

{
  "welcomeFile": "uimodule/index.html",
  "authenticationMethod": "none",
  "logout": {
    "logoutEndpoint": "/do/logout"
  },
  "routes": [

    {
      "source": "^/sdi/(.*)$",
      "target": "$1",
      "authenticationType": "xsuaa",
      "destination": "sdi"  //destination name created CMIS service key
    },
    {
      "source": "^/uimodule/(.*)$",
      "target": "$1",
      "authenticationType": "none",
      "localDir": "uimodule/webapp"
    }
  ]
}

Step 5:  Build and deploy the application to BTP cloud foundry runtime with following 3 command.

mbt build

cf login

cf deploy mta_archives/cmissearch4_0.0.1.mtar

q3-1.jpg

Step 6:  Test the deployed application in BTP cloud foundry runtime

q4-scaled.jpg
q5-scaled.jpg
q6-scaled.jpg
q7-scaled.jpg
q8-scaled.jpg
q9-scaled.jpg

The ends!

Thanks for your time!

Best Regards!

Jacky Liu


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK