<commit_before>/*
 * This is part of the Ktunaxa referral system.
 *
 * Copyright 2011 Ktunaxa Nation Council, http://www.ktunaxa.org/, Canada.
 */

package org.ktunaxa.referral.server.service;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

import javax.annotation.PostConstruct;

import org.apache.chemistry.opencmis.client.api.CmisObject;
import org.apache.chemistry.opencmis.client.api.Document;
import org.apache.chemistry.opencmis.client.api.Folder;
import org.apache.chemistry.opencmis.client.api.Repository;
import org.apache.chemistry.opencmis.client.api.Session;
import org.apache.chemistry.opencmis.client.api.SessionFactory;
import org.apache.chemistry.opencmis.client.runtime.SessionFactoryImpl;
import org.apache.chemistry.opencmis.commons.PropertyIds;
import org.apache.chemistry.opencmis.commons.SessionParameter;
import org.apache.chemistry.opencmis.commons.enums.BindingType;
import org.apache.chemistry.opencmis.commons.enums.VersioningState;
import org.apache.chemistry.opencmis.commons.exceptions.CmisConnectionException;
import org.apache.chemistry.opencmis.commons.exceptions.CmisRuntimeException;
import org.apache.chemistry.opencmis.commons.impl.dataobjects.ContentStreamImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * Implementation of the basic {@link CmisService} that uses a Spring configuration bean to acquire the correct CMIS
 * connection parameters.
 * 
 * @author <NAME>
 */
@Component
public class CmisServiceImpl implements CmisService {

	private final Logger log = LoggerFactory.getLogger(CmisConfig.class);

	@Autowired
	private CmisConfig config;

	private Repository repository;

	private Map<String, String> parameter = new HashMap<String, String>();
	
	@PostConstruct
	public void initialize() {
		if (StringUtils.hasText(config.getProxyHost())) {
			System.setProperty("java.net.useSystemProxies", "true");
			System.setProperty("http.proxyHost", config.getProxyHost());
			System.setProperty("http.proxyPort", Integer.toString(config.getProxyPort()));
			System.setProperty("https.proxyHost", config.getProxyHost());
			System.setProperty("https.proxyPort", Integer.toString(config.getProxyPort()));
		}
		parameter.put(SessionParameter.USER, config.getUserName());
		parameter.put(SessionParameter.PASSWORD, config.getPassword());
		String url = config.getUrl();
		if (!url.endsWith("/")) {
			url += "/";
		}
		parameter.put(SessionParameter.ATOMPUB_URL, url + "service/cmis");

		parameter.put(SessionParameter.BINDING_TYPE, BindingType.ATOMPUB.value());

		// Session locale.
		parameter.put(SessionParameter.LOCALE_ISO3166_COUNTRY, "");
		parameter.put(SessionParameter.LOCALE_ISO639_LANGUAGE, "nl");
		parameter.put(SessionParameter.LOCALE_VARIANT, "BE");

		parameter.put(SessionParameter.OBJECT_FACTORY_CLASS, "org.alfresco.cmis.client.impl.AlfrescoObjectFactoryImpl");
		// parameter.put(SessionParameter.REPOSITORY_ID, "Main Repository");

		// This supposes only one repository is available at the URL.
	}

	public Session createSession() {
		checkRepository();
		return repository.createSession();
	}

	private void checkRepository() {
		if (repository == null) {
			SessionFactory sessionFactory = SessionFactoryImpl.newInstance();
			try {
				repository = sessionFactory.getRepositories(parameter).get(0);
			} catch (Exception e) {
				log.error("Error: Initialize CmisService failed: " + e.getMessage(), e);
			}
		}
	}

	public String getBaseUrl() {
		return config.getUrl();
	}

	public Folder getWorkingFolder() throws IOException {
		try {
			Session session = createSession();
			Folder folder = session.getRootFolder();
			String path = config.getFolder();
			StringTokenizer tokenizer = new StringTokenizer(path, "/");
			while (tokenizer.hasMoreTokens()) {
				String name = tokenizer.nextToken();
				folder = getOrCreateSubFolder(folder, name);
			}
			return folder;
		} catch (CmisConnectionException e) {
			throw new IOException("The server is unreachable: " + e.getMessage(), e);
		} catch (CmisRuntimeException e) {
			throw new IOException("CMIS server error: " + e.getMessage(), e);
		}
	}

	public String getDownloadUrl(Document document) {
		String url = config.getUrl();
		if (url.endsWith("/")) {
			url += "d/a/";
		} else {
			url += "/d/a/";
		}
		String docId = document.getId().replaceAll("://", "/");
		return url + docId + "/" + document.getContentStreamFileName();
	}

	public String getDisplayUrl(Document document) {
		String url = config.getUrl();
		if (url.endsWith("/")) {
			url += "d/d/";
		} else {
			url += "/d/d/";
		}
		String docId = document.getId().replaceAll("://", "/");
		return url + docId + "/" + document.getContentStreamFileName();
	}

