signature:
public class CteConsultaCallbackHandler { /** * auto generated Axis2 call back method for cteConsultaCT method
 * override this method for handling normal response from cteConsultaCT operation */
public void receiveResultcteConsultaCT ( com . fincatto . documentofiscal . cte300 . webservices . consulta . CteConsultaStub . CteConsultaCTResult result ) { } }


signature:
public class MDFeConsNaoEncCallbackHandler { /** * auto generated Axis2 call back method for mdfeConsNaoEnc method
 * override this method for handling normal response from mdfeConsNaoEnc operation */
public void receiveResultmdfeConsNaoEnc ( com . fincatto . documentofiscal . mdfe3 . webservices . consultanaoencerrado . MDFeConsNaoEncStub . MdfeConsNaoEncResult result ) { } }


signature:
public class MDFeParser { /** * Transforma arquivo XML ( tag : MDFe ) para objeto ( MDFe )
 * @ param xml
 * @ return */
public MDFe mdfeParaObjeto ( final File xml ) { } }

implementation: try { return this . persister . read ( MDFe . class , xml ) ; } catch ( final Exception e ) { throw new IllegalArgumentException ( String . format ( "Nao foi possivel parsear o xml: %s" , e . getMessage ( ) ) ) ; }


signature:
public class MDFeParser { /** * Transforma arquivo XML ( tag : mdfeProc ) para objeto ( MDFProcessado )
 * @ param xml
 * @ return */
public MDFProcessado mdfeProcessadoParaObjeto ( final File xml ) { } }

implementation: try { return this . persister . read ( MDFProcessado . class , xml ) ; } catch ( final Exception e ) { throw new IllegalArgumentException ( String . format ( "Nao foi possivel parsear o xml: %s" , e . getMessage ( ) ) ) ; }


signature:
public class MDFeParser { /** * Transforma string XML ( tag : eventoMDFe ) para objeto ( MDFeEvento )
 * @ param xml
 * @ return */
public MDFeEvento mdfeEventoParaObjeto ( final String xml ) { } }

implementation: try { return this . persister . read ( MDFeEvento . class , xml ) ; } catch ( final Exception e ) { throw new IllegalArgumentException ( String . format ( "Nao foi possivel parsear o xml: %s" , e . getMessage ( ) ) ) ; }


signature:
public class StringValidador { /** * Método para validação de Strings .
 * @ param paraValidar String a ser validada
 * @ param info Informação de retorno caso haja erro .
 * @ param tamanho tamanho para validação da { @ code String } , pode ser { @ code null } :
 * @ param exatamente < pre >
 * se false { @ code null } a { @ code String }
 * não precisa ter o tamanho exato do parametro anterior .
 * < / pre >
 * @ param numerico se true { @ code null } a { @ code String } precisa ser numérica [ 0-9 ] .
 * @ param paraValidar } .
 * @ return retorna a própria { @ code String } { */
public static String validador ( final String paraValidar , final String info , Integer tamanho , Boolean exatamente , Boolean numerico ) { } }

implementation: tamanho = ObjectUtils . defaultIfNull ( tamanho , 1 ) ; exatamente = ObjectUtils . defaultIfNull ( exatamente , false ) ; numerico = ObjectUtils . defaultIfNull ( numerico , true ) ; if ( paraValidar != null ) { if ( numerico ) { StringValidador . apenasNumerico ( paraValidar , info ) ; } if ( exatamente ) { StringValidador . validaTamanhoExato ( paraValidar , tamanho , info ) ; } else { StringValidador . validaTamanhoMaximo ( paraValidar , tamanho , info ) ; } } return paraValidar ;


signature:
public class StringValidador { /** * Valida um número com N {
 * < pre >
 * StringValidador . capacidadeNDigitos ( " 10000 " , " info " , 5 ) = " 10000"
 * StringValidador . capacidadeNDigitos ( " 5 " , " info " , 2 ) = " 5"
 * < / pre >
 * @ param capacidade
 * @ param info
 * @ param digitos
 * @ return
 * @ throws IllegalStateException se < br >
 * { @ code capacidade = " 10000 " } & { @ code digitos = 3 } , ou seja , { @ code capacidade . length ( ) - 1 > digitos } */
public static String capacidadeNDigitos ( final String capacidade , final String info , final int digitos ) { } }

implementation: if ( capacidade != null ) { final Matcher matcher = Pattern . compile ( "^(0|[1-9]{1}[0-9]{0," + digitos + "})$" ) . matcher ( capacidade ) ; if ( ! matcher . find ( ) ) { throw new IllegalStateException ( String . format ( "%s fora do padrao (%s)" , info , capacidade ) ) ; } } return capacidade ;


signature:
public class CTeNotaEndereco { /** * Código do país < br >
 * Utilizar a tabela do BACEN */
public void setCodigoPais ( final String codigoPais ) { } }

implementation: StringValidador . tamanho4N ( codigoPais , "Código do país" ) ; this . codigoPais = DFPais . valueOfCodigo ( codigoPais ) ;


signature:
public class MDFeRecepcaoStub { /** * get the default envelope */
@ SuppressWarnings ( "unused" ) private org . apache . axiom . soap . SOAPEnvelope toEnvelope ( final org . apache . axiom . soap . SOAPFactory factory ) { } }

implementation: return factory . getDefaultEnvelope ( ) ;


signature:
public class RecepcaoEventoStub { /** * A utility method that copies the namepaces from the SOAPEnvelope */
private java . util . Map getEnvelopeNamespaces ( final org . apache . axiom . soap . SOAPEnvelope env ) { } }

implementation: final java . util . Map returnMap = new java . util . HashMap ( ) ; final java . util . Iterator namespaceIterator = env . getAllDeclaredNamespaces ( ) ; while ( namespaceIterator . hasNext ( ) ) { final org . apache . axiom . om . OMNamespace ns = ( org . apache . axiom . om . OMNamespace ) namespaceIterator . next ( ) ; returnMap . put ( ns . getPrefix ( ) , ns . getNamespaceURI ( ) ) ; } return returnMap ;


signature:
public class NfeConsultaCallbackHandler { /** * auto generated Axis2 call back method for nfeConsultaNF method
 * override this method for handling normal response from nfeConsultaNF operation */
public void receiveResultnfeConsultaNF ( com . fincatto . documentofiscal . nfe310 . webservices . nota . consulta . NfeConsultaStub . NfeConsultaNFResult result ) { } }


signature:
public class WSLoteEnvio { /** * Retorna o Lote assinado .
 * @ param lote
 * @ return
 * @ throws Exception */
NFLoteEnvio getLoteAssinado ( final NFLoteEnvio lote ) throws Exception { } }

implementation:
// adiciona a chave e o dv antes de assinar
for ( final NFNota nota : lote . getNotas ( ) ) { final NFGeraChave geraChave = new NFGeraChave ( nota ) ; nota . getInfo ( ) . getIdentificacao ( ) . setCodigoRandomico ( StringUtils . defaultIfBlank ( nota . getInfo ( ) . getIdentificacao ( ) . getCodigoRandomico ( ) , geraChave . geraCodigoRandomico ( ) ) ) ; nota . getInfo ( ) . getIdentificacao ( ) . setDigitoVerificador ( geraChave . getDV ( ) ) ; nota . getInfo ( ) . setIdentificador ( geraChave . getChaveAcesso ( ) ) ; } // assina o lote
final String documentoAssinado = new AssinaturaDigital ( this . config ) . assinarDocumento ( lote . toString ( ) ) ; final NFLoteEnvio loteAssinado = new DFParser ( ) . loteParaObjeto ( documentoAssinado ) ; // verifica se nao tem NFCe junto com NFe no lote e gera qrcode ( apos assinar mesmo , eh assim )
int qtdNF = 0 , qtdNFC = 0 ; for ( final NFNota nota : loteAssinado . getNotas ( ) ) { switch ( nota . getInfo ( ) . getIdentificacao ( ) . getModelo ( ) ) { case NFE : qtdNF ++ ; break ; case NFCE : final NFGeraQRCode geraQRCode = new NFGeraQRCode ( nota , this . config ) ; nota . setInfoSuplementar ( new NFNotaInfoSuplementar ( ) ) ; nota . getInfoSuplementar ( ) . setQrCode ( geraQRCode . getQRCode ( ) ) ; qtdNFC ++ ; break ; default : throw new IllegalArgumentException ( String . format ( "Modelo de nota desconhecida: %s" , nota . getInfo ( ) . getIdentificacao ( ) . getModelo ( ) ) ) ; } } // verifica se todas as notas do lote sao do mesmo modelo
if ( ( qtdNF > 0 ) && ( qtdNFC > 0 ) ) { throw new IllegalArgumentException ( "Lote contendo notas de modelos diferentes!" ) ; } return loteAssinado ;


signature:
public class MDFInfoEmitenteEndereco { /** * Logradouro */
public void setLogradouro ( final String logradouro ) { } }

implementation: StringValidador . tamanho2ate60 ( logradouro , "Logradouro no " + MDFInfoEmitenteEndereco . INFO ) ; this . logradouro = logradouro ;


signature:
public class MDFInfoEmitenteEndereco { /** * Número */
public void setNumero ( final String numero ) { } }

implementation: StringValidador . tamanho60 ( numero , "Número no " + MDFInfoEmitenteEndereco . INFO ) ; this . numero = numero ;


signature:
public class MDFInfoEmitenteEndereco { /** * Complemento */
public void setComplemento ( final String complemento ) { } }

implementation: StringValidador . tamanho60 ( complemento , "Complemento no " + MDFInfoEmitenteEndereco . INFO ) ; this . complemento = complemento ;


signature:
public class MDFInfoEmitenteEndereco { /** * Bairro */
public void setBairro ( final String bairro ) { } }

implementation: StringValidador . tamanho2ate60 ( bairro , "Bairro no " + MDFInfoEmitenteEndereco . INFO ) ; this . bairro = bairro ;


signature:
public class MDFInfoEmitenteEndereco { /** * Código do município ( utilizar a tabela do IBGE ) < br >
 * Informar 99999 para operações com o exterior . */
public void setCodigoMunicipio ( final String codigoMunicipio ) { } }

implementation: StringValidador . exatamente7N ( codigoMunicipio , "Código do município no " + MDFInfoEmitenteEndereco . INFO ) ; this . codigoMunicipio = codigoMunicipio ;


signature:
public class MDFInfoEmitenteEndereco { /** * Nome do município < br >
 * Informar EXTERIOR para operações com o exterior . */
public void setDescricaoMunicipio ( final String descricaoMunicipio ) { } }

implementation: StringValidador . tamanho2ate60 ( descricaoMunicipio , "Nome do município no " + MDFInfoEmitenteEndereco . INFO ) ; this . descricaoMunicipio = descricaoMunicipio ;


signature:
public class MDFInfoEmitenteEndereco { /** * CEP < br >
 * Informar os zeros não significativos */
public void setCep ( final String cep ) { } }

implementation: StringValidador . exatamente8N ( cep , "CEP no " + MDFInfoEmitenteEndereco . INFO ) ; this . cep = cep ;


signature:
public class MDFInfoEmitenteEndereco { /** * Sigla da UF < br >
 * Informar EX para operações com o exterior . */
public void setSiglaUF ( final String siglaUF ) { } }

implementation: StringValidador . exatamente2 ( siglaUF , "Sigla da UF no " + MDFInfoEmitenteEndereco . INFO ) ; this . siglaUF = siglaUF ;


signature:
public class WSFacade { /** * Faz o envio de lote para a Sefaz
 * @ param lote o lote a ser enviado para a Sefaz
 * @ return dados do lote retornado pelo webservice , alem do lote assinado
 * @ throws Exception caso nao consiga gerar o xml ou problema de conexao com o sefaz */
public NFLoteEnvioRetornoDados enviaLote ( final NFLoteEnvio lote ) throws Exception { } }

implementation: if ( lote . getIndicadorProcessamento ( ) . equals ( NFLoteIndicadorProcessamento . PROCESSAMENTO_SINCRONO ) && lote . getNotas ( ) . size ( ) > 1 ) { throw new IllegalArgumentException ( "Apenas uma nota permitida no modo sincrono!" ) ; } else if ( lote . getNotas ( ) . size ( ) == 0 ) { throw new IllegalArgumentException ( "Nenhuma nota informada no envio do Lote!" ) ; } return this . wsLoteEnvio . enviaLote ( lote ) ;


signature:
public class WSFacade { /** * Faz o envio assinado para a Sefaz de NF - e e NFC - e ATENCAO : Esse metodo deve ser utilizado para assinaturas A3
 * @ param loteAssinadoXml lote assinado no formato XML
 * @ param modelo modelo da nota ( NF - e ou NFC - e )
 * @ return dados do lote retornado pelo webservice
 * @ throws Exception caso nao consiga gerar o xml ou problema de conexao com o sefaz */
public NFLoteEnvioRetorno enviaLoteAssinado ( final String loteAssinadoXml , final DFModelo modelo ) throws Exception { } }

implementation: return this . wsLoteEnvio . enviaLoteAssinado ( loteAssinadoXml , modelo ) ;


