com.github.sardine.Sardine Java Examples

The following examples show how to use com.github.sardine.Sardine. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AWebdavHandler.java    From nextcloud-java-api with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Create a authenticate sardine connector
 * 
 * @return sardine connector to server including authentication
 */
protected Sardine buildAuthSardine()
{
    Sardine sardine = SardineFactory.begin();
    sardine.setCredentials(_serverConfig.getUserName(), _serverConfig.getPassword());
    sardine.enablePreemptiveAuthentication(_serverConfig.getServerName());
    
    return sardine;
}
 
Example #2
Source File: AWebdavHandler.java    From nextcloud-java-api with GNU General Public License v3.0 6 votes vote down vote up
/**
 * method to check if a remote object already exists
 *
 * @param remotePath path of the file/folder
 * @return boolean value if the given file/folder exists or not
 */
public boolean pathExists(String remotePath) {
    String path = buildWebdavPath(remotePath);
    Sardine sardine = buildAuthSardine();

    try
    {
        return sardine.exists(path);
    } catch (IOException e)
    {
        throw new NextcloudApiException(e);
    }
    finally
    {
        try
        {
            sardine.shutdown();
        }
        catch (IOException ex)
        {
            LOG.warn("error in closing sardine connector", ex);
        }
    }
}
 
Example #3
Source File: AWebdavHandler.java    From nextcloud-java-api with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Deletes the file/folder at the specified path
 *
 * @param remotePath path of the file/folder
 */
public void deletePath(String remotePath)
{
    String path=  buildWebdavPath( remotePath );

    Sardine sardine = buildAuthSardine();
    try {
        sardine.delete(path);
    } catch (IOException e) {
        throw new NextcloudApiException(e);
    }
    finally
    {
        try
        {
            sardine.shutdown();
        }
        catch (IOException ex)
        {
            LOG.warn("error in closing sardine connector", ex);
        }
    }
}
 
Example #4
Source File: Folders.java    From nextcloud-java-api with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates a folder at the specified path
 *
 * @param remotePath path of the folder
 */
public void createFolder(String remotePath)
{
    String path=  buildWebdavPath(remotePath );
    Sardine sardine = buildAuthSardine();

    try {
        sardine.createDirectory(path);
    } catch (IOException e) {
        throw new NextcloudApiException(e);
    }
    finally
    {
        try
        {
            sardine.shutdown();
        }
        catch (IOException ex)
        {
            LOG.warn("error in closing sardine connector", ex);
        }
    }
}
 
Example #5
Source File: Files.java    From nextcloud-java-api with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Downloads the file at the specified remotepath as an InputStream,
 *
 * @param remotePath Remotepath where the file is saved in the nextcloud
 * server
 * @return InputStream
 * @throws IOException  In case of IO errors
 */
public InputStream downloadFile(String remotePath) throws IOException {
    String path = buildWebdavPath(remotePath);
    Sardine sardine = buildAuthSardine();

    WebdavInputStream in = null;
    try
    {
        in = new WebdavInputStream(sardine, sardine.get(path));
    } catch (IOException e)
    {
        sardine.shutdown();
        throw new NextcloudApiException(e);
    }
    return in;
}
 
Example #6
Source File: Folders.java    From nextcloud-java-api with GNU General Public License v3.0 5 votes vote down vote up
/**
 * List all file names and subfolders of the specified path traversing 
 * into subfolders to the given depth.
 *
 * @param remotePath path of the folder
 * @param depth depth of recursion while listing folder contents
 * @param excludeFolderNames excludes the folder names from the list
 * @return found file names and subfolders
 */
public List<String> listFolderContent(String remotePath, int depth, boolean excludeFolderNames, boolean returnFullPath)
{
    String path = buildWebdavPath(remotePath);

    List<String> retVal = new LinkedList<>();
    Sardine sardine = buildAuthSardine();
    List<DavResource> resources;
    try {
        resources = sardine.list(path, depth);
    } catch (IOException e) {
        throw new NextcloudApiException(e);
    }
    finally
    {
        try
        {
            sardine.shutdown();
        }
        catch (IOException ex)
        {
            LOG.warn("error in closing sardine connector", ex);
        }
    }
    for (DavResource res : resources)
    {
        if (excludeFolderNames) {
            if (!res.isDirectory()) {
                retVal.add(returnFullPath ? res.getPath().replaceFirst("/remote.php/webdav/", "") : res.getName());
            }
        }
        else {
            retVal.add(returnFullPath ? res.getPath().replaceFirst("/remote.php/webdav/", "") : res.getName());
        }
    }
    return retVal;
}
 