	public Document create(String documentName, String mimeType, InputStream in) throws IOException {
		Folder folder = getWorkingFolder();

		// Go over all children and see if the document already exists:
		for (CmisObject object : folder.getChildren()) {<commit_msg>KTU-173 try to fix view/save<commit_after>/*
 * This is part of the Ktunaxa referral system.
 *
 * Copyright 2011 Ktunaxa Nation Council, http://www.ktunaxa.org/, Canada.
 */

package org.ktunaxa.referral.server.service;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

import javax.annotation.PostConstruct;

import org.apache.chemistry.opencmis.client.api.CmisObject;
import org.apache.chemistry.opencmis.client.api.Document;
import org.apache.chemistry.opencmis.client.api.Folder;
import org.apache.chemistry.opencmis.client.api.Repository;
import org.apache.chemistry.opencmis.client.api.Session;
import org.apache.chemistry.opencmis.client.api.SessionFactory;
import org.apache.chemistry.opencmis.client.runtime.SessionFactoryImpl;
import org.apache.chemistry.opencmis.commons.PropertyIds;
import org.apache.chemistry.opencmis.commons.SessionParameter;
import org.apache.chemistry.opencmis.commons.enums.BindingType;
import org.apache.chemistry.opencmis.commons.enums.VersioningState;
import org.apache.chemistry.opencmis.commons.exceptions.CmisConnectionException;
import org.apache.chemistry.opencmis.commons.exceptions.CmisRuntimeException;
import org.apache.chemistry.opencmis.commons.impl.dataobjects.ContentStreamImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * Implementation of the basic {@link CmisService} that uses a Spring configuration bean to acquire the correct CMIS
 * connection parameters.
 * 
 * @author <NAME>
 */
@Component
public class CmisServiceImpl implements CmisService {

	private final Logger log = LoggerFactory.getLogger(CmisConfig.class);

	@Autowired
	private CmisConfig config;

	private Repository repository;

	private Map<String, String> parameter = new HashMap<String, String>();
	
	@PostConstruct
	public void initialize() {
		if (StringUtils.hasText(config.getProxyHost())) {
			System.setProperty("java.net.useSystemProxies", "true");
			System.setProperty("http.proxyHost", config.getProxyHost());
			System.setProperty("http.proxyPort", Integer.toString(config.getProxyPort()));
			System.setProperty("https.proxyHost", config.getProxyHost());
			System.setProperty("https.proxyPort", Integer.toString(config.getProxyPort()));
		}
		parameter.put(SessionParameter.USER, config.getUserName());
		parameter.put(SessionParameter.PASSWORD, config.getPassword());
		String url = config.getUrl();
		if (!url.endsWith("/")) {
			url += "/";
		}
		parameter.put(SessionParameter.ATOMPUB_URL, url + "service/cmis");

		parameter.put(SessionParameter.BINDING_TYPE, BindingType.ATOMPUB.value());

		// Session locale.
		parameter.put(SessionParameter.LOCALE_ISO3166_COUNTRY, "");
		parameter.put(SessionParameter.LOCALE_ISO639_LANGUAGE, "nl");
		parameter.put(SessionParameter.LOCALE_VARIANT, "BE");

		parameter.put(SessionParameter.OBJECT_FACTORY_CLASS, "org.alfresco.cmis.client.impl.AlfrescoObjectFactoryImpl");
		// parameter.put(SessionParameter.REPOSITORY_ID, "Main Repository");

		// This supposes only one repository is available at the URL.
	}

	public Session createSession() {
		checkRepository();
		return repository.createSession();
	}

	private void checkRepository() {
		if (repository == null) {
			SessionFactory sessionFactory = SessionFactoryImpl.newInstance();
			try {
				repository = sessionFactory.getRepositories(parameter).get(0);
			} catch (Exception e) {
				log.error("Error: Initialize CmisService failed: " + e.getMessage(), e);
			}
		}
	}

	public String getBaseUrl() {
		return config.getUrl();
	}

	public Folder getWorkingFolder() throws IOException {
		try {
			Session session = createSession();
			Folder folder = session.getRootFolder();
			String path = config.getFolder();
			StringTokenizer tokenizer = new StringTokenizer(path, "/");
			while (tokenizer.hasMoreTokens()) {
				String name = tokenizer.nextToken();
				folder = getOrCreateSubFolder(folder, name);
			}
			return folder;
		} catch (CmisConnectionException e) {
			throw new IOException("The server is unreachable: " + e.getMessage(), e);
		} catch (CmisRuntimeException e) {
			throw new IOException("CMIS server error: " + e.getMessage(), e);
		}
	}

	public String getDownloadUrl(Document document) {
		return getDocumentUrl(document, "d/a/");
	}

	public String getDisplayUrl(Document document) {
		return getDocumentUrl(document, "d/d/");
	}

	private String getDocumentUrl(Document document, String restCommand) {
		String docId = document.getId().replaceAll("://", "/");
		return config.getUrl() + restCommand + docId + "/" + document.getContentStreamFileName();

	}

	public Document create(String documentName, String mimeType, InputStream in) throws IOException {
		Folder folder = getWorkingFolder();

		// Go over all children and see if the document already exists:
		for (CmisObject object : folder.getChildren()) {
{'fraction_non_alphanumeric': 0.1242672919109027, 'fraction_numerical': 0.003028526768268855, 'mean_word_length': 5.10799522673031, 'pattern_counts': {'":': 3, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5938278', 'n_tokens_mistral': 3334, 'n_tokens_neox': 3055, 'n_words': 628}