Giter Club home page Giter Club logo

nextcloud-java-api's Introduction

nextcloud-java-api

Java api library to access nextcloud features from java applications

Sonatype Nexus (Releases) Sonatype Nexus (Snapshots)

What is the nextcloud api library?

Use nextcloud features from inside your java application

Currently implemented features

  • Management of groups
  • Folder management (Without access control)
  • List shares and create new file shares (No way to delete/update shares atm.)
  • Tested against nextCloud 27.0.1 server version, but should also work with older nextCloud and ownCloud systems

Usage

  • Add this dependency to your pom.xml file
	<dependency>
	    <groupId>com.github.a-schild</groupId>
	    <artifactId>nextcloud-java-api</artifactId>
	    <version>13.1.0</version>
	</dependency>
  • The 13.x versions are now using the jakarta.xml binding stuff, to prevent problems with Java 11+ No API changes have been made in v13, but at some places the XML stuff is exposed Which made it necessary to bump the major version number
  • Create a NextcloudConnector instance and provide your server settings and authentification
  • Now you can use the methods exposed to access your nextcloud instance

When you wish to contribute to the project

Infos for contributors

Changelog

Changelog

(c) André Schild, Aarboard AG www.aarboard.ch

nextcloud-java-api's People

Contributors

a-schild avatar andusdev avatar col-panic avatar dependabot[bot] avatar jit-zoechmannc avatar lucnygr avatar manzsolutions-vsc avatar martinspielmann avatar mathiasbosman avatar mirkomack avatar raboof avatar simonit avatar thepiwo avatar tobiwinekenobi avatar torshid 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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

nextcloud-java-api's Issues

[Feature Request] get metadata of file

Hello, for me it would be great to be able to fetch some metadata for a file, but I don't know if this is possible. E.g. Date from Metadata App, Uploaded date or versions and maybe preview url that nextcloud gallery generated.

ResponseCode 404 when try to download files from a NextCloud Folder

org.aarboard.nextcloud nextcloud-api 11.5.1

IntelliJ Ultimate IntelliJ IDEA 2021.2.1 (Ultimate Edition)
Build #IU-212.5080.55, built on August 24, 2021
Java 11

Official and latest NextCloud Docker image without any further configurations

Given Folder structure "http://localhost:8080/apps/files/?dir=/TB/2021/2021-09/28&fileid=23365" contains XML- and PDF-Files.

// 1. Create Connection to NextCloud
NextcloudConnector connector = new NextcloudConnector("localhost", false, "8080", "admin", "mypwd");
// 2. List all files in testFolder = "/TB/2021/2021-09/28"
List fileNames = connector.listFolderContent(testFolder);
for (String fileName : fileNames) {
LOGGER.log(Level.INFO, "filename " + fileName);

    }
  1. But when i try to download all files with
    connector.download(fileName);
    then the Exception org.aarboard.nextcloud.api.exception.NextcloudApiException: com.github.sardine.impl.SardineException: status code: 404, reason phrase: Unexpected response (404 Not Found) is thrown:
    Full Stacktrace is:

    at org.aarboard.nextcloud.api.webdav.Folders.listFolderContent(Folders.java:106)
    at org.aarboard.nextcloud.api.webdav.Folders.listFolderContent(Folders.java:83)
    at org.aarboard.nextcloud.api.webdav.Folders.listFolderContent(Folders.java:70)
    at org.aarboard.nextcloud.api.NextcloudConnector.listFolderContent(NextcloudConnector.java:665)
    at de.pkv.nextcloud.NCFolderManagerTest.testGetPDF(NCFolderManagerTest.java:36)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:686)
    at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
    at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
    at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:205)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:201)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:137)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:71)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:248)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$5(DefaultLauncher.java:211)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:226)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:199)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:132)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
    Caused by: com.github.sardine.impl.SardineException: status code: 404, reason phrase: Unexpected response (404 Not Found)

Allow accepting all certificates

When developing against a server with a self-signed certificate, we should be able to use the library. The functionality should be the same like e.g. curl -k, --insecure Allow connections to SSL sites without certs (H)

Download file from server not working

I'm trying to download the file using Files API but keep on getting NullPointerException.

Exception in thread "Thread-1" java.lang.NullPointerException
	at org.aarboard.nextcloud.api.webdav.Files.downloadFile(Files.java:130)
	at com.netand.cloud.utility.DownloadFileTask.downloadFile(DownloadFileTask.java:29)
	at com.netand.cloud.utility.DownloadFileTask.run(DownloadFileTask.java:21)
	at java.lang.Thread.run(Unknown Source)

However after debug I get to know the fileExists(remotepath) returns false

Here is the example values of the Files class,

String path = "https://xxx.xxxxxxxx.xxx/xxxxxxx/remote.php/webdav/files/Test.txt";
String remotepath = "files/Test.txt";

Non-Ascii characters Supports

Url cations non-ascii will have exception

