I am trying to request a transcription of an MP3 file using Websockets and Java. The following is a snippet of my Maven dependency followed by the java code . I've put breakpoints in each of the Override methods but not hitting any of them. What am I doing wrong?
Maven Dependency:
<dependency>
<groupId>com.ibm.watson.developer_cloud</groupId>
<artifactId>java-sdk</artifactId>
<version>6.1.0</version>
</dependency>
Code:
SpeechToText speechToText = new SpeechToText();
speechToText.setEndPoint("https://stream.watsonplatform.net/speech-to-text/api/v1/recognize");
speechToText.setUsernameAndPassword("{myUsername}", "{myPassword}");
try {
RecognizeOptions recognizeOptions = new RecognizeOptions.Builder()
.audio(new FileInputStream("KATL-App-Final-All-Aug-01-2017-1630.mp3-edited.mp3"))
.contentType("audio/mp3")
.model("en-US_NarrowbandModel")
.interimResults(true)
.build();
BaseRecognizeCallback baseRecognizeCallback
= new BaseRecognizeCallback() {
#Override
public void onListening() {
System.out.println("Listening");
}
#Override
public void onConnected() {
System.out.println("Connected");
}
#Override
public void onTranscription(SpeechRecognitionResults speechRecognitionResults) {
System.out.println(speechRecognitionResults);
}
#Override
public void onDisconnected() {
System.exit(0);
}
};
speechToText.recognizeUsingWebSocket(recognizeOptions,
baseRecognizeCallback);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
for (;;) {
Thread.sleep(1000);
}
I think I have identified the problem, which is your end point.
The SpeechToText.recognizeUsingWebSocket() method contains this helpful(?) line of code:
HttpUrl.Builder urlBuilder = HttpUrl.parse(getEndPoint() + "/v1/recognize").newBuilder();
So try changing the end point to https://stream.watsonplatform.net/speech-to-text/api or better yet don't set it and just construct SpeechToText using the constructor:
SpeechToText(String username, String password)
This will remove the need to invoke setUsernameAndPassword() and use the default end point:
private static final String URL = "https://stream.watsonplatform.net/speech-to-text/api";
Related
I created a Main java file and I added an instruction for the bot: say "I love Pizza" on a public channel I created.
public class Main {
public static void main(String[] args) {
//create a new Telegram bot object to start talking with Telegram
TelegramBot bot = TelegramBotAdapter.build(“HERE YOUR API KEY”);
bot.sendMessage(“#pizzaciaopizza”, “I love Pizza”);
}
}
This worked. Good start. Thankfully my bot loves pizza.
I wanted to enable my bot to answer a command like "/recommendPizza" and to answer something.So how can one do this?
Any help?
You seem to be using https://github.com/pengrad/java-telegram-bot-api, right?
I have previously used https://github.com/rubenlagus/TelegramBots. It provides a simple listener API to receive updates:
public class PizzaBot {
private static final Logger LOG = Logger.getLogger(PizzaBot.class.getName());
public static void main(String... args) throws Exception {
TelegramBotsApi telegramBotsApi = new TelegramBotsApi();
telegramBotsApi.registerBot(new TelegramLongPollingBot() {
#Override
public void onUpdateReceived(Update update) {
Message message = update.getMessage();
Long chatId = message.getChatId();
String input = message.getText();
if ("/recommendPizza".equals(input)) {
SendMessage request = new SendMessage();
request.setChatId(chatId.toString());
request.setText("Have a calzone!");
try {
sendMessage(request);
} catch (TelegramApiException e) {
LOG.log(Level.SEVERE, "Could not send message", e);
}
}
}
#Override
public String getBotUsername() {
return "YOUR_BOT_USERNAME";
}
#Override
public String getBotToken() {
return "YOUR_BOT_TOKEN";
}
});
}
}
I want to get the data using twitter's fabric api but whenever i tend to verify credentials and use a callback it shows an error , specifically ,"The arguments differ in length"
void getUserData() {
Twitter.getApiClient(session).getAccountService()
.verifyCredentials(true, false, new Callback<User>() {
#Override
public void failure(TwitterException e) {
}
#Override
public void success(Result<User> userResult) {
User user = userResult.data;
String twitterImage = user.profileImageUrl;
try {
Log.d("imageurl", user.profileImageUrl);
Log.d("name", user.name);
Log.d("email",user.email);
Log.d("des", user.description);
Log.d("followers ", String.valueOf(user.followersCount));
Log.d("createdAt", user.createdAt);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
If you check the fabric documentation, it shows two version of the method, however when I tried to open the source code in Android Studio but it had only the version without the callback.
You can solve the isssue as follows:
//Getting the account service of the user logged in
Call<User> call = Twitter.getApiClient(session).getAccountService()
.verifyCredentials(true, false);
call.enqueue(new Callback<User>() {
#Override
public void failure(TwitterException e) {
//If any error occurs handle it here
}
#Override
public void success(Result<User> userResult) {
//If it succeeds creating a User object from userResult.data
User user = userResult.data;
String twitterImage = user.profileImageUrl;
try {
Log.d("imageurl", user.profileImageUrl);
Log.d("name", user.name);
Log.d("email",user.email);
Log.d("des", user.description);
Log.d("followers ", String.valueOf(user.followersCount));
Log.d("createdAt", user.createdAt);
} catch (Exception e) {
e.printStackTrace();
}
}
});
Source
Documentation
Just change the twitter dependency in your Build.Gradle
from
compile('com.twitter.sdk.android:twitter:2.0.0#aar') {
transitive = true;
}
to
compile('com.twitter.sdk.android:twitter:1.11.0#aar') {
transitive = true;
}
The new version of the .verifyCredentials() method doesn't accept a callback hence your error.
I have logs in the form of string. I want to send these logs form my application to influx Database. So, i have written these functions.
private String formatAsJsonArrayString(List<String> logs) {
Gson gson = new Gson();
return gson.toJson(logs);
}
public void startFlushToInfluxDbThread() {
Thread flushToInfluxDbThread = new Thread(new Runnable() {
#Override
public void run() {
while (true) {
try {
Thread.sleep(influxPostWaitTime);
List<String> logs = extractNEntries(queue, 1000);
String dataToPost = formatAsJsonArrayString(logs);
postToInfluxDB(dataToPost);
} catch (Exception e) {
e.printStackTrace();
}
}
}
but now i am unable to think how to write postToInfluxDB() function. Can somebody guide me to do this? I mean to say, how connection will be made and all that related stuff.
I am creating a basic POST JSON api endoint. I would like to unit test it, and want to make sure I am doing it appropriately in the Play framework. So far I am using Guice for dependency injection and JUnit for my unit testing library.
Here is my controller code:
public class NotificationController extends Controller {
private RabbitQueueService _rabbitQueueService;
#Inject
public NotificationController(RabbitQueueService service) {
_rabbitQueueService = service;
}
#BodyParser.Of(BodyParser.Json.class)
public Result post() {
ObjectMapper mapper = new ObjectMapper();
Notification notification;
try {
JsonNode notificationJsonNode = Controller.request().body().asJson();
notification = mapper.readValue(notificationJsonNode.toString(),
Notification.class);
_rabbitQueueService.push(notification);
return Results.created(notificationJsonNode, "UTF-8");
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return Results.badRequest();
}
}
My RabbitQueueService code:
public class RabbitQueueService {
private Channel _channel;
private Connection _connection;
public RabbitQueueService() {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(Config.RABBITMQ_HOST);
try {
_connection = factory.newConnection();
_channel = _connection.createChannel();
_channel.queueDeclare(Config.RABBITMQ_QUEUE, false, false, false, null);
_channel.exchangeDeclare(Config.RABBITMQ_EXCHANGE, "fanout");
_channel.queueBind(Config.RABBITMQ_QUEUE, Config.RABBITMQ_EXCHANGE, "");
} catch (IOException e) {
e.printStackTrace();
}
}
public void push(Notification notification) {
try {
_channel.basicPublish(Config.RABBITMQ_EXCHANGE, "", null, notification.getBytes());
_channel.close();
_connection.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void pop() {
}
}
My MockQueueService code:
public class MockQueueService extends RabbitQueueService {
#Override
public void push(Notification notification) {
/* Do nothing because you know... thats what I do */
}
#Override
public void pop() {
/* Do nothing because you know... thats what I do */
}
}
and finally my current unit test code:
public class ApplicationTest {
#Test
public void addMessageToQueue() {
running(fakeApplication(), new Runnable() {
public void run() {
FakeRequest request = new FakeRequest("/POST", "/api/v1/notifications");
Notification notification = new Notification(UUID.randomUUID(),
new NotificationType(UUID.randomUUID(),
"Critical"),
"Test notification message");
try {
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(notification);
JsonNode node;
node = mapper.readTree(json);
request.withJsonBody(node);
} catch (IOException e) {
e.printStackTrace();
}
route(request);
}
});
}
}
This all works fine when making a curl request to test my endpoint through play run. My main question is: how do I use the MockQueueService in my unit test? I don't see anyway to do it with fakeApplication() helper. I could instantiate it directly like
NotificationController nc = new NotificationController(new MockQueueService());
nc.post();
but the problem is I need to override the body of the play request with an appropriate request body and I think I need a FakeRequest for that.
Any help, samples, or advice would be helpful.
UPDATE
I have posted a gist example with the necessary example files. The things specifically that I did to get it working:
Setup a new GlobalUnitTest file that I passed into the fakeApplication helper
Changed NotificationController to be a singleton. This allowed me to pull in the NotificationController instance so I could check the QueueService count as part of the assertion.
FakeApplication takes a bunch of arguments that you could use to inject your new service. You could use a combination of any of these:
additionalPlugins
additionalConfiguration
withGlobal
They each let you specify some additional configuration you could use only during testing. Another thing you could do is have a separate Global object just for testing, that is used to create your controllers. The Global object is used to return your controller instance when you use # in your route definition. Then, you can create a separate application.test.conf that refers to GlobalTest that is loaded when you run play test.
I need some help concerning UnboundID. I heard it was a great choice but I'm not really used to it.
So I need to make a LDAP listener. On this listener, i should be able to catch bind request (from a ldap browser for example). I wonder how to get the DN and the password. Here is my code for the LDAP listener:
public ResultCode CreateLdapServer () throws LDAPException {
CannedResponseRequestHandler requestHandler = new CannedResponseRequestHandler();
LDAPListenerConfig config =
new LDAPListenerConfig(4243, requestHandler);
try
{
config.setListenAddress(
InetAddress.getByName("localhost"));
}
catch (final Exception e)
{
System.err.println("Unable to create the listen server.");
return ResultCode.PARAM_ERROR;
}
listener = new LDAPListener(config);
try
{
listener.startListening();
System.out.println("Serveur is listening ...");
}
catch (final Exception e)
{
System.err.println("Unable to start listening.");
return ResultCode.LOCAL_ERROR;
}
return ResultCode.SUCCESS;
}
public static void main(String[] args) throws LDAPException {
MyConnection connect = new MyConnection();
connect.CreateLdapServer();
}
I read a lot of UnboundID documentation, but i can't find any simple example of what I need.
Also, i'm not really sure of the utility of CannedResponseRequestHandler. For what i need, is it enough ?
An other question: I'm not sure, but I have the feeling that my server is not listening OR i don't catch anything (when I connect with a ldap Browser, nothing happened). Any Idea / Suggestion ?
Thanks and have a nice day !
EDIT : Thanks to xhochy, I was able to catch the password and the username. As he said, I subclassed LDAPListenerRequestyHandler to override, first, newInstance then ProcessBindRequest. Here is the code (it's absolutely not perfect and it's still a beginning).
public class MyConnection {
private LDAPListener listener;
public MyConnection(){
}
public ResultCode CreateLdapServer() throws LDAPException {
MyLDAPListenerRequestHandler requestHandler = new MyLDAPListenerRequestHandler();
LDAPListenerConfig config =
new LDAPListenerConfig(4243, requestHandler);
try
{
config.setListenAddress(
InetAddress.getByName("localhost"));
}
catch (final Exception e)
{
System.err.println("Unable to create the listen server.");
return ResultCode.PARAM_ERROR;
}
listener = new LDAPListener(config);
try
{
listener.startListening();
System.out.println("Serveur is listening ...");
}
catch (IOException e)
{
System.err.println("Unable to start listening.");
return ResultCode.LOCAL_ERROR;
}
return ResultCode.SUCCESS;
}
public static void main(String[] args) throws LDAPException {
MyConnection connect = new MyConnection();
connect.CreateLdapServer();
}
}
Then the subclass of LDAPListenerRequestHandler:
public class MyLDAPListenerRequestHandler extends LDAPListenerRequestHandler {
#Override
public LDAPListenerRequestHandler newInstance(
LDAPListenerClientConnection arg0) throws LDAPException {
System.out.println("New Instance.");
LDAPConnectionOptions option = new LDAPConnectionOptions();
LDAPConnection connection = new LDAPConnection(option, "yourIPadress", yourport);
System.out.println("Connected to : " + connection.getConnectedAddress()+ " " + connection.getConnectedPort());
return this;
}
#Override
public LDAPMessage processBindRequest(int arg0, BindRequestProtocolOp arg1,
List<Control> arg2) {
System.out.println(arg1.getBindDN());
System.out.println(arg1.getSimplePassword());
return null;
}
}
Thanks again !
Many LDAP server implementations will not return a password and many will not return a password you can use. (ie it maybe a hash).
I would be very curious why there could be a reason to return the password.
-jim
You should subclass LDAPListenerRequestHandler and implement processBindRequest. All the information you are looking for is included in BindRequestProtocolOp (second argument of processBindRequest). Add an empty implementation for all other abstract methods.
If request is your BindRequestProtocolOp instance then you get your information via:
String username = request.getBindDN();
ByteString password = request.getSimplePassword();