I have a simple table with these fields:
ID
int(11) NOT NULL AUTO_INCREMENT,
audio
longblob NOT NULL,
callid
varchar(45) NOT NULL,
causa
varchar(15) DEFAULT NULL,
duracion
varchar(45) DEFAULT NULL,
codigo
int(11) DEFAULT NULL,
numeroagente
int(8) DEFAULT NULL,
numeroreferencia
int(8) DEFAULT NULL,
solicitud
varchar(45) DEFAULT NULL,
fin
timestamp NULL DEFAULT NULL,
inicio
timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
I need to get the audio field, i use the external rest api datasource example to get all fields, but i need to get the audio field as a wave file.
I use,
def rows = sql.rows query
And for get my connection i use this method
protected Sql buildSql(ResourceProvider pageResourceProvider) {
Properties props = loadProperties "datasource.properties", pageResourceProvider
Context ctx = new InitialContext(props)
DataSource dataSource = (DataSource) ctx.lookup(props["datasourceLlamada.name"])
//DataSource dataSource = (DataSource) ctx.lookup("java:comp/env/jdbc/llamadaDS")
new Sql(dataSource)
}
if i try to serialize my object and convert to a base64 string i don’t have the correct result.
I don’t know if is because that my table is in format: latin1 and i need utf8 to see the same result.
Thanks for the help.
Eduardo Cortez
This is my entire Get.groovy class:
package org.bonitasoft.rest.api.extension.ws.llamada
import java.io.Serializable
import java.util.Map
import java.util.Properties
import groovy.json.JsonBuilder
import groovy.json.JsonSlurper
import groovy.sql.Sql
import javax.naming.Context
import javax.naming.InitialContext
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import javax.sql.DataSource
import org.bonitasoft.web.extension.ResourceProvider
import org.bonitasoft.web.extension.rest.RestAPIContext
import org.bonitasoft.web.extension.rest.RestApiController
import org.bonitasoft.web.extension.rest.RestApiResponse
import org.bonitasoft.web.extension.rest.RestApiResponseBuilder
import org.json.CDL
import org.json.JSONArray
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import wslite.json.JSONObject
import wslite.soap.SOAPClient
import wslite.soap.SOAPResponse
class Get implements RestApiController {
private static final Logger LOGGER = LoggerFactory.getLogger(Get.class)
@Override
RestApiResponse doHandle(HttpServletRequest request, RestApiResponseBuilder responseBuilder, RestAPIContext context) {
String queryId = request.getParameter "queryId"
if (queryId == null) {
return buildErrorResponse(responseBuilder, "The parameter queryId is missing.")
}
// Get the query SQL definition from the queries.properties file using query id.
String query = getQuery queryId, context.resourceProvider
if (query == null) {
return buildErrorResponse(responseBuilder, "The queryId does not refer to an existing query. Check your query id and queries.properties file content.")
}
// Build a map will all SQL queries parameters (all REST call parameters expect "queryId").
Map<String, String> params = getSqlParameters request
// Get the database connection using the data source declared in datasource.properties
Sql sql = buildSql context.resourceProvider
try {
// Run the query with or without parameters.
if(!params.isEmpty()){
for (String parameterName : request.getParameterNames()) {
query = query.replace(":"+parameterName, request.getParameter(parameterName))
}
}
def rows = sql.rows query
// Build the JSON answer with the query result
Map<String,String> result = [:]
for (row in rows) {
def headers = row.keySet()
for (header in headers) {
if(header == "audio"){
//result.put(header, serialize(row.getProperty(header)).encodeBase64().toString())
//row.getProperty("")
//return buildResponseWav(responseBuilder, row.get(header))
result.put(header, row.get(header))
}else{
result.put(header, row.get(header))
}
}
}
/*while (rows.next()) {
def columnCount = rows.metaData.columnCount
for(int i=0; i<columnCount;i++){
def columnName = rows.metaData.getColumnName(i)
if(columnName == "audio"){
result.put(columnName,rows.getClob(columnName))
}else{
result.put(columnName,rows.getString(columnName))
}
}
for (header in headers) {
if(header == "audio"){
result.put(header, serialize(row.getProperty(header)).encodeBase64().toString())
}else{
result.put(header, row.getProperty(header))
}
}
}*/
JsonBuilder builder = new JsonBuilder(result)
String table = builder.toPrettyString()
return buildResponse(responseBuilder, table)
//return buildResponseWav(responseBuilder, file)
}catch(Exception e){
return buildErrorResponse(responseBuilder, e.getMessage()+" query: "+query)
} finally {
sql.close()
}
}
protected byte[] serialize(Object obj) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(out);
os.writeObject(obj);
return out.toByteArray();
}
protected RestApiResponse buildErrorResponse(RestApiResponseBuilder apiResponseBuilder, String message) {
LOGGER.error message
Map<String, String> result = [:]
result.put "error", message
apiResponseBuilder.withResponseStatus(HttpServletResponse.SC_BAD_REQUEST)
buildResponse apiResponseBuilder, result
}
protected RestApiResponse buildExitoResponse(RestApiResponseBuilder apiResponseBuilder, String message) {
LOGGER.info message
Map<String, String> result = [:]
result.put "exito", message
apiResponseBuilder.withResponseStatus(HttpServletResponse.SC_BAD_REQUEST)
buildResponse apiResponseBuilder, result
}
protected RestApiResponse buildResponse(RestApiResponseBuilder apiResponseBuilder, Serializable result) {
apiResponseBuilder.with {
withResponse(result)
build()
}
}
protected Map<String, String> getSqlParameters(HttpServletRequest request) {
Map<String, String> params = [:]
for (String parameterName : request.getParameterNames()) {
params.put(parameterName, request.getParameter(parameterName))
}
params.remove("queryId")
params
}
protected Sql buildSql(ResourceProvider pageResourceProvider) {
Properties props = loadProperties "datasource.properties", pageResourceProvider
Context ctx = new InitialContext(props)
DataSource dataSource = (DataSource) ctx.lookup(props["datasourceLlamada.name"])
//DataSource dataSource = (DataSource) ctx.lookup("java:comp/env/jdbc/llamadaDS")
new Sql(dataSource)
}
protected String getQuery(String queryId, ResourceProvider resourceProvider) {
Properties props = loadProperties "queries.properties", resourceProvider
props[queryId]
}
protected Properties loadProperties(String fileName, ResourceProvider resourceProvider) {
Properties props = new Properties()
resourceProvider.getResourceAsStream(fileName).withStream { InputStream s ->
props.load s
}
props
}
protected RestApiResponse buildResponseWav(RestApiResponseBuilder apiResponseBuilder, Serializable result) {
apiResponseBuilder.with {
withMediaType("audio/wav")
//withCharacterSet("ISO-8859-5")
withAdditionalHeader("Content-disposition","attachment; filename=audio.wav")
withResponse(result)
build()
}
}
}