Flow that titles, I have a lasted next cloud 14 server in there. And I have a game mods will to upload timely.
Contains Non ASCii characters url will have a exception when upload. And I have a resolved method:

    private String getEncodeUrl(String s) {
        try {
            return URLEncoder.encode(s, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

Exceptions with NC 16

With the current version i cannnot make a connection to my nextcloud instance wich is a NC 16.0.1.
I have tested this with every possible parameter for NextcloudConnector.
Either your API is complaining about an invalid SSL message (even if the boolean for ssl is set to false), or a bad request, 405, or 400 is catched.

Implementing the Sardine connection by myself with the same config, works instead.

String url = "subdomain.domain.tld";
client = SardineFactory.begin();
client.setCredentials(u, p);
client.enablePreemptiveAuthentication(url);
client.list("https://" + url + "/");

It seems that you are doing something with the uri, is that correct?

401 on creating shares with ShareType.PUBLIC_LINK

Hello,

firstly thank you for creating this library!

I am using version 11.5.1 as a maven dependency and have the following problem:
When I create a share for a folder with ShareType.EMAIL everything works as expected thus I am pretty sure that authentication is working correctly.
However, when I try to create a share with ShareType.PUBLIC_LINK I get a response with status code 401.

My code looks as follows:

nc = new NextcloudConnector(...);

if (!nc.folderExists("Testfolder")) {
    nc.createFolder("Testfolder");
}

Share share = nc.doShare(
    "Testfolder",
    ShareType.PUBLIC_LINK,
    null, // I've also tried empty String
    false,
    "password",
    new SharePermissions(1)
);

While looking through the source code of this lib, I noticed that there is no check for empty Strings or null values for shareWith in the FilesharingConnector method

doShareAsync(
            String path,
            ShareType shareType,
            String shareWithUserOrGroupIdOrEmail,
            Boolean publicUpload,
            String password,
            SharePermissions permissions)
    {
    //...
    // line 190
    postParams.add(new BasicNameValuePair("shareWith", shareWithUserOrGroupIdOrEmail));

This results in the request URL containing the param ...&shareWith=&... with an empty value.
I'm not sure if that's actually causing the issue but I could imagine that nextcloud recognizes this as an invalid attempt to access some resource that the user is not allowed to.

It would be great if someone could look into this, or give me a hint of what I'm doing wrong.

Upload 0Kb, does api need to continue to configure on the server?

upload 0 Kb. Flow is my test code. wanna to help me.

package org.bklab.wot.warmonger;

import org.aarboard.nextcloud.api.NextcloudConnector;

import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@SuppressWarnings("unused")
public class UploadToBlueHawkCloud {

    private NextcloudConnector lanyingCloud = getConnection();
    private static final String base = "warmongers";
    private String s = initString();

    public static UploadToBlueHawkCloud create() {
        return new UploadToBlueHawkCloud();
    }

    public NextcloudConnector getConnection() {
        return new NextcloudConnector("example.com", true, 443, "admin", "password");
    }

    public UploadToBlueHawkCloud doUpload() {
        File upLoadDir = new File("E:\\Broderick Resources\\mods\\");
        List<File> modsList = Arrays.asList(upLoadDir.listFiles());
        System.out.println("start upload");
        InputStream stream = new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8));

        lanyingCloud.uploadFile(stream, base + "/a.txt");
        modsList.forEach(file -> {
            if(file.getName().endsWith(".wbp") || file.getName().endsWith(".txt")) {
                try {

                    System.out.println("uploading " + file.getName());
                    InputStream stream1 = new FileInputStream(file);
                    String remotePath = base + "/" + getEncodeUrl(file.getName());
                    lanyingCloud.uploadFile(stream1, remotePath);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        return this;
    }

    private String getEncodeUrl(String s) {
        try {
            return URLEncoder.encode(s, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static void main(String[] args) {
        UploadToBlueHawkCloud.create().doUpload();
    }


    private String initString() {
        return "test string, about 4KB";
    }

}

Uploaded WebSites:

Shared problem linked: https://xn--9kq.xn--fx1at73c.com/index.php/s/2KbrqgBK4peKA8t

jackson-databind-2.13.1.jar contains vulnerability

Hi,

First of all thanks for this handy API !
My Jenkins / OWASP dependency check failed because of :
CVE-2020-36518
jackson-databind before 2.13.0 allows a Java StackOverflow exception and denial of service via a large depth of nested objects.

I 'fixed' it in my projects POM by excluding this lib and using the more recent lib by adding:

<properties>
	<jackson.version>2.13.2.1</jackson.version>
</properties>

	    <exclusions>
			<exclusion>
				<groupId>com.fasterxml.jackson.core</groupId>
				<artifactId>jackson-databind</artifactId>
			</exclusion>
	    </exclusions>

	<dependency>
		<groupId>com.fasterxml.jackson.core</groupId>
		<artifactId>jackson-databind</artifactId>
		<version>${jackson.version}</version>			
	</dependency>

Perhaps this lib also can be upgraded in the nextcloud-java-api.
Cheers, Jan

How can i share a file without sharing folder?

Hello. I can easily share a folder with doShare method. But when i try to do the same with a file i have an error Nextcloud API call failed with statuscode 404 and message "Public upload is only possible for publicly shared folders"
And even if a file is in a shared folder i get the same error. I dont understand...
What did i do wrong? Is it possible to share a file only? Or how to resolve this error when i want to share a file from shared folder?
When i want to share my temp file from the cloud UI it works nice.

Example:

String testFolder = "test";
String testFile = "/test/temp.png";

ServerConfig _sc = new ServerConfig("cloud.mycloud.com", true, 443, user, pass);
FilesharingConnector fsc = new FilesharingConnector(_sc);
SharePermissions perm = new SharePermissions(SharePermissions.SingleRight.READ);

Share sFolder = fsc.doShare(testFolder, ShareType.PUBLIC_LINK, "", true,"1", perm);   //this one works fine
Share sFile = fsc.doShare(testFile, ShareType.PUBLIC_LINK, "", true, "1", perm); //error

UPD: When i try to share a folder after send "permissons=1" in response i get "permissions=15" somehow...
UPD2: Actually anything i write (READ, UPDATE, SHARE) turns into 15 in response.
UPD3: fsc.editShare(sFolder.getId(), ShareData.PERMISSIONS, "1") Works fine xD
UPD4: ok... fsc.doShare(testFile, ShareType.PUBLIC_LINK, null, null, "1234-Te$t", perm); Problem solved. But i cant delete the threat.

Authentication via Oauth Token

Hi,

Is there a possibility to provide the authentication method via Oauth token? rather than just the username and password?

I was able to test this with the simple file upload and the upload works fine, but can you please update the file upload method that will authenticate via a token (with the external authentication server like keycloak) rather than the password.

If atleast please provide some insights to implement this using this API code?

I have integrated and configured the keycloak with the nextcloud, and I want to use the same to upload the files programatically, this API would be very useful if this had the method to authenticate via Oauth token.

Regards
Karan

add ShareType email

I need the option to create a share with an email. The newest version of Nextcloud will send a notification to the provided email address after a share of the type EMAIL (enum value 4) has been created.

Help me! Error connecting and downloading files

`package com.vnnet.test.console;

import org.aarboard.nextcloud.api.*;

import java.io.IOException;

public class Test {
public static void main(String[] args) {
final String baseUrl = "https://tung95.duckdns.org//remote.php/webdav";
try {
NextcloudConnector nextcloudConnector = new NextcloudConnector("tung95.duckdns.org", true, 443, "nc_admin", "nextcloudpassword");
nextcloudConnector.downloadFile("/Photos/Coast1.jpg","/home/t94hp/Desktop/");
} catch (IOException e) {
e.printStackTrace();
}
}
}
`

Exception in thread "main" java.lang.NoSuchMethodError: org.apache.commons.codec.binary.Base64.(I)V
at org.apache.http.impl.auth.BasicScheme.authenticate(BasicScheme.java:166)
at org.apache.http.impl.auth.HttpAuthenticator.doAuth(HttpAuthenticator.java:233)
at org.apache.http.impl.auth.HttpAuthenticator.generateAuthResponse(HttpAuthenticator.java:213)
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:262)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:186)
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)
at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:72)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:221)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:165)
at com.github.sardine.impl.SardineImpl.execute(SardineImpl.java:1050)
at com.github.sardine.impl.SardineImpl.execute(SardineImpl.java:1019)
at com.github.sardine.impl.SardineImpl.exists(SardineImpl.java:1005)
at org.aarboard.nextcloud.api.webdav.AWebdavHandler.pathExists(AWebdavHandler.java:86)
at org.aarboard.nextcloud.api.webdav.Files.fileExists(Files.java:32)
at org.aarboard.nextcloud.api.webdav.Files.downloadFile(Files.java:106)
at org.aarboard.nextcloud.api.NextcloudConnector.downloadFile(NextcloudConnector.java:931)
at com.vnnet.test.console.Test.main(Test.java:12)

Process finished with exit code 1

Downloaded file size is always 0 KB

I'm able to get all the files from server.
But while downloading getting following exception,

Exception in thread "pool-1-thread-8" org.aarboard.nextcloud.api.exception.NextcloudApiException: com.github.sardine.impl.SardineException: Unexpected response (500 Internal Server Error)
	at org.aarboard.nextcloud.api.webdav.Files.fileExists(Files.java:47)
	at org.aarboard.nextcloud.api.webdav.Files.downloadFile(Files.java:111)
	at com.netand.cloud.utility.DownloadFileTask.downloadFile(DownloadFileTask.java:28)
	at com.netand.cloud.utility.DownloadFileTask.run(DownloadFileTask.java:21)
	at com.netand.cloud.SyncData.lambda$0(SyncData.java:45)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
	at java.lang.Thread.run(Unknown Source)
Caused by: com.github.sardine.impl.SardineException: Unexpected response (500 Internal Server Error)

Getting error 405 and error 404

Hello i am trying to use the library but i am lost .
I use
NextcloudConnector nextcloud = new NextcloudConnector("serverIPaddress/nextcloud",false,80,"admin","pass");

Then if i use
nextcloud.get methods i get error 404

if i use nextcloud.create methods i get error 405.

My nextcloud is installed on apache on ubuntu 20.0.4 .

Any help is appreciated. Thanks.

[Feature Request] Getting the InputStream of a remote file

Thanks for this nice lib.
It would be really great if there was a method for getting the InputStream of a remote file. I wanna directly process the retrieved file. Writing and then again reading from the hard drive are making the processing slower.

Implementation of JAXB-API has not been found on module path or classpath

I am trying to call getProperties() method from NextcloudConnector. For some reason I receive this exception:

Caused by: java.lang.ExceptionInInitializerError
	at com.github.sardine.impl.SardineImpl.addCustomProperties(SardineImpl.java:450)
	at com.github.sardine.impl.SardineImpl.propfind(SardineImpl.java:440)
	at [email protected]/org.aarboard.nextcloud.api.webdav.Files.getProperties(Files.java:271)
	at [email protected]/org.aarboard.nextcloud.api.NextcloudConnector.getProperties(NextcloudConnector.java:1034)
	at org.skilletti.xmowerconsole/org.skilletti.xmowerconsole.nextcloud.NextCloudUploader.uploadFile(NextCloudUploader.java:41)
	at org.skilletti.xmowerconsole/org.skilletti.xmowerconsole.main.resources.ResourcesController.clickedButtonAdd(ResourcesController.java:64)
	at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
	... 53 more
Caused by: java.lang.RuntimeException: javax.xml.bind.JAXBException: Implementation of JAXB-API has not been found on module path or classpath.
 - with linked exception:
[java.lang.ClassNotFoundException: com.sun.xml.bind.v2.ContextFactory]
	at com.github.sardine.util.SardineUtil.<clinit>(SardineUtil.java:92)
	... 60 more
Caused by: javax.xml.bind.JAXBException: Implementation of JAXB-API has not been found on module path or classpath.
 - with linked exception:
[java.lang.ClassNotFoundException: com.sun.xml.bind.v2.ContextFactory]
	at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:168)
	at javax.xml.bind.ContextFinder.find(ContextFinder.java:355)
	at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:508)
	at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:465)
	at com.github.sardine.util.SardineUtil.<clinit>(SardineUtil.java:88)
	... 60 more
