GithubHelp home page GithubHelp logo

kikovalle / plgsharepointrestapi-java Goto Github PK

View Code? Open in Web Editor NEW
38.0 38.0 30.0 181 KB

Easy to use wrapper for the Sharepoint Rest API v1. Even if this is not a full implementation it covers most common use cases and provides examples to extending this API.

License: MIT License

Java 100.00%

plgsharepointrestapi-java's People

Contributors

dependabot[bot] avatar kikovalle avatar vnashkev avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

plgsharepointrestapi-java's Issues

SEVERE: Initialization failed!! Please check the user, pass, domain and spSiteUri parameters you provided

Hi,

I am getting this following error when trying to run this program. I checked all parameter and they are valid.

Request Entity is fine. But reponse entity is having this message due to which securityToken.indexOf(clave1) is failing with java.lang.StringIndexOutOfBoundsException: String index out of range: -1.

This is the content of ResponseEntity & SecurityToken values.

Let me know what am I missing.

responseEntity:
<200,<S:Envelope xmlns:wsa="http://www.w3.org/2005/08/addressing" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:wst="http://schemas.xmlsoap.org/ws/2005/02/trust" xmlns:S="http://www.w3.org/2003/05/soap-envelope"><S:Header><psf:pp xmlns:psf="http://schemas.microsoft.com/Passport/SoapServices/SOAPFault">psf:serverVersion1</psf:serverVersion>psf:authstate0x80048800</psf:authstate>psf:reqstatus0x80048821</psf:reqstatus><psf:serverInfo ServerTime="2020-07-22T08:06:13.9354531Z">PROD-DUB2-010.ProdSlices rid:1203662d-bed0-4d8b-b377-a9f80f0f4c00</psf:serverInfo></psf:pp></S:Header><S:Body xmlns:S="http://www.w3.org/2003/05/soap-envelope"><S:Fault><S:Code><S:Value>S:Sender</S:Value><S:Subcode><S:Value>wst:FailedAuthentication</S:Value></S:Subcode></S:Code><S:Reason><S:Text xml:lang="en-US">Authentication Failure</S:Text></S:Reason><S:Detail><psf:error xmlns:psf="http://schemas.microsoft.com/Passport/SoapServices/SOAPFault">psf:value0x80048821</psf:value>psf:internalerrorpsf:code0x80048821</psf:code>psf:textAADSTS50126: Error validating credentials due to invalid username or password.</psf:text></psf:internalerror></psf:error></S:Detail></S:Fault></S:Body></S:Envelope>,[Cache-Control:"no-cache, no-store", Pragma:"no-cache", Content-Type:"application/soap+xml; charset=utf-8", Expires:"-1", Strict-Transport-Security:"max-age=31536000; includeSubDomains", X-Content-Type-Options:"nosniff", x-ms-request-id:"1203662d-bed0-4d8b-b377-a9f80f0f4c00", x-ms-ests-server:"2.1.10858.13 - DUB2 ProdSlices", P3P:"CP="DSP CUR OTPi IND OTRi ONL FIN"", Set-Cookie:"fpc=AlR-_K_q869GqDCmaMqrM9aApSWjAQAAAHTqqdYOAAAA; expires=Fri, 21-Aug-2020 08:06:13 GMT; path=/; secure; HttpOnly; SameSite=None", "x-ms-gateway-slice=prod; path=/; SameSite=None; secure; HttpOnly", "stsservicecookie=ests; path=/; SameSite=None; secure; HttpOnly", Date:"Wed, 22 Jul 2020 08:06:13 GMT", Content-Length:"1430"]>

Security Token:

10x800488000x80048821PROD-DUB2-010.ProdSlices rid:1203662d-bed0-4d8b-b377-a9f80f0f4c00S:Senderwst:FailedAuthentication**Authentication Failure**0x800488210x80048821**AADSTS50126: Error validating credentials due to invalid username or password.**

'folder' parameter to 'uploadFile' method

Kiko,

Suponiendo un dominio XYZ.sharepoint.com, un 'site' ABCDE, con mi usuario [email protected] contraseña ******, he sido capaz de subir manualmente (desde web) un documento a la ruta 'Documentos/General/INFO-Backup'. Tal como muestra la siguiente imagen:

image

Sin embargo, no he sido capaz de subir un documento programáticamente. Recibiendo un 403 forbidden.

result = wrapper.uploadFile("/sites/ABCDE/Documentos/General/INFO-Backup/", resource, metadata); //403 Forbidden

¿Sabes si es que estoy pasando mal el parámetro 'folder', o si debo llevar a cabo alguna acción de configuración/permisos desde la web?

De los logs extraje:

POST request for "https://XYZ.sharepoint.com/sites/ABCDE/_api/web/GetFolderByServerRelativeUrl('/sites/ABCDE/Documentos/General/INFO-Backup/')/Files/add(url='TEST.txt',overwrite=true)" resulted in 403 (Forbidden); invoking error handler

Gracias de antemano!

Invalid mime type "application": does not contain '/'

Dear @kikovalle,

I'm trying to download the bytes of a CSV file from a Sharepoint 2013 and I'm using PLGSharepointOnPremisesClient#downloadFile

I'm using the serverRelativeUrl which works when accessing it from the browser.

When using the call above, I receive this exception:

org.springframework.http.InvalidMediaTypeException: Invalid mime type "application": does not contain '/'
	at org.springframework.http.MediaType.parseMediaType(MediaType.java:620)
	at org.springframework.http.HttpHeaders.getContentType(HttpHeaders.java:992)
	at org.springframework.web.client.HttpMessageConverterExtractor.getContentType(HttpMessageConverterExtractor.java:136)
	at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:93)
	at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:1037)
	at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:1020)
	at com.panxoloto.sharepoint.rest.StreamRestTemplate$StreamResponseExtractor.extractData(StreamRestTemplate.java:163)
	at com.panxoloto.sharepoint.rest.StreamRestTemplate$StreamResponseExtractor.extractData(StreamRestTemplate.java:145)
	at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:778)
	at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:751)
	at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:621)
	at com.panxoloto.sharepoint.rest.PLGSharepointOnPremisesClient.downloadFile(PLGSharepointOnPremisesClient.java:430)

I've tried to submit "Accept: application/octet-stream" or omit sending the Accept header like here https://docs.microsoft.com/en-us/sharepoint/dev/sp-add-ins/working-with-folders-and-files-with-rest but this doesn't help.

Do you have experiences with that?

On-Premise Create Folder issue

Hi,

When trying to use the createFolder function in teh wrapper for a sharepoint on-premise site. I saw that the function as it stands was causing a 400 error to come back saying bad format or something along those lines.