Example #7
Source File: Files.java    From nextcloud-java-api with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Uploads a file at the specified path with the data from the InputStream
 *
 * @param inputStream InputStream of the file which should be uploaded
 * @param remotePath path where the file should be uploaded to
 */
public void uploadFile(InputStream inputStream, String remotePath) {
    String path = buildWebdavPath(remotePath);
    Sardine sardine = buildAuthSardine();

    try
    {
        sardine.put(path, inputStream);
    } catch (IOException e)
    {
        throw new NextcloudApiException(e);
    }
}
 
Example #8
Source File: Files.java    From nextcloud-java-api with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Uploads a file at the specified path with the data from the InputStream
 * with an additional continue header
 *
 * @param inputStream InputStream of the file which should be uploaded
 * @param remotePath path where the file should be uploaded to
 * @param continueHeader Continue header is added to receive a possible error by the server before any data is sent.
 */
public void uploadFile(InputStream inputStream, String remotePath, boolean continueHeader) {
    String path = buildWebdavPath(remotePath);
    Sardine sardine = buildAuthSardine();

    try
    {
        sardine.put(path, inputStream, null, continueHeader);
    } catch (IOException e)
    {
        throw new NextcloudApiException(e);
    }
}
 
Example #9
Source File: CSVParser.java    From substitution-schedule-parser with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public SubstitutionSchedule getSubstitutionSchedule() throws IOException, JSONException,
        CredentialInvalidException {
    String url = data.getString(PARAM_URL);
    SubstitutionSchedule schedule = SubstitutionSchedule.fromData(scheduleData);

    if (url.startsWith("webdav")) {
        UserPasswordCredential credential = (UserPasswordCredential) this.credential;
        try {
            Sardine client = getWebdavClient(credential);
            String httpUrl = url.replaceFirst("webdav", "http");
            List<DavResource> files = client.list(httpUrl);
            for (DavResource file : files) {
                if (!file.isDirectory() && !file.getName().startsWith(".")) {
                    LocalDateTime modified = new LocalDateTime(file.getModified());
                    if (schedule.getLastChange() == null || schedule.getLastChange().isBefore(modified)) {
                        schedule.setLastChange(modified);
                    }
                    InputStream stream = client.get(new URI(httpUrl).resolve(file.getHref()).toString());
                    parseCSV(IOUtils.toString(stream, "UTF-8"), schedule);
                }
            }
            return schedule;
        } catch (GeneralSecurityException | URISyntaxException e) {
            throw new IOException(e);
        }
    } else {
        new LoginHandler(scheduleData, credential, cookieProvider).handleLogin(executor, cookieStore);
        String response = httpGet(url);
        return parseCSV(response, schedule);
    }
}
 
Example #10
Source File: WebdavInputStream.java    From nextcloud-java-api with GNU General Public License v3.0 4 votes vote down vote up
public WebdavInputStream(Sardine sardine, InputStream in)
{
    super(in);
    this.sardine= sardine;
}
 
Example #11
Source File: Files.java    From nextcloud-java-api with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Downloads the file at the specified remotepath to the download directory,
 * and returns true if the download is successful
 *
 * @param remotePath Remotepath where the file is saved in the nextcloud
 * server
 * @param downloadDirPath Path where the file is downloaded, it would be
 * created if it doesn't exist.
 * @return boolean
 * @throws IOException  In case of IO errors
 */
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 = path.split("/");
        String filename = segments[segments.length - 1];
        downloadDirPath = downloadDirPath + "/" + filename;
    }
    InputStream in = null;
    try
    {
        in = sardine.get(path);
        byte[] buffer = new byte[AWebdavHandler.FILE_BUFFER_SIZE];
        int bytesRead;
        File targetFile = new File(downloadDirPath);
        try (OutputStream outStream = new FileOutputStream(targetFile))
        {
            while ((bytesRead = in.read(buffer)) != -1)
            {
                outStream.write(buffer, 0, bytesRead);
            }
            outStream.flush();
            outStream.close();
        }
        status = true;
    } catch (IOException e)
    {
        throw new NextcloudApiException(e);
    } finally
    {
        sardine.shutdown();
        if (in != null)
        {
            in.close();
        }
    }
    return status;
}
 