Caused by: java.lang.ClassNotFoundException: com.sun.xml.bind.v2.ContextFactory
	at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
	at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
	at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
	at javax.xml.bind.ServiceLoaderUtil.nullSafeLoadClass(ServiceLoaderUtil.java:122)
	at javax.xml.bind.ServiceLoaderUtil.safeLoadClass(ServiceLoaderUtil.java:155)
	at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:165)
	... 64 more

I suppose there is an issue with outdated packages from < Java8. I am running Java 19.

Can you please advice me a solution for my issue?

cant upload/download files

All actions about users like create、delete 、getInfo about users is good. but all action about files is bad like exists、upload、download。 the result is always true when I check the existence of a file. Also when I upload or download a file, will throw an exception like this.
gg
When I check the existence of a file.My docker's file below
git
But I get the result
image
After so many times tests, I still get the point. If you can send me an example to connect the next could by HttpClient way,so I can understand it's working principle. (I tried to follow this api, but failed because of so much packing steps)

Http Client keeps running

We need a method to shut down the http client. Otherwise it keeps running forever, and/or there is no clean app shutdown possible

Encoded file name on download

When downloading a file with URI encoded symbol like #, the downloaded filename have the symbol replaced by %23.

I tried to push a branch with the correction but can't push it and do a pull request. So here are the changes I made to make it work for us:
in org.aarboard.nextcloud.api.webdav.File