I did some research and found on the microsoft site (https://docs.microsoft.com/en-us/sharepoint/dev/sp-add-ins/working-with-folders-and-files-with-rest) how a create folder example should work. I compared this to the PLGSharepointOnPremisesClient class and noticed 2 changes that needed to happen.

1st. instead of
RequestEntity<String> requestEntity = new RequestEntity<>(payloadStr, headers, HttpMethod.POST, this.tokenHelper.getSharepointSiteUrl("/_api/web/GetFolderByServerRelativeUrl('" + baseFolderRemoteRelativeUrl + "')/folders"));

we need it to be
RequestEntity<String> requestEntity = new RequestEntity<>(payloadStr, headers, HttpMethod.POST, this.tokenHelper.getSharepointSiteUrl("/_api/web/folders") );
The 2nd change could be done either in the class or in the calling function.
But i noticed the payload object itself was also causing issues it looks like and when i passed a null payload to the createFolder function the logic you have in place properly generates a new payload. So either updating createFodler to not take in a payload or updating your readme example to pass a null payload should work.

After doing that i was able to get a folder created on my sharepoint site.

Hope this helps

AuthenticationException

I am trying to do "Get lists of a site" by using your code sample in README.md
I am getting AuthenticationException at AuthenticationResponseParser.java:40.

Thank you for your help.
-R kumar

Customize Type for multi choice Fields

I have a document list with a metadatafield, which is configured as Multi choise field. In this case, it is important to set the correct type.

I have to set the type like this:
{"ContractpartnerId":{"results":[2]},"__metadata":{"type":"SP.Data.MyContractItem"}}

If it is set to SP.ListItem, I received the error message:
{ "error": { "code": "-1, Microsoft.SharePoint.Client.InvalidClientQueryException", "message": { "lang": "en-US", "value": "An open collection property 'ContractpartnerId' was found. In OData, open collection properties are not supported." } } }

Is it possible, to set the type optionally to a custom type if required?

Currently, it seems to be hard coded.
UploadFile Function

Maybe just change it to:
if(!jsonMetadata.has("__metadata")){ JSONObject submeta = new JSONObject(); submeta.put("type", "SP.ListItem"); jsonMetadata.put("__metadata", submeta); }

Office 365 403

Hi!

Thank you for your work! I'm using office365 account and when I try to create folder or upload file I get 403 code as response. And GET methods give me 500 error.

Upload of large file fails with 400 Bad Request

Hey,
thanks for the great api! Listing files, downloading files or uploading small files works fine but I'm facing issue with larger files.
200 MB works fine, but the upload with
410 MB fails with with error message 400 Bad Request

I don't think it's a timeout as the response is returned after only 18 seconds.

Am I missing something? Maybe a property in the header?
I am grateful for all answers. Thanks in advance.

Below you can find the full stacktrace:

2021-11-08 15:45:34 DEBUG PLGSharepointClientOnline:454 - Uploading file 1636386334667my-test.zip to folder /sites/mysite/Shared Documents/test folder/
2021-11-08 15:45:34 DEBUG StreamRestTemplate:147 - HTTP POST https://myurl.com/sites/mysite/_api/web/GetFolderByServerRelativeUrl('/sites/mysite/Shared%20Documents/test%20folder/')/Files/add(url='1636386334667my-test.zip',overwrite=true)
2021-11-08 15:45:34 DEBUG StreamRestTemplate:147 - Accept=[text/plain, application/json, application/*+json, */*]
2021-11-08 15:45:34 DEBUG StreamRestTemplate:147 - Writing [file [/data/jenkins_dev/workspace/DBU_Test_Job/my-test.zip]] as "application/json;odata=verbose"
2021-11-08 15:45:52 DEBUG StreamRestTemplate:147 - Response 400 BAD_REQUEST
org.springframework.web.client.HttpClientErrorException$BadRequest: 400 Bad Request
	at org.springframework.web.client.HttpClientErrorException.create(HttpClientErrorException.java:79)
	at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:122)
	at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:102)
	at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63)
	at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:778)
	at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:736)
	at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:637)
	at com.panxoloto.sharepoint.rest.PLGSharepointClientOnline.uploadFile(PLGSharepointClientOnline.java:471)
	at sharepoint.api.SharepointAPI.uploadFile(SharepointAPI.java:66)
	at sharepoint.api.SharepointAPI.main(SharepointAPI.java:39)

403 Forbidden. Posibilidad de evitar conexión pasando por _api/contextinfo

Buenas,

