import com.dvelop.d3.server.core.D3
import groovy.json.JsonSlurper
import javax.net.ssl.HttpsURLConnection
 
/**
 * Beispiel um Dokumente anhand einer Kategorie und einer Eigenschaft zu suchen und mit dem JSON arbeiten zu können
 */
void searchDocuments(D3 d3, String sessionId, String searchCategory, String searchPropertyKey, String searchPropertyValue) {
    String searchFor = "?sourceid=/dms/r/$REPO_ID/source&sourcecategories=[\"$searchCategory\"]&sourceproperties={\"$searchPropertyKey\":[\"$searchPropertyValue\"]}"
    String baseRequest = "$BASE_URI/dms/r/$REPO_ID/srm$searchFor"
 
    HttpsURLConnection request = new URL(baseRequest).openConnection() as HttpsURLConnection
    request.requestMethod = "GET"
    request.setRequestProperty("Origin", BASE_URI)
    request.setRequestProperty("Accept", "application/json")
    request.setRequestProperty("Authorization", "Bearer $sessionId")
 
    if (request.responseCode == 200) {
        def json = request.inputStream.withCloseable { stream ->
            new JsonSlurper().parse(stream as InputStream)
        }
 
        //Alle gefundenen Dokumente durchgehen
        json.items?.each {
            //Dateinamen mit Endung jedes Dokuments holen
            String fileName = it.sourceProperties.find { property -> property.key == "property_filename" }.value
            File file = new File(exportDirectory, fileName)
 
            //Download starten
            downloadDocument(d3, sessionId, it._links.mainblobcontent.href, file.getPath())
        }
 
    } else {
        d3.log.error("Fehler bei der Suche nach Dokumenten $request.responseCode: $request.responseMessage")
    }
}
 
/**
 * Beispiel um ein Dokument herunter zu laden
 */
void downloadDocument(D3 d3, String sessionId, String downloadUrl, String filePath) {
    String baseRequest = BASE_URI + downloadUrl
 
    HttpsURLConnection request = new URL(baseRequest).openConnection() as HttpsURLConnection
    request.requestMethod = "GET"
    request.setRequestProperty("Origin", BASE_URI)
    request.setRequestProperty("Accept", "application/json")
    request.setRequestProperty("Authorization", "Bearer $sessionId")
 
    if (request.responseCode == 200) {
        d3.log.info("Starte Download von: " + downloadUrl)
        request.inputStream.withCloseable { stream ->
            new File(filePath) << stream.getBytes()
        }
    } else {
        d3.log.error("Fehler beim Herunterladen von $baseRequest")
    }
}