Example #12
Source File: WebDavServiceImpl.java    From studio with GNU General Public License v3.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public String upload(@ValidateStringParam(name = "site_id") final String site,
                     @ValidateStringParam(name = "profile") final String profileId,
                     @ValidateStringParam(name = "path") final String path,
                     @ValidateStringParam(name = "filename") final String filename,
                     final InputStream content)
    throws WebDavException {
    WebDavProfile profile = getProfile(site, profileId);
    String uploadUrl = StringUtils.appendIfMissing(profile.getBaseUrl(), "/");
    try {
        Sardine sardine = SardineFactory.begin(profile.getUsername(), profile.getPassword());

        if(StringUtils.isNotEmpty(path)) {
            String[] folders = StringUtils.split(path, "/");

            for(String folder : folders) {
                uploadUrl += StringUtils.appendIfMissing(folder, "/");

                logger.debug("Checking folder {0}", uploadUrl);
                if(!sardine.exists(uploadUrl)) {
                    logger.debug("Creating folder {0}", uploadUrl);
                    sardine.createDirectory(uploadUrl);
                    logger.debug("Folder {0} created", uploadUrl);
                } else {
                    logger.debug("Folder {0} already exists", uploadUrl);
                }
            }
        }

        uploadUrl =  StringUtils.appendIfMissing(uploadUrl, "/");
        String fileUrl = uploadUrl + UriUtils.encode(filename, charset.name());

        logger.debug("Starting upload of file {0}", filename);
        logger.debug("Uploading file to {0}", fileUrl);

        sardine.put(fileUrl, content);
        logger.debug("Upload complete for file {0}", fileUrl);
        if(StringUtils.isNotEmpty(profile.getDeliveryBaseUrl())) {
            fileUrl = StringUtils.replaceFirst(fileUrl, profile.getBaseUrl(), profile.getDeliveryBaseUrl());
        }
        return fileUrl;
    } catch (Exception e ) {
        throw new WebDavException("Error uploading file", e);
    }
}
 
Example #13
Source File: WebDavServiceImpl.java    From studio with GNU General Public License v3.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
@ValidateParams
@HasPermission(type = DefaultPermission.class, action = "webdav_write")
public WebDavItem upload(@ValidateStringParam(name = "siteId") @ProtectedResourceId("siteId") final String siteId,
                         @ValidateStringParam(name = "profileId") final String profileId,
                         @ValidateStringParam(name = "path") final String path,
                         @ValidateStringParam(name = "filename") final String filename,
                         final InputStream content)
    throws WebDavException {
    WebDavProfile profile = getProfile(siteId, profileId);
    String uploadUrl = StringUtils.appendIfMissing(profile.getBaseUrl(), "/");
    try {
        Sardine sardine = createClient(profile);

        if(StringUtils.isNotEmpty(path)) {
            String[] folders = StringUtils.split(path, "/");

            for(String folder : folders) {
                uploadUrl += StringUtils.appendIfMissing(folder, "/");

                logger.debug("Checking folder {0}", uploadUrl);
                if(!sardine.exists(uploadUrl)) {
                    logger.debug("Creating folder {0}", uploadUrl);
                    sardine.createDirectory(uploadUrl);
                    logger.debug("Folder {0} created", uploadUrl);
                } else {
                    logger.debug("Folder {0} already exists", uploadUrl);
                }
            }
        }

        uploadUrl =  StringUtils.appendIfMissing(uploadUrl, "/");
        String fileUrl = uploadUrl + UriUtils.encode(filename, charset.name());

        logger.debug("Starting upload of file {0}", filename);
        logger.debug("Uploading file to {0}", fileUrl);

        sardine.put(fileUrl, content);
        logger.debug("Upload complete for file {0}", fileUrl);

        return new WebDavItem(filename, String.format(urlPattern, profileId, path, filename), false);
    } catch (Exception e ) {
        throw new WebDavException("Error uploading file", e);
    }
}
 
Example #14
Source File: WebdavFileSystem.java    From xenon with Apache License 2.0 4 votes vote down vote up
protected WebdavFileSystem(String uniqueID, String name, String location, Credential credential, String server, Path entryPath, int bufferSize,
        Sardine client, XenonProperties properties) {
    super(uniqueID, name, location, credential, entryPath, bufferSize, properties);
    this.client = client;
    this.server = server;
}