Importar archivos (Solucionado) - Pronto subire un how to

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

Importar archivos (Solucionado) - Pronto subire un how to

Buenos dias

Soy bastante bastante novato en todo esto…. (malo si ya empiezo excusandome, jeje).

Mi problema es el siguiente. Quiero realizar una importación de ficheros he cogido de la api las siguientes lineas:


// specify the location within the Repository to import into
Location location = new Location(new StoreRef("workspace", "SpacesStore") );


// setup an ACP Package Handler to import from an ACP file
ImportPackageHandler handler = new ACPImportPackageHandler(…);


// import (note: in this example we're not interested in progress)
importer.importView(handler, location, null, null);

No he conseguido inizializar la clase ImporterService para poder utilizar el importView.

Ademas de esto entiendo que se debe pasar un fichero acp, me gustaria saber si hay alguna forma de generar estos ficheros…

Un saludo y gracias
41 Replies
pablo_zapico
Member II

Re: Importar archivos (Solucionado) - Pronto subire un how to

Creo y solo creo q lo q tenia q poner es


ImporterComponent importer = new ImporterComponent();

Ya me deja utilizar el importerView. Aun asi me gustaria saber si alguien me puede echar un cable o una soga…
pjcaracuel_2349
Active Member II

Re: Importar archivos (Solucionado) - Pronto subire un how to

Hola Pablo,

Echale un vistazo a este post por si te sirve
http://forums.alfresco.com/en/viewtopic.php?t=2490

Saludos
pablo_zapico
Member II

Re: Importar archivos (Solucionado) - Pronto subire un how to

Muchas gracias!!


Ya tengo un fichero acp para hacer pruebas. Me esta costando montar el servicio para hacer los envios.
pjcaracuel_2349
Active Member II

Re: Importar archivos (Solucionado) - Pronto subire un how to

Perfecto, luego si te acuerdas comparte tus conocimientos con el resto de los mortales.

Saludos
pablo_zapico
Member II

Re: Importar archivos (Solucionado) - Pronto subire un how to

No lo he conseguido de una forma limpia, solo lo necesito para trastear, pero cuando consiga montarlo si es q lo consigo lo contare.

Tengo problemas para conseguir enviar el fichero acp. No se muy bien los parametros que se deben indicar. Tngo lo siguiente


ImporterComponent importer = new ImporterComponent();
            StoreRef ref = new StoreRef("workspace", "SpacesStore");
            Location location = new Location(ref);


            // setup an ACP Package Handler to import from an ACP file
            ImportPackageHandler handler = new ACPImportPackageHandler(new File("c:\\GuestHome.acp"),"acp");


            // import (note: in this example we're not interested in progress)
            importer.importView(handler, location, null, null);
pjcaracuel_2349
Active Member II

Re: Importar archivos (Solucionado) - Pronto subire un how to

Pos esto es lo que viene en el javadoc

public void importView(ImportPackageHandler importHandler,
                       Location location,
                       ImporterBinding binding,
                       ImporterProgress progress)
                throws ImporterException

    Description copied from interface: ImporterService
    Import a Repository view into the specified location This import allows for a custom content importer.

    Specified by:
        importView in interface ImporterService

    Parameters:
        importHandler - custom content importer
        location - the location to import under
        binding - property values used for binding property place holders in import stream
        progress - progress monitor (optional)
    Throws:
        ImporterException


Que error te da??

Saludos
pablo_zapico
Member II

Re: Importar archivos (Solucionado) - Pronto subire un how to

Buenas.. Lo primero gracias por ayudarme..

No me da ningun resultado ese es el problema…

La cosa es que yo si realizo el import desde alfresco de mi acp, funciona correctamente - Con lo que el acp esta bien
He probado los servicios de los ejemplos como el de crear contenido y funcionan perfectamente - Con lo que se conectan bien y estan OK

Con lo cual tiene q ser o algun parametro que no este pasando bien o que me falta algo.

Llevo 3 dias con Alfresco y no paro de pegarmela, jejejej


Gracias, Saludos
pablo_zapico
Member II

Re: Importar archivos (Solucionado) - Pronto subire un how to

Quise poner que no me da ninguna excepcion…


Creo que tngo mal el servicio y no se esta conectando. Yo pensaba que se conecta cuando lanzo


importer.importView(handler, location, null, null);

Pero no debe de ser
pjcaracuel_2349
Active Member II

Re: Importar archivos (Solucionado) - Pronto subire un how to

A ver, yo es que llevo ya tiempo sin programar pero no se si habras visto ejemplo que te pongo


/*
* Copyright (C) 2005-2007 Alfresco Software Limited.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.

* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.

* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

* As a special exception to the terms and conditions of version 2.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* and Open Source Software ("FLOSS") applications as described in Alfresco's
* FLOSS exception.  You should have recieved a copy of the text describing
* the FLOSS exception, and it is also available here:
* http://www.alfresco.com/legal/licensing"
*/
package org.alfresco.tools;