public boolean downloadFile(String remotePath, String downloadDirPath) throws IOException {
        boolean status = false;
        String path = buildWebdavPath(remotePath);
        Sardine sardine = buildAuthSardine();
        File downloadFilepath = new File(downloadDirPath);
        if (!downloadFilepath.exists())
        {
            downloadFilepath.mkdir();
        }
        if (fileExists(remotePath))
        {
            //Extract the Filename from the path
            String[] segments = remotePath.split("/"); // Change is here remotePath instead of path
            String filename = segments[segments.length - 1];
            downloadDirPath = downloadDirPath + "/" + filename;
        }

The modification was tested on 1.5.1 since 1.6.0 is broken atm.

Thanks.

Working with downloaded InputStream fails

version: 11.3.0
java: 1.8

I used method InputStream downloadFile(String remotepath) and when I try to read all bytes from that stream, it throws
java.net.SocketException: socket closed

I believe the problem is where sardine is shutdown after the download

Restart logic for downloading big file

Is there any call to download the partial file from the server ?

For ex I have 1GB file and connection got lost on 800MB is there any provision to download the remaining bytes only on next call?

Trouble Sharing Folder

Just having some trouble sharing a folder via url. I know I'm doing it wrong but I'm not sure what.

//First I connect to nextcloud server
NextcloudConnector n = new NextcloudConnector(SERVER,HTTPS,PORT,USER_NAME,USER_PASS);
//Then I make a folder
n.createFolder("/test");
//I then make SharePermissions (This is the step where I defiantly feel like I'm going wrong)
SharePermissions permissions = new SharePermissions(SingleRight.READ);
//Finally I doShare
n.doShare("/test", ShareType.PUBLIC_LINK, "2", true, "1234", permissions);

I'm getting the following error

Exception in thread "main" org.aarboard.nextcloud.api.exception.NextcloudApiException: java.util.concurrent.ExecutionException: org.aarboard.nextcloud.api.exception.NextcloudApiException: Request failed with 401 Unauthorized

The folder is successfully created but not shared.

Also is there any documentation on this api I can have a read through?

Cheers,

java.net.UnknownHostException: myserver.deocs

I have a nextcloud instance running on myserver.de:444, WebDAV seems to work in general (with WinSCP) but when I'm trying to connect like this

static String serverName = "myserver.de";
static int port = 444;
static String userName = "myuser";
static String password = "mypass";
public static void main(String[] args) {
    NextcloudConnector nc = new NextcloudConnector(serverName, true, port, userName, password);
    Collection<Share> result = nc.getShares("/remote.php/dav/files/myuser", false, false);
    ...

I get the above error. Why does it append ocs to the hostname? Obviously, that hostname is then no longer valid.

Cant get connection

Nextcloud version: 18.0.4
Connector version: 11.3.0

Hi Everyone! Im trying to get connect to nextcloud using this api and i can't get it!.

This is my Java code:

String serverName = "192.168.0.19/nextcloud";
boolean useHTTPS = false;
int port = 80;
String userName = "nextcloud";
String password = "Kapasky3";
NextcloudConnector nxt = new NextcloudConnector(serverName, useHTTPS, port, userName, password);
nxt.createFolder("nextcloud1");
SharePermissions permissions = new SharePermissions(SingleRight.READ);
nxt.doShare("/test", ShareType.PUBLIC_LINK, "2", true, "1234", permissions);

And this is the output i get:

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Exception in thread "main" org.aarboard.nextcloud.api.exception.NextcloudApiException: com.github.sardine.impl.SardineException: status code: 405, reason phrase: Unexpected response (405 Method Not Allowed)
at org.aarboard.nextcloud.api.webdav.Folders.createFolder(Folders.java:157)
at org.aarboard.nextcloud.api.NextcloudConnector.createFolder(NextcloudConnector.java:692)
at com.mycompany.startnextcloud.StartNextCloud.main(StartNextCloud.java:37)
Caused by: com.github.sardine.impl.SardineException: status code: 405, reason phrase: Unexpected response (405 Method Not Allowed)
at com.github.sardine.impl.handler.ValidatingResponseHandler.validateResponse(ValidatingResponseHandler.java:48)
at com.github.sardine.impl.handler.VoidResponseHandler.handleResponse(VoidResponseHandler.java:34)
at com.github.sardine.impl.handler.VoidResponseHandler.handleResponse(VoidResponseHandler.java:29)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:223)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:165)
at com.github.sardine.impl.SardineImpl.execute(SardineImpl.java:1050)
at com.github.sardine.impl.SardineImpl.execute(SardineImpl.java:1019)
at com.github.sardine.impl.SardineImpl.createDirectory(SardineImpl.java:998)
at org.aarboard.nextcloud.api.webdav.Folders.createFolder(Folders.java:155)
... 2 more

