I downloaded a sample from https://github.com/GoogleCloudPlatform/java-docs-samples/tree/master/speech for Java with the same exact code.
I did everything the way it supposed to be and it worked for a while " I have Set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the file path of the JSON file " , and then idk what happen to it, started showing me this exception
com.google.api.gax.rpc.UnavailableException: io.grpc.StatusRuntimeException: UNAVAILABLE: Credentials failed to obtain metadata
/*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.speech;
// [START speech_transcribe_infinite_streaming]
import com.google.api.gax.rpc.ClientStream;
import com.google.api.gax.rpc.ResponseObserver;
import com.google.api.gax.rpc.StreamController;
import com.google.cloud.speech.v1.RecognitionConfig;
import com.google.cloud.speech.v1.SpeechClient;
import com.google.cloud.speech.v1.SpeechRecognitionAlternative;
import com.google.cloud.speech.v1.StreamingRecognitionConfig;
import com.google.cloud.speech.v1.StreamingRecognitionResult;
import com.google.cloud.speech.v1.StreamingRecognizeRequest;
import com.google.cloud.speech.v1.StreamingRecognizeResponse;
import com.google.protobuf.ByteString;
import java.util.ArrayList;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.DataLine.Info;
import javax.sound.sampled.TargetDataLine;
public class InfiniteStreamRecognize {
// Creating shared object
private static volatile BlockingQueue<byte[]> sharedQueue = new LinkedBlockingQueue();
private static TargetDataLine targetDataLine;
private static int BYTES_PER_BUFFER = 6400; // buffer size in bytes
public static void main(String... args) {
try {
infiniteStreamingRecognize();
} catch (Exception e) {
System.out.println("Exception caught: " + e);
}
}
/** Performs infinite streaming speech recognition */
public static void infiniteStreamingRecognize() throws Exception {
// Microphone Input buffering
class MicBuffer implements Runnable {
#Override
public void run() {
System.out.println("Start speaking...Press Ctrl-C to stop");
targetDataLine.start();
byte[] data = new byte[BYTES_PER_BUFFER];
while (targetDataLine.isOpen()) {
try {
int numBytesRead = targetDataLine.read(data, 0, data.length);
if ((numBytesRead <= 0) && (targetDataLine.isOpen())) {
continue;
}
sharedQueue.put(data.clone());
} catch (InterruptedException e) {
System.out.println("Microphone input buffering interrupted : " + e.getMessage());
}
}
}
}
// Creating microphone input buffer thread
MicBuffer micrunnable = new MicBuffer();
Thread micThread = new Thread(micrunnable);
ResponseObserver<StreamingRecognizeResponse> responseObserver = null;
try (SpeechClient client = SpeechClient.create()) {
ClientStream<StreamingRecognizeRequest> clientStream;
responseObserver =
new ResponseObserver<StreamingRecognizeResponse>() {
ArrayList<StreamingRecognizeResponse> responses = new ArrayList<>();
public void onStart(StreamController controller) {}
public void onResponse(StreamingRecognizeResponse response) {
responses.add(response);
StreamingRecognitionResult result = response.getResultsList().get(0);
// There can be several alternative transcripts for a given chunk of speech. Just
// use the first (most likely) one here.
SpeechRecognitionAlternative alternative = result.getAlternativesList().get(0);
System.out.printf("Transcript : %s\n", alternative.getTranscript());
}
public void onComplete() {
System.out.println("Done");
}
public void onError(Throwable t) {
System.out.println(t);
}
};
clientStream = client.streamingRecognizeCallable().splitCall(responseObserver);
RecognitionConfig recognitionConfig =
RecognitionConfig.newBuilder()
.setEncoding(RecognitionConfig.AudioEncoding.LINEAR16)
.setLanguageCode("en-US")
.setSampleRateHertz(16000)
.build();
StreamingRecognitionConfig streamingRecognitionConfig =
StreamingRecognitionConfig.newBuilder().setConfig(recognitionConfig).build();
StreamingRecognizeRequest request =
StreamingRecognizeRequest.newBuilder()
.setStreamingConfig(streamingRecognitionConfig)
.build(); // The first request in a streaming call has to be a config
clientStream.send(request);
try {
// SampleRate:16000Hz, SampleSizeInBits: 16, Number of channels: 1, Signed: true,
// bigEndian: false
AudioFormat audioFormat = new AudioFormat(16000, 16, 1, true, false);
DataLine.Info targetInfo =
new Info(
TargetDataLine.class,
audioFormat); // Set the system information to read from the microphone audio
// stream
if (!AudioSystem.isLineSupported(targetInfo)) {
System.out.println("Microphone not supported");
System.exit(0);
}
// Target data line captures the audio stream the microphone produces.
targetDataLine = (TargetDataLine) AudioSystem.getLine(targetInfo);
targetDataLine.open(audioFormat);
micThread.start();
long startTime = System.currentTimeMillis();
while (true) {
long estimatedTime = System.currentTimeMillis() - startTime;
if (estimatedTime >= 55000) {
clientStream.closeSend();
clientStream = client.streamingRecognizeCallable().splitCall(responseObserver);
request =
StreamingRecognizeRequest.newBuilder()
.setStreamingConfig(streamingRecognitionConfig)
.build();
startTime = System.currentTimeMillis();
} else {
request =
StreamingRecognizeRequest.newBuilder()
.setAudioContent(ByteString.copyFrom(sharedQueue.take()))
.build();
}
clientStream.send(request);
}
} catch (Exception e) {
System.out.println(e);
}
}
}
}
// [END speech_transcribe_infinite_streaming]
I expect to speak and get recognized " I don't know why it does this " although it was working well .. can anyone help >> thank you in advance;
Related
I want to load a gzipped rdf file into a org.eclipse.rdf4j.repository.Repository. During the upload, status messages must be logged to the console. The size of my rdf file is ~1GB of uncompressed or ~50MB of compressed data.
Actually an RDF4J repository will automatically process a compressed (zip/gzip) file correctly, already. So you can simply do this:
RepositoryConnection conn = ... ; // your store connection
conn.add(new File("file.zip"), null, RDFFormat.NTRIPLES):
If you want to include reporting, a different (somewhat simpler) approach is to use an org.eclipse.rdf4j.repository.util.RDFLoader class in combination with an RDFInserter:
RepositoryConnection conn = ... ; // your store connection
RDFInsert inserter = new RDFInserter(conn);
RDFLoader loader = new RDFLoader(conn.getParserConfig(), conn.getValueFactory());
loader.load(new File("file.zip"), RDFFormat.NTRIPLES, inserter));
The RDFLoader takes care of properly uncompressing the (zip or gzip) file.
To get intermediate reporting you can wrap your RDFInserter in your own custom AbstractRDFHandler that does the counting and reporting (before passing on to the wrapper inserter).
Variant 1
The following sample will load an InputStream with gzipped data into an in-memory rdf repository. The zipped format is supported directly by rdf4j.
Every 100000th statement will be printed to stdout using the RepositoryConnectionListenerAdapter.
import java.io.InputStream;
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.Resource;
import org.eclipse.rdf4j.model.Value;
import org.eclipse.rdf4j.repository.Repository;
import org.eclipse.rdf4j.repository.RepositoryConnection;
import org.eclipse.rdf4j.repository.event.base.NotifyingRepositoryConnectionWrapper;
import org.eclipse.rdf4j.repository.event.base.RepositoryConnectionListenerAdapter;
import org.eclipse.rdf4j.repository.sail.SailRepository;
import org.eclipse.rdf4j.rio.RDFFormat;
import org.eclipse.rdf4j.sail.memory.MemoryStore;
public class MyTripleStore {
Repository repo;
/**
* Creates an inmemory triple store
*
*/
public MyTripleStore() {
repo = new SailRepository(new MemoryStore());
repo.initialize();
}
/**
* #param in gzip compressed data on an inputstream
* #param format the format of the streamed data
*/
public void loadZippedFile(InputStream in, RDFFormat format) {
System.out.println("Load zip file of format " + format);
try (NotifyingRepositoryConnectionWrapper con =
new NotifyingRepositoryConnectionWrapper(repo, repo.getConnection());) {
RepositoryConnectionListenerAdapter myListener =
new RepositoryConnectionListenerAdapter() {
private long count = 0;
#Override
public void add(RepositoryConnection arg0, Resource arg1, IRI arg2,
Value arg3, Resource... arg4) {
count++;
if (count % 100000 == 0)
System.out.println("Add statement number " + count + "\n"
+ arg1+ " " + arg2 + " " + arg3);
}
};
con.addRepositoryConnectionListener(myListener);
con.add(in, "", format);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
Variant 2
This variant implements an AbstractRDFHandler to provide the reporting.
import java.io.InputStream;
import org.eclipse.rdf4j.model.Statement;
import org.eclipse.rdf4j.repository.Repository;
import org.eclipse.rdf4j.repository.RepositoryConnection;
import org.eclipse.rdf4j.repository.sail.SailRepository;
import org.eclipse.rdf4j.repository.util.RDFInserter;
import org.eclipse.rdf4j.repository.util.RDFLoader;
import org.eclipse.rdf4j.rio.RDFFormat;
import org.eclipse.rdf4j.rio.helpers.AbstractRDFHandler;
import org.eclipse.rdf4j.sail.memory.MemoryStore;
public class MyTripleStore {
Repository repo;
/**
* Creates an inmemory triple store
*
*/
public MyTripleStore() {
repo = new SailRepository(new MemoryStore());
repo.initialize();
}
/**
* #param in gzip compressed data on an inputstream
* #param format the format of the streamed data
*/
public void loadZippedFile1(InputStream in, RDFFormat format) {
try (RepositoryConnection con = repo.getConnection()) {
MyRdfInserter inserter = new MyRdfInserter(con);
RDFLoader loader =
new RDFLoader(con.getParserConfig(), con.getValueFactory());
loader.load(in, "", RDFFormat.NTRIPLES, inserter);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
class MyRdfInserter extends AbstractRDFHandler {
RDFInserter rdfInserter;
int count = 0;
public MyRdfInserter(RepositoryConnection con) {
rdfInserter = new RDFInserter(con);
}
#Override
public void handleStatement(Statement st) {
count++;
if (count % 100000 == 0)
System.out.println("Add statement number " + count + "\n"
+ st.getSubject().stringValue() + " "
+ st.getPredicate().stringValue() + " "
+ st.getObject().stringValue());
rdfInserter.handleStatement(st);
}
}
}
Here is, how to call the code
MyTripleStore ts = new MyTripleStore();
ts.loadZippedFile(new FileInputStream("your-ntriples-zipped.gz"),
RDFFormat.NTRIPLES);
I'm trying to learn how to use Apache HttpComponents to send an HttpResponse. I found some examples on the Apache site but they are very confusing and unclear.
In the code below, I cannot see where the HttpResponse is generated and sent back to the client. After following along in the code, it seems that it must be happening in the HttpFileHandler class's handle() method, but it's not clear where. The class just ends with
...
response.setEntity(body);
System.out.println("File " + file.getPath() + " not found");
...
without actually sending the response. It ends with setting the Entity.
Where does the sending of the response back to the client actually happen in this code?
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.examples;
import java.io.File;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URLDecoder;
import java.util.Locale;
import org.apache.http.ConnectionClosedException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.HttpServerConnection;
import org.apache.http.HttpStatus;
import org.apache.http.MethodNotSupportedException;
import org.apache.http.entity.ContentProducer;
import org.apache.http.entity.EntityTemplate;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.impl.DefaultHttpResponseFactory;
import org.apache.http.impl.DefaultHttpServerConnection;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.params.SyncBasicHttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpRequestHandler;
import org.apache.http.protocol.HttpRequestHandlerRegistry;
import org.apache.http.protocol.HttpService;
import org.apache.http.protocol.ImmutableHttpProcessor;
import org.apache.http.protocol.ResponseConnControl;
import org.apache.http.protocol.ResponseContent;
import org.apache.http.protocol.ResponseDate;
import org.apache.http.protocol.ResponseServer;
import org.apache.http.util.EntityUtils;
/**
* Basic, yet fully functional and spec compliant, HTTP/1.1 file server.
* <p>
* Please note the purpose of this application is demonstrate the usage of
* HttpCore APIs. It is NOT intended to demonstrate the most efficient way of
* building an HTTP file server.
*
*
*/
public class ElementalHttpServer {
public static void main(String[] args) throws Exception {
args = new String[] { "e:/tutoring/236369/Tutorials/httpCoreExamples/" };
if (args.length < 1) {
System.err.println("Please specify document root directory");
System.exit(1);
}
Thread t = new RequestListenerThread(8080, args[0]);
t.setDaemon(false);
t.start();
}
static class HttpFileHandler implements HttpRequestHandler {
private final String docRoot;
public HttpFileHandler(final String docRoot) {
super();
this.docRoot = docRoot;
}
#Override
public void handle(final HttpRequest request,
final HttpResponse response, final HttpContext context)
throws HttpException, IOException {
String method = request.getRequestLine().getMethod()
.toUpperCase(Locale.ENGLISH);
if (!method.equals("GET") && !method.equals("HEAD")
&& !method.equals("POST")) {
throw new MethodNotSupportedException(method
+ " method not supported");
}
String target = request.getRequestLine().getUri();
if (request instanceof HttpEntityEnclosingRequest) {
HttpEntity entity = ((HttpEntityEnclosingRequest) request)
.getEntity();
byte[] entityContent = EntityUtils.toByteArray(entity);
System.out.println("Incoming entity content (bytes): "
+ entityContent.length);
}
final File file = new File(this.docRoot, URLDecoder.decode(target));
if (!file.exists()) {
response.setStatusCode(HttpStatus.SC_NOT_FOUND);
EntityTemplate body = new EntityTemplate(new ContentProducer() {
#Override
public void writeTo(final OutputStream outstream)
throws IOException {
OutputStreamWriter writer = new OutputStreamWriter(
outstream, "UTF-8");
writer.write("<html><body><h1>");
writer.write("File ");
writer.write(file.getPath());
writer.write(" not found");
writer.write("</h1></body></html>");
writer.flush();
}
});
body.setContentType("text/html; charset=UTF-8");
response.setEntity(body);
System.out.println("File " + file.getPath() + " not found");
} else if (!file.canRead() || file.isDirectory()) {
response.setStatusCode(HttpStatus.SC_FORBIDDEN);
EntityTemplate body = new EntityTemplate(new ContentProducer() {
#Override
public void writeTo(final OutputStream outstream)
throws IOException {
OutputStreamWriter writer = new OutputStreamWriter(
outstream, "UTF-8");
writer.write("<html><body><h1>");
writer.write("Access denied");
writer.write("</h1></body></html>");
writer.flush();
}
});
body.setContentType("text/html; charset=UTF-8");
response.setEntity(body);
System.out.println("Cannot read file " + file.getPath());
} else {
response.setStatusCode(HttpStatus.SC_OK);
FileEntity body = new FileEntity(file, "text/html");
response.setEntity(body);
System.out.println("Serving file " + file.getPath());
}
}
}
static class RequestListenerThread extends Thread {
private final ServerSocket serversocket;
private final HttpParams params;
private final HttpService httpService;
public RequestListenerThread(int port, final String docroot)
throws IOException {
this.serversocket = new ServerSocket(port);
this.params = new SyncBasicHttpParams();
this.params
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE,
8 * 1024)
.setBooleanParameter(
CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.ORIGIN_SERVER,
"HttpComponents/1.1");
// Set up the HTTP protocol processor
HttpProcessor httpproc = new ImmutableHttpProcessor(
new HttpResponseInterceptor[] { new ResponseDate(),
new ResponseServer(), new ResponseContent(),
new ResponseConnControl() });
// Set up request handlers
HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();
reqistry.register("*", new HttpFileHandler(docroot));
// Set up the HTTP service
this.httpService = new HttpService(httpproc,
new DefaultConnectionReuseStrategy(),
new DefaultHttpResponseFactory(), reqistry, this.params);
}
#Override
public void run() {
System.out.println("Listening on port "
+ this.serversocket.getLocalPort());
while (!Thread.interrupted()) {
try {
// Set up HTTP connection
Socket socket = this.serversocket.accept();
DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
System.out.println("Incoming connection from "
+ socket.getInetAddress());
conn.bind(socket, this.params);
// Start worker thread
Thread t = new WorkerThread(this.httpService, conn);
t.setDaemon(true);
t.start();
} catch (InterruptedIOException ex) {
break;
} catch (IOException e) {
System.err
.println("I/O error initialising connection thread: "
+ e.getMessage());
break;
}
}
}
}
static class WorkerThread extends Thread {
private final HttpService httpservice;
private final HttpServerConnection conn;
public WorkerThread(final HttpService httpservice,
final HttpServerConnection conn) {
super();
this.httpservice = httpservice;
this.conn = conn;
}
#Override
public void run() {
System.out.println("New connection thread");
HttpContext context = new BasicHttpContext(null);
try {
while (!Thread.interrupted() && this.conn.isOpen()) {
this.httpservice.handleRequest(this.conn, context);
}
} catch (ConnectionClosedException ex) {
System.err.println("Client closed connection");
} catch (IOException ex) {
System.err.println("I/O error: " + ex.getMessage());
} catch (HttpException ex) {
System.err.println("Unrecoverable HTTP protocol violation: "
+ ex.getMessage());
} finally {
try {
this.conn.shutdown();
} catch (IOException ignore) {
}
}
}
}
}
You are running a server here.
The generic code to "talk HTTP" is already implemented by the library.
You just have to plug in the "business logic" (in the form of an HTTPRequestHandler).
Your "business logic" gets an instance of HTTPResponse as a parameter. This object has already been created for you by the library. You can set parameters and write data to.
When your handler method returns (or even before that as you manipulate the response object), the library takes care of getting the data over the network.
Where does the sending of the response back to the client actually happen in this code?
As the result of method handle the response object now contains an Entity with your inner class that can write out a file. That code will be called to send the data.
It might be instructive (or possibly overwhelming) to put a breakpoint in your code and step through (including the part after handle returns) to see the control flow.
In my quest to create a simple Java program to extract tweets from Twitter's streaming API, I have modified this (http://cotdp.com/dl/TwitterConsumer.java) code snippet to work with the OAuth method. The result is the below code, which when executed, throws a Connection Refused Exception.
I am aware of Twitter4J however I want to create a program that relies least on other APIs.
I have done my research and it looks like the oauth.signpost library is suitable for Twitter's streaming API. I have also ensured my authentication details are correct. My Twitter Access level is 'Read-only'.
I couldn't find a simple Java example that shows how to use the streaming API without relying on e.g. Twitter4j.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
/**
* A hacky little class illustrating how to receive and store Twitter streams
* for later analysis, requires Apache Commons HTTP Client 4+. Stores the data
* in 64MB long JSON files.
*
* Usage:
*
* TwitterConsumer t = new TwitterConsumer("username", "password",
* "http://stream.twitter.com/1/statuses/sample.json", "sample");
* t.start();
*/
public class TwitterConsumer extends Thread {
//
static String STORAGE_DIR = "/tmp";
static long BYTES_PER_FILE = 64 * 1024 * 1024;
//
public long Messages = 0;
public long Bytes = 0;
public long Timestamp = 0;
private String accessToken = "";
private String accessSecret = "";
private String consumerKey = "";
private String consumerSecret = "";
private String feedUrl;
private String filePrefix;
boolean isRunning = true;
File file = null;
FileWriter fw = null;
long bytesWritten = 0;
public static void main(String[] args) {
TwitterConsumer t = new TwitterConsumer(
"XXX",
"XXX",
"XXX",
"XXX",
"http://stream.twitter.com/1/statuses/sample.json", "sample");
t.start();
}
public TwitterConsumer(String accessToken, String accessSecret, String consumerKey, String consumerSecret, String url, String prefix) {
this.accessToken = accessToken;
this.accessSecret = accessSecret;
this.consumerKey = consumerKey;
this.consumerSecret = consumerSecret;
feedUrl = url;
filePrefix = prefix;
Timestamp = System.currentTimeMillis();
}
/**
* #throws IOException
*/
private void rotateFile() throws IOException {
// Handle the existing file
if (fw != null)
fw.close();
// Create the next file
file = new File(STORAGE_DIR, filePrefix + "-"
+ System.currentTimeMillis() + ".json");
bytesWritten = 0;
fw = new FileWriter(file);
System.out.println("Writing to " + file.getAbsolutePath());
}
/**
* #see java.lang.Thread#run()
*/
public void run() {
// Open the initial file
try { rotateFile(); } catch (IOException e) { e.printStackTrace(); return; }
// Run loop
while (isRunning) {
try {
OAuthConsumer consumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
consumer.setTokenWithSecret(accessToken, accessSecret);
HttpGet request = new HttpGet(feedUrl);
consumer.sign(request);
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(request);
BufferedReader reader = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
while (true) {
String line = reader.readLine();
if (line == null)
break;
if (line.length() > 0) {
if (bytesWritten + line.length() + 1 > BYTES_PER_FILE)
rotateFile();
fw.write(line + "\n");
bytesWritten += line.length() + 1;
Messages++;
Bytes += line.length() + 1;
}
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Sleeping before reconnect...");
try { Thread.sleep(15000); } catch (Exception e) { }
}
}
}
}
I tried to simulate the code and found that the error was very simple. You should use https instead of http in the url :)
I'm having a bit of problem with an example I'm currently testing. For some reason, the execution blocks when writing at oos.writeObject(new SimpleObject());, despite that fact that the pipe should transfer the data across, even (I'd assume) if it had to do it in smaller operations due to a small pipe size. Anyway, the example succeeds when the pipe size is larger than the object, and fails when the pipe size is smaller than the object. If anyone could shed some light on this, it'd be much appreciated.
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.nio.ByteBuffer;
import org.apache.mina.filter.codec.serialization.ObjectSerializationInputStream;
import org.apache.mina.filter.codec.serialization.ObjectSerializationOutputStream;
public class ObjTest4 {
public static void main(String[] args) {
System.out.println("exec1");
int objectsToSend = 10;
int objectsRecvd = 0;
try {
System.out.println("exec2");
PipedOutputStream pos = new PipedOutputStream();
ObjectSerializationOutputStream oos = new ObjectSerializationOutputStream(pos);
PipedInputStream pis = new PipedInputStream(pos, 500);
ObjectSerializationInputStream ois = new ObjectSerializationInputStream(pis);
oos.setMaxObjectSize(2000);
ois.setMaxObjectSize(2000);
while (objectsRecvd < objectsToSend) {
System.out.println("exec3");
oos.writeObject(new SimpleObject());
System.out.println("exec3.1");
oos.flush();
System.out.println("exec3.2");
System.out.println("oisavail: " + ois.available());
Object o = ois.readObject();
if (o != null) {
objectsRecvd++;
System.out.println("o: " + o);
} else {
System.out.println("recvd null");
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
and the class for the object being serialised:
package objtest;
import java.io.Serializable;
import java.util.EnumSet;
public class SimpleObject implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
public String moo = "moo";
public EnumSet<EnumTest> set = EnumSet.of(EnumTest.Test);
public String moo2 = "moo2";
public String moo3 = "moo3";
public String moo4 = "moo4_";
{
for (int i = 0; i < 8; i++) {
moo4 += moo4;
}
}
/**
*
*/
public SimpleObject() {
// TODO Auto-generated constructor stub
}
/**
* #return the moo
*/
public String getMoo() {
return moo;
}
/**
* #param moo the moo to set
*/
public void setMoo(String moo) {
this.moo = moo;
}
}
Cheers,
Chris
Sorry, I found the problem -- the Java documentation says not to use piped streams from a single thread, as it may deadlock the thread:
Attempting to use both objects from a
single thread is not recommended, as
it may deadlock the thread.
I'm playing around with javafx and I have modified the code of the MediaPleyer demo trying to reproduce a wav file. It doesn't work.
/*
* Copyright (c) 2009, SUN Microsystems, Inc.
* All rights reserved.
*/
package javafx.tools.fxd.demos.mediaplayer;
import javafx.scene.*;
import javafx.scene.media.*;
import javafx.stage.*;
var player = javafx.scene.media.MediaPlayer {
repeatCount: 1
media: Media {
source: "{__DIR__}Door_Open.wav"
};
};
class MyMediaPlayerUI extends MediaPlayerUI {
override protected function contentLoaded() {
super.contentLoaded();
var s = player.media.source;
var i = s.lastIndexOf ("/");
if (i >= 0) {
s = s.substring (i + 1);
}
fileName.content = s;
}
}
var stage : Stage;
var ui = MyMediaPlayerUI {};
var skins = [ "{__DIR__}MediaPlayer1.fxz", "{__DIR__}MediaPlayer2.fxz" ];
var index = 0;
ButtonController {
pressed: bind ui.playPressed
hovered: bind ui.playHovered
normal: bind ui.playNormal
activeArea: bind ui.playActiveArea
action: function () {
player.play ();
}
}
ButtonController {
pressed: bind ui.pausePressed
hovered: bind ui.pauseHovered
normal: bind ui.pauseNormal
activeArea: bind ui.pauseActiveArea
action: function () {
player.pause ();
}
}
ButtonController {
pressed: bind ui.switchPressed
hovered: bind ui.switchHovered
normal: bind ui.switchNormal
activeArea: bind ui.switchActiveArea
action: function () {
index = (index + 1) mod skins.size ();
ui.url = skins[index];
}
}
stage = Stage {
title: "Media Player"
//visible: true
resizable: false
onClose: function() { java.lang.System.exit (0); }
scene: Scene {
content: ui
}
}
The wav file is not reproduced without giving any exception.
If I change the repeatCount property to
repeatCount: javafx.scene.media.MediaPlayer.REPEAT_FOREVER
eventually gives a heap space exception:
Exception in thread "PlayerLoop" java.lang.OutOfMemoryError: Java heap space
There is any problem in the code above? There is a way to reproduce wav files? I think this is essential for javafx since wavs are a very spread audio format.
Thanks.
The JavaFx documentation is strange on that one. On one page it says playing wav files placed in jar files works on another it says it does not work.
For me it does not work like for you. (What works is playing .wav files which are not placed in jar files.)
Here is my solution for the problem (My own audioplayer)
import java.net.URL;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;
public class AudioPlayer {
private static final int EXTERNAL_BUFFER_SIZE = 128000;
private URL url_;
public AudioPlayer(URL filename) {
url_ = filename;
}
public void play() throws Exception {
AudioInputStream audioInputStream = null;
audioInputStream = AudioSystem.getAudioInputStream(url_);
AudioFormat audioFormat = audioInputStream.getFormat();
SourceDataLine line = null;
DataLine.Info info = new DataLine.Info(SourceDataLine.class,
audioFormat);
line = (SourceDataLine) AudioSystem.getLine(info);
line.open(audioFormat);
line.start();
int nBytesRead = 0;
byte[] abData = new byte[EXTERNAL_BUFFER_SIZE];
while (nBytesRead != -1) {
nBytesRead = audioInputStream.read(abData, 0, abData.length);
if (nBytesRead >= 0) {
line.write(abData, 0, nBytesRead);
}
}
line.drain();
line.close();
}
}
import javafx.async.RunnableFuture;
public class PlayAudioImpl implements RunnableFuture {
private AudioPlayer audio;
public PlayAudioImpl(AudioPlayer audio) {
this.audio = audio;
}
#Override
public void run() throws Exception {
audio.play();
}
}
import javafx.async.JavaTaskBase;
import javafx.async.RunnableFuture;
import java.net.URL;
public class PlayAudio extends JavaTaskBase {
public-init var source:String;
public override function create() : RunnableFuture {
var player = new AudioPlayer(new URL(source));
return new PlayAudioImpl(player);
}
public function play() : Void {
start();
}
}
Play the audio using:
PlayAudio {
source: "{__DIR__}audio/audio.wav"
}.play();