AnsweredAssumed Answered

Problema al buscar contenido desde explorador

Question asked by aplikadote on Nov 19, 2013
Latest reply on Nov 27, 2013 by aplikadote
Para un proyecto necesitamos subir/descargar/eliminar archivos sobre Alfresco. He logrado implementar todas estas acciones usando codigo java: los archivos se visualizan bien en 'Alfresco Explorer' y usando el 'Node Browser' verifique que los UUID archivos existen. Tambien los puedo descargar desde 'Alfresco Explorer'.

El problema es que luego de subir un archivo a Alfresco usando mi codigo y querer buscarlo desde 'Alfresco Explorer' no obtengo ningun resultado. Si subo un archivo manualmente, este problema no ocurre. Claramente estoy pasando por alto algun detalle.

Les dejo mi codigo completo para subir un archivo. Estoy usando 'alfresco-4.0.d'.
Bibliotecas:
  {ALFRESCO_SDK_DIR}/lib/remote/dependencies/*.*
  {ALFRESCO_SDK_DIR}/lib/remote/alfresco-web-service-client-4.0.d.jar
  {ALFRESCO_SDK_DIR}/lib/server/dependencies/commons/*.*
  {ALFRESCO_SDK_DIR}/lib/server/dependencies/axis-1.4.jar
  {ALFRESCO_SDK_DIR}/lib/server/dependencies/json.jar


public class AlfrescoManager {

    public static Store STORE = new Store(Constants.WORKSPACE_STORE, "SpacesStore");

    private String user;
    private String pass;
    private String server;
    //
    private String ticket = null;

    public AlfrescoManager(String user, String pass, String server) {
        this.user = user;
        this.pass = pass;
        this.server = server;
    }

    public void startSession() throws Exception {
        createTicket();
        try {
            WebServiceFactory.setEndpointAddress(server + "/api");
            AuthenticationUtils.startSession(user, pass);
        } catch (AuthenticationFault e) {
            destroyTicket();
            throw new Exception("Autentificacion invalida o no pudo ser realizada");
        }
    }

    private void createTicket() throws Exception {
        try {
            String url = server + "/service/api/login";
            String jsonInput = "{ \"username\" : \"" + user + "\", \"password\" : \"" + pass + "\" }";

            PostMethod method = new PostMethod(url);
            StringRequestEntity requestEntity = new StringRequestEntity(jsonInput, "application/json", "UTF-8");
            method.setRequestEntity(requestEntity);
            HttpClient client = new HttpClient();

            int status = client.executeMethod(method);
            if (status == HttpStatus.SC_OK) {
                String jsonResponse = method.getResponseBodyAsString();
                JSONObject jsonObj = new JSONObject(jsonResponse);
                JSONObject data = (JSONObject) jsonObj.get("data");
                this.ticket = data.get("ticket").toString();
            } else {
                throw new Exception("Autentificacion invalida, status: " + HttpStatus.getStatusText(status));
            }
        } catch (Exception e) {
            throw new Exception("Error al obtener ticket", e);
        }
    }

    public void endSession() {
        try {
            destroyTicket();
        } catch (Exception e) {
            e.printStackTrace();
        }
        AuthenticationUtils.endSession();
    }

    private void destroyTicket() throws Exception {
        try {
            String url = server + "/service/api/login/ticket/" + ticket + "?alf_ticket=" + ticket;

            DeleteMethod method = new DeleteMethod(url);
            HttpClient client = new HttpClient();

            int status = client.executeMethod(method);
            if (status == HttpStatus.SC_OK) {
//                log.debug("ticket borrado");
            } else {
                throw new Exception("Error al eliminar ticket, status: " + HttpStatus.getStatusText(status));
            }
        } catch (Exception e) {
            throw new Exception("Error al eliminar el ticket: " + ticket, e);
        }
    }

    public String upload(String parentUuid, byte[] bytes, String filename, String desc) throws Exception {
        try {
            // SUBIENDO ARCHIVO VIA API RESTFUL
            String url = server + "/upload/workspace/SpacesStore/" + parentUuid + "/";
            PutMethod putMethod = new PutMethod(url + filename + "?ticket=" + ticket);

            Part[] parts = new Part[3];
            parts[0] = new FilePart("filedata", new ByteArrayPartSource(filename, bytes));
            parts[1] = new StringPart("filename", filename);
            parts[2] = new StringPart("description", desc);
            putMethod.setRequestEntity(new MultipartRequestEntity(parts, putMethod.getParams()));

            HttpClient client = new HttpClient();
            int status = client.executeMethod(putMethod);
            if (status == HttpStatus.SC_OK) {
                String content = putMethod.getResponseBodyAsString();

                // ACTUALIZANDO EL CONTENIDO VIA WEBSERVICES CON CMI
                ParentReference parentRef = new ParentReference(STORE, parentUuid, null, Constants.ASSOC_CONTAINS, null);
                parentRef.setChildName("cm:" + filename);

                NamedValue[] properties = new NamedValue[2];
                properties[0] = Utils.createNamedValue(Constants.PROP_NAME, filename);
                properties[1] = Utils.createNamedValue(Constants.PROP_CONTENT, content);
                CMLCreate create = new CMLCreate("1", parentRef, null, null, null, Constants.TYPE_CONTENT, properties);

                NamedValue[] titledProps = new NamedValue[2];
                titledProps[0] = Utils.createNamedValue(Constants.PROP_TITLE, "titulo");
                titledProps[1] = Utils.createNamedValue(Constants.PROP_DESCRIPTION, "descripcion");
                CMLAddAspect aspect = new CMLAddAspect(Constants.ASPECT_TITLED, titledProps, null, "1");

                CML cml = new CML();
                cml.setCreate(new CMLCreate[] { create });
                cml.setAddAspect(new CMLAddAspect[] { aspect });

                RepositoryServiceSoapBindingStub repositoryServiceStub = WebServiceFactory.getRepositoryService();
                UpdateResult[] update = repositoryServiceStub.update(cml);
                return update[0].getDestination().getUuid();
            } else {
                throw new Exception("Error al subir fichero'" + filename + "', status: " + HttpStatus.getStatusText(status));
            }
        } catch (Exception e) {
            throw new Exception("Error al subir archivo", e);
        }
    }
   
    public static void main(String[] args) {
        String user = "admin";
        String pass = "admin";
        String server = "http://localhost:8080/alfresco-4.0.d";
        Alfresco alfresco = new Alfresco(user, pass, server);
        try {
            alfresco.startSession();

            File file = new File("D:\\archivo2.pdf");
            byte[] fileToBytes = fileToBytes(file);
            String companyHomeUuid = alfresco.getCompanyHomeUuid();
            String uuid = alfresco.upload(companyHomeUuid, fileToBytes, file.getName(), "descripcion");
            System.out.println(uuid);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            alfresco.endSession();
        }
    }
   
    public static byte[] fileToBytes(File file) throws Exception {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            for (int readNum; (readNum = fis.read(buf)) != -1;) {
                bos.write(buf, 0, readNum);
            }
            return bos.toByteArray();
        } catch (Exception ex) {
            throw new Exception("El archivo no existe");
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}



Outcomes