signature:
public class WSFacade { /** * Faz a consulta do lote na Sefaz ( NF - e e NFC - e )
 * @ param numeroRecibo numero do recibo do processamento
 * @ param modelo modelo da nota ( NF - e ou NFC - e )
 * @ return dados de consulta de lote retornado pelo webservice
 * @ throws Exception caso nao consiga gerar o xml ou problema de conexao com o sefaz */
public NFLoteConsultaRetorno consultaLote ( final String numeroRecibo , final DFModelo modelo ) throws Exception { } }

implementation: return this . wsLoteConsulta . consultaLote ( numeroRecibo , modelo ) ;


signature:
public class WSFacade { /** * Faz a consulta de status responsavel pela UF
 * @ param uf uf UF que deseja consultar o status do sefaz responsavel
 * @ param modelo modelo da nota ( NF - e ou NFC - e )
 * @ return dados da consulta de status retornado pelo webservice
 * @ throws Exception caso nao consiga gerar o xml ou problema de conexao com o sefaz */
public NFStatusServicoConsultaRetorno consultaStatus ( final DFUnidadeFederativa uf , final DFModelo modelo ) throws Exception { } }

implementation: return this . wsStatusConsulta . consultaStatus ( uf , modelo ) ;


signature:
public class WSFacade { /** * Faz a correcao da nota
 * @ param chaveDeAcesso chave de acesso da nota
 * @ param textoCorrecao texto de correcao
 * @ param numeroSequencialEvento numero sequencial de evento , esse numero nao pode ser repetido !
 * @ return dados da correcao da nota retornado pelo webservice
 * @ throws Exception caso nao consiga gerar o xml ou problema de conexao com o sefaz */
public NFEnviaEventoRetorno corrigeNota ( final String chaveDeAcesso , final String textoCorrecao , final int numeroSequencialEvento ) throws Exception { } }

implementation: return this . wsCartaCorrecao . corrigeNota ( chaveDeAcesso , textoCorrecao , numeroSequencialEvento ) ;


signature:
public class WSFacade { /** * Faz a correcao da nota com o evento ja assinado ATENCAO : Esse metodo deve ser utilizado para assinaturas A3
 * @ param chave chave de acesso da nota
 * @ param eventoAssinadoXml evento ja assinado em formato XML
 * @ return dados da correcao da nota retornado pelo webservice
 * @ throws Exception caso nao consiga gerar o xml ou problema de conexao com o sefaz */
public NFEnviaEventoRetorno corrigeNotaAssinada ( final String chave , final String eventoAssinadoXml ) throws Exception { } }

implementation: return this . wsCartaCorrecao . corrigeNotaAssinada ( chave , eventoAssinadoXml ) ;


signature:
public class WSFacade { /** * Faz o cancelamento da nota
 * @ param chave chave de acesso da nota
 * @ param numeroProtocolo numero do protocolo da nota
 * @ param motivo motivo do cancelamento
 * @ return dados do cancelamento da nota retornado pelo webservice
 * @ throws Exception caso nao consiga gerar o xml ou problema de conexao com o sefaz */
public NFEnviaEventoRetorno cancelaNota ( final String chave , final String numeroProtocolo , final String motivo ) throws Exception { } }

implementation: return this . wsCancelamento . cancelaNota ( chave , numeroProtocolo , motivo ) ;


signature:
public class WSFacade { /** * Faz o cancelamento da nota com evento ja assinado ATENCAO : Esse metodo deve ser utilizado para assinaturas A3
 * @ param chave chave de acesso da nota
 * @ param eventoAssinadoXml evento ja assinado em formato XML
 * @ return dados do cancelamento da nota retornado pelo webservice
 * @ throws Exception caso nao consiga gerar o xml ou problema de conexao com o sefaz */
public NFEnviaEventoRetorno cancelaNotaAssinada ( final String chave , final String eventoAssinadoXml ) throws Exception { } }

implementation: return this . wsCancelamento . cancelaNotaAssinada ( chave , eventoAssinadoXml ) ;


signature:
public class WSFacade { /** * Inutiliza a nota com o evento assinado ATENCAO : Esse metodo deve ser utilizado para assinaturas A3
 * @ param eventoAssinadoXml evento assinado em XML
 * @ param modelo modelo da nota ( NF - e ou NFC - e )
 * @ return dados da inutilizacao da nota retornado pelo webservice
 * @ throws Exception caso nao consiga gerar o xml ou problema de conexao com o sefaz */
public NFRetornoEventoInutilizacao inutilizaNotaAssinada ( final String eventoAssinadoXml , final DFModelo modelo ) throws Exception { } }

implementation: return this . wsInutilizacao . inutilizaNotaAssinada ( eventoAssinadoXml , modelo ) ;


signature:
public class WSFacade { /** * Inutiliza a nota
 * @ param anoInutilizacaoNumeracao ano de inutilizacao
 * @ param cnpjEmitente CNPJ emitente da nota
 * @ param serie serie da nota
 * @ param numeroInicial numero inicial da nota
 * @ param numeroFinal numero final da nota
 * @ param justificativa justificativa da inutilizacao
 * @ param modelo modelo da nota ( NF - e ou NFC - e )
 * @ return dados da inutilizacao da nota retornado pelo webservice
 * @ throws Exception caso nao consiga gerar o xml ou problema de conexao com o sefaz */
public NFRetornoEventoInutilizacao inutilizaNota ( final int anoInutilizacaoNumeracao , final String cnpjEmitente , final String serie , final String numeroInicial , final String numeroFinal , final String justificativa , final DFModelo modelo ) throws Exception { } }

implementation: return this . wsInutilizacao . inutilizaNota ( anoInutilizacaoNumeracao , cnpjEmitente , serie , numeroInicial , numeroFinal , justificativa , modelo ) ;


signature:
public class WSFacade { /** * Realiza a consulta de cadastro de pessoa juridica com inscricao estadual
 * @ param cnpj CNPJ da pessoa juridica
 * @ param uf UF da pessoa juridica
 * @ return dados da consulta da pessoa juridica retornado pelo webservice
 * @ throws Exception caso nao consiga gerar o xml ou problema de conexao com o sefaz */
public NFRetornoConsultaCadastro consultaCadastro ( final String cnpj , final DFUnidadeFederativa uf ) throws Exception { } }

implementation: return this . wsConsultaCadastro . consultaCadastro ( cnpj , uf ) ;


signature:
public class WSFacade { /** * Faz a manifestação do destinatário da nota
 * @ param chave chave de acesso da nota
 * @ param tipoEvento tipo do evento da manifestacao do destinatario
 * @ param motivo motivo do cancelamento
 * @ param cnpj cnpj do autor do evento
 * @ return dados da manifestacao do destinatario da nota retornado pelo webservice
 * @ throws Exception caso nao consiga gerar o xml ou problema de conexao com o sefaz */
public NFEnviaEventoRetorno manifestaDestinatarioNota ( final String chave , final NFTipoEventoManifestacaoDestinatario tipoEvento , final String motivo , final String cnpj ) throws Exception { } }

implementation: return this . wSManifestacaoDestinatario . manifestaDestinatarioNota ( chave , tipoEvento , motivo , cnpj ) ;


signature:
public class WSFacade { /** * Faz a manifestação do destinatário da nota com evento ja assinado ATENCAO : Esse metodo deve ser utilizado para assinaturas A3
 * @ param chave chave de acesso da nota
 * @ param eventoAssinadoXml evento ja assinado em formato XML
 * @ return dados da manifestacao do destinatario da nota retornado pelo webservice
 * @ throws Exception caso nao consiga gerar o xml ou problema de conexao com o sefaz */
public NFEnviaEventoRetorno manifestaDestinatarioNotaAssinada ( final String chave , final String eventoAssinadoXml ) throws Exception { } }

implementation: return this . wSManifestacaoDestinatario . manifestaDestinatarioNotaAssinada ( chave , eventoAssinadoXml ) ;


signature:
public class WSFacade { /** * Faz consulta de distribuicao das notas fiscais . Pode ser feita pela chave de acesso ou utilizando o NSU ( numero sequencial unico ) da receita .
 * @ param cnpj CNPJ da pessoa juridica a consultar
 * @ param uf Unidade federativa da pessoa juridica a consultar
 * @ param nsu Número Sequencial Único . Geralmente esta consulta será utilizada quando identificado pelo interessado um NSU faltante .
 * O Web Service retornará o documento ou informará que o NSU não existe no Ambiente Nacional . Assim , esta
 * consulta fechará a lacuna do NSU identificado como faltante .
 * @ param ultNsu Último NSU recebido pelo ator . Caso seja informado com zero , ou com um NSU muito antigo , a consulta retornará unicamente as
 * informações resumidas e documentos fiscais eletrônicos que tenham sido recepcionados pelo
 * Ambiente Nacional nos últimos 3 meses .
 * @ return dados da consulta retornado pelo webservice limitando um total de 50 registros
 * @ throws Exception caso nao consiga gerar o xml ou problema de conexao com o sefaz */
public NFDistribuicaoIntRetorno consultarDistribuicaoDFe ( final String cnpj , final DFUnidadeFederativa uf , final String chaveAcesso , final String nsu , final String ultNsu ) throws Exception { } }

implementation: return this . wSDistribuicaoNFe . consultar ( cnpj , uf , chaveAcesso , nsu , ultNsu ) ;


signature:
public class WSDistribuicaoNFe { /** * Metodo para consultar os dados das notas fiscais por chave de acesso ou NSU e retorna o objeto de retorno de distribuicao < br > */
public NFDistribuicaoIntRetorno consultar ( final String cnpj , final DFUnidadeFederativa uf , final String chaveAcesso , final String nsu ) throws Exception { } }

implementation: return consultar ( cnpj , uf , chaveAcesso , nsu , null ) ;


signature:
public class WSDistribuicaoNFe { /** * Metodo para consultar os dados das notas fiscais por chave de acesso ou NSU e retorna o objeto de retorno de distribuicao < br > */
public NFDistribuicaoIntRetorno consultar ( final String cnpj , final DFUnidadeFederativa uf , final String chaveAcesso , final String nsu , final String ultNsu ) throws Exception { } }

implementation:
try { String xmlEnvio = this . gerarNFDistribuicaoInt ( cnpj , uf , chaveAcesso , nsu , ultNsu ) . toString ( ) ; // valida o lote assinado , para verificar se o xsd foi satisfeito , antes de comunicar com a sefaz
XMLValidador . validaConsultaDfe ( xmlEnvio ) ; final OMElement ome = AXIOMUtil . stringToOM ( xmlEnvio ) ; final NFeDistribuicaoDFeSoapStub . NFeDadosMsg_type0 dadosMsgType0 = new NFeDistribuicaoDFeSoapStub . NFeDadosMsg_type0 ( ) ; dadosMsgType0 . setExtraElement ( ome ) ; final NFeDistribuicaoDFeSoapStub . NFeDistDFeInteresse distDFeInteresse = new NFeDistribuicaoDFeSoapStub . NFeDistDFeInteresse ( ) ; distDFeInteresse . setNFeDadosMsg ( dadosMsgType0 ) ; final NFeDistribuicaoDFeSoapStub stub = new NFeDistribuicaoDFeSoapStub ( NFAutorizador31 . AN . getNFeDistribuicaoDFe ( this . config . getAmbiente ( ) ) ) ; final NFeDistribuicaoDFeSoapStub . NFeDistDFeInteresseResponse result = stub . nfeDistDFeInteresse ( distDFeInteresse ) ; final String resultadoConsulta = result . getNFeDistDFeInteresseResult ( ) . getExtraElement ( ) . toString ( ) ; return new Persister ( new DFRegistryMatcher ( ) ) . read ( NFDistribuicaoIntRetorno . class , resultadoConsulta ) ; } catch ( RemoteException | XMLStreamException e ) { throw new Exception ( e . getMessage ( ) ) ; }


signature:
public class MDFInfoEmitente { /** * Razão social ou Nome do emitente */
public void setRazaoSocial ( final String xNome ) { } }

implementation: StringValidador . tamanho2ate60 ( xNome , "Razão social ou Nome em " + MDFInfoEmitente . INFO ) ; this . razaoSocial = xNome ;


signature:
public class MDFInfoEmitente { /** * Nome fantasia */
public void setNomeFantasia ( final String xFant ) { } }

implementation: StringValidador . tamanho2ate60 ( xFant , "Nome fantasia em " + MDFInfoEmitente . INFO ) ; this . nomeFantasia = xFant ;


signature:
public class CteRecepcaoCallbackHandler { /** * auto generated Axis2 call back method for cteRecepcaoLote method
 * override this method for handling normal response from cteRecepcaoLote operation */
public void receiveResultcteRecepcaoLote ( com . fincatto . documentofiscal . cte300 . webservices . recepcao . CteRecepcaoStub . CteRecepcaoLoteResult result ) { } }