Could you please help me with this ! Thanks !

The self-generated HTTPS certificate is not trusted

Hi, I'm from China.I built nextCloud in the local use is the certificate generated by their own, when using the API call method prompted: "General SSLEngine problem", "incapable to find valid certification path to requested target".I want to trust all the SSL certificates when I request, how should I do? Thank you very much for your advice

Apply expiration time for file share

Expiration time does not apply HH: mm: ss

    SharePermissions permissions = new SharePermissions(SharePermissions.SingleRight.READ);
    Share result_doShare = nextcloudConnector.doShare("/Musics/" + sysNotification.getFileName(), ShareType.PUBLIC_LINK, null, null, null, permissions);
    SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date = new Date(System.currentTimeMillis());
    Calendar c1 = Calendar.getInstance();
    c1.setTime(date);

    c1.add(Calendar.MINUTE, 20);

    boolean result = nextcloudConnector.editShare(result_doShare.getId(), ShareData.EXPIREDATE, formatter.format(c1.getTime()));

Einbinden der Library

Hi
Ich habe NextCloud12 als Container im Docker laufen. Dabei würdet der default http Port auf 12321 gesetzt. Nun versuche ich die „nextcloud-Java-api“ in meinen (noch recht jungfräulichen) Code zu implementieren. Leider bislang ohne Erfolg.
Gibt es die Möglichkeit, eine kurze Beispiel Implementierung zu posten, anhand hervorgeht wie die Lib genutzt bzw. Angesprochen werden muss?

Danke im Voraus
Vg
Stephan

"Principal name not found" error on downloading a file

I am trying to download a file from Nextcloud (self-hosted, version is 20.0.8.1). The top level view in Nextcloud has a file "Nextcloud.mp4". I have verified that the username and password is correct (got a 401 error when I used the wrong password). I have also tried other methods without success (see the commented lines).

Here is my code:

        try {
            NextcloudConnector nc = new NextcloudConnector("nextcloud.example.com", true, 443, "[email protected]", "mypassword");
            InputStream file = nc.downloadFile("/Nextcloud.mp4");
            //nc.createFolder("/Test");
            //List fileNames = nc.listFolderContent("/");
        } catch (Exception e) {
            System.out.println(e);
        }

And here is the log file output:

