0

CallOut Method:

public static void callout(String jsonString, String jsonStringWS, List lstId){ //do callout here rest or soap

    System.debug('jsonString>:'+jsonString);
    System.debug('jsonStringWS>:'+jsonStringWS);
    System.debug('lstId>:'+lstId);

    List<Contentversion> documentLst = new List<Contentversion>([Select Id, Title,VersionData,PathOnClient,ContentDocumentId,FileType,FileExtension,CreatedById from ContentVersion where ContentDocumentId IN: lstId]);
    //List<Contentversion> documentLst = New List<Contentversion>([Select Id, Title,VersionData,PathOnClient,ContentDocumentId,FileType,FileExtension,CreatedById from ContentVersion where Id='0680Q000000N5TeQAK']); //where Id='0680Q000000N5TeQAK'

    List<MIDAS_Workspace__c> workspaceLst = (List<MIDAS_Workspace__c>)JSON.deSerialize(jsonStringWS,List<MIDAS_Workspace__c>.class);
    //List<ContentVersion> documentLst = (List<ContentVersion>)JSON.deSerialize(jsonString,List<ContentVersion>.class);
    //ContentVersion documentLst = (ContentVersion)JSON.deSerialize(contentVersionOj,ContentVersion.class);

    String workspaceId = workspaceLst[0].Workspace__c;
    //System.debug('-->LegalId'+workspaceId);
    System.Debug('**'+workspaceLst);

    List<String> lstHtmlBody = new List<String>();
    lstDocStatus = new List<String>();
    for(Integer i=0;i<documentLst.size();i++){
        Contentversion doc1 = documentLst[i];
        String DocumentName = documentLst[i].Title;
        System.Debug('Title>:'+documentLst[i].Title);
        System.Debug('FileType>:'+documentLst[i].FileType);
        System.Debug('FileExtension>:'+documentLst[i].FileExtension);

        for(Integer j=0;j<workspaceLst.size();j++){

            //System.Debug('**LstDoc'+documentLst[i]);
            System.Debug('**Workspace12'+workspaceLst[j]);
            //System.debug('-->DocLst'+doccontentVersionOj.VersionData);

            //Contentversion doc1 = [Select Id, Title,VersionData,PathOnClient,ContentDocumentId,FileType,CreatedById from ContentVersion where Id =: contentVerId];
            String targetURL = 'https://0aade-dmobility.imanage.work/api/v1/folders/'+workspaceLst[j].Workspace__c+'/documents';
            //System.debug('doc1.VersionData>:'+doc1.VersionData);

            final String boundary = '---------------BOUNDARY_STRING';

            //String loginToken = getLoginToken1();
            String loginToken = MSOP_iManage_Service.getLoginToken();
            System.debug('-->'+loginToken);
            String body = '';     
            body+=(CRLF); 

            //String first =  addSimpleFormData('name', '{"doc_profile":{"name": "'+doc1.title+'","extension":"'+doc1.FileType+'"}}', boundary);
            string first = '';
            String paramName = 'name';
            String fileExtension = doc1.FileExtension;
            //fileExtension = 'txt'; //hardcoded
            String wert = '{"doc_profile":{"name": "'+doc1.title+'","extension":"'+fileExtension+'"}}';
            first+=('--')+boundary+(CRLF);  
            first+=('Content-Disposition: form-data; name="' + paramName + '"')+(CRLF);
            first+=('Content-Type: application/json; charset=' + CHARSET)+(CRLF);  
            first+=(CRLF);
            first+=wert+(CRLF);

            body+=first; 

            //String second = addFileData('file', DocumentName, EncodingUtil.base64Encode(doc1.VersionData), boundary);
            String second = ''; 
            paramName = 'file';
            //String contentType = 'text/plain';
            String contentType = '';
            if(fileExtension !=null && fileExtension.contains('txt')){
                contentType = 'text/plain';
            }else if(fileExtension !=null && fileExtension.contains('xls')){
                contentType = 'application/vnd.ms-excel';
                System.debug('contentType of ExcelSheet:'+contentType);
            }else if(fileExtension !=null && fileExtension.contains('xlsx')){
                contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
                System.debug('contentType of ExcelSheet:'+contentType);
            }else if(fileExtension !=null && fileExtension.contains('docx')){
                //contentType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
                contentType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.template';
                //contentType = 'application/vnd.google-apps.document';
                System.debug('contentType of DcoumentX:'+contentType);
            }else if(fileExtension !=null && fileExtension.contains('doc')){
                //contentType = 'application/msword';
                contentType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.template';
                //contentType = 'application/vnd.google-apps.document';
                System.debug('contentType of WorkDcoument:'+contentType);
            }else if(fileExtension !=null && fileExtension.contains('pdf')){
                contentType = 'application/pdf';
                System.debug('contentType of Pdf:'+contentType);
            }else if(fileExtension !=null && fileExtension.contains('zip')){
                contentType = 'application/x-zip-compressed';
                System.debug('contentType of Zip:'+contentType);
            }else if(fileExtension !=null && fileExtension.contains('jpg')){
                contentType = 'image/jpeg';
                System.debug('contentType of jpg:'+contentType);

            }else {
                contentType = 'application/octet-stream';
            }


            String filename = DocumentName;
            second+=('--')+boundary+(CRLF);
            second+=('Content-Disposition: form-data; name="' + paramName + '"; filename="' + filename + '"')+(CRLF);
            //second+=('Content-Type: application/octet-stream')+(CRLF);
            //second+=('Content-Type: text/plain')+(CRLF);
            second+='Content-Type: '+contentType+(CRLF);  
            second+=('Content-Transfer-Encoding: binary')+(CRLF); 
            second+=(CRLF);

            //New code for trial2
            body+=second;
            String header = body;
            // no trailing padding on header by adding ' ' before the last "\n\n" characters
            String headerEncoded = EncodingUtil.base64Encode(Blob.valueOf(header+'\n\n'));
            //this ensures no trailing "=" padding
            while(headerEncoded.endsWith('='))
            {
                header+=' ';
                headerEncoded = EncodingUtil.base64Encode(Blob.valueOf(header+'\n\n'));
            }
            System.debug('headerEncoded-->'+headerEncoded);

            String bodyEncoded = EncodingUtil.base64Encode(doc1.VersionData); //Body Encoded
            body+=bodyEncoded; //not needed this
            body+=(CRLF);
            System.debug('bodyEncoded--> :'+ bodyEncoded);

            //String third = addCloseDelimiter(boundary);
            String footer = '';
            footer+=(CRLF); //newly added
            //footer+=('--')+boundary+('--')+(CRLF);
            footer+=('--')+boundary+('--');
            String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer)); //Body Encoded
            System.debug('footerEncoded--> :'+ footerEncoded);

            Blob bodyBlob = null;
            //last encoded body bytes
            String last4Bytes = bodyEncoded.substring(bodyEncoded.length()-4,bodyEncoded.length());
            //if the last 4 bytes encoded base64 ends with the padding character (= or ==) then re-encode those bytes with the footer
            //to ensure the padding is added only at the end of the body
            if(last4Bytes.endsWith('='))
            {
                Blob decoded4Bytes = EncodingUtil.base64Decode(last4Bytes);
                HttpRequest tmp = new HttpRequest();
                tmp.setBodyAsBlob(decoded4Bytes);
                String last4BytesFooter = tmp.getBody()+footer;   
                bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded.substring(0,bodyEncoded.length()-4)+EncodingUtil.base64Encode(Blob.valueOf(last4BytesFooter)));
            }
            else
            {
                bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded+footerEncoded);
            }

            body+=footer; 
            //System.debug('Body Before POST:'+body);
            //System.debug('bodyBlob--> :'+ bodyBlob);

            // create request object
            try{
                HttpRequest req = new HttpRequest();
                req.setEndpoint(targetURL);
                req.setHeader('x-auth-token', loginToken);
                req.setHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
                req.setMethod('POST');    
               // req.setHeader('Content-Transfer-Encoding'+'base64');      
                //set the body created through formatting to request object.. this is a key to this functionality.
                //req.setBody(body);
                req.setBodyAsBlob(bodyBlob);
                System.debug('Final Request Body--> :'+req.getBody());

                Http http = new Http();   
                HTTPResponse res;   
                res = http.send(req); 
                System.debug('response getBody>:'+res.getBody());
                System.debug('response status>:'+res.getStatus());
                if(res.getStatus() == '201' || res.getStatus() == 'Created'){
                    statusFile = 'Success';
                    String statusFile1 = 'Doc Id:<br/>'+doc1.Id+'Status Of Document:<br/>'+statusFile;
                    lstDocStatus.add(statusFile1);
                    System.debug('**Status Success or Not:'+statusFile);
                }else{
                    statusFile = 'Fail';
                    System.debug('**Status Failure or Not:'+statusFile);
                    String statusFile1 = 'Doc Id:<br/>'+doc1.Id+'Status Of Document:<br/>'+statusFile;
                    lstDocStatus.add(statusFile1);

                }
                Workspace wrapper=parseResponse(res.getBody());

                String iwl  = wrapper.data.iwl;
                String iwl1 = 'https://0aade-dmobility.imanage.work/lib/Legal!';
                String iw = 'https://0aade-dmobility.imanage.work/work/web/r/libraries/Legal/folders/'+workspaceLst[j].Workspace__c+'?selectedItem=';
                String[] iwl2 = iwl.split('&&');
                String docnumber = iwl2[2].split('=').get(1);
                System.debug('-->Document url number'+docnumber);
                String docversion = iwl2[3].split('=').get(1);
                System.debug('-->Document version number'+docversion);

                iw +=  docnumber+'.1';

                String HtmlBody = 'Uploaded file details into Midas.<br/><br/>'+'Name of the Document:<br/>'+'<b>'+doc1.Title+'</b>'+'<br/><br/>Workspace and Folder Name:<br/>'+'<b>'+wrapper.data.location+'</b>'+'<br/><br/>Hyper link to navigate into Midas:<br/>'+'<b> <a href='+iw+'>click here</a></b>';
                System.debug(HtmlBody);
                lstHtmlBody.add(HtmlBody);
                System.debug('-->List of HTML :'+lstHtmlBody); 
            }catch(Exception e){
                // ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error while uploading file in MIDAS'));

                system.debug('Error while uploading file in MIDAS');
            }

        }

marked as duplicate by Pranay Jaiswal, David Reed Apr 5 at 11:17

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

Browse other questions tagged or ask your own question.