signature:
public class CteInutilizacaoStub { /** * Auto generated method signature Inutilização de numeração de CT - e
 * @ param cteDadosMsg0
 * @ param cteCabecMsg1 */
public com . fincatto . documentofiscal . cte300 . webservices . inutilizacao . CteInutilizacaoStub . CteInutilizacaoCTResult cteInutilizacaoCT ( final com . fincatto . documentofiscal . cte300 . webservices . inutilizacao . CteInutilizacaoStub . CteDadosMsg cteDadosMsg0 , final com . fincatto . documentofiscal . cte300 . webservices . inutilizacao . CteInutilizacaoStub . CteCabecMsgE cteCabecMsg1 ) throws java . rmi . RemoteException { } }

implementation:
org . apache . axis2 . context . MessageContext _messageContext = null ; try { final org . apache . axis2 . client . OperationClient _operationClient = this . _serviceClient . createClient ( this . _operations [ 0 ] . getName ( ) ) ; _operationClient . getOptions ( ) . setAction ( "http://www.portalfiscal.inf.br/cte/wsdl/CteInutilizacao/cteInutilizacaoCT" ) ; _operationClient . getOptions ( ) . setExceptionToBeThrownOnSOAPFault ( true ) ; this . addPropertyToOperationClient ( _operationClient , org . apache . axis2 . description . WSDL2Constants . ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR , "&" ) ; // create a message context
_messageContext = new org . apache . axis2 . context . MessageContext ( ) ; // create SOAP envelope with that payload
org . apache . axiom . soap . SOAPEnvelope env ; env = this . toEnvelope ( Stub . getFactory ( _operationClient . getOptions ( ) . getSoapVersionURI ( ) ) , cteDadosMsg0 , this . optimizeContent ( new javax . xml . namespace . QName ( "http://www.portalfiscal.inf.br/cte/wsdl/CteInutilizacao" , "cteInutilizacaoCT" ) ) , new javax . xml . namespace . QName ( "http://www.portalfiscal.inf.br/cte/wsdl/CteInutilizacao" , "cteInutilizacaoCT" ) ) ; env . build ( ) ; // add the children only if the parameter is not null
if ( cteCabecMsg1 != null ) { final org . apache . axiom . om . OMElement omElementcteCabecMsg1 = this . toOM ( cteCabecMsg1 , this . optimizeContent ( new javax . xml . namespace . QName ( "http://www.portalfiscal.inf.br/cte/wsdl/CteInutilizacao" , "cteInutilizacaoCT" ) ) ) ; this . addHeader ( omElementcteCabecMsg1 , env ) ; } // adding SOAP soap _ headers
this . _serviceClient . addHeadersToEnvelope ( env ) ; // set the message context with that soap envelope
_messageContext . setEnvelope ( env ) ; // add the message contxt to the operation client
_operationClient . addMessageContext ( _messageContext ) ; // execute the operation client
_operationClient . execute ( true ) ; final org . apache . axis2 . context . MessageContext _returnMessageContext = _operationClient . getMessageContext ( org . apache . axis2 . wsdl . WSDLConstants . MESSAGE_LABEL_IN_VALUE ) ; final org . apache . axiom . soap . SOAPEnvelope _returnEnv = _returnMessageContext . getEnvelope ( ) ; final java . lang . Object object = this . fromOM ( _returnEnv . getBody ( ) . getFirstElement ( ) , com . fincatto . documentofiscal . cte300 . webservices . inutilizacao . CteInutilizacaoStub . CteInutilizacaoCTResult . class , this . getEnvelopeNamespaces ( _returnEnv ) ) ; return ( com . fincatto . documentofiscal . cte300 . webservices . inutilizacao . CteInutilizacaoStub . CteInutilizacaoCTResult ) object ; } catch ( final org . apache . axis2 . AxisFault f ) { final org . apache . axiom . om . OMElement faultElt = f . getDetail ( ) ; if ( faultElt != null ) { if ( this . faultExceptionNameMap . containsKey ( new org . apache . axis2 . client . FaultMapKey ( faultElt . getQName ( ) , "cteInutilizacaoCT" ) ) ) { // make the fault by reflection
try { final java . lang . String exceptionClassName = ( java . lang . String ) this . faultExceptionClassNameMap . get ( new org . apache . axis2 . client . FaultMapKey ( faultElt . getQName ( ) , "cteInutilizacaoCT" ) ) ; final java . lang . Class exceptionClass = java . lang . Class . forName ( exceptionClassName ) ; final java . lang . reflect . Constructor constructor = exceptionClass . getConstructor ( String . class ) ; final java . lang . Exception ex = ( java . lang . Exception ) constructor . newInstance ( f . getMessage ( ) ) ; // message class
final java . lang . String messageClassName = ( java . lang . String ) this . faultMessageMap . get ( new org . apache . axis2 . client . FaultMapKey ( faultElt . getQName ( ) , "cteInutilizacaoCT" ) ) ; final java . lang . Class messageClass = java . lang . Class . forName ( messageClassName ) ; final java . lang . Object messageObject = this . fromOM ( faultElt , messageClass , null ) ; final java . lang . reflect . Method m = exceptionClass . getMethod ( "setFaultMessage" , messageClass ) ; m . invoke ( ex , messageObject ) ; throw new java . rmi . RemoteException ( ex . getMessage ( ) , ex ) ; } catch ( final ClassCastException | InstantiationException | IllegalAccessException | java . lang . reflect . InvocationTargetException | NoSuchMethodException | ClassNotFoundException e ) { // we cannot intantiate the class - throw the original Axis fault
throw f ; } } else { throw f ; } } else { throw f ; } } finally { if ( _messageContext . getTransportOut ( ) != null ) { _messageContext . getTransportOut ( ) . getSender ( ) . cleanup ( _messageContext ) ; } }


signature:
public class CteInutilizacaoStub { /** * Auto generated method signature for Asynchronous Invocations Inutilização de numeração de CT - e
 * @ param cteDadosMsg0
 * @ param cteCabecMsg1 */
public void startcteInutilizacaoCT ( final com . fincatto . documentofiscal . cte300 . webservices . inutilizacao . CteInutilizacaoStub . CteDadosMsg cteDadosMsg0 , final com . fincatto . documentofiscal . cte300 . webservices . inutilizacao . CteInutilizacaoStub . CteCabecMsgE cteCabecMsg1 , final com . fincatto . documentofiscal . cte300 . webservices . inutilizacao . CteInutilizacaoCallbackHandler callback ) throws java . rmi . RemoteException { } }

implementation:
final org . apache . axis2 . client . OperationClient _operationClient = this . _serviceClient . createClient ( this . _operations [ 0 ] . getName ( ) ) ; _operationClient . getOptions ( ) . setAction ( "http://www.portalfiscal.inf.br/cte/wsdl/CteInutilizacao/cteInutilizacaoCT" ) ; _operationClient . getOptions ( ) . setExceptionToBeThrownOnSOAPFault ( true ) ; this . addPropertyToOperationClient ( _operationClient , org . apache . axis2 . description . WSDL2Constants . ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR , "&" ) ; // create SOAP envelope with that payload
org . apache . axiom . soap . SOAPEnvelope env ; final org . apache . axis2 . context . MessageContext _messageContext = new org . apache . axis2 . context . MessageContext ( ) ; // Style is Doc .
env = this . toEnvelope ( Stub . getFactory ( _operationClient . getOptions ( ) . getSoapVersionURI ( ) ) , cteDadosMsg0 , this . optimizeContent ( new javax . xml . namespace . QName ( "http://www.portalfiscal.inf.br/cte/wsdl/CteInutilizacao" , "cteInutilizacaoCT" ) ) , new javax . xml . namespace . QName ( "http://www.portalfiscal.inf.br/cte/wsdl/CteInutilizacao" , "cteInutilizacaoCT" ) ) ; // add the soap _ headers only if they are not null
if ( cteCabecMsg1 != null ) { final org . apache . axiom . om . OMElement omElementcteCabecMsg1 = this . toOM ( cteCabecMsg1 , this . optimizeContent ( new javax . xml . namespace . QName ( "http://www.portalfiscal.inf.br/cte/wsdl/CteInutilizacao" , "cteInutilizacaoCT" ) ) ) ; this . addHeader ( omElementcteCabecMsg1 , env ) ; } // adding SOAP soap _ headers
this . _serviceClient . addHeadersToEnvelope ( env ) ; // create message context with that soap envelope
_messageContext . setEnvelope ( env ) ; // add the message context to the operation client
_operationClient . addMessageContext ( _messageContext ) ; _operationClient . setCallback ( new org . apache . axis2 . client . async . AxisCallback ( ) { @ Override public void onMessage ( final org . apache . axis2 . context . MessageContext resultContext ) { try { final org . apache . axiom . soap . SOAPEnvelope resultEnv = resultContext . getEnvelope ( ) ; final java . lang . Object object = CteInutilizacaoStub . this . fromOM ( resultEnv . getBody ( ) . getFirstElement ( ) , com . fincatto . documentofiscal . cte300 . webservices . inutilizacao . CteInutilizacaoStub . CteInutilizacaoCTResult . class , CteInutilizacaoStub . this . getEnvelopeNamespaces ( resultEnv ) ) ; callback . receiveResultcteInutilizacaoCT ( ( com . fincatto . documentofiscal . cte300 . webservices . inutilizacao . CteInutilizacaoStub . CteInutilizacaoCTResult ) object ) ; } catch ( final org . apache . axis2 . AxisFault e ) { callback . receiveErrorcteInutilizacaoCT ( e ) ; } } @ Override public void onError ( final java . lang . Exception error ) { if ( error instanceof org . apache . axis2 . AxisFault ) { final org . apache . axis2 . AxisFault f = ( org . apache . axis2 . AxisFault ) error ; final org . apache . axiom . om . OMElement faultElt = f . getDetail ( ) ; if ( faultElt != null ) { if ( CteInutilizacaoStub . this . faultExceptionNameMap . containsKey ( new org . apache . axis2 . client . FaultMapKey ( faultElt . getQName ( ) , "cteInutilizacaoCT" ) ) ) { // make the fault by reflection
try { final java . lang . String exceptionClassName = ( java . lang . String ) CteInutilizacaoStub . this . faultExceptionClassNameMap . get ( new org . apache . axis2 . client . FaultMapKey ( faultElt . getQName ( ) , "cteInutilizacaoCT" ) ) ; final java . lang . Class exceptionClass = java . lang . Class . forName ( exceptionClassName ) ; final java . lang . reflect . Constructor constructor = exceptionClass . getConstructor ( String . class ) ; final java . lang . Exception ex = ( java . lang . Exception ) constructor . newInstance ( f . getMessage ( ) ) ; // message class
final java . lang . String messageClassName = ( java . lang . String ) CteInutilizacaoStub . this . faultMessageMap . get ( new org . apache . axis2 . client . FaultMapKey ( faultElt . getQName ( ) , "cteInutilizacaoCT" ) ) ; final java . lang . Class messageClass = java . lang . Class . forName ( messageClassName ) ; final java . lang . Object messageObject = CteInutilizacaoStub . this . fromOM ( faultElt , messageClass , null ) ; final java . lang . reflect . Method m = exceptionClass . getMethod ( "setFaultMessage" , messageClass ) ; m . invoke ( ex , messageObject ) ; callback . receiveErrorcteInutilizacaoCT ( new java . rmi . RemoteException ( ex . getMessage ( ) , ex ) ) ; } catch ( final ClassCastException | org . apache . axis2 . AxisFault | InstantiationException | IllegalAccessException | java . lang . reflect . InvocationTargetException | NoSuchMethodException | ClassNotFoundException e ) { // we cannot intantiate the class - throw the original Axis fault
callback . receiveErrorcteInutilizacaoCT ( f ) ; } } else { callback . receiveErrorcteInutilizacaoCT ( f ) ; } } else { callback . receiveErrorcteInutilizacaoCT ( f ) ; } } else { callback . receiveErrorcteInutilizacaoCT ( error ) ; } } @ Override public void onFault ( final org . apache . axis2 . context . MessageContext faultContext ) { final org . apache . axis2 . AxisFault fault = org . apache . axis2 . util . Utils . getInboundFaultFromMessageContext ( faultContext ) ; this . onError ( fault ) ; } @ Override public void onComplete ( ) { try { _messageContext . getTransportOut ( ) . getSender ( ) . cleanup ( _messageContext ) ; } catch ( final org . apache . axis2 . AxisFault axisFault ) { callback . receiveErrorcteInutilizacaoCT ( axisFault ) ; } } } ) ; org . apache . axis2 . util . CallbackReceiver _callbackReceiver ; if ( this . _operations [ 0 ] . getMessageReceiver ( ) == null && _operationClient . getOptions ( ) . isUseSeparateListener ( ) ) { _callbackReceiver = new org . apache . axis2 . util . CallbackReceiver ( ) ; this . _operations [ 0 ] . setMessageReceiver ( _callbackReceiver ) ; } // execute the operation client
_operationClient . execute ( false ) ;


signature:
public class CteRetRecepcaoCallbackHandler { /** * auto generated Axis2 call back method for cteRetRecepcao method
 * override this method for handling normal response from cteRetRecepcao operation */
public void receiveResultcteRetRecepcao ( com . fincatto . documentofiscal . cte300 . webservices . retrecepcao . CteRetRecepcaoStub . CteRetRecepcaoResult result ) { } }