09:50:31.858 [main] DEBUG org.apache.http.headers - http-outgoing-1 >> GET /remote.php/dav/files/[email protected]/Nextcloud.mp4/ HTTP/1.1
09:50:31.858 [main] DEBUG org.apache.http.headers - http-outgoing-1 >> Host: nextcloud.example.com:443
09:50:31.858 [main] DEBUG org.apache.http.headers - http-outgoing-1 >> Connection: Keep-Alive
09:50:31.858 [main] DEBUG org.apache.http.headers - http-outgoing-1 >> User-Agent: Sardine/5.10
09:50:31.858 [main] DEBUG org.apache.http.headers - http-outgoing-1 >> Accept-Encoding: gzip,deflate
09:50:31.858 [main] DEBUG org.apache.http.headers - http-outgoing-1 >> Authorization: Basic QXJu.....
09:50:31.858 [main] DEBUG org.apache.http.wire - http-outgoing-1 >> "GET /remote.php/dav/files/[email protected]/Nextcloud.mp4/ HTTP/1.1[\r][\n]"
09:50:31.858 [main] DEBUG org.apache.http.wire - http-outgoing-1 >> "Host: nextcloud.example.com:443[\r][\n]"
09:50:31.859 [main] DEBUG org.apache.http.wire - http-outgoing-1 >> "Connection: Keep-Alive[\r][\n]"
09:50:31.859 [main] DEBUG org.apache.http.wire - http-outgoing-1 >> "User-Agent: Sardine/5.10[\r][\n]"
09:50:31.859 [main] DEBUG org.apache.http.wire - http-outgoing-1 >> "Accept-Encoding: gzip,deflate[\r][\n]"
09:50:31.859 [main] DEBUG org.apache.http.wire - http-outgoing-1 >> "Authorization: Basic QXJu...[\r][\n]"
09:50:31.859 [main] DEBUG org.apache.http.wire - http-outgoing-1 >> "[\r][\n]"
09:50:33.499 [main] DEBUG org.apache.http.wire - http-outgoing-1 << "HTTP/1.1 404 Not Found[\r][\n]"
09:50:33.499 [main] DEBUG org.apache.http.wire - http-outgoing-1 << "Date: Wed, 06 Oct 2021 07:50:31 GMT[\r][\n]"
09:50:33.499 [main] DEBUG org.apache.http.wire - http-outgoing-1 << "Server: Apache/2.4.25 (Debian)[\r][\n]"
09:50:33.499 [main] DEBUG org.apache.http.wire - http-outgoing-1 << "Strict-Transport-Security: max-age=15768000 ; includeSubDomains[\r][\n]"
09:50:33.499 [main] DEBUG org.apache.http.wire - http-outgoing-1 << "Expires: Thu, 19 Nov 1981 08:52:00 GMT[\r][\n]"
09:50:33.499 [main] DEBUG org.apache.http.wire - http-outgoing-1 << "Cache-Control: no-store, no-cache, must-revalidate[\r][\n]"
09:50:33.499 [main] DEBUG org.apache.http.wire - http-outgoing-1 << "Pragma: no-cache[\r][\n]"
09:50:33.499 [main] DEBUG org.apache.http.wire - http-outgoing-1 << "Content-Security-Policy: default-src 'none';[\r][\n]"
09:50:33.499 [main] DEBUG org.apache.http.wire - http-outgoing-1 << "Referrer-Policy: no-referrer[\r][\n]"
09:50:33.499 [main] DEBUG org.apache.http.wire - http-outgoing-1 << "X-Content-Type-Options: nosniff[\r][\n]"
09:50:33.499 [main] DEBUG org.apache.http.wire - http-outgoing-1 << "X-Download-Options: noopen[\r][\n]"
09:50:33.499 [main] DEBUG org.apache.http.wire - http-outgoing-1 << "X-Frame-Options: SAMEORIGIN[\r][\n]"
09:50:33.499 [main] DEBUG org.apache.http.wire - http-outgoing-1 << "X-Permitted-Cross-Domain-Policies: none[\r][\n]"
09:50:33.499 [main] DEBUG org.apache.http.wire - http-outgoing-1 << "X-Robots-Tag: none[\r][\n]"
09:50:33.499 [main] DEBUG org.apache.http.wire - http-outgoing-1 << "X-XSS-Protection: 1; mode=block[\r][\n]"
09:50:33.499 [main] DEBUG org.apache.http.wire - http-outgoing-1 << "Content-Length: 253[\r][\n]"
09:50:33.499 [main] DEBUG org.apache.http.wire - http-outgoing-1 << "Content-Type: application/xml; charset=utf-8[\r][\n]"
09:50:33.499 [main] DEBUG org.apache.http.wire - http-outgoing-1 << "Set-Cookie: oc4ld86aguy6=0ca6a655f8a1e9e694af6eaf6b4b2616; path=/; secure; HttpOnly; SameSite=Lax[\r][\n]"
09:50:33.499 [main] DEBUG org.apache.http.wire - http-outgoing-1 << "Set-Cookie: oc_sessionPassphrase=An5OH5L.....; path=/; secure; HttpOnly; SameSite=Lax[\r][\n]"
09:50:33.499 [main] DEBUG org.apache.http.wire - http-outgoing-1 << "Set-Cookie: oc4ld8....; path=/; secure; HttpOnly; SameSite=Lax[\r][\n]"
09:50:33.499 [main] DEBUG org.apache.http.wire - http-outgoing-1 << "Set-Cookie: __Host-nc_sameSiteCookielax=true; path=/; httponly;secure; expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=lax[\r][\n]"
09:50:33.499 [main] DEBUG org.apache.http.wire - http-outgoing-1 << "Set-Cookie: __Host-nc_sameSiteCookiestrict=true; path=/; httponly;secure; expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=strict[\r][\n]"
09:50:33.499 [main] DEBUG org.apache.http.wire - http-outgoing-1 << "Set-Cookie: oc4ld86a....; path=/; secure; HttpOnly; SameSite=Lax[\r][\n]"
09:50:33.500 [main] DEBUG org.apache.http.wire - http-outgoing-1 << "Set-Cookie: cookie_test=test; expires=Wed, 06-Oct-2021 08:50:33 GMT; Max-Age=3600[\r][\n]"
09:50:33.500 [main] DEBUG org.apache.http.wire - http-outgoing-1 << "Keep-Alive: timeout=5, max=100[\r][\n]"
09:50:33.500 [main] DEBUG org.apache.http.wire - http-outgoing-1 << "Connection: Keep-Alive[\r][\n]"
09:50:33.500 [main] DEBUG org.apache.http.wire - http-outgoing-1 << "[\r][\n]"
09:50:33.500 [main] DEBUG org.apache.http.wire - http-outgoing-1 << "<?xml version="1.0" encoding="utf-8"?>[\n]"
09:50:33.500 [main] DEBUG org.apache.http.wire - http-outgoing-1 << "<d:error xmlns:d="DAV:" xmlns:s="http://sabredav.org/ns">[\n]"
09:50:33.500 [main] DEBUG org.apache.http.wire - http-outgoing-1 << "  <s:exception>Sabre\DAV\Exception\NotFound</s:exception>[\n]"
09:50:33.500 [main] DEBUG org.apache.http.wire - http-outgoing-1 << "  <s:message>Principal with name [email protected] not found</s:message>[\n]"
09:50:33.500 [main] DEBUG org.apache.http.wire - http-outgoing-1 << "</d:error>[\n]"
...
org.aarboard.nextcloud.api.exception.NextcloudApiException: com.github.sardine.impl.SardineException: Unexpected response (404 Not Found)