import java.io.File;
import java.io.Serializable;
import java.nio.charset.Charset;

import org.alfresco.repo.importer.ACPImportPackageHandler;
import org.alfresco.repo.importer.FileImportPackageHandler;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.cmr.security.AccessPermission;
import org.alfresco.service.cmr.view.ImportPackageHandler;
import org.alfresco.service.cmr.view.ImporterBinding;
import org.alfresco.service.cmr.view.ImporterException;
import org.alfresco.service.cmr.view.ImporterProgress;
import org.alfresco.service.cmr.view.ImporterService;
import org.alfresco.service.cmr.view.Location;
import org.alfresco.service.cmr.view.ImporterBinding.UUID_BINDING;
import org.alfresco.service.namespace.QName;



/**
* Import Tool.
*
* @author David Caruana
*/
public class Import extends Tool
{
    /** Import Tool Context */
    private ImportContext context;
   
   
    /**
     * Entry Point
     *
     * @param args
     */
    public static void main(String[] args)
    {
        Tool tool = new Import();
        tool.start(args);
    }
   
    /* (non-Javadoc)
     * @see org.alfresco.tools.Tool#processArgs(java.lang.String[])
     */
    protected @Override
    /*package*/ ToolContext processArgs(String[] args)
       throws ToolArgumentException
    {
        context = new ImportContext();
        context.setLogin(true);

        int i = 0;
        while (i < args.length)
        {
            if (args[i].equals("-h") || args[i].equals("-help"))
            {
                context.setHelp(true);
                break;
            }
            else if (args[i].equals("-s") || args[i].equals("-store"))
            {
                i++;
                if (i == args.length || args[i].length() == 0)
                {
                    throw new ToolArgumentException("The value <store> for the option -store must be specified");
                }
                context.storeRef = new StoreRef(args[i]);
            }
            else if (args[i].equals("-p") || args[i].equals("-path"))
            {
                i++;
                if (i == args.length || args[i].length() == 0)
                {
                    throw new ToolArgumentException("The value <path> for the option -path must be specified");
                }
                context.path = args[i];
            }
            else if (args[i].equals("-d") || args[i].equals("-dir"))
            {
                i++;
                if (i == args.length || args[i].length() == 0)
                {
                    throw new ToolArgumentException("The value <dir> for the option -dir must be specified");
                }
                context.sourceDir = args[i];
            }
            else if (args[i].equals("-user"))
            {
                i++;
                if (i == args.length || args[i].length() == 0)
                {
                    throw new ToolArgumentException("The value <user> for the option -user must be specified");
                }
                context.setUsername(args[i]);
            }
            else if (args[i].equals("-pwd"))
            {
                i++;
                if (i == args.length || args[i].length() == 0)
                {
                    throw new ToolArgumentException("The value <password> for the option -pwd must be specified");
                }
                context.setPassword(args[i]);
            }
            else if (args[i].equals("-encoding"))
            {
                i++;
                if (i == args.length || args[i].length() == 0)
                {
                    throw new ToolArgumentException("The value <encoding> for the option -encoding must be specified");
                }
                context.encoding = args[i];
            }
            else if (args[i].equals("-uuidBinding"))
            {
                i++;
                try
                {
                    context.uuidBinding = UUID_BINDING.valueOf(UUID_BINDING.class, args[i]);
                }
                catch(IllegalArgumentException e)
                {
                    throw new ToolArgumentException("The value " + args[i] + " is an invalid uuidBinding");
                }
            }
            else if (args[i].equals("-quiet"))
            {
                context.setQuiet(true);
            }
            else if (args[i].equals("-verbose"))
            {
                context.setVerbose(true);
            }
            else if (i == (args.length - 1))
            {
                context.packageName = args[i];
            }
            else
            {
                throw new ToolArgumentException("Unknown option " + args[i]);
            }

            // next argument
            i++;
        }

        return context;
    }
   
    /* (non-Javadoc)
     * @see org.alfresco.tools.Tool#displayHelp()
     */
    protected @Override
    /*package*/ void displayHelp()
    {
       logError("Usage: import -user username -s[tore] store [options] packagename");
       logError("");
       logError("username: username for login");
        logError("store: the store to import into the form of scheme://store_name");
        logError("packagename: the filename to import from (with or without extension)");
        logError("");
        logError("Options:");
        logError(" -h[elp] display this help");
        logError(" -p[ath] the path within the store to extract into (default: /)");
        logError(" -d[ir] the source directory to import from (default: current directory)");
        logError(" -pwd password for login");
        logError(" -encoding package file encoding (default: " + Charset.defaultCharset() + ")");
        logError(" -uuidBinding CREATE_NEW, REMOVE_EXISTING, REPLACE_EXISTING, UPDATE_EXISTING, THROW_ON_COLLISION (default: CREATE_NEW)");
        logError(" -quiet do not display any messages during import");
        logError(" -verbose report import progress");
    }
   