Me falla la conexión a determinado dominio (https://company-z.sharepoint.com/) en el método getFormDigestValue de la clase AuthTokenHelperOnline.

Concretamente en la línea siguiente.
ResponseEntity<String> responseEntity = restTemplate.exchange(requestEntity, String.class);

Falla con un 403 Forbidden.

Y en las trazas:
"{"error":{"code":"-2147024891, System.UnauthorizedAccessException","message":{"lang":"en-US","value":"Attempted to perform an unauthorized operation."}}}

¿Hay alguna forma de intentar conectar sin pasar por https://company-z.sharepoint.com/_api/contextinfo? (ya que es donde parece que falla)
¿O algún otro “truco”? … ¿o seteo de cabeceras o algo así?

Gracias y un saludo

403 Forbidden: Before opening files in this location, you must first browse the website and select the option to login automatically

First of all, love this project, it might save my currrent internship, really, thanks a lot for doing this.
Secondly: I'm having no problem fetching lists or info about a file or whatnot, but whe I try to download a file, I always get the same error: 403 Forbidden: "{"error":{"code":"-2147024891, System.UnauthorizedAccessException","message":{"lang":"en-US","value":"Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))"}}}", and when Itried to read the logs, I saw this: 1583 [main] DEBUG org.apache.http.headers - http-outgoing-1 << X-MSDAVEXT_Error: 917656; Access+denied.+Before+opening+files+in+this+location%2c+you+must+first+browse+to+the+web+site+and+select+the+option+to+login+automatically.
I tried searching for something like that on the internet, but all I could find was advices on using IE or somehow manipulating your registry. Would you know how to fix this ?

My code:

String folder = "/sites/{site_name}/{path to folder}";
String fileName = "myFile.aspx";
wrapper.getFileInfo(folder + "/" + fileName);
wrapper.downloadFile(folder + "/" + fileName); // Error there

400 Bad request issue

Hey!
Great work, thanks a lot.

When I try to create a new folder/upload a file below mentioned error is thrown

org.springframework.web.client.HttpClientErrorException: 400 Bad Request at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91) at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:667) at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:620) at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:595) at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:557) at com.demo.SharePointTestClient.createFolder(SharePointTestClient.java:124) at com.demo.web.SpdemoController.doGet(SpdemoController.java:29) at javax.servlet.http.HttpServlet.service(HttpServlet.java:626) at javax.servlet.http.HttpServlet.service(HttpServlet.java:733) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:543) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:615) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:818) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1626) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.base/java.lang.Thread.run(Thread.java:832)

reqstatus=0x8004882c errorstatus=0x80045b00 when authenticating

Hi,

I've got the typical simple cmd line client for accessing the company Sharepoint which is secured by the company AD:

import org.json.JSONObject;
import com.panxoloto.sharepoint.rest.PLGSharepointClient;
import com.panxoloto.sharepoint.rest.PLGSharepointClientOnline;

public class SharepointDownloader {
    public static void main(String[] args) throws Exception {
        String user = "domain\\username";
        String passwd = "password";
        String domain = "company.sharepoint.com";
        String spSiteUrl = "/sites/asite";

        PLGSharepointClient wrapper = new PLGSharepointClientOnline(user, passwd, domain, spSiteUrl);
        JSONObject result = wrapper.getAllLists("{}");
        System.out.println(result);
    }
}

and I always get the above error codes

<?xml version="1.0" encoding="utf-8"?> <S:Envelope xmlns:wsa="http://www.w3.org/2005/08/addressing" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:wst="http://schemas.xmlsoap.org/ws/2005/02/trust" xmlns:S="http://www.w3.org/2003/05/soap-envelope"> <S:Header> <wsa:Action S:mustUnderstand="1" wsu:Id="Action">http://schemas.xmlsoap.org/ws/2005/02/trust/RSTR/Issue</wsa:Action> <wsa:To S:mustUnderstand="1" wsu:Id="To">http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:To> <wsse:Security S:mustUnderstand="1"> <wsu:Timestamp wsu:Id="TS" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"> <wsu:Created>2021-08-20T13:24:48.331086Z</wsu:Created> <wsu:Expires>2021-08-20T13:29:48.331086Z</wsu:Expires> </wsu:Timestamp> </wsse:Security> </S:Header> <S:Body xmlns:S="http://www.w3.org/2003/05/soap-envelope"> <wst:RequestSecurityTokenResponse xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:wst="http://schemas.xmlsoap.org/ws/2005/02/trust"> <wsp:AppliesTo> <wsa:EndpointReference xmlns:wsa="http://www.w3.org/2005/08/addressing"> <wsa:Address>company.sharepoint.com</wsa:Address> </wsa:EndpointReference> </wsp:AppliesTo> <psf:pp xmlns:psf="http://schemas.microsoft.com/Passport/SoapServices/SOAPFault"> <psf:reqstatus>0x8004882c</psf:reqstatus> <psf:errorstatus>0x80045b00</psf:errorstatus> </psf:pp> </wst:RequestSecurityTokenResponse> </S:Body> </S:Envelope>

All I found was this Stackoverflow article https://stackoverflow.com/questions/59320628/unable-to-get-access-token-from-sharepoint

Is there a problem when accessing with AD accounts?

Gradle

