Aplicao Java cliente do Data Service Openbus Tecgraf
Aplicação Java cliente do Data. Service Openbus Tecgraf PUC-Rio maio de 2011
Sobre o exemplo • Mostraremos um exemplo de uma aplicação cliente que usa o Data. Service publicado pelo Serviço de Projetos dos sistemas CSBase. • Para tal, vamos assumir que existe um CSGrid (ou outro sistema CSBase) executando e que tenha publicado em um barramento Open. Bus o Data. Service. • O serviço de Projetos CSBase implementa um componente de serviço IHierarchical. Data. Service
Passo 1: Obtendo as libs do Data. Service • A última versão das bibliotecas java do Serviço de Dados pode ser obtida em: • https: //jira. tecgraf. pucrio. br/confluence/pages/viewpage. action? page. Id= 27067037 • A biblioteca com os tipos usados no serviço de dados data sources (ex: repositório de projetos do CSGrid) devem ser requisitadas ao administrador do próprio sistema.
Libs do Data. Service • Core: • openbus-data_service-api-1. 0. 1. jar • openbus-data_service-idl-jacorb-1. 0. 1. jar • openbus-data_service-valuetype-1. 0. 1. jar • Serviço de Projetos CSBase: • openbus-data_service-project-idl-jacorb-1. 0. 1. jar • openbus-data_service-project-valuetype-1. 0. 1. jar
Passo 2: Implementando o Cliente • O programa cliente se encarrega de: – inicializar o Openbus e registrar as fábricas dos value types utilizados – fazer a autenticação no barramento – exibir a estrutura de pastas e arquivos que compôem um projeto CSBase – copiar o conteúdo de um arquivo local para uma pasta de um projeto CSBase – ler um arquivo remoto
Registro das fábricas dos valuetypes import import. . . tecgraf. openbus. data_service. Data. Description. Factory; tecgraf. openbus. data_service. Data. Description. Helper; tecgraf. openbus. project. Project. Item. Description. Helper; tecgraf. openbus. data_service. project. Project. Item. Description. Factory; tecgraf. openbus. data_service. Unstructured. Data. Helper; Openbus = Openbus. get. Instance(); ORB orb = (ORB) bus. get. ORB(); orb. register_value_factory(Data. Description. Helper. id(), new Data. Description. Factory()); orb. register_value_factory(Project. Item. Description. Helper. id(), new Project. Item. Description. Factory()); orb. register_value_factory(Unstructured. Data. Helper. id(), new Unstructured. Data. Factory());
Procurando o serviço Project. Data. Service String component. Name = props. get. Property("dataservice. component. name”); String component. Version = props. get. Property("dataservice. component. version”); String component. Id = component. Name + ": " + component. Version; Property property = new Property("component_id", new String[] { component. Id }); String facet. Name = "Project. Data. Service"; Service. Offer[] services. Offers = registry. Service. find. By. Criteria( new String[] {facet. Name}, new Property[] { property }); if (services. Offers. length == 0) { throw new Project. Service. Client. Exception("Não foi encontrado um serviço " + facet. Name + " com identificador: " + component. Id); } if (services. Offers. length > 1) { throw new Project. Service. Client. Exception( "Foi encontrado mais de um serviço " + facet. Name + " com identificador: " + component. Id); } Service. Offer service. Offer = services. Offers[0]; IComponent component = service. Offer. member; IHierarchical. Data. Service data. Service = IHierarchical. Data. Service. Helper. narrow(component. get. Facet(IHierarchical. Data. Service. Helper. id())); • Outra forma de procurar pelo componente é usando a propriedade registered_by com o nome da entidade que publicou o componente f
Obtendo o descritor da raiz do projeto String project. Name = props. get. Property("dataservice. project. name"); Data. Description[] root. Desc. List = data. Service. get. Roots(); if (root. Desc. List. length < 1) { throw new Project. Service. Client. Exception("O usuário não possui projetos"); } for (int i = 0; i < root. Desc. List. length; i++) { Data. Description root. Desc = root. Desc. List[i]; if (!(root. Desc instanceof Project. Item. Description)) { throw new Project. Service. Client. Exception("Descritor inválido: " + root. Desc. to. String()); } if (root. Desc. f. Name. equals(project. Name)) { return root. Desc; } } • O valuetype Project. Item. Description precisa estar registrado no ORB com a sua respectiva fábrica
Exibindo a árvore de dados do projeto private void show. Folder(int count, Data. Description desc) throws Project. Service. Client. Exception { try { String. Buffer ident = new String. Buffer(); for (int i = 0; i < count; i++) { ident. append(' '); } Data. Description[] children = data. Service. get. Children(desc. f. Key); for (Data. Description child : children) { String child. Name = child. f. Name; Project. Item. Description child. Desc = (Project. Item. Description) data. Service. get. Data. Description(child. f. Key); if (child. Desc. f. Is. Container) { System. out. println(ident + "+ Diretorio: " + child. Name); show. Folder(count + 3, child); } else { System. out. println(ident + "- Arquivo: " + child. Name); } } } catch (Exception e) { throw new Project. Service. Client. Exception( "Erro na exibição do conteúdo da pasta" + desc. f. Name, e); } }
Para criar um arquivo • Precisamos instanciar um Project. Item. Description. Impl /** * Constrói uma descrição de um item de projeto. * @param key A chave unívoca do item de projeto. * @param name O nome do item de projeto. * @param views As visões oferecidas para o item de projeto. * @param metadata Os metadados do item de projeto. * @param owner O dono do item. * @param description Um texto explicativo. * @param path O caminho. * @param type O tipo. * @param size O tamanho. * @param is. Container Indica se o item pode conter outros itens. * @param can. Read Indica se o item pode ser lido. * @param can. Write Indica se o item pode ser alterado. * @param creation. Date A data de criação. * @param modification. Date A data de última modificação. */ public Project. Item. Description. Impl(byte[] key, String name, Set<String> views, List<Metadata> metadata, String owner, String description, String path, String type, long size, boolean is. Container, boolean can. Read, boolean can. Write, long creation. Date, long modification. Date) {. . . }
Escrevendo um arquivo usando o FTC public Data. Description create. Remote. File(String file. Name, byte[] data, Data. Description desc) throws Project. Service. Client. Exception { try { long current. Date = Calendar. get. Instance(). get. Time. In. Millis(); Project. Item. Description prototype = new Project. Item. Description. Impl(file. Name, new Hash. Set<String>(), new Array. List<Metadata>(), user. Login, null, "TEXT", 0, false, true, current. Date); byte[] file. Key = data. Service. create. Data(desc. f. Key, prototype); Unstructured. Data view = (Unstructured. Data) data. Service. get. Data. View(file. Key, Unstructured. Data. Helper. id()); Data. Key data. Key = new Data. Key(view. f. Key); Remote. File. Channel rfc = new Remote. File. Channel. Impl(data. Key. get. Data. Id(). get. Bytes( Utils. CHARSET_ENCODING), view. f. Writable, view. f. Host, view. f. Port, view. f. Access. Key); rfc. open(false); rfc. write(data); rfc. close(); return data. Service. get. Data. Description(file. Key); } catch (Exception e) { throw new Project. Service. Client. Exception( "Erro na criação de um arquivo na pasta", e); } }
Lendo um arquivo usando o FTC public byte[] read. Remote. File(Data. Description desc) throws Project. Service. Client. Exception { try { Unstructured. Data view = (Unstructured. Data) data. Service. get. Data. View(desc. f. Key, Unstructured. Data. Helper. id()); Data. Key data. Key = new Data. Key(view. f. Key); Remote. File. Channel rfc = new Remote. File. Channel. Impl(data. Key. get. Data. Id(). get. Bytes( Utils. CHARSET_ENCODING), view. f. Writable, view. f. Host, view. f. Port, view. f. Access. Key); rfc. open(true); int file. Size = (int) rfc. get. Size(); byte[] buffer = new byte[file. Size]; if (file. Size != 0) { rfc. read(buffer); } rfc. close(); return buffer; } catch (Exception e) { throw new Project. Service. Client. Exception( "Erro na leitura de um dado da pasta", e); } }
- Slides: 12