signature:
public class WSCartaCorrecao { /** * Retorna XML assinado para uso externo .
 * @ param chaveAcesso
 * @ param textoCorrecao
 * @ param numeroSequencialEvento
 * @ return
 * @ throws Exception */
public String getXmlAssinado ( final String chaveAcesso , final String textoCorrecao , final int numeroSequencialEvento ) throws Exception { } }

implementation: final String cartaCorrecaoXML = this . gerarDadosCartaCorrecao ( chaveAcesso , textoCorrecao , numeroSequencialEvento ) . toString ( ) ; return new AssinaturaDigital ( this . config ) . assinarDocumento ( cartaCorrecaoXML ) ;


signature:
public class RecepcaoEventoCallbackHandler { /** * auto generated Axis2 call back method for cteRecepcaoEvento method
 * override this method for handling normal response from cteRecepcaoEvento operation */
public void receiveResultcteRecepcaoEvento ( com . fincatto . documentofiscal . cte300 . webservices . recepcaoevento . RecepcaoEventoStub . CteRecepcaoEventoResult result ) { } }


signature: public class MDFeConsNaoEncStub { @ SuppressWarnings ( "rawtypes" ) private java . lang . Object fromOM ( final org . apache . axiom . om . OMElement param , final java . lang . Class type , final java . util . Map extraNamespaces ) throws org . apache . axis2 . AxisFault { } }

implementation: try { if ( com . fincatto . documentofiscal . mdfe3 . webservices . consultanaoencerrado . MDFeConsNaoEncStub . MdfeDadosMsg . class . equals ( type ) ) { return com . fincatto . documentofiscal . mdfe3 . webservices . consultanaoencerrado . MDFeConsNaoEncStub . MdfeDadosMsg . Factory . parse ( param . getXMLStreamReaderWithoutCaching ( ) ) ; } if ( com . fincatto . documentofiscal . mdfe3 . webservices . consultanaoencerrado . MDFeConsNaoEncStub . MdfeConsNaoEncResult . class . equals ( type ) ) { return com . fincatto . documentofiscal . mdfe3 . webservices . consultanaoencerrado . MDFeConsNaoEncStub . MdfeConsNaoEncResult . Factory . parse ( param . getXMLStreamReaderWithoutCaching ( ) ) ; } if ( com . fincatto . documentofiscal . mdfe3 . webservices . consultanaoencerrado . MDFeConsNaoEncStub . MdfeCabecMsgE . class . equals ( type ) ) { return com . fincatto . documentofiscal . mdfe3 . webservices . consultanaoencerrado . MDFeConsNaoEncStub . MdfeCabecMsgE . Factory . parse ( param . getXMLStreamReaderWithoutCaching ( ) ) ; } if ( com . fincatto . documentofiscal . mdfe3 . webservices . consultanaoencerrado . MDFeConsNaoEncStub . MdfeCabecMsgE . class . equals ( type ) ) { return com . fincatto . documentofiscal . mdfe3 . webservices . consultanaoencerrado . MDFeConsNaoEncStub . MdfeCabecMsgE . Factory . parse ( param . getXMLStreamReaderWithoutCaching ( ) ) ; } } catch ( final java . lang . Exception e ) { throw org . apache . axis2 . AxisFault . makeFault ( e ) ; } return null ;


signature:
public class CTeNotaInfo { /** * Identificador da tag a ser assinada < br >
 * Informar a chave de acesso do CT - e e precedida do literal " CTe " */
public void setIdentificador ( final String identificador ) { } }

implementation: StringValidador . exatamente44N ( identificador , "Identificador" ) ; this . identificador = CTeNotaInfo . IDENT + identificador ;


signature:
public class WSFacade { /** * Faz o cancelamento do CTe
 * @ param chave chave de acesso da nota
 * @ param numeroProtocolo numero do protocolo da nota
 * @ param motivo motivo do cancelamento
 * @ return dados do cancelamento da nota retornado pelo webservice
 * @ throws Exception caso nao consiga gerar o xml ou problema de conexao com o sefaz */
public CTeRetornoCancelamento cancelaNota ( final String chave , final String numeroProtocolo , final String motivo ) throws Exception { } }

implementation: return this . wsCancelamento . cancelaNota ( chave , numeroProtocolo , motivo ) ;


signature:
public class WSFacade { /** * Faz o cancelamento da nota com evento ja assinado
 * ATENCAO : Esse metodo deve ser utilizado para assinaturas A3
 * @ param chave chave de acesso da nota
 * @ param eventoAssinadoXml evento ja assinado em formato XML
 * @ return dados do cancelamento da nota retornado pelo webservice
 * @ throws Exception caso nao consiga gerar o xml ou problema de conexao com o sefaz */
public CTeRetornoCancelamento cancelaNotaAssinada ( final String chave , final String eventoAssinadoXml ) throws Exception { } }

implementation: return this . wsCancelamento . cancelaNotaAssinada ( chave , eventoAssinadoXml ) ;


signature:
public class NfeAutorizacaoStub { /** * / * methods to provide back word compatibility */
private java . lang . Object fromOM ( final org . apache . axiom . om . OMElement param , final java . lang . Class < ? > type , final java . util . Map < String , String > extraNamespaces ) throws org . apache . axis2 . AxisFault { } }

implementation: try { if ( NfeAutorizacaoStub . NfeDadosMsgZip . class . equals ( type ) ) { return NfeAutorizacaoStub . NfeDadosMsgZip . Factory . parse ( param . getXMLStreamReaderWithoutCaching ( ) ) ; } if ( NfeAutorizacaoStub . NfeAutorizacaoLoteZipResult . class . equals ( type ) ) { return NfeAutorizacaoStub . NfeAutorizacaoLoteZipResult . Factory . parse ( param . getXMLStreamReaderWithoutCaching ( ) ) ; } if ( NfeAutorizacaoStub . NfeCabecMsgE . class . equals ( type ) ) { return NfeAutorizacaoStub . NfeCabecMsgE . Factory . parse ( param . getXMLStreamReaderWithoutCaching ( ) ) ; } if ( NfeAutorizacaoStub . NfeCabecMsgE . class . equals ( type ) ) { return NfeAutorizacaoStub . NfeCabecMsgE . Factory . parse ( param . getXMLStreamReaderWithoutCaching ( ) ) ; } if ( NfeAutorizacaoStub . NfeDadosMsg . class . equals ( type ) ) { return NfeAutorizacaoStub . NfeDadosMsg . Factory . parse ( param . getXMLStreamReaderWithoutCaching ( ) ) ; } if ( NfeAutorizacaoStub . NfeAutorizacaoLoteResult . class . equals ( type ) ) { return NfeAutorizacaoStub . NfeAutorizacaoLoteResult . Factory . parse ( param . getXMLStreamReaderWithoutCaching ( ) ) ; } if ( NfeAutorizacaoStub . NfeCabecMsgE . class . equals ( type ) ) { return NfeAutorizacaoStub . NfeCabecMsgE . Factory . parse ( param . getXMLStreamReaderWithoutCaching ( ) ) ; } if ( NfeAutorizacaoStub . NfeCabecMsgE . class . equals ( type ) ) { return NfeAutorizacaoStub . NfeCabecMsgE . Factory . parse ( param . getXMLStreamReaderWithoutCaching ( ) ) ; } } catch ( final java . lang . Exception e ) { throw org . apache . axis2 . AxisFault . makeFault ( e ) ; } return null ;


signature:
public class MDFeConsultaCallbackHandler { /** * auto generated Axis2 call back method for mdfeConsultaMDF method
 * override this method for handling normal response from mdfeConsultaMDF operation */
public void receiveResultmdfeConsultaMDF ( com . fincatto . documentofiscal . mdfe3 . webservices . consulta . MDFeConsultaStub . MdfeConsultaMDFResult result ) { } }


signature:
public class MDFeRetRecepcaoCallbackHandler { /** * auto generated Axis2 call back method for mdfeRetRecepcao method
 * override this method for handling normal response from mdfeRetRecepcao operation */
public void receiveResultmdfeRetRecepcao ( com . fincatto . documentofiscal . mdfe3 . webservices . retornorecepcao . MDFeRetRecepcaoStub . MdfeRetRecepcaoResult result ) { } }


signature:
public class WSFacade { /** * Faz o download do xml da nota para um cnpj Informando até 10 chaves de acesso
 * @ param cnpj para quem foi emitida a nota
 * @ param chave chave de acesso da nota
 * @ return dados do download da nota retornado pelo webservice
 * @ throws Exception caso nao consiga gerar o xml ou problema de conexao com o sefaz */
public NFDownloadNFeRetorno downloadNota ( final String cnpj , final String chave ) throws Exception { } }

implementation: return this . wsNotaDownload . downloadNota ( cnpj , chave ) ;


signature:
public class NfeInutilizacao2Stub { /** * / * methods to provide back word compatibility */
private java . lang . Object fromOM ( final org . apache . axiom . om . OMElement param , final java . lang . Class < ? > type , final java . util . Map < String , String > extraNamespaces ) throws org . apache . axis2 . AxisFault { } }

implementation: try { if ( NfeInutilizacao2Stub . NfeDadosMsg . class . equals ( type ) ) { return NfeInutilizacao2Stub . NfeDadosMsg . Factory . parse ( param . getXMLStreamReaderWithoutCaching ( ) ) ; } if ( NfeInutilizacao2Stub . NfeInutilizacaoNF2Result . class . equals ( type ) ) { return NfeInutilizacao2Stub . NfeInutilizacaoNF2Result . Factory . parse ( param . getXMLStreamReaderWithoutCaching ( ) ) ; } if ( NfeInutilizacao2Stub . NfeCabecMsgE . class . equals ( type ) ) { return NfeInutilizacao2Stub . NfeCabecMsgE . Factory . parse ( param . getXMLStreamReaderWithoutCaching ( ) ) ; } if ( NfeInutilizacao2Stub . NfeCabecMsgE . class . equals ( type ) ) { return NfeInutilizacao2Stub . NfeCabecMsgE . Factory . parse ( param . getXMLStreamReaderWithoutCaching ( ) ) ; } } catch ( final java . lang . Exception e ) { throw org . apache . axis2 . AxisFault . makeFault ( e ) ; } return null ;


signature:
public class WSFacade { /** * Faz o cancelamento do MDFe
 * @ param chave chave de acesso da nota
 * @ param numeroProtocolo numero do protocolo da nota
 * @ param motivo motivo do cancelamento
 * @ return dados do cancelamento da nota retornado pelo webservice
 * @ throws Exception caso nao consiga gerar o xml ou problema de conexao com o sefaz */
public MDFeRetorno cancelaMdfe ( final String chave , final String numeroProtocolo , final String motivo ) throws Exception { } }


signature:
public class WSFacade { /** * Faz o cancelamento da nota com evento ja assinado
 * ATENCAO : Esse metodo deve ser utilizado para assinaturas A3
 * @ param chave chave de acesso da nota
 * @ param eventoAssinadoXml evento ja assinado em formato XML
 * @ return dados do cancelamento da nota retornado pelo webservice
 * @ throws Exception caso nao consiga gerar o xml ou problema de conexao com o sefaz */
public MDFeRetorno cancelaMdfeAssinado ( final String chave , final String eventoAssinadoXml ) throws Exception { } }


signature:
public class WSFacade { /** * Faz o encerramento do MDFe
 * @ param chaveAcesso chave de acesso da nota
 * @ param numeroProtocolo numero do protocolo da nota
 * @ param codigoMunicipio Informar o código do município do encerramento do manifesto
 * @ param dataEncerramento Data em que o manifesto foi encerrado .
 * @ param unidadeFederativa Informar a UF de encerramento do manifesto
 * @ return dados do encerramento da nota retornado pelo webservice
 * @ throws Exception caso nao consiga gerar o xml ou problema de conexao com o sefaz */
public MDFeRetorno encerramento ( final String chaveAcesso , final String numeroProtocolo , final String codigoMunicipio , final LocalDate dataEncerramento , final DFUnidadeFederativa unidadeFederativa ) throws Exception { } }

implementation: return this . wsEncerramento . encerraMdfe ( chaveAcesso , numeroProtocolo , codigoMunicipio , dataEncerramento , unidadeFederativa ) ;


signature:
public class WSFacade { /** * Faz o encerramento do MDFe assinado
 * @ param chaveAcesso
 * @ param eventoAssinadoXml
 * @ return
 * @ throws Exception */
public MDFeRetorno encerramentoAssinado ( final String chaveAcesso , final String eventoAssinadoXml ) throws Exception { } }

implementation: return this . wsEncerramento . encerramentoMdfeAssinado ( chaveAcesso , eventoAssinadoXml ) ;


signature:
public class WSFacade { /** * Faz a inclusão de condutor do veículo de MDF - e Rodoviário .
 * @ param chaveAcesso
 * @ param nomeCondutor
 * @ param cpfCondutor
 * @ return
 * @ throws Exception */
public MDFeRetorno incluirCondutor ( final String chaveAcesso , final String nomeCondutor , final String cpfCondutor ) throws Exception { } }