    /* (non-Javadoc)
     * @see org.alfresco.tools.Tool#getToolName()
     */
    protected @Override
    /*package*/ String getToolName()
    {
        return "Alfresco Repository Importer";
    }
   
    /* (non-Javadoc)
     * @see org.alfresco.tools.Tool#execute()
     */
    protected @Override
    /*package*/ int execute() throws ToolException
    {
        ImporterService importer = getServiceRegistry().getImporterService();
       
        // determine type of import (from zip or file system)
        ImportPackageHandler importHandler;
        if (context.zipFile)
        {
            importHandler = new ZipHandler(context.getSourceDir(), context.getPackageFile(), context.encoding);
        }
        else
        {
            importHandler = new FileHandler(context.getSourceDir(), context.getPackageFile(), context.encoding);
        }
       
        try
        {
            ImportBinding binding = new ImportBinding(context.uuidBinding);
            importer.importView(importHandler, context.getLocation(), binding, new ImportProgress());
        }
        catch(ImporterException e)
        {
            throw new ToolException("Failed to import package due to " + e.getMessage(), e);
        }
       
        return 0;
    }

    /**
     * Handler for importing Repository content from zip package
     *
     * @author David Caruana
     */
    private class ZipHandler extends ACPImportPackageHandler
    {
        /**
         * Construct
         *
         * @param sourceDir
         * @param dataFile
         * @param dataFileEncoding
         */
        public ZipHandler(File sourceDir, File dataFile, String dataFileEncoding)
        {
            super(new File(sourceDir, dataFile.getPath()), dataFileEncoding);
        }

        /**
         * Log Export Message
         *
         * @param message  message to log
         */
        protected void log(String message)
        {
            Import.this.logInfo(message);
        }
    }
   
    /**
     * Handler for importing Repository content from file system files
     *
     * @author David Caruana
     */
    private class FileHandler extends FileImportPackageHandler
    {
        /**
         * Construct
         *
         * @param sourceDir
         * @param dataFile
         * @param dataFileEncoding
         */
        public FileHandler(File sourceDir, File dataFile, String dataFileEncoding)
        {
            super(sourceDir, dataFile, dataFileEncoding);
        }

        /**
         * Log Export Message
         *
         * @param message  message to log
         */
        protected void log(String message)
        {
            Import.this.logInfo(message);
        }
    }
   
    /**
     * Report Import Progress
     *
     * @author David Caruana
     */
    private class ImportProgress implements ImporterProgress
    {
        /* (non-Javadoc)
         * @see org.alfresco.service.cmr.view.ImporterProgress#nodeCreated(org.alfresco.service.cmr.repository.NodeRef, org.alfresco.service.cmr.repository.NodeRef, org.alfresco.service.namespace.QName, org.alfresco.service.namespace.QName)
         */
        public void nodeCreated(NodeRef nodeRef, NodeRef parentRef, QName assocName, QName childName)
        {
            logVerbose("Imported node " + nodeRef + " (parent=" + parentRef + ", childname=" + childName + ", association=" + assocName + ")");           
        }

        /*
         * (non-Javadoc)
         * @see org.alfresco.service.cmr.view.ImporterProgress#nodeLinked(org.alfresco.service.cmr.repository.NodeRef, org.alfresco.service.cmr.repository.NodeRef, org.alfresco.service.namespace.QName, org.alfresco.service.namespace.QName)
         */
        public void nodeLinked(NodeRef nodeRef, NodeRef parentRef, QName assocName, QName childName)
        {
        }
       
        /* (non-Javadoc)
         * @see org.alfresco.service.cmr.view.ImporterProgress#contentCreated(org.alfresco.service.cmr.repository.NodeRef, java.lang.String)
         */
        public void contentCreated(NodeRef nodeRef, String sourceUrl)
        {
        }

        /* (non-Javadoc)
         * @see org.alfresco.service.cmr.view.ImporterProgress#propertySet(org.alfresco.service.cmr.repository.NodeRef, org.alfresco.service.namespace.QName, java.io.Serializable)
         */
        public void propertySet(NodeRef nodeRef, QName property, Serializable value)
        {
        }

        /* (non-Javadoc)
         * @see org.alfresco.service.cmr.view.ImporterProgress#permissionSet(org.alfresco.service.cmr.repository.NodeRef, org.alfresco.service.cmr.security.AccessPermission)
         */
        public void permissionSet(NodeRef nodeRef, AccessPermission permission)
        {
        }