The url "https://nextcloud.example.com/remote.php/dav/files/[email protected]/Nextcloud.mp4/" results in fact in a 404 error when pasted into the browser. However, when I replace the user name part with the uuid that is listed in the Nextcloud administrator user listing near my full name ("https://nextcloud.example.com/remote.php/dav/files/BA00370B-3FFZ-4295-8D76-C232DA9B3565/Nextcloud.mp4/"), I can successfully download the file via the browser.

So this shows that the path to the file in the nc.downloadFile call seems to be correct. I also tried replacing my user name by the uuid in the code, but then the login fails.

Please advise what to do to successfully download the file by a Java program.

GAV wrong in README.md

The "Usage" sections says:

<groupId>com.github.a-schild</groupId>
<artifactId>nextcloud-java-api</artifactId>

While infact it should state (as per pom.xml):

<groupId>org.aarboard.nextcloud</groupId>
<artifactId>nextcloud-api</artifactId>

downloadFolder not working with special charater

We are using the org.aarboard.nextcloud.api.NextcloudConnector.downloadFolder function and had an issue with the special character. For example for the filename "MobaXterm backup.zip" sardine.exists gave us a malformated URI exception because space was not escaped.

We tried to use the buildWebdavPath but it seems complex to use as the function is called previously on the root path.
I will try to make the pull request work this time if not will edit the issue with the code we used to correct it.

Thanks

Initialization of the Apache HttpAsyncClient

Hi,

I've been successfully using this library for some weeks now, it really helped me a lot, however, recently I stumbled across a feature that I'm missing somehow. It's about missing configuration options related to the initialization of the http client that you're using. The only customization that you currently provide is about SSL, so I've been wondering if that's been chosen intentionally. If not I'd like to change the current default initialization of the http client in order to be able to provide system properties to the http client. The main reason behind this is the fact that I'd like to be able to tune the number of concurrent requests, which is possible using system properties, which, though, have to be activated during initialization of the client.
Long story short, the question is if it's worth doing so and whether or not you would eventually accept a corresponding pull request.

Thx a lot!
Best regards,
Christian

Error uploading files

Netxlcoud version: 18.0
Connector version: 11.3.0

I am creating folders and uploading files to a dockerized Nextcloud Server from teh official image. I´m doing a batch upload (multiple files, sequentially) and it fails on some files, after creating all the folder structure. All the files are <1MB.
As a side note, I´m using Spring Boot as framework. Tryed the same WebDav operation from Postman and it works all the time. Also if I use Nextcloud UI. If you need any other info please let me know.

Does anybody knows why this could be happening?

My code snippet:

