How can i attach multiple images with email in Blackberry? - email

I want to attach multiple images with email in BB. How can I do this? Does any body have an idea? please help me.Below is my code which works fine when i send only one image with email. so what modification should I make in my code for attaching multiple images.
public static void SendMailAttachment(Bitmap screenshot)
{
String htmlContent = "String" ;
try
{
Multipart mp = new Multipart();
Message msg = new Message();
Address[] addresses = {new Address("","")};
for (int i = 0; i<2 ; i++)
{
PNGEncodedImage img = PNGEncodedImage.encode(screenshot);
SupportedAttachmentPart pt = new SupportedAttachmentPart(mp, img.getMIMEType(),
"Weed.png", img.getData());
mp.addBodyPart(pt);
}
msg.setContent(mp);
msg.setContent(htmlContent);
msg.addRecipients(RecipientType.TO, addresses);
msg.setSubject("Subject");
Invoke.invokeApplication(Invoke.APP_TYPE_MESSAGES, new MessageArguments(msg));
}
catch (AddressException ex)
{
System.out.println("Exception -->"+ex.getMessage());
}
catch (MessagingException ex)
{
System.out.println("Exception -->"+ex.getMessage());
}
}
Thanx in advance.

following code can be used to attach multiple images or files.
public void upload()
{
Multipart mp = new Multipart();
String fileName = null;
for (int i = 0; i<2 ; i++)
{
// Dialog.alert(image.);
byte[] stream = readStream("file:///SDCard/IMG00001-20110404-1119.JPEG");
SupportedAttachmentPart sap = new SupportedAttachmentPart(mp, MIMETypeAssociations.getMIMEType("IMG00001-20110404-1119.JPEG"),"IMG00001-20110404-1119.JPEG", stream);
mp.addBodyPart(sap);
}
TextBodyPart tbp = new TextBodyPart(mp,"test bodyString");
mp.addBodyPart(tbp);
Folder folders[] = Session.getDefaultInstance().getStore().list(Folder.SENT);
Message message = new Message(folders[0]);
Address[] toAdds = new Address[1];
try {
toAdds[0] = new Address("testmailid", null);
message.addRecipients(Message.RecipientType.TO,toAdds);
// message.setFrom(new InternetAddress(_from));
// message.addRecipients(Message.RecipientType.FROM,toAdds);
message.setContent(mp);
message.setSubject("test subject");
Transport.send(message);
Dialog.alert("message send successfully.");
} catch (AddressException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
Dialog.alert(e.getMessage());
} catch (MessagingException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
Dialog.alert(e.getMessage());
}
}
private byte[] readStream(String path)
{
InputStream in = null;
FileConnection fc = null;
byte[] bytes = null;
try
{
fc = (FileConnection) Connector.open(path);
if (fc !=null && fc.exists())
{
in = fc.openInputStream();
if (in !=null)
{
bytes = IOUtilities.streamToBytes(in);
}
}
}
catch(IOException e)
{
}
finally
{
try
{
if (in != null)
{
in.close();
}
}
catch(IOException e)
{
}
try
{
if (fc !=null)
{
fc.close();
}
}
catch(IOException e)
{
}
}
return bytes;
}
i have used this code. it works fine.

Just create a new SupportedAttachmentPart for each image and add them to the message with the addBodyPart method.
Once the multipart is populated with the body part and the attachment parts, call msg.setContent(mp).

Related

In socket programming exe file memory increasing gradually and also socket remain open

