Text to Speech in Java using Google - java

I have used the following code to convert text to speech, but I am getting the following errors:
errors
Caused by: java.io.IOException: Server returned HTTP response code: 503 for URL: http://ipv4.google.com/sorry/IndexRedirect?continue=http://translate.google.com/translate_tts%3Fie%3DUTF-8%26q%3DHello%2BWorld%26tl%3Dde%26prev%3Dinput&q=CGMSBCmIeyUYvpnkrwUiGQDxp4NLHAGq2VYVjoplnZ0vwMrZvShTrYA
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at us.monoid.web.AbstractResource.fill(AbstractResource.java:30)
... 5 more
Java Codes
public class TextToSpeech {
private static final String BASE_URL = "http://translate.google.com/translate_tts?ie=UTF-8&q={0}&tl={1}&prev=input";
public static void main(String[] args) {
say("Hello World");
}
public static void say(String text) {
try {
File f = new File("translate.mp3");
String sentence = URLEncoder.encode(text, "UTF-8");
String urlString = MessageFormat.format(BASE_URL, sentence, "de");
BinaryResource res = new Resty().bytes(new URI(urlString));
res.save(f);
FileInputStream in = new FileInputStream(f);
Player p = new Player(in);
p.play();
p.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (JavaLayerException e) {
e.printStackTrace();
}
Note that I have already included the jar files JLayer & Resty.. Please help ! Thanks

Related

Reading objects from assets

something is really messed up. I've got a ".ser" document in the assets folder, which stores an ArrayList of Objetcs. In an android application, I want to read this objects. There are a lot of posts related to this issue, however none of them could solve my problem. The strange part is, when I am using similar code in non - android context / "normal" java, it works properly. Here, the last line throws a NullPointerException - What is going wrong?
public void getData() {
ArrayList<MyClass> output= null;
InputStream is = null;
ObjectInputStream ois = null;
try{
is = this.getAssets().open("data.ser");
ois = new ObjectInputStream(is);
output = (ArrayList<MyClass>)ois.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Log.d("TAG", output.get(0).getId());
}
I would create a class and place the array within a single object:
public class ListObjects implements Serializable {
List<MyClass> listMyClass = new ArrayList<>();
public ListObjects(){
}
public List<MyClass> getListMyClass() {
return listMyClass;
}
public void setListMyClass(List<MyClass> listMyClass) {
this.listMyClass = listMyClass;
}
}
I had a similar problem. And it was because the name of the package in the java app was not called the same as the package name in android. And therefore I did not recognize them as equal objects. This is how I do it:
public static Object fromData(byte[] data) {
ObjectInputStream ois = null;
Object object = null;
try {
ois = new ObjectInputStream(
new ByteArrayInputStream(data));
object = ois.readObject();
} catch (Exception ex) {
Logger.getLogger(ModeloApp.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
ois.close();
} catch (Exception ex) {
Logger.getLogger(ModeloApp.class.getName()).log(Level.SEVERE, null, ex);
}
}
return object;
}

How to read multiple same objects from a file

I am trying to read objects from a file(same objects of a class), using Serializable, but whenit reads all objects it gives me error IOException, java.io.ObjectInputStream$BlockDataInputStream.peekByte.
I am reading objects and then saving to list. But as it reached lets say EOF it throws error.
Here is my method:
private static void updateBook(String name) {
// TODO Auto-generated method stub
FileInputStream fis = null;
ObjectInputStream in = null;
Object obj = new Object();
List<Object> libb = new ArrayList<Object>();
File file = new File(name + ".ser");
if (file.exists()) {
try {
fis = new FileInputStream(file);
in = new ObjectInputStream(fis);
try {
while (true) {
obj = in.readObject();
libb.add(obj);
}
} catch (OptionalDataException e) {
if (!e.eof) throw e;
//JOptionPane.showMessageDialog(null, "Done!");
} finally {
in.close();
//fis.close();
}
for(int j = 0; j < libb.size(); ++j) {
Book li = new Book();
li = (Book) libb.get(j);
System.out.println(li.getBookName());
}
//
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} else {
System.out.println("\nThe file does not Exist!");
}
}
Can anyone please tell me how to avoid this error from while(true).
Complete error:
java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
On your try statement you are missing the catch clause for the EOFException:
try {
while (true) {
obj = in.readObject();
libb.add(obj);
}
} catch (OptionalDataException e) {
if (!e.eof) throw e;
//JOptionPane.showMessageDialog(null, "Done!");
} catch (EOFException eofe) {
// treat it as you like
} finally {
in.close();
//fis.close();
}
you should add:
catch (EOFException e){
// do stuffs
}
as EOFException is not being caught.

Using jcifs for copying files to network drive

I was trying to implement the functionality of transferring local files to a network drive using jcifs library but upon running the program on the command line I was receiving following exception:
Exception in thread "main" java.lang.NullPointerException
jcifs.smb.ServerMessageBlock.writeString(ServerMessageBlock.java: 202)
To understand the error I tried debugging the code on eclipse and while doing so at line:
NtlmPasswordAuthentication authentication = new NtlmPasswordAuthentication("xxxxxx.xx.com",username,password);
I received an exception stating ClassNotFoundException. But I have the jcifs.jar in the build path.
A quick google search for 'ntlmpasswordauthentication' classnotfoundexception landed me on two threads with same issue but no resolution.
Please let me know how can I resolve this.
Thank you
Here is the whole function, just in case needed:
private static void TransferFiles()
{
File transfer_files = new File (sourcepath);
File[] files = transfer_files.listFiles();
String username = properties.getProperty("user");
String password = properties.getProperty("password");
String source = sourcepath;
SmbFileOutputStream outputStream = null;
FileInputStream inputStream = null;
SmbFile copyFile = null;
byte[] buffer = new byte[16*1024*1024];
int length = 0;
jcifs.smb.NtlmPasswordAuthentication authentication = new NtlmPasswordAuthentication("xxxxxxx",username,password);
try
{
copyFile = new SmbFile(destinationpath,authentication);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
try
{
outputStream = new SmbFileOutputStream(copyFile);
}
catch (SmbException | MalformedURLException | UnknownHostException e)
{
e.printStackTrace();
}
try
{
inputStream = new FileInputStream(sourceFile);
}
catch (FileNotFoundException e1)
{
e1.printStackTrace();
}
try
{
while((length = inputStream.read(buffer))>0)
{
outputStream.write(buffer, 0, length);
}
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
inputStream.close();
outputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}

EOFException after calling socket.shutdownOutput()

like the headline says I´m getting an EOFException on the serverside after i called shutdownOutput() at the clientside
this is at the serverside:
public void getRestaurant() {
String tempRestaurant=null;
try { BufferedReader fr =
new BufferedReader( new FileReader( "Restaurant.txt" ));
tempRestaurant = fr.readLine();
System.out.println( tempRestaurant );
System.out.println("writing tempRestaurant is the next Step");
oos.writeObject(tempRestaurant);
System.out.println("tempRestaurant has been written");
oos.close();
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
and this is the code at the clientside:
protected String doInBackground(Void... params) {
connecttoServer();
System.out.println("connecting to server...");
try {
oos.writeInt(1);
System.out.println("next step is closing");
serverside.shutdownOutput();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
System.out.println("connected to server");
Restaurant=(String) ois.readObject();
System.out.println("doInBackground(): "+Restaurant);
and this is the error code:
java.io.EOFException
at java.io.DataInputStream.readInt(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.readInt(Unknown Source)
at java.io.ObjectInputStream.readInt(Unknown Source)
at prealphaserverpackage.clientsidethreads.handlerequest(Serverpart.java:355)
at prealphaserverpackage.clientsidethreads.run(Serverpart.java:156)
pls comment if you need any further informations i will put them online as soon as possible :)
I forgot to call oos.flush(); While the server was still waiting for the data, I closed the stream. That was the reason for the EOFException.

Redirecting Error/Exception to HTML page

Needs to redirect the error and exceptions which i found in the catch block to .html page
This is my code now i want if anytime any file not found excpetion will come then it should redirect to .html page or borwser
public class XmlToHtml {
public static void main(String[] args) {
if (args.length == 3 && args.length !=0) {
String dataXML = args[0];
String inputXSL = args[1];
String outputHTML = args[2];
XmlToHtml xmltoHtml = new XmlToHtml();
try {
xmltoHtml.transform(dataXML, inputXSL, outputHTML);
} catch (TransformerConfigurationException e) {
e.printStackTrace();
System.out.println("TransformerConfigurationException" + e);
} catch (TransformerException e) {
e.printStackTrace();
System.out.println("TransformerException" + e);
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("FileNotFoundException" + e);
}
} else {
System.err.println("Wrong Input");
System.err
.println("Please Enter in the follwing format : Data.xml Input.xsl Output.html");
}
}
public void transform(String dataXML, String inputXSL, String outputHTML)
throws FileNotFoundException, TransformerException,
TransformerConfigurationException {
TransformerFactory tFactory = TransformerFactory.newInstance();
Source xslDoc = new StreamSource(inputXSL);
Source xmlDoc = new StreamSource(dataXML);
OutputStream htmlDoc = new FileOutputStream(outputHTML);
Transformer transformer = tFactory.newTransformer(xslDoc);
transformer.transform(xmlDoc, new StreamResult(htmlDoc));
Desktop dk = Desktop.getDesktop();
try {
dk.open(new File(outputHTML));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Categories