Crear un documento sobre una carpeta especifica [Solucionado

cancel
Showing results for 
Search instead for 
Did you mean: 
rafex
Member II

Crear un documento sobre una carpeta especifica [Solucionado

Mi duda es cómo creo un documento sobre una carpeta especifica, ya que puedo crear documentos cuando creo la carpeta

Map<String, Object> properties = new HashMap<String, Object>();
      properties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
      properties.put(PropertyIds.NAME, "carpeta"+System.currentTimeMillis());

      // create the folder
      Folder parent = root.createFolder(properties);
      //System.out.println("folder parent:  " + parent);
      //System.out.println("folder parent:  " + parent.getPath());

      String name = "myNewDocumentds"+System.currentTimeMillis()+".txt";
      // properties
      // (minimal set: name and object type id)
      Map<String, Object> properties2 = new HashMap<String, Object>();
      properties2.put(PropertyIds.OBJECT_TYPE_ID, "cmis:document");
      properties2.put(PropertyIds.NAME, name);

      // content
      byte[] content = "Hello World, kakkakskaskaks!!!!".getBytes();
      InputStream stream = new ByteArrayInputStream(content);
      ContentStream contentStream = new ContentStreamImpl(name, BigInteger.valueOf(content.length), "text/plain", stream);

      // create a major version
      Document newDoc = parent.createDocument(properties2, contentStream, VersioningState.MAJOR);

pero quiero crear el documento sobre una carpeta que exista previamente, si alguien me puede orientar porfavor!
2 Replies
pjcaracuel_2349
Active Member II

Re: Crear un documento sobre una carpeta especifica [Solucionado

Buenas,

La respuesta es muy facil, en lugar de usar
Document newDoc = parent.createDocument(properties2, contentStream, VersioningState.MAJOR);

Debes instanciarte el objeto folder con el id de la carpeta a la que quieras asociar el documento. Te paso dos metodos cortesia de CristinaMR y de cybermakoki que te ayudaran.

Saludos



/**
         * Método que, dado el nombre de un espacio, devuelve su Id (nodeRef)
         * @param session
         * @param nombre
         * @return nodeRef (id)
         */
       
       
        public static String getFolderId(Session session, String nombre){
               
               
               
                String queryString = "SELECT cmis:objectId FROM cmis:folder WHERE cmis:name = '" + nombre+"'";
               
                ItemIterable<QueryResult> results = session.query(queryString, false);
               
                String id = "";
               
                for (QueryResult qResult : results) {
                   String objectId = qResult.getPropertyValueByQueryName("cmis:objectId");
                   Folder folder = (Folder) session.getObject(session.createObjectId(objectId));
                   id = folder.getId();
                   logger.info("Listado de carpetas: "+folder.getId());
                }
               
                               
                return id;
               
        }
       
        /**
         * Método que crea un contenido/espacio en el respositorio.
         * @param session
         * @param parent, carpeta donde se crea el contenido
         * @param type, espacio o contenido
         * @param name
         * @return
         */
       
        public static CmisObject createContent(Session session, Folder parent, String type, String name){
                       

                // properties
                // (minimal set: name and object type id)
                Map<String, Object> properties = new HashMap<String, Object>();
                properties.put(PropertyIds.OBJECT_TYPE_ID, type);
                properties.put(PropertyIds.NAME, name);        
               
                Document doc = session.getRootFolder().createDocument(properties, null, null);
               
                // create a major version
                CmisObject newContent = null;
               
                try {
               
                        if(type != null && type.equals(Constantes.CMIS_TYPE_DOCUMENT)){
                                // content
                                byte[] content = "Hello World!".getBytes();
                               
                                InputStream stream = new ByteArrayInputStream(content);
                                ContentStream contentStream = new ContentStreamImpl(name, new BigInteger(content), Constantes.CONTENT_TYPE_TEXT, stream);
                                newContent = parent.createDocument(properties, contentStream, VersioningState.MAJOR);
                        }else if(type != null && type.equals(Constantes.CMIS_TYPE_FOLDER)){
                                newContent = parent.createFolder(properties);
                        }
               
                }catch(Exception e){
                        logger.error("Ha ocurrido un error creando contenido: "+ e.getMessage());
                }
               
                return newContent;
       
        }

rafex
Member II

Re: Crear un documento sobre una carpeta especifica [Solucionado

Muchas gracias pjcaracuel!

Otra forma que encontré de resolverlo fue la siguiente:

Folder folder = (Folder) session.getObject(idfolder);

Dónde idfolder es un simple String dónde le envio el id de la carpeta, ejemplo:
workspace://SpacesStore/b20d3964-5dea-4c69-8614-231359e5cf67

Así que les regalo una clase muy sencilla que hace esto:

import java.io.ByteArrayInputStream;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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.ItemIterable;
import org.apache.chemistry.opencmis.client.api.QueryResult;
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.data.ContentStream;
import org.apache.chemistry.opencmis.commons.data.PropertyData;
import org.apache.chemistry.opencmis.commons.enums.BindingType;
import org.apache.chemistry.opencmis.commons.enums.VersioningState;
import org.apache.chemistry.opencmis.commons.exceptions.CmisConstraintException;
import org.apache.chemistry.opencmis.commons.impl.dataobjects.ContentStreamImpl;
import org.apache.log4j.Logger;


/**
* @author Raúl González by @rafex
*
*/
public class Controller {
   
   private static Logger logger = Logger.getLogger(Controller.class);
   private Session session = null;
   
   
   public Controller(){
      Map<String, String> parameter = new HashMap<String, String>();
      // Set the user credentials
      parameter.put(SessionParameter.USER, "user");
      parameter.put(SessionParameter.PASSWORD, "passUser");
      // Specify the connection settings
      parameter.put(SessionParameter.ATOMPUB_URL, "http://127.0.0.1:9090/alfresco/service/cmis");
      parameter.put(SessionParameter.BINDING_TYPE, BindingType.ATOMPUB.value());
      // Set the alfresco object factory
      parameter.put(SessionParameter.OBJECT_FACTORY_CLASS, "org.alfresco.cmis.client.impl.AlfrescoObjectFactoryImpl");
      // Create a session
      SessionFactory factory = SessionFactoryImpl.newInstance();
      //this.session = factory.getRepositories(parameter).get(0).createSession();      
      // create session
        List<Repository> repositories = factory.getRepositories(parameter);       
        if (repositories != null && !repositories.isEmpty()) {
            this.session = factory.getRepositories(parameter).get(0).createSession();
        } else {
            logger.error("No se encontro repositorio");          
        }         
   }
   
   public Controller(String usuario, String contrasenia){      
      Map<String, String> parameter = new HashMap<String, String>();
      // Set the user credentials
      parameter.put(SessionParameter.USER, usuario);
      parameter.put(SessionParameter.PASSWORD, contrasenia);
      // Specify the connection settings
      parameter.put(SessionParameter.ATOMPUB_URL, "http://127.0.0.1:9090/alfresco/service/cmis");
      parameter.put(SessionParameter.BINDING_TYPE, BindingType.ATOMPUB.value());
      // Set the alfresco object factory
      parameter.put(SessionParameter.OBJECT_FACTORY_CLASS, "org.alfresco.cmis.client.impl.AlfrescoObjectFactoryImpl");
      // Create a session
      SessionFactory factory = SessionFactoryImpl.newInstance();
      //this.session = factory.getRepositories(parameter).get(0).createSession();      
      // create session
        List<Repository> repositories = factory.getRepositories(parameter);       
        if (repositories != null && !repositories.isEmpty()) {
            this.session = factory.getRepositories(parameter).get(0).createSession();
        } else {
            logger.error("Not found repository");          
        }      
   }

public String uploadFile(Folder folder,byte[] bytes,String fileName,String contentType) {
      String idDoc = null;
      // properties
       Map<String, Object> newDocProps = new HashMap<String, Object>();
       newDocProps.put(PropertyIds.OBJECT_TYPE_ID, "cmis:document");
       newDocProps.put(PropertyIds.NAME, fileName);
       ContentStream contentStream = new ContentStreamImpl(fileName, BigInteger.valueOf(bytes.length),contentType, new ByteArrayInputStream(bytes));
       try{
          // create the file
          Document doc = folder.createDocument(newDocProps, contentStream,VersioningState.NONE);
          idDoc = doc.getId();
       } catch(CmisConstraintException e){
          logger.error("Could not create file");
       }
       return idDoc;
   }
   
   public String uploadFile(String idfolder,byte[] bytes,String fileName,String contentType) {
      String idDoc = null;
      // properties
      Folder folder = (Folder) session.getObject(idfolder);
      Map<String, Object> newDocProps = new HashMap<String, Object>();
       newDocProps.put(PropertyIds.OBJECT_TYPE_ID, "cmis:document");
       newDocProps.put(PropertyIds.NAME, fileName);
       ContentStream contentStream = new ContentStreamImpl(fileName, BigInteger.valueOf(bytes.length),contentType, new ByteArrayInputStream(bytes));
       try{
          // create the file
          Document doc = folder.createDocument(newDocProps, contentStream,VersioningState.NONE);
          idDoc = doc.getId();
       } catch(CmisConstraintException e){
          logger.error("Could not create file");
       }
       return idDoc;
   }
}