Java tomcat sound - java

i got the folloing warning
28-Jun-2016 16:09:36.482 WARNING [localhost-startStop-2]
org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesThreads
The web application [PickByVoice] appears to have started a thread
named [Java Sound Event Dispatcher] but has failed to stop it. This is
very likely to create a memory leak. Stack trace of thread:
java.lang.Object.wait(Native Method)
java.lang.Object.wait(Object.java:502)
com.sun.media.sound.EventDispatcher.dispatchEvents(EventDispatcher.java:182)
com.sun.media.sound.EventDispatcher.run(EventDispatcher.java:222)
java.lang.Thread.run(Thread.java:745)
I got a webservice and when a request is called the webservice will playback a sound file. It doesnt work.
It works in eclipse useing the tomcat server. dont know why
hope someone can help me
thx

here is some code:
class Webservice
import java.io.IOException;
import javax.inject.Singleton;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
//Import all the needed classfiles
import org.PickByVoice.bluetooth.btautoconnect;
import org.PickByVoice.model.Languages;
import org.PickByVoice.model.WavFile;
import org.PickByVoice.service.AudioService;
import org.PickByVoice.service.UploadService;
import org.PickByVoice.exception.Statues;
#Path("restwebservice") //rootpath of the Servlet
#Singleton //Singleton is used to creat only one instance for all requests. So the Wav-Filelist needs to initiate only once.
#Produces(MediaType.TEXT_HTML)
#Consumes(MediaType.TEXT_HTML)
public class RaspberryPiResources {
//creating instance, setting variables
long startTime=System.currentTimeMillis();
Languages listLanguages=new Languages();
AudioService audioService = new AudioService();
btautoconnect bluetoothAutoConnection=new btautoconnect();
public static WavFile wavFileList;
final String
String currentId="",currentShelfId="",currentstate="nothing scanned",language,location,currentthread;
int i=0;
public RaspberryPiResources(){
language="eng";
audioService.seterrorList("eng"); // Language specific error files are loaded
}
#GET
#Path("init")
public Response initialization(#DefaultValue("eng") #QueryParam ("language") String language,#QueryParam("warehouse") String country) throws InterruptedException, IOException{
audioService.playinit(1L,language);
return Response.status(Statues.INITSUCESS).type(MediaType.TEXT_PLAIN).entity("ok").build(); //Status code 600
}
#GET
#Path("/sounds/messages/{messageId}")
public Response outputErrorSounds(#PathParam("messageId") final long soundId) throws InterruptedException, IOException{
currentthread=Thread.currentThread().getName();
audioService.setcurrentThread(currentthread);
audioService.errorSound(soundId,language,currentstate,currentId,currentthread); //Playing the error message and repeating the scann-Id
return Response.status(Statues.OK).entity(Statues.OK.getReasonPhrase()).build(); //Status code 603
}
class AudioService
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
public class AudioService{
public AudioInputStream audioInStream = null;
public FilterIds filterId=new FilterIds();
public File file;
public SourceDataLine sourceDataLine;
char firstcharacter;
String compare="",currentThread="",Threadcompare="",vrrr="";
WavFile wav;
public AudioService() {
// TODO Auto-generated constructor stub
}
//Stops and closes the SourceDataLine
public void closeAudioLine(){
sourceDataLine.stop();
sourceDataLine.flush();
sourceDataLine.close();
}
public void playinit(Long idOfSound, String language) throws InterruptedException, IOException{
wav=new WavFile(language);
String soundpath=wav.getErrorSoundFileList().get(idOfSound);
currentThread="init";
playAudio(soundpath);
}
public synchronized String errorSound(Long soundId, String language,String currentState,String currentId, String Threadname) throws InterruptedException, IOException{
currentThread="playerrorSound";
if(!currentThread.equals("playerrorSound")){
ack();
}
if(Threadname.equals(Thread.currentThread().getName()))
{
Threadcompare=Thread.currentThread().getName();
String soundpath=wav.getErrorSoundFileList().get(soundId);
playAudio(soundpath);
try{
audioInStream.close();
}catch(IOException ioe)
{ioe.printStackTrace();}
}
return "end";
}

Related

Prometheus 'expected label name, got "BCLOSE"' error

I have an application running on port 7070 on my local. It exposes and endpoint /metrics and shows all the tags that are available. Prometheus is not able to get these data and it says 'expected label name, got "BCLOSE"'.
I have been trying to figure this out but not sure why this code doesn't work:
import io.micrometer.prometheus.PrometheusMeterRegistry;
import io.prometheus.client.exporter.common.TextFormat;
import metrics.PrometheusRegistry;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
#Path("/metrics")
public class MetricsController {
private final PrometheusMeterRegistry prometheusRegistry = PrometheusRegistry.INSTANCE();
#GET
public Response getMetrics(#Context HttpHeaders headers) {
Writer writer = new StringWriter();
try {
TextFormat.write004(writer, prometheusRegistry.getPrometheusRegistry().metricFamilySamples());
} catch (IOException e) {
e.printStackTrace();
}
return writer.toString();
}
}
Also, the application is neither a sprintboot nor a spring project.
Tried this:
#GET
public Response getMetrics(#Context HttpHeaders headers) {
String accept = headers.getRequestHeader("Accept").get(0);
System.out.println("Accept Header --------------------------> " + accept);
return Response.ok(prometheusRegistry.scrape(), "application/openmetrics-text").build();
}
Even then the same error as above SS.
This worked for me:
#GET
public Response getMetrics() {
return Response.ok(prometheusRegistry.scrape(), TextFormat.CONTENT_TYPE_004).build();
}

JDA Will not register my event(Discord Bot Java)

I've been having a problem with registering JDA events. Everytime I start the bot, it shows this. Can someone help me with this please?
Here's my Main code:
import Events.Information;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.entities.Activity;
import net.dv8tion.jda.api.entities.ChannelType;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.MessageChannel;
import net.dv8tion.jda.api.events.ReadyEvent;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import javax.security.auth.login.LoginException;
public class Main {
public static String prefix = "!";
public static void main(String[] args) throws LoginException {
JDABuilder jda = JDABuilder.createDefault("I inserted bot key here");
jda.setActivity(Activity.watching("baldness"));
jda.addEventListeners(new Information());
jda.build();
}
}
Here's my Information class code:
package Events;
import com.sun.tools.javac.Main;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
public class Information {
public void onGuildMessageReceived(GuildMessageReceivedEvent e) {
String[] args = e.getMessage().getContentRaw().split("\\s+");
if (args[0].equals("!commands")) {
EmbedBuilder info = new EmbedBuilder();
info.setTitle("Commands");
info.setDescription("!info - Pops up with this!");
info.setColor(0xf45642);
info.setFooter("Bot created by Jason", e.getMember().getUser().getAvatarUrl());
e.getChannel().sendTyping().queue();
e.getChannel().sendMessage(info.build()).queue();
}
}
}
Here's my layering of classes and packages:
Image

Error while adding servlet mapping for path

I am trying to deploy my application on a local Websphere Application Server (Version "8.5.5.5").
If I click "Run on Server", I always get:
Error while adding servlet mapping for path-->/xcc-admin/test/query,
wrapper-->ServletWrapper[XCCAdminServlet.XCCAdminMain:[/XCCAdminMain,
/xcc-admin/rest/query, /xcc-admin/test/query]],
application-->xcc-admin.
Code:
package XCCAdminServlet;
import java.io.IOException;
import javax.annotation.Resource;
import javax.annotation.Resource.AuthenticationType;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
/**
* Servlet implementation class XCCAdminMain
*/
#WebServlet({"/XCCAdminMain", "/xcc-admin/rest/query", "/xcc-admin/test/query"})
#Resource(name = "jdbc/MyDataSource", type = javax.sql.DataSource.class, shareable = true, authenticationType = AuthenticationType.CONTAINER)
public class XCCAdminMain extends HttpServlet {
private static final long serialVersionUID = 1L;
#PersistenceUnit(unitName = "XCCAdminUnit")
private EntityManagerFactory emf;
/**
* #see HttpServlet#HttpServlet()
*/
public XCCAdminMain() {
super();
// TODO Auto-generated constructor stub
}
#GET
#Path("/{param}")
public Response getQuery(#PathParam("param") String msg) throws ServletException {
return Response.status( 200 ).entity( "Get Request received, queryparam: " + msg ).build();
}
}
How to fix this?

Using a Session interface in another class

I have a web application I am making using a websocket API to handle the websockets, here is the code for that part
package comm2.hello;
import java.io.IOException;
import java.util.ArrayList;
import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import org.apache.catalina.session.*;
#ServerEndpoint(value = "/echo")
public class wschat {
private static ArrayList<Session> sessionList = new ArrayList<Session>();
#OnOpen
public void onOpen(Session session) {
try {
sessionList.add(session);
// asynchronous communication
session.getBasicRemote().sendText("hello");
} catch (IOException e) {
}
}
public void send(String text, Session session) throws IOException {
session.getBasicRemote().sendText(text);
}
}
I am trying to have another java class then call into the send method to send messages, using the following code.
package comms;
import java.io.IOException;
import java.util.ArrayList;
import javax.websocket.Session;
import javax.websocket.Session;
import comm2.hello.*;
public class main {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
wschat h = new wschat();
String text = "hello";
//session shouldn't be null but not sure what to make it
Session session = null;
h.send(text,session);
}
}
As you can see, I have the session variable in the main.java class set to null which will thus always produce a null pointer error. This is because I am not sure what to make session equal to, does anyone have any idea what to initialize the session variable to in main.java?

java unit test mock HttpClient and webdav

Hello I have a class for doing webdav related operations such as creating a directory, Implementatiion can be seen below (the createDir method). The question is how to test it nicely, perhaps using EasyMock or a similar lib. Any ideas? thanks!
package foobar;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.jackrabbit.webdav.client.methods.DavMethod;
import org.apache.jackrabbit.webdav.client.methods.MkColMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import mypackage.httpdclient.util.URLHandler;
public class WebDavImpl{
private static final String SEPARATOR = " ----- ";
private HttpClient httpClient;
public StorageSpaceClientImpl() {
httpClient = new HttpClient();
}
public String createDir(String dirName) {
String response = null;
String url = URLHandler.getInstance().getDirectoryUrl(dirName);
DavMethod mkcol = new MkColMethod(url);
try {
httpClient.executeMethod(mkcol);
response = mkcol.getStatusCode() + SEPARATOR + mkcol.getStatusText();
} catch (IOException ex) {
} finally {
mkcol.releaseConnection();
}
return response;
}
}

Categories