How to add it to an android project?

Usage question

Hallo,
First of all thank you for the lib. It makes pleasure working with it.

Some methods have a parameter [String jsonExtendedAttrs].
public JSONObject getFolderByRelativeUrl(String folder, String jsonExtendedAttrs).

What is purpose of this parameter?
Some usage examples would be very helpful.

Thank you in advance,
Vitali

Connection timeout

Hi Kikovalle,

First of all, thanks heap for sharing your API. It's a big help for us.

I created a Java executable with your API, which basically copies binary files from a Linux server and uploads to the designated SharePoint directory. A shell batch script calls the Java executable a daily base.

It worked as expected when I ran the shell script from my work laptop (windows 10) for testing.
It uploaded the files in my laptop to the SharePoint directory.

However, I got the connection timeout error as below when I ran the shell script from a linux server.
I used the same files in the directory in the Linux server.

[main] ERROR xxx.xxx.xx.ict.sharepointupload.UploadFile - I/O error on POST request for https://login.microsoftonline.com/extSTS.srf: Connect to login.microsoftonline.com:443 [login.microsoftonline.com/xx.xxx.14.163, login.microsoftonline.com/xx.xxx.142.166, login.microsoftonline.com/xx.xxx.142.165, login.microsoftonline.com/xx.xxx.142.164, login.microsoftonline.com/xx.xxx.14.162, login.microsoftonline.com/xx.xxx.142.167, login.microsoftonline.com/xx.xxx.14.160, login.microsoftonline.com/xx.xxx.14.164] failed: Connection timed out (Connection timed out); nested exception is org.apache.http.conn.HttpHostConnectException: Connect to login.microsoftonline.com:443 [login.microsoftonline.com/xx.xxx.14.163, login.microsoftonline.com/xx.xxx.142.166, login.microsoftonline.com/xx.xxx.142.165, login.microsoftonline.com/xx.xxx.142.164, login.microsoftonline.com/xx.xxx.14.162, login.microsoftonline.com/xx.xxx.142.167, login.microsoftonline.com/xx.xxx.14.160, login.microsoftonline.com/xx.xxx.14.164] failed: Connection timed out (Connection timed out)

can you please shed some light on this error?

#403 UnauthorizedAccessException

The user account I'm using is the Owner of a group named veninvTest, which has a library named Invoices. I'm using the following code to upload a .pdf file to this folder:

import org.json.JSONObject;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import com.panxoloto.sharepoint.rest.*;

public class fileUpload {
public static void main(String args[]) throws Exception {
	String user = "user";
	String passwd = "password";
	String domain = "company.sharepoint.com";
	String spSiteUrl = "/sites/veninvTest";
	
	// Initialize the API
	PLGSharepointClient wrapper = new PLGSharepointClient(user, passwd, domain, spSiteUrl);

	String folder = "sites/veninvTest/Invoices";
        JSONObject jsonMetadata = new JSONObject();
	Resource resource = new ClassPathResource("invoice_637309551232273978.pdf");
        wrapper.uploadFile(folder, resource, jsonMetadata);
	}
}

When I run this, I receive the following error:

Exception in thread "main" org.springframework.web.client.HttpClientErrorException$Forbidden: 403 Forbidden: [{"error":{"code":"-2147024891, System.UnauthorizedAccessException","message":{"lang":"en-US","value":"Access denied. You do not have permission to perform this action or access this resource."}}}]
	at org.springframework.web.client.HttpClientErrorException.create(HttpClientErrorException.java:109)
	at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:184)
	at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:125)
	at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63)
	at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:782)
	at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:740)
	at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:641)
	at com.panxoloto.sharepoint.rest.PLGSharepointClient.uploadFile(PLGSharepointClient.java:324)
	at util.fileUpload.main(fileUpload.java:23)

The user has Full Access permissions for this site and is a Site Collection Administrator. Is there anything I'm doing wrong in my program that could cause this error?

Authentification Failure while trying to login with userID and password (2 factor authentification) issue?

Hey kikovalle,

I've checked my Sharepoint Mail-Address and my Sharepoint Domain, but I still get an authentification failure exception when I'm trying to create your wrapper PLGSharepointClientOnline.