implementation: return this . wsIncluirCondutor . incluirCondutor ( chaveAcesso , nomeCondutor , cpfCondutor ) ;


signature:
public class WSFacade { /** * Faz a inclusão de condutor do veículo de MDF - e Rodoviário evento assinado
 * @ param chaveAcesso
 * @ param eventoAssinadoXml
 * @ return
 * @ throws Exception */
public MDFeRetorno incluirCondutorAssinado ( final String chaveAcesso , final String eventoAssinadoXml ) throws Exception { } }

implementation: return this . wsIncluirCondutor . incluirCondutorAssinado ( chaveAcesso , eventoAssinadoXml ) ;


signature:
public class MDFeStatusServicoCallbackHandler { /** * auto generated Axis2 call back method for mdfeStatusServicoMDF method
 * override this method for handling normal response from mdfeStatusServicoMDF operation */
public void receiveResultmdfeStatusServicoMDF ( com . fincatto . documentofiscal . mdfe3 . webservices . statusservico . MDFeStatusServicoStub . MdfeStatusServicoMDFResult result ) { } }


signature:
public class WSStatusConsulta { /** * este metodo teve que ser implementado pois a Bahia trata de forma diferente */
private OMElement efetuaConsultaStatusBahia ( final OMElement omElement ) throws RemoteException { } }

implementation: final NfeStatusServicoStub . NfeCabecMsg cabec = new NfeStatusServicoStub . NfeCabecMsg ( ) ; cabec . setCUF ( DFUnidadeFederativa . BA . getCodigoIbge ( ) ) ; cabec . setVersaoDados ( this . config . getVersao ( ) ) ; final NfeStatusServicoStub . NfeCabecMsgE cabecEnv = new NfeStatusServicoStub . NfeCabecMsgE ( ) ; cabecEnv . setNfeCabecMsg ( cabec ) ; final NfeStatusServicoStub . NfeDadosMsg dados = new NfeStatusServicoStub . NfeDadosMsg ( ) ; dados . setExtraElement ( omElement ) ; final NFAutorizador31 autorizador = NFAutorizador31 . valueOfCodigoUF ( DFUnidadeFederativa . BA ) ; final String endpoint = autorizador . getNfeStatusServico ( this . config . getAmbiente ( ) ) ; if ( endpoint == null ) { throw new IllegalArgumentException ( "Nao foi possivel encontrar URL para StatusServico " + DFModelo . NFE . name ( ) + ", autorizador " + autorizador . name ( ) + ", UF " + DFUnidadeFederativa . BA . name ( ) ) ; } return new NfeStatusServicoStub ( endpoint ) . nfeStatusServicoNF ( dados , cabecEnv ) . getExtraElement ( ) ;


signature:
public class BriteDatabase { /** * Begin a transaction for this thread .
 * Transactions may nest . If the transaction is not in progress , then a database connection is
 * obtained and a new transaction is started . Otherwise , a nested transaction is started .
 * Each call to { @ code newTransaction } must be matched exactly by a call to
 * { @ link Transaction # end ( ) } . To mark a transaction as successful , call
 * { @ link Transaction # markSuccessful ( ) } before calling { @ link Transaction # end ( ) } . If the
 * transaction is not successful , or if any of its nested transactions were not successful , then
 * the entire transaction will be rolled back when the outermost transaction is ended .
 * Transactions queue up all query notifications until they have been applied .
 * Here is the standard idiom for transactions :
 * < pre > { @ code
 * try ( Transaction transaction = db . newTransaction ( ) ) {
 * transaction . markSuccessful ( ) ;
 * } < / pre >
 * Manually call { @ link Transaction # end ( ) } when try - with - resources is not available :
 * < pre > { @ code
 * Transaction transaction = db . newTransaction ( ) ;
 * try {
 * transaction . markSuccessful ( ) ;
 * } finally {
 * transaction . end ( ) ;
 * } < / pre >
 * @ see SupportSQLiteDatabase # beginTransaction ( ) */
@ CheckResult @ NonNull public Transaction newTransaction ( ) { } }

implementation: SqliteTransaction transaction = new SqliteTransaction ( transactions . get ( ) ) ; transactions . set ( transaction ) ; if ( logging ) log ( "TXN BEGIN %s" , transaction ) ; getWritableDatabase ( ) . beginTransactionWithListener ( transaction ) ; return this . transaction ;


signature:
public class BriteDatabase { /** * Begins a transaction in IMMEDIATE mode for this thread .
 * Transactions may nest . If the transaction is not in progress , then a database connection is
 * obtained and a new transaction is started . Otherwise , a nested transaction is started .
 * Each call to { @ code newNonExclusiveTransaction } must be matched exactly by a call to
 * { @ link Transaction # end ( ) } . To mark a transaction as successful , call
 * { @ link Transaction # markSuccessful ( ) } before calling { @ link Transaction # end ( ) } . If the
 * transaction is not successful , or if any of its nested transactions were not successful , then
 * the entire transaction will be rolled back when the outermost transaction is ended .
 * Transactions queue up all query notifications until they have been applied .
 * Here is the standard idiom for transactions :
 * < pre > { @ code
 * try ( Transaction transaction = db . newNonExclusiveTransaction ( ) ) {
 * transaction . markSuccessful ( ) ;
 * } < / pre >
 * Manually call { @ link Transaction # end ( ) } when try - with - resources is not available :
 * < pre > { @ code
 * Transaction transaction = db . newNonExclusiveTransaction ( ) ;
 * try {
 * transaction . markSuccessful ( ) ;
 * } finally {
 * transaction . end ( ) ;
 * } < / pre >
 * @ see SupportSQLiteDatabase # beginTransactionNonExclusive ( ) */
@ CheckResult @ NonNull public Transaction newNonExclusiveTransaction ( ) { } }

implementation: SqliteTransaction transaction = new SqliteTransaction ( transactions . get ( ) ) ; transactions . set ( transaction ) ; if ( logging ) log ( "TXN BEGIN %s" , transaction ) ; getWritableDatabase ( ) . beginTransactionWithListenerNonExclusive ( transaction ) ; return this . transaction ;


signature:
public class BriteDatabase { /** * Create an observable which will notify subscribers with a { @ linkplain Query query } for
 * execution . Subscribers are responsible for < b > always < / b > closing { @ link Cursor } instance
 * returned from the { @ link Query } .
 * Subscribers will receive an immediate notification for initial data as well as subsequent
 * notifications for when the supplied { @ code table } ' s data changes through the { @ code insert } ,
 * { @ code update } , and { @ code delete } methods of this class . Unsubscribe when you no longer want
 * updates to a query .
 * Since database triggers are inherently asynchronous , items emitted from the returned
 * observable use the { @ link Scheduler } supplied to { @ link SqlBrite # wrapDatabaseHelper } . For
 * consistency , the immediate notification sent on subscribe also uses this scheduler . As such ,
 * calling { @ link Observable # subscribeOn subscribeOn } on the returned observable has no effect .
 * Note : To skip the immediate notification and only receive subsequent notifications when data
 * has changed call { @ code skip ( 1 ) } on the returned observable .
 * < b > Warning : < / b > this method does not perform the query ! Only by subscribing to the returned
 * { @ link Observable } will the operation occur .
 * @ see SupportSQLiteDatabase # query ( String , Object [ ] ) */
@ CheckResult @ NonNull public QueryObservable createQuery ( @ NonNull final String table , @ NonNull String sql , @ NonNull Object ... args ) { } }

implementation: return createQuery ( new DatabaseQuery ( singletonList ( table ) , new SimpleSQLiteQuery ( sql , args ) ) ) ;


signature:
public class BriteDatabase { /** * See { @ link # createQuery ( String , String , Object . . . ) } for usage . This overload allows for
 * monitoring multiple tables for changes .
 * @ see SupportSQLiteDatabase # query ( String , Object [ ] ) */
@ CheckResult @ NonNull public QueryObservable createQuery ( @ NonNull final Iterable < String > tables , @ NonNull String sql , @ NonNull Object ... args ) { } }

implementation: return createQuery ( new DatabaseQuery ( tables , new SimpleSQLiteQuery ( sql , args ) ) ) ;


signature:
public class BriteDatabase { /** * Create an observable which will notify subscribers with a { @ linkplain Query query } for
 * execution . Subscribers are responsible for < b > always < / b > closing { @ link Cursor } instance
 * returned from the { @ link Query } .
 * Subscribers will receive an immediate notification for initial data as well as subsequent
 * notifications for when the supplied { @ code table } ' s data changes through the { @ code insert } ,
 * { @ code update } , and { @ code delete } methods of this class . Unsubscribe when you no longer want
 * updates to a query .
 * Since database triggers are inherently asynchronous , items emitted from the returned
 * observable use the { @ link Scheduler } supplied to { @ link SqlBrite # wrapDatabaseHelper } . For
 * consistency , the immediate notification sent on subscribe also uses this scheduler . As such ,
 * calling { @ link Observable # subscribeOn subscribeOn } on the returned observable has no effect .
 * Note : To skip the immediate notification and only receive subsequent notifications when data
 * has changed call { @ code skip ( 1 ) } on the returned observable .
 * < b > Warning : < / b > this method does not perform the query ! Only by subscribing to the returned
 * { @ link Observable } will the operation occur .
 * @ see SupportSQLiteDatabase # query ( SupportSQLiteQuery ) */
@ CheckResult @ NonNull public QueryObservable createQuery ( @ NonNull final String table , @ NonNull SupportSQLiteQuery query ) { } }

implementation: return createQuery ( new DatabaseQuery ( singletonList ( table ) , query ) ) ;


signature:
public class BriteDatabase { /** * See { @ link # createQuery ( String , SupportSQLiteQuery ) } for usage . This overload allows for
 * monitoring multiple tables for changes .
 * @ see SupportSQLiteDatabase # query ( SupportSQLiteQuery ) */
@ CheckResult @ NonNull public QueryObservable createQuery ( @ NonNull final Iterable < String > tables , @ NonNull SupportSQLiteQuery query ) { } }

implementation: return createQuery ( new DatabaseQuery ( tables , query ) ) ;


signature:
public class BriteDatabase { /** * Runs the provided SQL and returns a { @ link Cursor } over the result set .
 * @ see SupportSQLiteDatabase # query ( String , Object [ ] ) */
@ CheckResult @ WorkerThread public Cursor query ( @ NonNull String sql , @ NonNull Object ... args ) { } }

implementation: Cursor cursor = getReadableDatabase ( ) . query ( sql , args ) ; if ( logging ) { log ( "QUERY\n  sql: %s\n  args: %s" , indentSql ( sql ) , Arrays . toString ( args ) ) ; } return cursor ;


signature:
public class BriteDatabase { /** * Runs the provided { @ link SupportSQLiteQuery } and returns a { @ link Cursor } over the result set .
 * @ see SupportSQLiteDatabase # query ( SupportSQLiteQuery ) */
@ CheckResult @ WorkerThread public Cursor query ( @ NonNull SupportSQLiteQuery query ) { } }

implementation: Cursor cursor = getReadableDatabase ( ) . query ( query ) ; if ( logging ) { log ( "QUERY\n  sql: %s" , indentSql ( query . getSql ( ) ) ) ; } return cursor ;


signature:
public class BriteDatabase { /** * Insert a row into the specified { @ code table } and notify any subscribed queries .
 * @ see SupportSQLiteDatabase # insert ( String , int , ContentValues ) */
@ WorkerThread public long insert ( @ NonNull String table , @ ConflictAlgorithm int conflictAlgorithm , @ NonNull ContentValues values ) { } }

implementation:
SupportSQLiteDatabase db = getWritableDatabase ( ) ; if ( logging ) { log ( "INSERT\n  table: %s\n  values: %s\n  conflictAlgorithm: %s" , table , values , conflictString ( conflictAlgorithm ) ) ; } long rowId = db . insert ( table , conflictAlgorithm , values ) ; if ( logging ) log ( "INSERT id: %s" , rowId ) ; if ( rowId != - 1 ) { // Only send a table trigger if the insert was successful .
sendTableTrigger ( Collections . singleton ( table ) ) ; } return rowId ;


signature:
public class BriteDatabase { /** * Delete rows from the specified { @ code table } and notify any subscribed queries . This method
 * will not trigger a notification if no rows were deleted .
 * @ see SupportSQLiteDatabase # delete ( String , String , Object [ ] ) */
@ WorkerThread public int delete ( @ NonNull String table , @ Nullable String whereClause , @ Nullable String ... whereArgs ) { } }

implementation:
SupportSQLiteDatabase db = getWritableDatabase ( ) ; if ( logging ) { log ( "DELETE\n  table: %s\n  whereClause: %s\n  whereArgs: %s" , table , whereClause , Arrays . toString ( whereArgs ) ) ; } int rows = db . delete ( table , whereClause , whereArgs ) ; if ( logging ) log ( "DELETE affected %s %s" , rows , rows != 1 ? "rows" : "row" ) ; if ( rows > 0 ) { // Only send a table trigger if rows were affected .
sendTableTrigger ( Collections . singleton ( table ) ) ; } return rows ;