        /* (non-Javadoc)
         * @see org.alfresco.service.cmr.view.ImporterProgress#aspectAdded(org.alfresco.service.cmr.repository.NodeRef, org.alfresco.service.namespace.QName)
         */
        public void aspectAdded(NodeRef nodeRef, QName aspect)
        {
        }

        /* (non-Javadoc)
         * @see org.alfresco.service.cmr.view.ImporterProgress#started()
         */
        public void started()
        {
        }

        /* (non-Javadoc)
         * @see org.alfresco.service.cmr.view.ImporterProgress#completed()
         */
        public void completed()
        {
        }

        /* (non-Javadoc)
         * @see org.alfresco.service.cmr.view.ImporterProgress#error(java.lang.Throwable)
         */
        public void error(Throwable e)
        {
        }
    }
   
    /**
     * Import Tool Context
     *
     * @author David Caruana
     */
    private class ImportContext extends ToolContext
    {
        /** Store Reference to import into */
        private StoreRef storeRef;
        /** Path to import into */
        private String path;
        /** Source directory to import from */
        private String sourceDir;
        /** The package name to import */
        private String packageName;
        /** The package encoding */
        private String encoding = null;
        /** The UUID Binding */
        private UUID_BINDING uuidBinding = UUID_BINDING.CREATE_NEW;
        /** Zip Package? */
        private boolean zipFile = false;

        /* (non-Javadoc)
         * @see org.alfresco.tools.ToolContext#validate()
         */
        @Override
        /*package*/ void validate()
        {
            super.validate();
           
            if (storeRef == null)
            {
                throw new ToolArgumentException("Store to import into has not been specified.");
            }
            if (packageName == null)
            {
                throw new ToolArgumentException("Package name has not been specified.");
            }
            if (sourceDir != null)
            {
                File fileSourceDir = getSourceDir();
                if (fileSourceDir.exists() == false)
                {
                    throw new ToolArgumentException("Source directory " + fileSourceDir.getAbsolutePath() + " does not exist.");
                }
            }
            if (packageName.endsWith(".acp") || packageName.endsWith(".zip"))
            {
                File packageFile = new File(getSourceDir(), packageName);
                if (!packageFile.exists())
                {
                    throw new ToolArgumentException("Package zip file " + packageFile.getAbsolutePath() + " does not exist.");
                }
                zipFile = true;
            }
            else
            {
                File packageFile = new File(getSourceDir(), getDataFile().getPath());
                if (!packageFile.exists())
                {
                    throw new ToolArgumentException("Package file " + packageFile.getAbsolutePath() + " does not exist.");
                }
            }
        }

        /**
         * Get the location within the Repository to import into
         *
         * @return the location
         */
        private Location getLocation()
        {
            Location location = new Location(storeRef);
            location.setPath(path);
            return location;
        }
       
        /**
         * Get the source directory
         *
         * @return the source directory (or null if current directory)
         */
        private File getSourceDir()
        {
            File dir = (sourceDir == null) ? null : new File(sourceDir);
            return dir;
        }

        /**
         * Get the xml import file
         *
         * @return the package file
         */
        private File getDataFile()
        {
            String dataFile = (packageName.indexOf('.') != -1) ? packageName : packageName + ".xml";
            File file = new File(dataFile);
            return file;
        }
       
        /**
         * Get the zip import file (.acp - alfresco content package)
         *
         * @return the zip package file
         */
        private File getPackageFile()
        {
            return (zipFile) ? new File(packageName) : getDataFile();
        }       
    }


    /**
     * Import Tool Binding
     *
     * @author davidc
     */
    private class ImportBinding implements ImporterBinding
    {
        private UUID_BINDING uuidBinding = null;
   
        /**
         * Construct
         *
         * @param uuidBinding
         */
        public ImportBinding(UUID_BINDING uuidBinding)
        {
            this.uuidBinding = uuidBinding;
        }
       
        /*
         *  (non-Javadoc)
         * @see org.alfresco.service.cmr.view.ImporterBinding#getUUIDBinding()
         */
        public UUID_BINDING getUUIDBinding()
        {
            return uuidBinding;
        }

        /*
         *  (non-Javadoc)
         * @see org.alfresco.service.cmr.view.ImporterBinding#allowReferenceWithinTransaction()
         */
        public boolean allowReferenceWithinTransaction()
        {
            return false;
        }

        /*
         *  (non-Javadoc)
         * @see org.alfresco.service.cmr.view.ImporterBinding#getValue(java.lang.String)
         */
        public String getValue(String key)
        {
            return null;
        }

        public QName[] getExcludedClasses()
        {
            return new QName[] {};
        }
    }
}


A ver si te ayuda a entender un poco el tema.

Saludos