I just provided my password additionally. Nothing works. I've checked for several hours.

When I was trying to Logout from Sharepoint and Login again with that userID and that Domain I've was asked for a second factor authentification via my smartphone. Is this the reason, why your wrapper ist not working? Do you have an suggestion what workaround will work? Do I need a technical user without 2FA?

Thank you so much. I wish you best!

Benedikt

File Upload

Can you please tell how to create resource object?
public JSONObject uploadFile(String folder, Resource resource, JSONObject jsonMetadata, File file) throws Exception

I tried creating a new resource object passing file path, file name. Not working.

Multi-factor authentication issue

Hi, when running my program I'm receiving the following error:

[main] ERROR com.panxoloto.sharepoint.rest.PLGSharepointClient - Initialization failed!! Please check the user, pass, domain and spSiteUri parameters you provided

with the following value for responseEntity:

<200,<?xml version="1.0" encoding="utf-8"?><S:Envelope xmlns:wsa="http://www.w3.org/2005/08/addressing" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:wst="http://schemas.xmlsoap.org/ws/2005/02/trust" xmlns:S="http://www.w3.org/2003/05/soap-envelope"><S:Header><psf:pp xmlns:psf="http://schemas.microsoft.com/Passport/SoapServices/SOAPFault"><psf:serverVersion>1</psf:serverVersion><psf:authstate>0x80048800</psf:authstate><psf:reqstatus>0x800434d4</psf:reqstatus><psf:serverInfo ServerTime="2020-08-24T20:45:06.2266655Z">PROD-SAN-012.ProdSlices rid:9a469a67-57dc-4f63-8c32-94a07e9d9f00</psf:serverInfo></psf:pp></S:Header><S:Body xmlns:S="http://www.w3.org/2003/05/soap-envelope"><S:Fault><S:Code><S:Value>S:Sender</S:Value><S:Subcode><S:Value>wst:FailedAuthentication</S:Value></S:Subcode></S:Code><S:Reason><S:Text xml:lang="en-US">Authentication Failure</S:Text></S:Reason><S:Detail><psf:error xmlns:psf="http://schemas.microsoft.com/Passport/SoapServices/SOAPFault"><psf:value>0x800434D4</psf:value><psf:internalerror><psf:code>0x800434D4</psf:code><psf:text>AADSTS50076: Due to a configuration change made by your administrator, or because you moved to a new location, you must use multi-factor authentication to access ''.</psf:text></psf:internalerror></psf:error></S:Detail></S:Fault></S:Body></S:Envelope>,[Cache-Control:"no-store, no-cache", Pragma:"no-cache", Content-Type:"application/soap+xml; charset=utf-8", Expires:"-1", Strict-Transport-Security:"max-age=31536000; includeSubDomains", X-Content-Type-Options:"nosniff", P3P:"CP="DSP CUR OTPi IND OTRi ONL FIN"", x-ms-request-id:"9a469a67-57dc-4f63-8c32-94a07e9d9f00", x-ms-ests-server:"2.1.10963.13 - SAN ProdSlices", Set-Cookie:"fpc=An3CgYC5t4RCuBSIOg6fMAzu_EH-AQAAANId1tYOAAAA; expires=Wed, 23-Sep-2020 20:45:06 GMT; path=/; secure; HttpOnly; SameSite=None", "x-ms-gateway-slice=prod; path=/; secure; samesite=none; httponly", "stsservicecookie=ests; path=/; secure; samesite=none; httponly", Date:"Mon, 24 Aug 2020 20:45:05 GMT", Content-Length:"1516"]>

So if I'm correct, the O365 Multi-factor authentication is creating the issue for me here. Would there be any easy workaround for this, or is connecting with a non-MFA account the only option?

moveFolder() fails HttpClientErrorException

Call of moveFolder() results in HttpClientErrorException.
The exception contains a detailMessage:
400 Bad Request: "{"error":{"code":"-1, Microsoft.SharePoint.Client.InvalidClientQueryException","message":{"lang":"en-US","value":"The parameter name flags is not valid."}}}"