When received sting from multiple client at time some socket remain open so created mis file size increasing gradually so at time exe file become 2 GB from 35 kb so how can i reduce open sockect
private void Server_Load(object sender, EventArgs e)
{
try
{
this.tcpListener = new TcpListener(IPAddress.Any, port);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
}
catch (Exception ex)
{ }
finally
{
if (this.tcpListener != null)
{
this.tcpListener.Stop();
}
}
}
Mangae Client request by server continuously from load method
private void ListenForClients()
{
TcpClient client = null;
try
{
this.tcpListener.Start();
while (true)
{
client = this.tcpListener.AcceptTcpClient();
ThreadPool.QueueUserWorkItem(new WaitCallback(HandleClientComm),
client);
}
}
catch (Exception ex)
{
LogHelperISPL.Logger.Info("ListenForClients: " + ex.Message);
this.tcpListener.Stop();
}
finally
{
if(this.tcpListener != null)
{
this.tcpListener.Stop();
}
if (client != null)
{
client.Close();
}
}
}
Take data from client and insert into table and mange pass tcpclient and networkstream with close connection
private void HandleClientComm(object client)
{
TcpClient tcpClient = null;
NetworkStream clientStream = null;
try
{
tcpClient = (TcpClient)client;
clientStream = tcpClient.GetStream();
string InsertedRecord = string.Empty;
byte[] messageBytes = new byte[4096];
int bytesRead;
bool end = false;
while (!end)
{
bytesRead = 0;
try
{
if (clientStream != null)
{
bytesRead = clientStream.Read(messageBytes, 0,
messageBytes.Length);
}
}
catch (SocketException ex)
{
if (clientStream != null)
{
clientStream.Flush();
clientStream.Close();
}
if (tcpClient != null)
{
tcpClient.Close();
}
break;
}
catch (Exception ex)
{
if (clientStream != null)
{
clientStream.Flush();
clientStream.Close();
}
if (tcpClient != null)
{
tcpClient.Close();
}
break;
}
if (bytesRead <= 0)
{
break;
}
ASCIIEncoding encoder = new ASCIIEncoding();
string Datareceived = encoder.GetString(messageBytes, 0, bytesRead);
if (!string.IsNullOrEmpty(Datareceived))
{
string[] Multistrings = Datareceived.Split('!');
for (int i = 0; i < Multistrings.Length; i++)
{
if (!string.IsNullOrEmpty(Multistrings[i]))
{
if (Multistrings[i].Length >= 90)
{
InsertedRecord = InsertRawData(Multistrings[i]);
}
else
{
InsertedRecord =
InsertRawDataGarbage(Multistrings[i]);
}
}
}
}
}
}
catch (Exception ex)
{
LogHelperISPL.Logger.Info("While loop: " + ex.Message);
}
finally
{
if (clientStream != null)
{
clientStream.Flush();
clientStream.Close();
}
if (tcpClient != null)
{
tcpClient.Close();
}
}
}

Whether to use Flowable.create or Flowable.generate to make a file observable?

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?

Javafx Task for Bluetooth data reciever