signature:
public class BriteDatabase { /** * Update rows in the specified { @ code table } and notify any subscribed queries . This method
 * will not trigger a notification if no rows were updated .
 * @ see SupportSQLiteDatabase # update ( String , int , ContentValues , String , Object [ ] ) */
@ WorkerThread public int update ( @ NonNull String table , @ ConflictAlgorithm int conflictAlgorithm , @ NonNull ContentValues values , @ Nullable String whereClause , @ Nullable String ... whereArgs ) { } }

implementation:
SupportSQLiteDatabase db = getWritableDatabase ( ) ; if ( logging ) { log ( "UPDATE\n  table: %s\n  values: %s\n  whereClause: %s\n  whereArgs: %s\n  conflictAlgorithm: %s" , table , values , whereClause , Arrays . toString ( whereArgs ) , conflictString ( conflictAlgorithm ) ) ; } int rows = db . update ( table , conflictAlgorithm , values , whereClause , whereArgs ) ; if ( logging ) log ( "UPDATE affected %s %s" , rows , rows != 1 ? "rows" : "row" ) ; if ( rows > 0 ) { // Only send a table trigger if rows were affected .
sendTableTrigger ( Collections . singleton ( table ) ) ; } return rows ;


signature:
public class BriteDatabase { /** * Execute { @ code sql } provided it is NOT a { @ code SELECT } or any other SQL statement that
 * returns data . No data can be returned ( such as the number of affected rows ) . Instead , use
 * { @ link # insert } , { @ link # update } , et al , when possible .
 * No notifications will be sent to queries if { @ code sql } affects the data of a table .
 * @ see SupportSQLiteDatabase # execSQL ( String ) */
@ WorkerThread public void execute ( String sql ) { } }

implementation: if ( logging ) log ( "EXECUTE\n  sql: %s" , indentSql ( sql ) ) ; getWritableDatabase ( ) . execSQL ( sql ) ;


signature:
public class BriteDatabase { /** * Execute { @ code sql } provided it is NOT a { @ code SELECT } or any other SQL statement that
 * returns data . No data can be returned ( such as the number of affected rows ) . Instead , use
 * { @ link # insert } , { @ link # update } , et al , when possible .
 * No notifications will be sent to queries if { @ code sql } affects the data of a table .
 * @ see SupportSQLiteDatabase # execSQL ( String , Object [ ] ) */
@ WorkerThread public void execute ( String sql , Object ... args ) { } }

implementation: if ( logging ) log ( "EXECUTE\n  sql: %s\n  args: %s" , indentSql ( sql ) , Arrays . toString ( args ) ) ; getWritableDatabase ( ) . execSQL ( sql , args ) ;


signature:
public class BriteDatabase { /** * Execute { @ code sql } provided it is NOT a { @ code SELECT } or any other SQL statement that
 * returns data . No data can be returned ( such as the number of affected rows ) . Instead , use
 * { @ link # insert } , { @ link # update } , et al , when possible .
 * A notification to queries for { @ code table } will be sent after the statement is executed .
 * @ see SupportSQLiteDatabase # execSQL ( String ) */
@ WorkerThread public void executeAndTrigger ( String table , String sql ) { } }

implementation: executeAndTrigger ( Collections . singleton ( table ) , sql ) ;


signature:
public class BriteDatabase { /** * See { @ link # executeAndTrigger ( String , String ) } for usage . This overload allows for triggering multiple tables .
 * @ see BriteDatabase # executeAndTrigger ( String , String ) */
@ WorkerThread public void executeAndTrigger ( Set < String > tables , String sql ) { } }

implementation: execute ( sql ) ; sendTableTrigger ( tables ) ;


signature:
public class BriteDatabase { /** * Execute { @ code sql } provided it is NOT a { @ code SELECT } or any other SQL statement that
 * returns data . No data can be returned ( such as the number of affected rows ) . Instead , use
 * { @ link # insert } , { @ link # update } , et al , when possible .
 * A notification to queries for { @ code table } will be sent after the statement is executed .
 * @ see SupportSQLiteDatabase # execSQL ( String , Object [ ] ) */
@ WorkerThread public void executeAndTrigger ( String table , String sql , Object ... args ) { } }

implementation: executeAndTrigger ( Collections . singleton ( table ) , sql , args ) ;


signature:
public class BriteDatabase { /** * Execute { @ code statement } , if the the number of rows affected by execution of this SQL
 * statement is of any importance to the caller - for example , UPDATE / DELETE SQL statements .
 * @ return the number of rows affected by this SQL statement execution .
 * @ throws android . database . SQLException If the SQL string is invalid
 * @ see SupportSQLiteStatement # executeUpdateDelete ( ) */
@ WorkerThread public int executeUpdateDelete ( String table , SupportSQLiteStatement statement ) { } }

implementation: return executeUpdateDelete ( Collections . singleton ( table ) , statement ) ;


signature:
public class BriteDatabase { /** * See { @ link # executeUpdateDelete ( String , SupportSQLiteStatement ) } for usage . This overload
 * allows for triggering multiple tables .
 * @ see BriteDatabase # executeUpdateDelete ( String , SupportSQLiteStatement ) */
@ WorkerThread public int executeUpdateDelete ( Set < String > tables , SupportSQLiteStatement statement ) { } }

implementation:
if ( logging ) log ( "EXECUTE\n %s" , statement ) ; int rows = statement . executeUpdateDelete ( ) ; if ( rows > 0 ) { // Only send a table trigger if rows were affected .
sendTableTrigger ( tables ) ; } return rows ;


signature:
public class BriteDatabase { /** * Execute { @ code statement } and return the ID of the row inserted due to this call .
 * The SQL statement should be an INSERT for this to be a useful call .
 * @ return the row ID of the last row inserted , if this insert is successful . - 1 otherwise .
 * @ throws android . database . SQLException If the SQL string is invalid
 * @ see SupportSQLiteStatement # executeInsert ( ) */
@ WorkerThread public long executeInsert ( String table , SupportSQLiteStatement statement ) { } }

implementation: return executeInsert ( Collections . singleton ( table ) , statement ) ;


signature:
public class BriteDatabase { /** * See { @ link # executeInsert ( String , SupportSQLiteStatement ) } for usage . This overload allows for
 * triggering multiple tables .
 * @ see BriteDatabase # executeInsert ( String , SupportSQLiteStatement ) */
@ WorkerThread public long executeInsert ( Set < String > tables , SupportSQLiteStatement statement ) { } }

implementation:
if ( logging ) log ( "EXECUTE\n %s" , statement ) ; long rowId = statement . executeInsert ( ) ; if ( rowId != - 1 ) { // Only send a table trigger if the insert was successful .
sendTableTrigger ( tables ) ; } return rowId ;


signature:
public class SqlBrite { /** * Wrap a { @ link SupportSQLiteOpenHelper } for observable queries .
 * While not strictly required , instances of this class assume that they will be the only ones
 * interacting with the underlying { @ link SupportSQLiteOpenHelper } and it is required for
 * automatic notifications of table changes to work . See { @ linkplain BriteDatabase # createQuery the
 * < code > query < / code > method } for more information on that behavior .
 * @ param scheduler The { @ link Scheduler } on which items from { @ link BriteDatabase # createQuery }
 * will be emitted . */
@ CheckResult @ NonNull public BriteDatabase wrapDatabaseHelper ( @ NonNull SupportSQLiteOpenHelper helper , @ NonNull Scheduler scheduler ) { } }

implementation: return new BriteDatabase ( helper , logger , scheduler , queryTransformer ) ;


signature:
public class SqlBrite { /** * Wrap a { @ link ContentResolver } for observable queries .
 * @ param scheduler The { @ link Scheduler } on which items from
 * { @ link BriteContentResolver # createQuery } will be emitted . */
@ CheckResult @ NonNull public BriteContentResolver wrapContentProvider ( @ NonNull ContentResolver contentResolver , @ NonNull Scheduler scheduler ) { } }

implementation: return new BriteContentResolver ( contentResolver , logger , scheduler , queryTransformer ) ;


signature:
public class BriteContentResolver { /** * Create an observable which will notify subscribers with a { @ linkplain Query query } for
 * execution . Subscribers are responsible for < b > always < / b > closing { @ link Cursor } instance
 * returned from the { @ link Query } .
 * Subscribers will receive an immediate notification for initial data as well as subsequent
 * notifications for when the supplied { @ code uri } ' s data changes . Unsubscribe when you no longer
 * want updates to a query .
 * Since content resolver triggers are inherently asynchronous , items emitted from the returned
 * observable use the { @ link Scheduler } supplied to { @ link SqlBrite # wrapContentProvider } . For
 * consistency , the immediate notification sent on subscribe also uses this scheduler . As such ,
 * calling { @ link Observable # subscribeOn subscribeOn } on the returned observable has no effect .
 * Note : To skip the immediate notification and only receive subsequent notifications when data
 * has changed call { @ code skip ( 1 ) } on the returned observable .
 * < b > Warning : < / b > this method does not perform the query ! Only by subscribing to the returned
 * { @ link Observable } will the operation occur .
 * @ see ContentResolver # query ( Uri , String [ ] , String , String [ ] , String )
 * @ see ContentResolver # registerContentObserver ( Uri , boolean , ContentObserver ) */
@ CheckResult @ NonNull public QueryObservable createQuery ( @ NonNull final Uri uri , @ Nullable final String [ ] projection , @ Nullable final String selection , @ Nullable final String [ ] selectionArgs , @ Nullable final String sortOrder , final boolean notifyForDescendents ) { } }

implementation:
final Query query = new Query ( ) { @ Override public Cursor run ( ) { long startNanos = nanoTime ( ) ; Cursor cursor = contentResolver . query ( uri , projection , selection , selectionArgs , sortOrder ) ; if ( logging ) { long tookMillis = NANOSECONDS . toMillis ( nanoTime ( ) - startNanos ) ; log ( "QUERY (%sms)\n  uri: %s\n  projection: %s\n  selection: %s\n  selectionArgs: %s\n  " + "sortOrder: %s\n  notifyForDescendents: %s" , tookMillis , uri , Arrays . toString ( projection ) , selection , Arrays . toString ( selectionArgs ) , sortOrder , notifyForDescendents ) ; } return cursor ; } } ; Observable < Query > queries = Observable . create ( new ObservableOnSubscribe < Query > ( ) { @ Override public void subscribe ( final ObservableEmitter < Query > e ) throws Exception { final ContentObserver observer = new ContentObserver ( contentObserverHandler ) { @ Override public void onChange ( boolean selfChange ) { if ( ! e . isDisposed ( ) ) { e . onNext ( query ) ; } } } ; contentResolver . registerContentObserver ( uri , notifyForDescendents , observer ) ; e . setCancellable ( new Cancellable ( ) { @ Override public void cancel ( ) throws Exception { contentResolver . unregisterContentObserver ( observer ) ; } } ) ; if ( ! e . isDisposed ( ) ) { e . onNext ( query ) ; // Trigger initial query .
} } } ) ; return queries . observeOn ( scheduler ) . compose ( queryTransformer ) // Apply the user ' s query transformer .
. to ( QUERY_OBSERVABLE ) ;


signature:
public class QueryObservable { /** * Given a function mapping the current row of a { @ link Cursor } to { @ code T } , transform each
 * emitted { @ link Query } which returns a single row to { @ code T } .
 * It is an error for a query to pass through this operator with more than 1 row in its result
 * set . Use { @ code LIMIT 1 } on the underlying SQL query to prevent this . Result sets with 0 rows
 * do not emit an item .
 * This method is equivalent to :
 * < pre > { @ code
 * flatMap ( q - > q . asRows ( mapper ) . take ( 1 ) )
 * } < / pre >
 * and a convenience operator for :
 * < pre > { @ code
 * lift ( Query . mapToOne ( mapper ) )
 * } < / pre >
 * @ param mapper Maps the current { @ link Cursor } row to { @ code T } . May not return null . */
@ CheckResult @ NonNull public final < T > Observable < T > mapToOne ( @ NonNull Function < Cursor , T > mapper ) { } }

implementation: return lift ( Query . mapToOne ( mapper ) ) ;


signature:
public class QueryObservable { /** * Given a function mapping the current row of a { @ link Cursor } to { @ code T } , transform each
 * emitted { @ link Query } which returns a single row to { @ code T } .
 * It is an error for a query to pass through this operator with more than 1 row in its result
 * set . Use { @ code LIMIT 1 } on the underlying SQL query to prevent this . Result sets with 0 rows
 * emit { @ code defaultValue } .
 * This method is equivalent to :
 * < pre > { @ code
 * flatMap ( q - > q . asRows ( mapper ) . take ( 1 ) . defaultIfEmpty ( defaultValue ) )
 * } < / pre >
 * and a convenience operator for :
 * < pre > { @ code
 * lift ( Query . mapToOneOrDefault ( mapper , defaultValue ) )
 * } < / pre >
 * @ param mapper Maps the current { @ link Cursor } row to { @ code T } . May not return null .
 * @ param defaultValue Value returned if result set is empty */
@ CheckResult @ NonNull public final < T > Observable < T > mapToOneOrDefault ( @ NonNull Function < Cursor , T > mapper , @ NonNull T defaultValue ) { } }

