How do I call the synthesize method of the TextToSpeech service within the java-sdk API? - text-to-speech

The API documentation can be found here: https://github.com/watson-developer-cloud/java-sdk
When I try and use the service, it authenticates properly and then fails on the synthesize method.
TextToSpeech tts_service = new TextToSpeech();
tts_service.setUsernameAndPassword("<username>", "<password>");
tts_service.synthesize("The cat sat on the mat", Voice.EN_LISA, "audio/ogg; codecs=opus");
The stack trace for the error is shown below. I have tried the synthesize method without the voice and format arguments too (since it has a default) but the service fails with the same error when I do this.
Nov 25, 2015 4:58:55 PM
com.ibm.watson.developer_cloud.service.WatsonService execute SEVERE:
https://stream.watsonplatform.net/text-to-speech/api/v1/synthesize?text=The%20cat%20sat%20on%20the%20mat&voice=en-US_LisaVoice&Accept=audio%2Fogg%3B%20codecs%3Dopus,
status: 400, error: The argument(s) [u'Accept'] are not allowed. Nov
25, 2015 4:58:55 PM com.vaadin.server.DefaultErrorHandler doDefault
SEVERE: com.ibm.watson.developer_cloud.service.BadRequestException:
The argument(s) [u'Accept'] are not allowed. at
com.ibm.watson.developer_cloud.service.WatsonService.execute(WatsonService.java:128)
at
com.ibm.watson.developer_cloud.text_to_speech.v1.TextToSpeech.synthesize(TextToSpeech.java:119)
I'd appreciate some help with this please and want to use the java API rather than the REST calls.
Thanks.

The Java-SDK is sending Accept instead of accept(rocky mistake).
A workaround until our next release is to extend the TextToSpeech class and override:
InputStream synthesize(final String text, final Voice voice, final String outputFormat)
Example:
public class TextToSpeechHotFix extends TextToSpeech {
#Override
public InputStream synthesize(final String text, final Voice voice, final String outputFormat) {
final RequestBuilder request = RequestBuilder.get(PATH_SYNTHESIZE);
request.withQuery(TEXT, text);
request.withQuery(VOICE, voice.getName());
if (outputFormat != null && !outputFormat.startsWith("audio/"))
throw new IllegalArgumentException(
"format needs to be an audio mime type, for example: audio/wav or audio/ogg; codecs=opus");
request.withQuery(ACCEPT, outputFormat != null ? outputFormat : HttpMediaType.AUDIO_WAV);
final Response response = execute(request.build());
return ResponseUtil.getInputStream(response);
}
}

Related

Locale aware bean validation message interpolation at ExceptionMapper in openliberty

