# Referencia: Servicos e Endpoints de Integracao Fluig

## Metodos de Autenticacao

| Metodo | Quando Usar | Como Configurar |
|---|---|---|
| `fluigAPI.getAuthorizeClientService()` | Servico registrado no Painel Fluig | Painel > Servicos > Novo Servico |
| `java.net.URL` + `HttpURLConnection` | Sem registro no Painel (legado/direto) | Hardcode ou dataset de config |
| `ServiceManager.getService()` | WebService SOAP registrado | Painel > Servicos > WSDL |
| `ServiceManager.getServiceInstance()` | WebService SOAP via classe Java | Singleton do ServiceManager |

## fluigAPI — Servico REST Registrado (RECOMENDADO)

```javascript
// 1. Obter o servico pelo nome cadastrado no Painel
var clientService = fluigAPI.getAuthorizeClientService();
var oAuthClient = clientService.getAuthorizeClient("NomeServico");

// 2. Propriedades disponiveis
oAuthClient.getEndpoint();        // URL base do servico
oAuthClient.getAccessToken();     // Token OAuth (se configurado)
oAuthClient.getConsumerKey();     // Consumer Key
oAuthClient.getConsumerSecret();  // Consumer Secret
oAuthClient.getTokenKey();        // Token Key
oAuthClient.getTokenSecret();     // Token Secret

// 3. Chamada REST
var data = clientService.invoke(url, "GET", null, null, null, null);
// invoke(url, method, headers, body, params, cookies)

// 4. Resultado
var resultado = data.getResult();    // String com o body da resposta
var statusCode = data.getStatusCode(); // HTTP status code
```

## java.net.URL — Chamada HTTP Direta

```javascript
var url = new java.net.URL("https://api.exemplo.com/endpoint");
var conn = url.openConnection();
conn.setRequestMethod("GET");  // ou "POST", "PUT", "DELETE"
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "Bearer " + token);
conn.setConnectTimeout(30000);  // 30 segundos
conn.setReadTimeout(30000);

// Para POST com body:
conn.setDoOutput(true);
var os = new java.io.DataOutputStream(conn.getOutputStream());
os.writeBytes(JSON.stringify(payload));
os.flush();
os.close();

// Ler resposta
var responseCode = conn.getResponseCode();
var stream = (responseCode >= 200 && responseCode < 300)
    ? conn.getInputStream()
    : conn.getErrorStream();
var reader = new java.io.BufferedReader(new java.io.InputStreamReader(stream, "UTF-8"));
var response = "";
var line;
while ((line = reader.readLine()) != null) {
    response += line;
}
reader.close();
conn.disconnect();  // SEMPRE desconectar
```

## ServiceManager — SOAP/WebService

```javascript
// 1. Obter instancia do servico
var serviceLocator = ServiceManager.getServiceInstance("NomeServico");
var service = serviceLocator.getService();
var port = service.getPort();  // varia conforme o WSDL

// 2. Alternativa: getService direto
var serviceHelper = ServiceManager.getService("NomeServico");
var servicePort = serviceHelper.getRealServicePort();

// 3. Object Factory (para criar tipos complexos)
var objectFactory = serviceHelper.getObjectFactory();
var param = objectFactory.createTipoComplexo();
param.setAtributo("valor");
```

## WebServices Nativos do Fluig

| Servico | Classe | Uso Comum |
|---|---|---|
| ECMWorkflowEngineService | `com.datasul.technology.webdesk.workflow.ws` | Iniciar processos programaticamente |
| DocumentService | `com.datasul.technology.webdesk.dm.ws` | CRUD de documentos GED |
| ECMColleagueService | `com.datasul.technology.webdesk.organization.ws` | Consultar colaboradores |
| ECMGroupService | `com.datasul.technology.webdesk.organization.ws` | Gerenciar grupos |
| ECMFolderService | `com.datasul.technology.webdesk.dm.ws` | Gerenciar pastas |
| ECMCardService | `com.datasul.technology.webdesk.workflow.ws` | Operacoes com fichas |

## Datasul — ExecBO

```javascript
// Via dataset sincronizado
function defineStructure() { /* colunas */ }
function onSync(lastSyncDate) {
    var serviceHelper = ServiceManager.getService("EAIService");
    var servicePort = serviceHelper.getRealServicePort();
    var objectFactory = serviceHelper.getObjectFactory();
    // Chamar BO via ExecBO
}
```

## Tratamento de JSON (Server-side)

```javascript
// Parsear JSON (Rhino)
var obj = new org.json.JSONObject(jsonString);
var arr = new org.json.JSONArray(jsonString);

// Acessar valores
obj.getString("chave");
obj.optString("chave", "default");
obj.getInt("numero");
obj.getBoolean("flag");
obj.getJSONObject("sub_objeto");
obj.getJSONArray("lista");

// Iterar array
for (var i = 0; i < arr.length(); i++) {
    var item = arr.getJSONObject(i);
}

// Criar JSON
var novoObj = new org.json.JSONObject();
novoObj.put("chave", "valor");
var novoArr = new org.json.JSONArray();
novoArr.put(novoObj);
```