implementation: return lift ( Query . mapToOneOrDefault ( mapper , defaultValue ) ) ;


signature:
public class QueryObservable { /** * Given a function mapping the current row of a { @ link Cursor } to { @ code T } , transform each
 * emitted { @ link Query } which returns a single row to { @ code Optional < T > } .
 * It is an error for a query to pass through this operator with more than 1 row in its result
 * set . Use { @ code LIMIT 1 } on the underlying SQL query to prevent this . Result sets with 0 rows
 * emit { @ link Optional # empty ( ) Optional . empty ( ) }
 * This method is equivalent to :
 * < pre > { @ code
 * flatMap ( q - > q . asRows ( mapper ) . take ( 1 ) . map ( Optional : : of ) . defaultIfEmpty ( Optional . empty ( ) )
 * } < / pre >
 * and a convenience operator for :
 * < pre > { @ code
 * lift ( Query . mapToOptional ( mapper ) )
 * } < / pre >
 * @ param mapper Maps the current { @ link Cursor } row to { @ code T } . May not return null . */
@ RequiresApi ( Build . VERSION_CODES . N ) @ CheckResult @ NonNull public final < T > Observable < Optional < T > > mapToOptional ( @ NonNull Function < Cursor , T > mapper ) { } }

implementation: return lift ( Query . mapToOptional ( mapper ) ) ;


signature:
public class QueryObservable { /** * Given a function mapping the current row of a { @ link Cursor } to { @ code T } , transform each
 * emitted { @ link Query } to a { @ code List < T > } .
 * Be careful using this operator as it will always consume the entire cursor and create objects
 * for each row , every time this observable emits a new query . On tables whose queries update
 * frequently or very large result sets this can result in the creation of many objects .
 * This method is equivalent to :
 * < pre > { @ code
 * flatMap ( q - > q . asRows ( mapper ) . toList ( ) )
 * } < / pre >
 * and a convenience operator for :
 * < pre > { @ code
 * lift ( Query . mapToList ( mapper ) )
 * } < / pre >
 * Consider using { @ link Query # asRows } if you need to limit or filter in memory .
 * @ param mapper Maps the current { @ link Cursor } row to { @ code T } . May not return null . */
@ CheckResult @ NonNull public final < T > Observable < List < T > > mapToList ( @ NonNull Function < Cursor , T > mapper ) { } }

implementation: return lift ( Query . mapToList ( mapper ) ) ;


signature:
public class RDFPMMLUtils { /** * Validates that the encoded PMML model received matches expected schema .
 * @ param pmml { @ link PMML } encoding of a decision forest
 * @ param schema expected schema attributes of decision forest */
public static void validatePMMLVsSchema ( PMML pmml , InputSchema schema ) { } }

implementation: List < Model > models = pmml . getModels ( ) ; Preconditions . checkArgument ( models . size ( ) == 1 , "Should have exactly one model, but had %s" , models . size ( ) ) ; Model model = models . get ( 0 ) ; MiningFunction function = model . getMiningFunction ( ) ; if ( schema . isClassification ( ) ) { Preconditions . checkArgument ( function == MiningFunction . CLASSIFICATION , "Expected classification function type but got %s" , function ) ; } else { Preconditions . checkArgument ( function == MiningFunction . REGRESSION , "Expected regression function type but got %s" , function ) ; } DataDictionary dictionary = pmml . getDataDictionary ( ) ; Preconditions . checkArgument ( schema . getFeatureNames ( ) . equals ( AppPMMLUtils . getFeatureNames ( dictionary ) ) , "Feature names in schema don't match names in PMML" ) ; MiningSchema miningSchema = model . getMiningSchema ( ) ; Preconditions . checkArgument ( schema . getFeatureNames ( ) . equals ( AppPMMLUtils . getFeatureNames ( miningSchema ) ) ) ; Integer pmmlIndex = AppPMMLUtils . findTargetIndex ( miningSchema ) ; if ( schema . hasTarget ( ) ) { int schemaIndex = schema . getTargetFeatureIndex ( ) ; Preconditions . checkArgument ( pmmlIndex != null && schemaIndex == pmmlIndex , "Configured schema expects target at index %s, but PMML has target at index %s" , schemaIndex , pmmlIndex ) ; } else { Preconditions . checkArgument ( pmmlIndex == null ) ; }


signature:
public class ALSUtils { /** * Computes how the estimated strength of interaction in the model should change - - to what target
 * value - - in response to a new interaction .
 * @ param implicit whether the model is implicit feedback
 * @ param value new interaction ' s strength
 * @ param currentValue existing estimated of strength of interaction
 * @ return new target estimated of strength of interaction , or NaN to signal " no change needed " */
public static double computeTargetQui ( boolean implicit , double value , double currentValue ) { } }

implementation:
// We want Qui to change based on value . What ' s the target value , Qui ' ?
if ( implicit ) { // Target is really 1 , or 0 , depending on whether value is positive or negative .
// This wouldn ' t account for the strength though . Instead the target is a function
// of the current value and strength . If the current value is c , and value is positive
// then the target is somewhere between c and 1 depending on the strength . If current
// value is already > = 1 , there ' s no effect . Similarly for negative values .
if ( value > 0.0f && currentValue < 1.0 ) { double diff = 1.0 - Math . max ( 0.0 , currentValue ) ; return currentValue + ( value / ( 1.0 + value ) ) * diff ; } if ( value < 0.0f && currentValue > 0.0 ) { double diff = - Math . min ( 1.0 , currentValue ) ; return currentValue + ( value / ( value - 1.0 ) ) * diff ; } // No change
return Double . NaN ; } else { // Non - implicit - - value is supposed to be the new value
return value ; }


signature:
public class ALSUtils { /** * Computes how a user vector Xu changes in response to interaction with an item vector Yi .
 * This can also be used to compute how an item vector changes in response to a user interaction ,
 * even though the code naming follows the former convention .
 * @ param solver solver helping solve for Xu in Qu * Y = Xu * ( Yt * Y )
 * @ param value strength of interaction
 * @ param Xu current user vector ( null if no existing user vector )
 * @ param Yi current item vector
 * @ param implicit whether the model is implicit feedback
 * @ return new user vector Xu , or { @ code null } if no update should be made ( i . e . there was no
 * item vector ; the update would push the new Qui farther out of range ) */
public static float [ ] computeUpdatedXu ( Solver solver , double value , float [ ] Xu , float [ ] Yi , boolean implicit ) { } }

implementation:
if ( Yi == null ) { return null ; } boolean noXu = Xu == null ; double Qui = noXu ? 0.0 : VectorMath . dot ( Xu , Yi ) ; // Qui ' is the target , new value of Qui
// 0.5 reflects a " don ' t know " state
double targetQui = computeTargetQui ( implicit , value , noXu ? 0.5 : Qui ) ; if ( Double . isNaN ( targetQui ) ) { return null ; } double dQui = targetQui - Qui ; double [ ] dQuiYi = new double [ Yi . length ] ; for ( int i = 0 ; i < dQuiYi . length ; i ++ ) { dQuiYi [ i ] = Yi [ i ] * dQui ; } double [ ] dXu = solver . solveDToD ( dQuiYi ) ; float [ ] newXu = noXu ? new float [ dXu . length ] : Xu . clone ( ) ; for ( int i = 0 ; i < newXu . length ; i ++ ) { newXu [ i ] += dXu [ i ] ; } return newXu ;


signature:
public class KMeansPMMLUtils { /** * Validates that the encoded PMML model received matches expected schema .
 * @ param pmml { @ link PMML } encoding of KMeans Clustering
 * @ param schema expected schema attributes of KMeans Clustering */
public static void validatePMMLVsSchema ( PMML pmml , InputSchema schema ) { } }

implementation: List < Model > models = pmml . getModels ( ) ; Preconditions . checkArgument ( models . size ( ) == 1 , "Should have exactly one model, but had %s" , models . size ( ) ) ; Model model = models . get ( 0 ) ; Preconditions . checkArgument ( model instanceof ClusteringModel ) ; Preconditions . checkArgument ( model . getMiningFunction ( ) == MiningFunction . CLUSTERING ) ; DataDictionary dictionary = pmml . getDataDictionary ( ) ; Preconditions . checkArgument ( schema . getFeatureNames ( ) . equals ( AppPMMLUtils . getFeatureNames ( dictionary ) ) , "Feature names in schema don't match names in PMML" ) ; MiningSchema miningSchema = model . getMiningSchema ( ) ; Preconditions . checkArgument ( schema . getFeatureNames ( ) . equals ( AppPMMLUtils . getFeatureNames ( miningSchema ) ) ) ;


signature:
public class VectorMath { /** * Computes cosine similarity of values in two given arrays , when the norm of one array is
 * known in advance , which is a not - uncommon case .
 * @ param x one array
 * @ param y the other array
 * @ param normY norm of y
 * @ return cosine similarity = dot ( x , y ) / ( norm ( x ) * norm ( y ) ) */
public static double cosineSimilarity ( float [ ] x , float [ ] y , double normY ) { } }

implementation: int length = x . length ; double dot = 0.0 ; double totalXSq = 0.0 ; for ( int i = 0 ; i < length ; i ++ ) { double xi = x [ i ] ; totalXSq += xi * xi ; dot += xi * y [ i ] ; } return dot / ( Math . sqrt ( totalXSq ) * normY ) ;


signature:
public class SolverCache { /** * Proactively try to compute the solver asynchronously , if not already computed .
 * Does not block . */
public void compute ( ) { } }

implementation:
// Make sure only one attempts to build at one time
if ( solverUpdating . compareAndSet ( false , true ) ) { executor . execute ( LoggingCallable . log ( ( ) -> { try { log . info ( "Computing cached solver" ) ; // Not as much hurry if one already exists
boolean lowPriority = solver . get ( ) != null ; Solver newYTYSolver = LinearSystemSolver . getSolver ( vectorPartitions . getVTV ( lowPriority ) ) ; if ( newYTYSolver != null ) { log . info ( "Computed new solver {}" , newYTYSolver ) ; solver . set ( newYTYSolver ) ; } } finally { // Allow any threads waiting for initial model to proceed .
// It ' s possible the solver is still null here if there is no input .
solverInitialized . countDown ( ) ; solverUpdating . set ( false ) ; } } ) . asRunnable ( ) ) ; }


signature:
public class HadoopUtils { /** * Adds a shutdown hook that tries to call { @ link Closeable # close ( ) } on the given argument
 * at JVM shutdown . This integrates with Hadoop ' s { @ link ShutdownHookManager } in order to
 * better interact with Spark ' s usage of the same .
 * @ param closeable thing to close */
public static void closeAtShutdown ( Closeable closeable ) { } }

implementation:
if ( SHUTDOWN_HOOK . addCloseable ( closeable ) ) { try { // Spark uses SHUTDOWN _ HOOK _ PRIORITY + 30 ; this tries to execute earlier
ShutdownHookManager . get ( ) . addShutdownHook ( SHUTDOWN_HOOK , FileSystem . SHUTDOWN_HOOK_PRIORITY + 40 ) ; } catch ( IllegalStateException ise ) { log . warn ( "Can't close {} at shutdown since shutdown is in progress" , closeable ) ; } }


signature:
public class AbstractSpeedModelManager { /** * Convenience method that is called by the default implementation of
 * { @ link # consume ( Iterator , Configuration ) } , to process one key - message pair .
 * It does nothing , except log the message . This should generally be overridden
 * if and only if { @ link # consume ( Iterator , Configuration ) } is not .
 * @ param key key to process ( non - null )
 * @ param message message to process
 * @ param hadoopConf Hadoop configuration for process
 * @ throws IOException if an error occurs while processing the message
 * @ since 2.3.0 */
public void consumeKeyMessage ( String key , U message , Configuration hadoopConf ) throws IOException { } }

implementation: log . info ( "{} : {}" , key , message ) ;


signature:
public class ALSServingModel { /** * Like { @ link # retainRecentAndUserIDs ( Collection ) } and { @ link # retainRecentAndItemIDs ( Collection ) }
 * but affects the known - items data structure .
 * @ param users users that should be retained , which are coming in the new model updates
 * @ param items items that should be retained , which are coming in the new model updates */
void retainRecentAndKnownItems ( Collection < String > users , Collection < String > items ) { } }

implementation:
// Keep all users in the new model , or , that have been added since last model
MutableSet < String > recentUserIDs = UnifiedSet . newSet ( ) ; X . addAllRecentTo ( recentUserIDs ) ; try ( AutoLock al = knownItemsLock . autoWriteLock ( ) ) { knownItems . keySet ( ) . removeIf ( key -> ! users . contains ( key ) && ! recentUserIDs . contains ( key ) ) ; } // This will be easier to quickly copy the whole ( smallish ) set rather than
// deal with locks below
MutableSet < String > allRecentKnownItems = UnifiedSet . newSet ( ) ; Y . addAllRecentTo ( allRecentKnownItems ) ; Predicate < String > notKeptOrRecent = value -> ! items . contains ( value ) && ! allRecentKnownItems . contains ( value ) ; try ( AutoLock al = knownItemsLock . autoReadLock ( ) ) { knownItems . values ( ) . forEach ( knownItemsForUser -> { synchronized ( knownItemsForUser ) { knownItemsForUser . removeIf ( notKeptOrRecent ) ; } } ) ; }