I copied the moveFolder() method and modified it to leave the flags away. So the URL is not
https://<company-site>/_api/web/GetFolderByServerRelativeUrl('/sites/<site>/<from>/')/moveto(newUrl='/sites/<site>/<to>/',flags=1)
but instead
https://<company-site>/_api/web/GetFolderByServerRelativeUrl('/sites/<site>/<from>/')/moveto(newUrl='/sites/<site>/<to>/')
With this modification the exception did not occur anymore, and the folder was moved as expected.

can you make this available on a different licence ?

Hello, I was looking for a java SDK providing connection to sharepoint services and found on stackoverflow a link to yours. It looks as a nice piece of software. Would you mind releasing it using a corporate-friendlier open source license (which is btw the typical use for such code)? GPL3 is very restrictive regarding the distribution of commercial software. Basically, every piece of source code that is linked against your library, and is distributed into a product, has to be released, made available.
Thanks,
P.

XML resereved characters in user password

If user password parameter contains one of xml-resereved characters then api call fails with NullPointerException.

PLGSharepointClient wrapper = new PLGSharepointClientOnline(user, "p&ssword", domain, spSiteUrl); wrapper.getFolderFilesByRelativeUrl(base, "{ }");
I think xml-reserved characters at least for password parameter must be escaped.

xml predefined entities

Thank you in advance,
Vitali

UploadFile() method

Hi there just a little confused with the uploadFile() method, specifically, the Resource parameter for it.

How do I get this from "File" to a resource? I've tried putting it into a BufferedStream then casting, but no joy.

Any help appreciated. Thanks

App only authentication

Hi there, do you know if this supports app-only authentication? So, using a client id and password only?

How to filename when uploading

Hi! first of all thank you for this library, super easy to use!

How can I can I set the filename I upload? I tried doing this (sharepoint site is in spanish)

JSONObject payload = new JSONObject();
payload.put("Nombre", nombreArchivo);
payload.put("nombre", nombreArchivo);
payload.put("name", nombreArchivo);
payload.put("Name", nombreArchivo);
JSONObject result = wrapper.uploadFile(spSiteUrl + spFolder + spBackupFolder, archivo, payload);

but it always uploads the file as "null"
image
image

Maven Central?

Are there any plans to publish to maven central? It makes build pipelines a lot easier.

Use of getListItems

I'm trying to traverse a sharepoint site using the api to migrate data from SP into another system. I'm just a small test to retrieve all files in the documents list for a site. I'm able to get all lists, get information about the 'documents' list. However I'm getting messed up with getting the document list items (via getListItems api call). I'm not sure what the filter parameter is used for. I've messed around with leaving filter null, or try to specify a non restrictive filter.

I really could use a good example if you have the time.

Thanks for creating the project!

Enforced checkout

Hi, do you have any advice on how to handle an enforced checkout policy? I've run into this issue whereby of I deliver the file again it will trigger a forced checkout.

Authentication response does not contain mandatory element

What kind of problem is that?
Caused by: com.panxoloto.sharepoint.rest.helper.AuthenticationException: Authentication response does not contain mandatory element {http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd}BinarySecurityToken
at com.panxoloto.sharepoint.rest.helper.AuthenticationResponseParser.token(AuthenticationResponseParser.java:66)
at com.panxoloto.sharepoint.rest.helper.AuthenticationResponseParser.parseAuthenticationResponse(AuthenticationResponseParser.java:42)
at com.panxoloto.sharepoint.rest.helper.AuthTokenHelperOnline.getSecurityTokenUsingUserName(AuthTokenHelperOnline.java:133)
at com.panxoloto.sharepoint.rest.helper.AuthTokenHelperOnline.receiveSecurityToken(AuthTokenHelperOnline.java:110)
at com.panxoloto.sharepoint.rest.helper.AuthTokenHelperOnline.init(AuthTokenHelperOnline.java:182)
at com.panxoloto.sharepoint.rest.PLGSharepointClientOnline.init(PLGSharepointClientOnline.java:77)
at com.panxoloto.sharepoint.rest.PLGSharepointClientOnline.(PLGSharepointClientOnline.java:49)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.