I am creating javafx application where I have this case that I need to listen for data sent over Bluetooth.
I have one fxml window on which I need to initialize Bluetooth and start listening from data.
Following is my Code for fxml controller:
//all imports
public class NewBarcodeInvoicePaneController implements Initializable{
private BluetoothController bc;
public BluetoothController getBc() {
return bc;
}
#Override
public void initialize(URL location, ResourceBundle resources) {
try {
bc = new BluetoothController();
new Thread(bc).start();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
And BluetoothController is task where I initialize bluettoth and listen to the data
public class BluetoothController extends Task<Void> {
#Override
protected Void call() throws Exception {
LocalDevice local = null;
StreamConnectionNotifier notifier;
StreamConnection connection = null;
// setup the server to listen for connection
try {
local = LocalDevice.getLocalDevice();
try {
local.setDiscoverable(DiscoveryAgent.GIAC);
} catch (BluetoothStateException e) {
}
UUID uuid = new UUID(80087355); // "04c6093b-0000-1000-8000-00805f9b34fb"
String url = "btspp://localhost:" + uuid.toString() + ";name=RemoteBluetooth";
notifier = (StreamConnectionNotifier) Connector.open(url);
} catch (Exception e) {
e.printStackTrace();
return null;
}
try {
System.err.println("THIS IS HAPENING");
connection = notifier.acceptAndOpen();
System.err.println("HAPENING???????????????????????????");
InputStream inputStream = connection.openInputStream();
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream));
String lineRead = bReader.readLine();
connection.close();
inputStream.close();
notifier.close();
local.setDiscoverable(DiscoveryAgent.NOT_DISCOVERABLE);
JSONParser parser = new JSONParser();
Object obj = parser.parse(lineRead);
JSONArray array = (JSONArray) obj;
array.stream().map((o) -> (String) o).forEach((stringObj) -> {
System.out.println(stringObj);
});
System.out.println("AFTER DATA RECIEVED");
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
}
It Works fine if I send data over bluetooth and blocking call to notifier.acceptAndOpen() is unblocked.
My problem is when we do not pass any data and I just want to close the window I opened..
It still have blocking call open with extra thread by the task.
I tried to cancel BluetoothController task in Main controller where I open this window like following
private void openNewBarcodeInvoicePane(ActionEvent ae) {
//following are custom classes to open windows from fxml and getting controller back for further manipulation
PostoryModalWindow modalWindow = new PostoryModalWindow();
modalWindow.openNewModalPaneWithParent("New Invoice", "fxml/newbarcodeinvoicepane.fxml", ae);
//getting controller object
NewBarcodeInvoicePaneController controller = (NewBarcodeInvoicePaneController) modalWindow.getDswFromController();
controller.getWindowStage().showAndWait();
BluetoothController bc = controller.getBc();
if(bc != null){
System.err.println("CANCELLING");
bc.cancel(true);
}
}
But it doesn't throw InterrupttedExeption (In which I might have Choice to close Bluetooth thread) and after research I found that waiting on Socket doesn't work on interrupt.
Any help on this?
Thanks
Got Solution After Some Research.
I just added new task to call notifier.acceptAndOpen();
And added method to close Bluetooth notifier.
public class BluetoothController extends Task<Void> {
private final ObservableList<Item> items = FXCollections.observableArrayList();
public ObservableList<Item> getItems() {
return items;
}
StreamConnectionNotifier notifier;
#Override
protected Void call() throws Exception {
try {
BluetoothConnectionTask bct = new BluetoothConnectionTask(items);
new Thread(bct).start();
Thread.sleep(2000);
notifier = bct.getNotifier();
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
public void cancelandExit() {
try {
if (notifier != null) {
notifier.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Here is new task for blocking call
public class BluetoothConnectionTask extends Task<Void>{
private StreamConnectionNotifier notifier;
private StreamConnection connection;
private ObservableList<Item> items = FXCollections.observableArrayList();
public StreamConnection getConnection() {
return connection;
}
public StreamConnectionNotifier getNotifier() {
return notifier;
}
public BluetoothConnectionTask(ObservableList<Item> is){
items = is;
}
#Override
protected Void call() throws Exception {
try {
LocalDevice local = LocalDevice.getLocalDevice();
try {
local.setDiscoverable(DiscoveryAgent.GIAC);
} catch (BluetoothStateException e) {
}
UUID uuid = new UUID(80087355); // "04c6093b-0000-1000-8000-00805f9b34fb"
String url = "btspp://localhost:" + uuid.toString() + ";name=RemoteBluetooth";
notifier = (StreamConnectionNotifier) Connector.open(url);
} catch (Exception e) {
e.printStackTrace();
return null;
}
connection = notifier.acceptAndOpen();
InputStream inputStream = connection.openInputStream();
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream));
String lineRead = bReader.readLine();
connection.close();
inputStream.close();
notifier.close();
LocalDevice local = LocalDevice.getLocalDevice();
local.setDiscoverable(DiscoveryAgent.NOT_DISCOVERABLE);
JSONParser parser = new JSONParser();
Object obj = parser.parse(lineRead);
JSONArray array = (JSONArray) obj;
ItemDAO idao = new ItemDAO();
array.stream().map((o) -> (String) o).forEach((stringObj) -> {
String barcode = (String) stringObj;
Item i = idao.getItemByBarCode(barcode);
System.err.println("Adding Item "+i.getName());
items.add(i);
});
System.out.println("AFTER DATA RECIEVED");
return null;
}
}
Now for cancelling closing my bluetooth thread I am calling cancelandExit() after window is closed.

wicket download output stream

I want to download csv file , i take the response content and write to it , apprently wicket write after me and the content iam getting is the page html where it should be my csv
I have seen in the example the usage of throw new AbortException();
I am using version 6.7 , do you know if my version wicket has somthing instead of it ?
or rather I am doing somthing wrong ....
can you please help me ...
add(new Link<Void>("export") {
#Override
public void onClick() {
WebResponse response = (WebResponse) getResponse();
response.setAttachmentHeader("export.csv");
response.setContentType("text/csv");
OutputStream out = getResponse().getOutputStream();
try {
c.exportData(dataSource.getListForExport(), columns, out);
} catch (Exception ex) {
System.err.println(ex);
}
}
});
public <T> void exportData(List<T> list, List<IGridColumn<IDataSource<T>, T, String>> columns, OutputStream outputStream)
throws IOException {
long startTime = System.nanoTime();
PrintWriter out = new PrintWriter(new OutputStreamWriter(outputStream, Charset.forName(characterSet)));
try {
if (isExportHeadersEnabled()) {
boolean first = true;
for (IGridColumn<IDataSource<T>, T, String> col : columns) {
if (first) {
first = false;
} else {
out.print(delimiter);
System.out.println(delimiter);
}
if (col.getId().equals("checkBox")) {
continue;
}
out.print(quoteValue(col.getId()));
System.out.println(col.getId());
}
out.print("\r\n");
System.out.println("\r\n");
}
Iterator<? extends T> rowIterator = list.iterator();
while (rowIterator.hasNext()) {
T row = rowIterator.next();
boolean first = true;
for (IGridColumn<IDataSource<T>, T, String> col : columns) {
if (first) {
first = false;
} else {
out.print(delimiter);
System.out.println(delimiter);
}
if (col.getId().equals("checkBox")) {
continue;
}
Object o = (new PropertyModel<>(row, col.getId())).getObject();// ((AbstractColumn<T,
if (o != null) {
Class<?> c = o.getClass();
String s;
IConverter converter = Application.get().getConverterLocator().getConverter(c);
if (converter == null) {
s = o.toString();
} else {
s = converter.convertToString(o, Session.get().getLocale());
}
out.print(quoteValue(s));
System.out.println(quoteValue(s));
}
}
out.print("\r\n");
System.out.println("\r\n");
}
} catch (Exception ex) {
System.out.println(ex);
} finally {
System.out.println(out);
out.close();
// measure
System.out.print(System.nanoTime() - startTime);
}
}
The best way to do this is using dynamic resources. I'll suggest you to read chapter "Resource managment with Wicket" of this magnific free Wicket guide: https://code.google.com/p/wicket-guide/.
Here you have a similar example given in this guide in the section "Custom resources".
public class RSSProducerResource extends AbstractResource {
#Override
protected ResourceResponse newResourceResponse(Attributes attributes) {
ResourceResponse resourceResponse = new ResourceResponse();
resourceResponse.setContentType("text/xml");
resourceResponse.setTextEncoding("utf-8");
resourceResponse.setWriteCallback(new WriteCallback()
{
#Override
public void writeData(Attributes attributes) throws IOException
{
OutputStream outputStream = attributes.getResponse().getOutputStream();
Writer writer = new OutputStreamWriter(outputStream);
SyndFeedOutput output = new SyndFeedOutput();
try {
output.output(getFeed(), writer);
} catch (FeedException e) {
throw new WicketRuntimeException("Problems writing feed to response...");
}
}
});
return resourceResponse;
}
// method getFeed()...
}
And then you need to add the link in the desired page or component:
add(new ResourceLink("rssLink", new RSSProducerResource()));

Sending mail in blackberry

i want to create an application which can send a email in blackberry. can i have a sample code or tutorial
thanks alot
U can send Email two types using API Directly or Programatically
public void sendemail(String s){
Message m = new Message();
Address a = null;
try
{
a = new Address("","");
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Address[] addresses = {a};
try
{
m.addRecipients(net.rim.blackberry.api.mail.Message.RecipientType.TO, addresses);
m.setContent(s);
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
m.setSubject(" My Croxley ");
Invoke.invokeApplication(Invoke.APP_TYPE_MESSAGES, new MessageArguments(m));
}
And Another this way
public boolean SendEmail(String emailFrom, String emailTo, String subject, String messageData, String fileName, byte[] fileData)
{
// create a multipart message
Multipart mp = new Multipart();
TextBodyPart tbp = new TextBodyPart(mp, messageData);
mp.addBodyPart(tbp);
SupportedAttachmentPart sap = new SupportedAttachmentPart(mp, "audio/amr", fileName, fileData);
mp.addBodyPart(sap);
// create a message in the sent items folder
Folder folders[] = Session.getDefaultInstance().getStore().list(Folder.SENT);
Message message = new Message(folders[0]);
// add recipients to the message and send
try
{
Address toAdd = new Address(emailTo, emailTo);
Address toAdds[] = new Address[1];
toAdds[0] = toAdd;
message.addRecipients(Message.RecipientType.TO, toAdds);
message.setSubject(subject);
message.setContent(mp);
//sets priority
//message.setPriority(Message.Priority.HIGH);
net.rim.blackberry.api.mail.Transport.send(message);
return true;
}
catch (Exception e)
{
return false;
}
}
Ypu can get started with this: http://www.blackberry.com/developers/docs/6.0.0api/Messaging-summary.html#MG_1