File srcFile = new File("name.pdf);
FileUtils.writeByteArrayToFile(srcFile, byteArray);
connector.uploadFile(srcFile, "MyFiles/docs/" + srcFile.getName());
srcFile.delete();

Logs:

Caused by: org.aarboard.nextcloud.api.exception.NextcloudApiException: org.apache.http.NoHttpResponseException: xxx_server_xxx:8080 failed to respond
        at org.aarboard.nextcloud.api.webdav.Files.uploadFile(Files.java:59) ~[nextcloud-api-11.3.0.jar!/:na]
        at org.aarboard.nextcloud.api.NextcloudConnector.uploadFile(NextcloudConnector.java:798) ~[nextcloud-api-11.3.0.jar!/:na]
        at com.saenz.cconline.repository.NextCloudRepository.upload(NextCloudRepository.java:54) ~[classes!/:1.9.0]
        ... 42 common frames omitted
Caused by: org.apache.http.NoHttpResponseException: xxx_server_xxx:8080 failed to respond
        at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:141) ~[httpclient-4.5.12.jar!/:4.5.12]
        at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:56) ~[httpclient-4.5.12.jar!/:4.5.12]
        at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:259) ~[httpcore-4.4.13.jar!/:4.4.13]
        at org.apache.http.impl.DefaultBHttpClientConnection.receiveResponseHeader(DefaultBHttpClientConnection.java:163) ~[httpcore-4.4.13.jar!/:4.4.13]
        at org.apache.http.impl.conn.CPoolProxy.receiveResponseHeader(CPoolProxy.java:157) ~[httpclient-4.5.12.jar!/:4.5.12]
        at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:273) ~[httpcore-4.4.13.jar!/:4.4.13]
        at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:125) ~[httpcore-4.4.13.jar!/:4.4.13]
        at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:272) ~[httpclient-4.5.12.jar!/:4.5.12]
        at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:186) ~[httpclient-4.5.12.jar!/:4.5.12]
        at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89) ~[httpclient-4.5.12.jar!/:4.5.12]
        at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110) ~[httpclient-4.5.12.jar!/:4.5.12]
        at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185) ~[httpclient-4.5.12.jar!/:4.5.12]
        at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:72) ~[httpclient-4.5.12.jar!/:4.5.12]
        at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:221) ~[httpclient-4.5.12.jar!/:4.5.12]
        at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:165) ~[httpclient-4.5.12.jar!/:4.5.12]
        at com.github.sardine.impl.SardineImpl.execute(SardineImpl.java:1050) ~[sardine-5.9.jar!/:5.9]
        at com.github.sardine.impl.SardineImpl.execute(SardineImpl.java:1019) ~[sardine-5.9.jar!/:5.9]
        at com.github.sardine.impl.SardineImpl.put(SardineImpl.java:930) ~[sardine-5.9.jar!/:5.9]
        at com.github.sardine.impl.SardineImpl.put(SardineImpl.java:913) ~[sardine-5.9.jar!/:5.9]
        at com.github.sardine.impl.SardineImpl.put(SardineImpl.java:901) ~[sardine-5.9.jar!/:5.9]
        at com.github.sardine.impl.SardineImpl.put(SardineImpl.java:958) ~[sardine-5.9.jar!/:5.9]
        at org.aarboard.nextcloud.api.webdav.Files.uploadFile(Files.java:56) ~[nextcloud-api-11.3.0.jar!/:na]

Premature end of Content-Length delimited message body

No problem using org.aarboard.nextcloud.api.NextcloudConnector.downloadFile(String, String) to directly save a file.
But if I use org.aarboard.nextcloud.api.NextcloudConnector.downloadFile(String) :

try (InputStream in = nextcloud.downloadFile(path + "/" + fileName)) {
	int bytesRead;
	byte[] buffer = new byte[4096];
	try (OutputStream outStream = new FileOutputStream("/Users/development/" + fileName)) {
		while ((bytesRead = in.read(buffer)) != -1) {
			outStream.write(buffer, 0, bytesRead);
		}
		outStream.flush();
		outStream.close();
	}
}

it fails with:

org.apache.http.ConnectionClosedException: Premature end of Content-Length delimited message body (expected: 2,208,611; received: 6,745)
	at org.apache.http.impl.io.ContentLengthInputStream.read(ContentLengthInputStream.java:140) ~[httpcore-4.4.14.jar:4.4.14]
	at org.apache.http.conn.EofSensorInputStream.read(EofSensorInputStream.java:118) ~[httpclient-4.5.13.jar:4.5.13]
	at com.github.sardine.impl.io.ByteCountInputStream.read(ByteCountInputStream.java:44) ~[sardine-5.10.jar:5.10]
	at com.github.sardine.impl.io.ContentLengthInputStream.read(ContentLengthInputStream.java:50) ~[sardine-5.10.jar:5.10]
	at org.apache.commons.io.input.ProxyInputStream.read(ProxyInputStream.java:62) ~[commons-io-2.8.0.jar:2.8.0]

Am I doing something wrong?

Library version: 11.5.0
Nextcloud version: 17.0.0

Download File

Is there any API for download file from server ?

Didn't find any in package.
Do I have to use the curl call with passing username and password ?

API method to download a file?

Hello,

Nice work. But I dont see a method to download a file from the server. Would be great if that can be added. Do you still plan to work on this?

or please let me know how to get started and I will be happy to contribute

is there any way to auto sync the data?

I would like to keep my custom desktop app in auto sync with web and android device.
Is there any way(api) to get desktop client notified about the change in other platform data.

How can i get the urls of the files

I'd tried the method "doShare" but i'd got the error 401.

Code like below:
SharePermissions permissions = new SharePermissions(SingleRight.READ);
FilesharingConnector instance=new FilesharingConnector(this.getSever());
Share result=instance.doShare("testing",ShareType.EMAIL,"[email protected]", null,null,null);

And i found the issus which had this same problem, i changed the depenency "hettpClient" to the version 4.5.6 but it still dosen't work. But the method like uploadfile and creatfolder are working well.

I'm not sure if "doShare" can get the urls of the files. If not, do we have any other method to realise it?
Thank you for your ##attention.

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.