signature:
public class IOUtils { /** * Deletes the given path , and if it is a directory , all files and subdirectories within it .
 * @ param rootDir directory to delete
 * @ throws IOException if any error occurs while deleting files or directories */
public static void deleteRecursively ( Path rootDir ) throws IOException { } }

implementation: if ( rootDir == null || ! Files . exists ( rootDir ) ) { return ; } Files . walkFileTree ( rootDir , new SimpleFileVisitor < Path > ( ) { @ Override public FileVisitResult visitFile ( Path file , BasicFileAttributes attrs ) throws IOException { Files . delete ( file ) ; return FileVisitResult . CONTINUE ; } @ Override public FileVisitResult postVisitDirectory ( Path dir , IOException exc ) throws IOException { Files . delete ( dir ) ; return FileVisitResult . CONTINUE ; } } ) ;


signature:
public class ClassUtils { /** * Like { @ link # loadInstanceOf ( String , Class ) } where the reference returned is of the same type as
 * the class being loaded - - not any supertype .
 * @ param clazz { @ link Class } to make an instance of
 * @ param < T > type of returned instance
 * @ return instance of { @ code clazz } */
public static < T > T loadInstanceOf ( Class < T > clazz ) { } }

implementation: return loadInstanceOf ( clazz . getName ( ) , clazz ) ;


signature:
public class ClassUtils { /** * Like { @ link # loadInstanceOf ( String , Class , Class [ ] , Object [ ] ) } for no - arg constructors .
 * @ param implClassName implementation class name
 * @ param superClass superclass or interface that the implementation extends
 * @ param < T > type of returned instance
 * @ return instance of { @ code implClassName } */
public static < T > T loadInstanceOf ( String implClassName , Class < T > superClass ) { } }

implementation: return loadInstanceOf ( implClassName , superClass , NO_TYPES , NO_ARGS ) ;


signature:
public class ClassUtils { /** * Loads and instantiates a named implementation class , a subclass of a given supertype ,
 * whose constructor takes the given arguments .
 * @ param implClassName implementation class name
 * @ param superClass superclass or interface that the implementation extends
 * @ param constructorTypes argument types of constructor to use
 * @ param constructorArgs actual constructor arguments
 * @ param < T > type of returned instance
 * @ return instance of { @ code implClassName } */
public static < T > T loadInstanceOf ( String implClassName , Class < T > superClass , Class < ? > [ ] constructorTypes , Object [ ] constructorArgs ) { } }

implementation: try { Class < ? extends T > configClass = loadClass ( implClassName , superClass ) ; Constructor < ? extends T > constructor = configClass . getConstructor ( constructorTypes ) ; return constructor . newInstance ( constructorArgs ) ; } catch ( NoSuchMethodException | InstantiationException | IllegalAccessException e ) { throw new IllegalArgumentException ( "No valid " + superClass + " binding exists" , e ) ; } catch ( InvocationTargetException ite ) { throw new IllegalStateException ( "Could not instantiate " + superClass + " due to exception" , ite . getCause ( ) ) ; }


signature:
public class EstimateForAnonymous { /** * Builds a temporary user feature vector given an ( optional ) existing user vector and a context
 * of items .
 * @ param model current ALS model
 * @ param parsedPathSegments request path segments containing item - value pairs
 * @ param Xu existing feature vector for the user ( may be { @ code null } )
 * @ return user feature vector */
static float [ ] buildTemporaryUserVector ( ALSServingModel model , List < Pair < String , Double > > parsedPathSegments , float [ ] Xu ) throws OryxServingException { } }

implementation:
boolean implicit = model . isImplicit ( ) ; Solver solver = model . getYTYSolver ( ) ; check ( solver != null , Response . Status . SERVICE_UNAVAILABLE , "No solver available for model yet" ) ; for ( Pair < String , Double > itemValue : parsedPathSegments ) { float [ ] Yi = model . getItemVector ( itemValue . getFirst ( ) ) ; // Given value is taken to be the fictitious current value of Qui = Xu * Yi ^ T
float [ ] newXu = ALSUtils . computeUpdatedXu ( solver , itemValue . getSecond ( ) , Xu , Yi , implicit ) ; if ( newXu != null ) { Xu = newXu ; } } return Xu ;


signature:
public class JVMUtils { /** * Adds a shutdown hook that tries to call { @ link Closeable # close ( ) } on the given argument
 * at JVM shutdown .
 * @ param closeable thing to close */
public static void closeAtShutdown ( Closeable closeable ) { } }

implementation: if ( SHUTDOWN_HOOK . addCloseable ( closeable ) ) { try { Runtime . getRuntime ( ) . addShutdownHook ( new Thread ( SHUTDOWN_HOOK , "OryxShutdownHookThread" ) ) ; } catch ( IllegalStateException ise ) { log . warn ( "Can't close {} at shutdown since shutdown is in progress" , closeable ) ; } }


signature:
public class MLUpdate { /** * Optionally , publish additional model - related information to the update topic ,
 * after the model has been written . This is needed only in specific cases , like the
 * ALS algorithm , where the model serialization in PMML can ' t contain all of the info .
 * @ param sparkContext active Spark Context
 * @ param pmml model for which extra data should be written
 * @ param newData data that has arrived in current interval
 * @ param pastData all previously - known data ( may be { @ code null } )
 * @ param modelParentPath directory containing model files , if applicable
 * @ param modelUpdateTopic message topic to write to */
public void publishAdditionalModelData ( JavaSparkContext sparkContext , PMML pmml , JavaRDD < M > newData , JavaRDD < M > pastData , Path modelParentPath , TopicProducer < String , String > modelUpdateTopic ) { } }

implementation: // Do nothing by default


signature:
public class ConfigUtils { /** * Helper to set a { @ link Path } value correctly for use with { @ link # overlayOn ( Map , Config ) } .
 * @ param overlay key - value pairs to overlay on a { @ link Config }
 * @ param key key to set
 * @ param path { @ link Path } value
 * @ throws IOException if { @ link Path } can ' t be made canonical */
public static void set ( Map < String , Object > overlay , String key , Path path ) throws IOException { } }

implementation: Path finalPath = Files . exists ( path , LinkOption . NOFOLLOW_LINKS ) ? path . toRealPath ( LinkOption . NOFOLLOW_LINKS ) : path ; overlay . put ( key , "\"" + finalPath . toUri ( ) + "\"" ) ;


signature:
public class SilhouetteCoefficient { /** * Computes the Silhouette Coefficient for this clustering .
 * See https : / / en . wikipedia . org / wiki / Silhouette _ ( clustering )
 * @ param clusterPointsByID map of cluster ID to points that map to that cluster ,
 * for whom Silhouette coefficient needs to be computed
 * @ return Silhouette Coefficient in range [ - 1,1 ] ; higher is better */
double silhouetteCoefficient ( Map < Integer , Iterable < double [ ] > > clusterPointsByID ) { } }

implementation:
double totalSilhouetteCoefficient = 0.0 ; long sampleCount = 0L ; for ( Map . Entry < Integer , Iterable < double [ ] > > entry : clusterPointsByID . entrySet ( ) ) { List < double [ ] > clusteredPoints = iterableToList ( entry . getValue ( ) ) ; long clusterSize = clusteredPoints . size ( ) ; // Increment the total sample count for computing silhouette coefficient
sampleCount += clusterSize ; // if there ' s only one element in a cluster , then assume the silhouetteCoefficient for
// the cluster = 0 , this is an arbitrary choice per Section 2 : Construction of Silhouettes
// in the referenced paper
if ( clusterSize > 1 ) { for ( double [ ] point : clusteredPoints ) { double pointIntraClusterDissimilarity = clusterDissimilarityForPoint ( point , clusteredPoints , true ) ; double pointInterClusterDissimilarity = minInterClusterDissimilarityForPoint ( entry . getKey ( ) , point , clusterPointsByID ) ; totalSilhouetteCoefficient += silhouetteCoefficient ( pointIntraClusterDissimilarity , pointInterClusterDissimilarity ) ; } } } return sampleCount == 0 ? 0.0 : totalSilhouetteCoefficient / sampleCount ;


signature:
public class Evaluation { /** * Computes root mean squared error of { @ link Rating # rating ( ) } versus predicted value . */
static double rmse ( MatrixFactorizationModel mfModel , JavaRDD < Rating > testData ) { } }

implementation: JavaPairRDD < Tuple2 < Integer , Integer > , Double > testUserProductValues = testData . mapToPair ( rating -> new Tuple2 < > ( new Tuple2 < > ( rating . user ( ) , rating . product ( ) ) , rating . rating ( ) ) ) ; @ SuppressWarnings ( "unchecked" ) RDD < Tuple2 < Object , Object > > testUserProducts = ( RDD < Tuple2 < Object , Object > > ) ( RDD < ? > ) testUserProductValues . keys ( ) . rdd ( ) ; JavaRDD < Rating > predictions = testData . wrapRDD ( mfModel . predict ( testUserProducts ) ) ; double mse = predictions . mapToPair ( rating -> new Tuple2 < > ( new Tuple2 < > ( rating . user ( ) , rating . product ( ) ) , rating . rating ( ) ) ) . join ( testUserProductValues ) . values ( ) . mapToDouble ( valuePrediction -> { double diff = valuePrediction . _1 ( ) - valuePrediction . _2 ( ) ; return diff * diff ; } ) . mean ( ) ; return Math . sqrt ( mse ) ;


signature:
public class Evaluation { /** * Computes AUC ( area under the ROC curve ) as a recommender evaluation metric .
 * Really , it computes what might be described as " Mean AUC " , as it computes AUC per
 * user and averages them . */
static double areaUnderCurve ( JavaSparkContext sparkContext , MatrixFactorizationModel mfModel , JavaRDD < Rating > positiveData ) { } }

implementation:
// This does not use Spark ' s BinaryClassificationMetrics . areaUnderROC because it
// is intended to operate on one large set of ( score , label ) pairs . The computation
// here is really many small AUC problems , for which a much faster direct computation
// is available .
// Extract all positive ( user , product ) pairs
JavaPairRDD < Integer , Integer > positiveUserProducts = positiveData . mapToPair ( rating -> new Tuple2 < > ( rating . user ( ) , rating . product ( ) ) ) ; JavaPairRDD < Integer , Iterable < Rating > > positivePredictions = predictAll ( mfModel , positiveData , positiveUserProducts ) ; // All distinct item IDs , to be broadcast
Broadcast < List < Integer > > allItemIDsBC = sparkContext . broadcast ( positiveUserProducts . values ( ) . distinct ( ) . collect ( ) ) ; JavaPairRDD < Integer , Integer > negativeUserProducts = positiveUserProducts . groupByKey ( ) . flatMapToPair ( new PairFlatMapFunction < Tuple2 < Integer , Iterable < Integer > > , Integer , Integer > ( ) { private final RandomGenerator random = RandomManager . getRandom ( ) ; @ Override public Iterator < Tuple2 < Integer , Integer > > call ( Tuple2 < Integer , Iterable < Integer > > userIDsAndItemIDs ) { Integer userID = userIDsAndItemIDs . _1 ( ) ; Collection < Integer > positiveItemIDs = Sets . newHashSet ( userIDsAndItemIDs . _2 ( ) ) ; int numPositive = positiveItemIDs . size ( ) ; Collection < Tuple2 < Integer , Integer > > negative = new ArrayList < > ( numPositive ) ; List < Integer > allItemIDs = allItemIDsBC . value ( ) ; int numItems = allItemIDs . size ( ) ; // Sample about as many negative examples as positive
for ( int i = 0 ; i < numItems && negative . size ( ) < numPositive ; i ++ ) { Integer itemID = allItemIDs . get ( random . nextInt ( numItems ) ) ; if ( ! positiveItemIDs . contains ( itemID ) ) { negative . add ( new Tuple2 < > ( userID , itemID ) ) ; } } return negative . iterator ( ) ; } } ) ; JavaPairRDD < Integer , Iterable < Rating > > negativePredictions = predictAll ( mfModel , positiveData , negativeUserProducts ) ; return positivePredictions . join ( negativePredictions ) . values ( ) . mapToDouble ( t -> { // AUC is also the probability that random positive examples
// rank higher than random examples at large . Here we compare all random negative
// examples to all positive examples and report the totals as an alternative
// computation for AUC
long correct = 0 ; long total = 0 ; for ( Rating positive : t . _1 ( ) ) { for ( Rating negative : t . _2 ( ) ) { if ( positive . rating ( ) > negative . rating ( ) ) { correct ++ ; } total ++ ; } } if ( total == 0 ) { return 0.0 ; } return ( double ) correct / total ; } ) . mean ( ) ;