I have a snippet to download a file from jersey 2.22,
StreamingOutput stream = (OutputStream os) -> {
try {
os.write( get a byte array here);
} catch (Exception e) {
LOGGER.error("Failed to fetch file, id:" + fileName, e);
throw new Exception());
}
};
the above code is working, but i'm wondering if the output stream I'm writing in needs to close.
I searched jersey's source code, in OutboundMessageContext
public void close() {
if(this.hasEntity()) {
try {
OutputStream e = this.getEntityStream();
e.flush();
e.close();
} catch (IOException var10) {
Logger.getLogger(OutboundMessageContext.class.getName()).log(Level.FINE, var10.getMessage(), var10);
} finally {
if(!this.committingOutputStream.isClosed()) {
try {
this.committingOutputStream.close();
} catch (IOException var9) {
Logger.getLogger(OutboundMessageContext.class.getName()).log(Level.FINE, var9.getMessage(), var9);
}
}
}
}
}
this method is to close entity stream. I'm not sure if this is the right close method working with StreamingOutput, can anyone help?
Related
I have looked at the examples for subscribing to a NodeId and im wondering how I could stop/delete a subscription afterward.
Eclipse Milo v0.3.8 Client.
Here's what I've tried.
protected boolean unsubscribe(TransactionDefinition transactionDefinition) {
// Finds the mathing TransactionDefinition from the map where all subscriptions
// are stored, together with the clientHandle.
// private Map<UInteger, TransactionDefinition> subscriptions = new HashMap<>();
try {
UInteger subscriptionClientHandle = null;
for (Map.Entry<UInteger, TransactionDefinition> entry : subscriptions.entrySet()) {
if (entry.getValue().equals(transactionDefinition))
subscriptionClientHandle = entry.getKey();
}
if (subscriptionClientHandle == null) return false;
try {
client.getSubscriptionManager().deleteSubscription(subscriptionClientHandle).get();
return true;
} catch (Exception e) {
log.error("Subscription not found: {}", e.getMessage(), e.getCause());
e.printStackTrace();
}
} catch (ClassCastException e) {
log.error("TransactionDefinition trigger not found. {}", e.getMessage(), e.getCause());
e.printStackTrace();
}
return false;
}
UaSubscription has a deleteMonitoredItems method on it.
UaSubscriptionManager has a deleteSubscription method on it.
You could also call either of these services "manually" by invoking the "raw" service methods on the UaClient instance.
From https://github.com/ReactiveX/RxJava/wiki/Backpressure-(2.0)
the following snippet is provide to indicate correct usage for RXified file reading.
Flowable<Integer> o = Flowable.generate(
() -> new FileInputStream("data.bin"),
(inputstream, output) -> {
try {
int byte = inputstream.read();
if (byte < 0) {
output.onComplete();
} else {
output.onNext(byte);
}
} catch (IOException ex) {
output.onError(ex);
}
return inputstream;
},
inputstream -> {
try {
inputstream.close();
} catch (IOException ex) {
RxJavaHooks.onError(ex);
}
}
);
I am doing the following
public Flowable<byte[]> createFlowable(File file) {
return Flowable.create(source -> {
try (FileInputStream fin = new FileInputStream(file);
BufferedInputStream in = new BufferedInputStream(fin)) {
while (in.available() > 0) {
byte[] data = getMessageRawData(in);
source.onNext(data);
}
source.onComplete();
}
catch (Exception ex) {
source.onError(ex);
}
}, BackpressureStrategy.BUFFER);
}
Does my code (uses try with resource) suffer from resource leakage if dispose is called mid way or what other side effects can be expected or is it just a different way of doing things?
I am trying to implement javadrone (AR.Drone Java API) in my project. However, it was occurred state changed error when I compile my java code and try to fly it. I was able to send command to AR.Drone and fly for the first time. After successfully take off for the first time,it won't take off again due to "state changed" error. I have no idea what went wrong in my code. Please help me out. Thanks! There are 3 files that are required in this project. My java file(arDroneFrame.java),NavData.java(from javadrone), and ARDrone.java(from javadrone).The The main java file: arDroneFrame.java. When I press the TakeOff button, it should make AR.Drone fly and land afterwards.
In my arDroneFrame.java,
private void jButtonTakeOffActionPerformed(java.awt.event.ActionEvent evt) {
com.codeminders.ardrone.ARDrone drone;
try{
drone = new com.codeminders.ardrone.ARDrone();
drone.connect();
drone.clearEmergencySignal();
// Wait until drone is ready
drone.waitForReady(CONNECT_TIMEOUT);
// do TRIM operation
drone.trim();
// Take off
System.err.println("Taking off");
drone.takeOff();
// Fly a little :)
Thread.sleep(5000);
//Land
System.err.println("Landing");
drone.land();
// Give it some time to land
Thread.sleep(2000);
// Disconnect from the done
drone.disconnect();
} catch (UnknownHostException ex) {
Logger.getLogger(arDroneFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(arDroneFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (InterruptedException ex) {
Logger.getLogger(arDroneFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
In ARDrone.java, I had commented out some java coding.This is because only when I comment out those java code, it can only works. If I uncomment them, my program will be stuck there (no respond at all).
public void waitForReady(long how_long) throws IOException
{
/*long since = System.currentTimeMillis();
synchronized(state_mutex)
{
while(true)
{
if((System.currentTimeMillis() - since) >= how_long)
{
try
{
disconnect();
} catch(IOException e)
{
}
// Timeout, too late
throw new IOException("Timeout connecting to ARDrone");
} else if(state == State.DEMO)
{
return; // OK! We are now connected
} else if(state == State.ERROR || state == State.DISCONNECTED)
{
throw new IOException("Connection Error");
}
long p = Math.min(how_long - (System.currentTimeMillis() - since), how_long);
if(p > 0)
{
try
{
state_mutex.wait(p);
} catch(InterruptedException e)
{
// Ignore
}
}
}
}*/
while(state == State.DEMO)
{
System.out.println("Changed to DEMO !");
return; // OK! We are now connected
}
}
Program Output:
126 [Thread-7] DEBUG ardrone.ARDrone - State changed from TAKING_OFF to ERROR with exception
java.lang.NullPointerException
at com.codeminders.ardrone.NavData$FlyingState.fromControlState(NavData.java:58)
at com.codeminders.ardrone.NavData.getFlyingState(NavData.java:622)
at com.codeminders.ardrone.ARDrone.navDataReceived(ARDrone.java:431)
at com.codeminders.ardrone.NavDataReader.run(NavDataReader.java:92)
at java.lang.Thread.run(Thread.java:745)
When /api/upload REST endpoint is accessed I have a UploadController that uses a service UploadService to upload a file to an ftp server with org.apache.commons.net.ftp.FTPClient. I would like to be able to send information back to the user if the ftp client was unable to connect or timed out, or successfully sent the file. I have some IOException handling, but I don't know how to turn that around and send it back to the front-end. Any help appreciated, thanks!
public void upload(InputStream inputStream) {
String filename = "file.txt"
client = new FTPClient();
try {
client.connect("ftpsite");
client.login("username", "password");
client.storeFile(filename, inputStream);
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (inputStream!= null) {
inputStream.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
return null;
}
You should throw a new Exception in your catch statement.
For example, you could create a RequestTimeoutException class:
#ResponseStatus(HttpStatus.REQUEST_TIMEOUT)
public class RequestTimeoutException extends RuntimeException { }
and then throw it when need be:
catch (IOException ioe) {
//do some logging while you're at it
throw new RequestTimeoutException();
}
I want to use java nio in java ee.
But I don't know how to do it right.
I need to after server has deploy java.nio.selector always listens the port and processing socket connection.
I try do it there:
#Singleton
#Lock(LockType.READ)
public class TaskManager {
private static final int LISTENINGPORT;
static {
LISTENINGPORT = ConfigurationSettings.getConfigureSettings().getListeningPort();
}
private ArrayList<ServerCalculationInfo> serverList;
public TaskManager() {
serverList = new ArrayList<ServerCalculationInfo>();
select();
}
#Asynchronous
public void select() {
try {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
Selector selector = Selector.open();
serverSocketChannel.configureBlocking(false);
serverSocketChannel.socket().bind(new InetSocketAddress(LISTENINGPORT));
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
try {
selector.select();
} catch (IOException ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
break;
}
Iterator it = selector.selectedKeys().iterator();
while (it.hasNext()) {
SelectionKey selKey = (SelectionKey) it.next();
it.remove();
try {
processSelectionKey(serverSocketChannel, selKey);
} catch (IOException e) {
serverList.remove(serverCalculationInfo);
}
}
}
} catch (IOException e) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, e);
} catch (Exception e) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, e);
}
}
}
It don't work correctly. The process hangs during deploy and redeploy application possible only after restart Glassfish.
How can I do right it?
It works correctly if invoke #Asynchronous method from the #PostConstructor:
#PostConstruct
public void postTaskManager() {
serverList = new ArrayList<ServerCalculationInfo>();
select();
}
instead of invoke it from constructor.
But class must be without #Startup annotation.