when use mina-sshd to execute command ,timeout occurred,how can i deal with it - timeout

Here follows is my code,how can i deal with it
public ConnectResponse runCommand(UserInfo userInfo, String command, long timeout) {
SshClient sshClient = SshClient.setUpDefaultClient();
sshClient.start();
ChannelExec execChannel = null;
try (ClientSession session = sshClient
.connect(userInfo.getUsername(), userInfo.getTargetIp(), 22)
.verify(CLIENT_VERIFY_TIMEOUT)
.getClientSession();) {
session.addPasswordIdentity(userInfo.getAuthentication());
session.auth().verify(SESSION_VERIFY_TIMEOUT);
execChannel = session.createExecChannel(command);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayOutputStream err = new ByteArrayOutputStream();
execChannel.setOut(out);
execChannel.setErr(err);
execChannel.open();
Set<ClientChannelEvent> events = execChannel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(timeout));
session.close(false);
if (events.contains(ClientChannelEvent.TIMEOUT)) {
throw new BusinessException(500, String.format("执行命令 {%s} 超时了!", command));
}
return new ConnectResponse(out.toString(), err.toString(), execChannel.getExitStatus());
} catch (Exception e) {
throw new BusinessException(e.getCause(), 500, String.format("执行命令 {%s} 出现了一行了!", command));
} finally {
if (!Objects.isNull(execChannel)) {
try {
execChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Related

Vaadin upload with PipedInputStream & PipedOutputStream example

I just started learning Vaadin 8 and my first example is Upload button. I was stuck with an issue where I could not solve the problem for many hours and hours.
Here it is,
I am returning PipedOutputStream in the receiveUpload method,
Here is the code for receiveUpload method,
public OutputStream receiveUpload(String filename, String mimeType) {
this.fileName = filename;
this.mimeType = mimeType;
try {
pipedOutputStream = new PipedOutputStream();
pipedInputStream = new PipedInputStream(pipedOutputStream);
if (filename == null || filename.trim().length() == 0) {
upload.interruptUpload();
} else {
}
} catch (Exception e) {
e.printStackTrace();
}
return pipedOutputStream;
}
In the uploadSucceeded method, I need to take the pipedinputstream and send it another method to load the stream into the database
public void uploadSucceeded(SucceededEvent event) {
try {
fileUploadOperation.upload(pipedInputStream); --> I need to push all the stream data in one go into a method to generate a file at the business layer
} catch (Exception e) {
e.printStackTrace();
}
}
When I was running the application, it hangs out for a long time and I could not figure out where it is. Later I could notice that both piped input and piped output streams should be created in separate threads or at least one of them in a separate thread but don't know how to handle it.
Any help
I am pasting the complete class for more information,
public class WebCommunityView implements Receiver, FailedListener, SucceededListener, StartedListener, FinishedListener {
private PipedOutputStream pipedOutputStream = null;
private PipedInputStream pipedInputStream = null;
private Upload upload = null;
private String fileName = null, mimeType = null;
private Grid<FileListProperties> fileListGrid = null;
public final static WebCommunityView newInstance(WebContentScreen screen) {
vw.initBody();
return vw;
}
protected void initBody() {
VerticalLayout verticalLayout = new VerticalLayout();
fileListGrid = new Grid<FileListProperties>();
fileListGrid.addColumn(FileListProperties::getCreatedDate).setCaption("Date");
fileListGrid.addColumn(FileListProperties::getFileName).setCaption("File Name");
fileListGrid.addColumn(FileListProperties::getUserName).setCaption("User Name");
fileListGrid.addComponentColumn(this::buildDownloadButton).setCaption("Download");
fileListGrid.setItems(loadGridWithFileInfo());
upload = new Upload("", this);
upload.setImmediateMode(false);
upload.addFailedListener((Upload.FailedListener) this);
upload.addSucceededListener((Upload.SucceededListener) this);
upload.addStartedListener((Upload.StartedListener) this);
upload.addFinishedListener((Upload.FinishedListener) this);
Label fileUploadLabel = new Label("Label"));
verticalLayout.addComponent(currentListLabel);
verticalLayout.addComponent(fileListGrid);
verticalLayout.addComponent(fileUploadLabel);
verticalLayout.addComponent(upload);
mainbody.addComponent(verticalLayout);
}
#Override
public void uploadSucceeded(SucceededEvent event) {
try {
//Model Layer
fileUploadOperation.upload(pipedInputStream);
fileUploadOperation.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void uploadFailed(FailedEvent event) {
if (event.getFilename() == null) {
Notification.show("Upload failed", Notification.Type.HUMANIZED_MESSAGE);
}
try {
//Model Layer
fileUploadOperation.abort();
} catch (Exception e) {
e.printStackTrace();
}
}
public OutputStream receiveUpload(String filename, String mimeType) {
this.fileName = filename;
this.mimeType = mimeType;
try {
pipedOutputStream = new PipedOutputStream();
new Thread() {
public void run() {
try {
System.out.println("pipedInputStream Thread started");
pipedInputStream = new PipedInputStream(pipedOutputStream);
} catch (Exception e) {
e.printStackTrace();
}
};
}.start();
if (filename == null || filename.trim().length() == 0) {
screen.displayMessage("Please select a file to upload !", WebContentScreen.MESSAGE_TYPE_WARNING);
upload.interruptUpload();
} else {
Properties properties = new Properties();
properties.setProperty("NAME", fileName);
properties.setProperty("MIME_TYPE", mimeType);
//Model Layer
fileUploadOperation.initialize(properties);
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("pipedOutputStream:"+pipedOutputStream);
return pipedOutputStream;
}
private List<FileListProperties> loadGridWithFileInfo() {
List<FileListProperties> list = null;
DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
try {
list = new ArrayList<FileListProperties>(1);
Collection<FileInfo> fileInfoList = fileCommandQuery.lstFilesForDownload();
for (Iterator iterator = fileInfoList.iterator(); iterator.hasNext();) {
FileInfo fileInfo = (FileInfo) iterator.next();
Properties properties = fileInfo.getProperties();
Collection<String> mandatoryParameters = fileInfo.getMandatoryProperties();
FileListProperties fileListProperties = new FileListProperties();
for (Iterator iterator2 = mandatoryParameters.iterator(); iterator2.hasNext();) {
String key = (String) iterator2.next();
String value = properties.getProperty(key);
if (key != null && key.equalsIgnoreCase("NAME")) {
fileListProperties.setFileName(value);
} else if (key != null && key.equalsIgnoreCase("USER_NAME")) {
fileListProperties.setUserName(value);
} else if (key != null && key.equalsIgnoreCase("CREATED_DATE")) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(1550566760000L);
fileListProperties.setCreatedDate(dateFormat.format(calendar.getTime()));
}
}
if (fileListProperties != null) {
list.add(fileListProperties);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
dateFormat = null;
}
return list;
}
private Button buildDownloadButton(FileListProperties fileListProperties) {
Button button = new Button("...");
button.addClickListener(e -> downloadFile(fileListProperties));
return button;
}
private void downloadFile(FileListProperties fileListProperties) {
}
}
The problem in your example is that you need to do the actual file handling in a separate thread. The Viritin add-on contains a component called UploadFileHandler that simplifies this kind of usage a lot. It will provide you InputStream to consume. The integration test for the component contains this kind of usage example.
Also, my recent blog entry about the subject might help.

Clear packets sent/ received

Is it possible to clear the amount packets sent/ received and start from 0 again??
The Code to get sent or received packets:
long no_of_packet_Sent = RadioInfo.getNumberOfPacketsSent();
long no_of_packet_Received = RadioInfo.getNumberOfPacketsReceived();
I never found the answer to this but another option is to write the data to a text file then minus the data in the text file from the "get number of packets" .
private static String fileFormatString(String filename) {
return filename.replace(" ".charAt(0),"_".charAt(0));
}
public static String readTextFile(String fName) {
fName = fileFormatString(fName);
String result = null;
FileConnection fconn = null;
DataInputStream is = null;
try {
fconn = (FileConnection) Connector.open(fName, Connector.READ_WRITE);
is = fconn.openDataInputStream();
byte[] data = IOUtilities.streamToBytes(is);
result = new String(data);
} catch (IOException e) {
System.out.println("Error on read: "+fName+" - " + e.getMessage());
} finally {
try {
if (null != is) is.close();
if (null != fconn) fconn.close();
} catch (IOException e) {
System.out.println("Error on read IO: "+fName+" - " + e.getMessage());
}
}
return result;
}
public static void writeTextFile(String fName, String text) {
fName = fileFormatString(fName);
DataOutputStream os = null;
FileConnection fconn = null;
try {
fconn = (FileConnection) Connector.open(fName, Connector.READ_WRITE);
if (fconn.exists());
if (!fconn.exists()) fconn.create();
os = fconn.openDataOutputStream();
os.write(text.getBytes());
} catch (IOException e) {
System.out.println("Error on write: "+fName+" - " + e.getMessage());
} finally {
try {
if (null != os) os.close();
if (null != fconn) fconn.close();
} catch (IOException e) {
System.out.println("Error on write IO: "+fName+" - " + e.getMessage());
}
}
}
long no_of_packet = RadioInfo.getNumberOfPacketsSent()+RadioInfo.getNumberOfPacketsReceived();
DTHelper.writeTextFile(text_file_name,""+no_of_packet );
String readnumberofkbytes=readTextFile(text_file_name);
long Longreadnumberofbytes = Long.parseLong(readnumberofbytes);
long CurrentNumberofDataUsed= no_of_packet -Longreadnumberofbytes;

How to send an audio file as attachment in BlackBerry?

How to send an audio file as attachment in BlackBerry SDK 6?
You can convert the audiofile into a bytearray and then use the following method
public synchronized boolean sendMail(final byte []data,
final boolean licensed)
{
Folder[] folders = store.list(4);
Folder sentfolder = folders[0];
// create a new message and store it in the sent folder
msg = new Message(sentfolder);
multipart = new Multipart();
textPart = new TextBodyPart(multipart,"Audio");
Address recipients[] = new Address[1];
try {
recipients[0] = new Address(address, "XYZ");
msg.addRecipients(Message.RecipientType.TO, recipients);
msg.setSubject("Audio");
try {
Thread thread = new Thread("Send mail") {
public void run() {
emailSenderIsBusy = true;
try {
attach = new SupportedAttachmentPart(
multipart, "application/octet-stream",
"title",data);
multipart.addBodyPart(textPart);
multipart.addBodyPart(attach);
msg.setContent(multipart);
Transport.send(msg);
}
catch(SendFailedException e)
{
}
catch (final MessagingException e) {
}
catch (final Exception e) {
}
}
};
thread.start();
return true;
}
catch (final Exception e)
{
}
}catch (final Exception e) {
}
return false;
}

Blackberry - send sms timeout

I have simple code to send sms. It works fine. Just little problem. How can I figure out that sms can not be send? Some timeout for Connection or other way? Let's say if there is no network, no sim card or no credit. Thanks
Here is code:
public static void sendSMS(String content, String number) {
MessageConnection mc = null;
TextMessage msg;
try {
mc = (MessageConnection) Connector.open("sms://" + number,Connector.WRITE,true);
msg = (TextMessage) mc.newMessage(MessageConnection.TEXT_MESSAGE);
msg.setPayloadText(content);
mc.send(msg);
} catch (final Exception e) {
e.printStackTrace();
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert(e.getMessage());
}
});
} finally {
try {
if (mc != null) {
mc.close();
}
} catch (IOException e) {
}
}
}
private void sendSMS(final String no, final String msg) {
try {
new Thread() {
public void run() {
if (RadioInfo.getNetworkType() == RadioInfo.NETWORK_CDMA) {
DatagramConnection dc = null;
try {
dc = (DatagramConnection) Connector.open("sms://" + no);
byte[] data = msg.getBytes();
Datagram dg = dc.newDatagram(dc.getMaximumLength());
dg.setData(data, 0, data.length);
dc.send(dg);
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
try {
System.out.println("Message Sent Successfully : Datagram");
Dialog.alert("Message Sent Successfully");
} catch (Exception e) {
System.out.println("Exception **1 : " + e.toString());
e.printStackTrace();
}
}
});
} catch (Exception e) {
System.out.println("Exception 1 : " + e.toString());
e.printStackTrace();
} finally {
try {
dc.close();
dc = null;
} catch (IOException e) {
System.out.println("Exception 2 : " + e.toString());
e.printStackTrace();
}
}
} else {
MessageConnection conn = null;
try {
conn = (MessageConnection) Connector.open("sms://" + no);
//generate a new text message
TextMessage tmsg = (TextMessage) conn.newMessage(MessageConnection.TEXT_MESSAGE);
//set the message text and the address
tmsg.setAddress("sms://" + no);
tmsg.setPayloadText(msg);
//finally send our message
conn.send(tmsg);
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
try {
System.out.println("Message Sent Successfully : TextMessage");
Dialog.alert("Message Sent Successfully : TextMessage");
} catch (Exception e) {
System.out.println("Exception **1 : " + e.toString());
e.printStackTrace();
}
}
});
} catch (Exception e) {
System.out.println("Exception 3 : " + e.toString());
e.printStackTrace();
} finally {
try {
conn.close();
conn = null;
} catch (IOException e) {
System.out.println("Exception 4 : " + e.toString());
e.printStackTrace();
}
}
}
}
}.start();
} catch (Exception e) {
System.out.println("Exception 5 : " + e.toString());
e.printStackTrace();
}

J2ME/Blackberry - how to read/write text file?

please give me a sample code for read/write text file in blackberry application.
My code snippet for string read/write files:
private String readTextFile(String fName) {
String result = null;
FileConnection fconn = null;
DataInputStream is = null;
try {
fconn = (FileConnection) Connector.open(fName, Connector.READ_WRITE);
is = fconn.openDataInputStream();
byte[] data = IOUtilities.streamToBytes(is);
result = new String(data);
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
try {
if (null != is)
is.close();
if (null != fconn)
fconn.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
return result;
}
private void writeTextFile(String fName, String text) {
DataOutputStream os = null;
FileConnection fconn = null;
try {
fconn = (FileConnection) Connector.open(fName, Connector.READ_WRITE);
if (!fconn.exists())
fconn.create();
os = fconn.openDataOutputStream();
os.write(text.getBytes());
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
try {
if (null != os)
os.close();
if (null != fconn)
fconn.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
Using
FileConnection Interface

Resources