I have a JAX-RS #POST endpoint whose input data has to be #Valid:
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response myEndpoint(#javax.validation.Valid MyInputData input) { /*...*/ }
With MyInputData class annotated with many constraints:
#lombok.Data
public class InputData {
#Size(min = 1, max = 3)
private String someString;
/* ... */
}
Beyond that I have an ExceptionMapper<ConstraintViolationException> that transform the Exception into a Collection<String> (basically every single ConstraintViolation transformed to String using its getMesssage() method), then returns a Response.status(Status.BAD_REQUEST).entity(list).build().
Everything is working nicely. Fed an invalid input and I get back a HTTP 400 with a nice array of constraint violations in json format.
So far, so good...
BUT... the messages are in server's locale. Even if HTTP post sends a Accept-language header (and it is correctly detected when getting HttpServletRequest::getLocale).
By the time the ExceptionMapper gets hold of ConstraintViolation every message has already been interpolated, so no chance set the client locale.
Since the validation runs even before the JAX-RS resource (indeed, the JAX-RS resource isn't even called in case of invalid input), this locale aware message interpolator must be configured somewhere else.
Where? Is there already a MessageInterpolator implementation whose operation takes the HttpServletRequest locale into account?

Escaping ampersands (&) on generated requests from a WCF class

I'm having issues with strings containing ampersands in my client generated from dotnet-svcutil.
When I recieve a response through the client all ampersands are serialized as
<Users xsi:type=\"xsd:string\">John & Jane</Users>
When i extract the value from the request in my code it has been deserialized as an ampersand
UserResponse users = await GetUsersAsync()
users.Names = "John & Jane"
In a later stage i need to send the value of the users back like this
await SetUsersAsync(users.Names);
When i intercept the generated soap request I can see that the ampersand has not been escaped
public class MyMessageInspector : IClientMessageInspector
{
public void AfterReceiveReply(ref Message reply, object correlationState)
{
var xml = reply.ToString(); // This shows <Users xsi:type=\"xsd:string\">John & Jane</Users>
}
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
var xml = request.ToString(); // This shows <Users xsi:type=\"xsd:string\">John & Jane</Users>
return null;
}
}
This causes the whole request to fail in the connected service. From the information I've found online the ampersand should be converted to & by the serializer. I could convert the value myself, but since I'm only returning a value I got from the soap client, I would have to check and convert every single string that is returned back.
Do you have any suggestions on how I could configure the generated client to automatically escape ampersands?
For .net core 2.1+:
Use the HtmlEncode method of HttpUtility available in System.Web to encode the strings you send to the client.
using System.Web;
await SetUsersAsync(HttpUtility.HtmlEncode(users.Names));
For .net core 2.0 (or .net 1.* with a package install):
use HtmlEncoder.Default.Encode(users.Names)
which is available in System.Text.Encodings.Web

Spring Data Rest Content Type

I am writing unit tests for my application with Spring Data Rest MongoDB. Based on Josh's "Building REST services with Spring" get start guide, I have the following test code:
#Test
public void readSingleAccount() throws Exception {
mockMvc.perform(get("/accounts/"
+ this.account.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("$.id", is(this.account.getId())))
.andExpect(jsonPath("$.email", is(this.account.getEmail())))
.andExpect(jsonPath("$.password", is(this.account.getPassword())));
}
And this test fails on the content type.
Content type expected:<application/json;charset=UTF-8> but was: <application/hal+json>
Expected :application/json;charset=UTF-8
Actual :application/hal+json
I don't see MediaType come with HAL. Is the content type defined in another class?
Had the same Problem when not using tomcat (which is configured to return utf-8 using Spring Boot). The solution is to set the accept header in your GET request so the response gets the correct content type:
private MediaType contentType = new MediaType("application", "hal+json", Charset.forName("UTF-8"));
and in your request, do
#Test
public void readSingleAccount() throws Exception {
mockMvc.perform(get("/accounts/"
+ this.account.getId()).**accept(contentType)**)
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("$.id", is(this.account.getId())))
.andExpect(jsonPath("$.email", is(this.account.getEmail())))
.andExpect(jsonPath("$.password", is(this.account.getPassword())));
}

CRM 2011 - ITracingService getting access to the traceInfo at runtime

I have some custom logging in my plugin and want to include the contents of my tracingService in my custom logging (which is called within a catch block, before the plugin finishes).
I cant seem to access the content of tracingService. I wonder if it is accessible at all?
I tried tracingService.ToString() just incase the devs had provided a useful overload, alas as expected I get name of the class "Microsoft.Crm.Sandbox.SandboxTracingService".
Obviously Dynamics CRM makes use of the tracingService content towards the end of the pipeline if it needs to.
Anybody have any ideas on this?
Kind Regards,
Gary
The tracing service does not provide access to the trace text during execution but that can be overcome by creating your own implementation of ITracingService. Note, you cannot get any text that was written to the trace log prior to the Execute method of your plugin being called - meaning if you have multiple plugins firing you won't get their trace output in the plugin that throws the exception.
public class CrmTracing : ITracingService
{
ITracingService _tracingService;
StringBuilder _internalTrace;
public CrmTracing(ITracingService tracingService)
{
_tracingService = tracingService;
_internalTrace = new StringBuilder();
}
public void Trace(string format, params object[] args)
{
if (_tracingService != null) _tracingService.Trace(format, args);
_internalTrace.AppendFormat(format, args).AppendLine();
}
public string GetTraceBuffer()
{
return _internalTrace.ToString();
}
}
Just instantiate it in your plugin passing in the CRM provided ITracingService. Since it is the same interface it works the same if you pass it to other classes and methods.
public class MyPlugin : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
var tracingService = new CrmTracing((ITracingService)serviceProvider.GetService(typeof(ITracingService)));
tracingService.Trace("Works same as always.");
var trace = tracingService.GetTraceBuffer();
}
}
To get the traceInfo string from traceService at runtime I used debugger to interrogate the tracingService contents.
So the trace string is accessible from these expressions...
for Plugins
((Microsoft.Crm.Extensibility.PipelineTracingService)(tracingService)).TraceInfo
for CWA
((Microsoft.Crm.Workflow.WorkflowTracingService)(tracingService)).TraceInfo
You can drill into the tracing service by debugging and extract the expression.
However, at design time neither of these expressions seem to be accessible from any of the standard CRM 2011 SDK dlls... so not sure if its possible as yet.

FileHelper library - custom error messages

I am use the FileHelper to parse CSV files. Error messages encountered when parsing the file are displayed to the end user. The end user may not be able to make sense of the technical error message. Not too many clerks know what an Int32 is or Class: UploadFooDto.
I would like to customize the error messages so they are more user friendly. Something like:
Line 1. Column 2. A string (a) was entered instead of a number
Line 2. Column 3. '13-14-15' is not a valid date
I cannot find anything in the API that would allow me to customize the error messages. The most I have so far are some extension methods to clean up the errors:
public static class FileHelperExceptionExtensions
{
public static string BuildMessage(this ErrorInfo error)
{
if (error.ExceptionInfo is ConvertException)
{
return ((ConvertException)error.ExceptionInfo).BuildMessage();
}
if (error.ExceptionInfo is BadUsageException)
{
var message = error.ExceptionInfo.Message;
var readTo = message.IndexOf("Class:");
return message.Substring(0, readTo);
}
return string.Format("Line: {0}. An unspecific error occured.", error.LineNumber);
}
public static string BuildMessage(this ConvertException exception)
{
return string.Format("Line: {0}. Column: {1}. Field: {2}. Cannot convert '{3}' to type: '{4}'", exception.LineNumber, exception.ColumnNumber, exception.FieldName, exception.FieldStringValue, exception.FieldType.Name);
}
}
but these extensions still leave a lot to be desired. Is it possible to customize the error messages?
It's hard to improve on your extension methods without it being more hassle than it's worth.
You cannot subclass the default converters (e.g., FileHelpers.ConvertHelpers.Int32Converter since they are internal and sealed). You could create your own custom converter for each type (and base it on the corresponding source code from FileHelpers, e.g., Int32Converter). Then you can raise an alternative to ConvertException (also sealed so you cannot subclass) which would format the message differently.