Sending email from Blackberry java development - blackberry-eclipse-plugin

I have a question with sending email from Blackberry java development.
My application sends mail correctly, but it defaults in FROM the previously configured mail on the BlackBerry device, I don't know how to replace the header FROM for another email diferent like the email configured in the Blackberry device, I put my code below:
try {
Address() ad = new Address ("emailexample#hotmail.com", "Maria Gomez");
} Catch (AddressException e) {
try {
Store store = Session.getDefaultInstance().getStore ();
Folder [] folders = store.list (Folder.SENT);
Sentfolder folder = folders [0];
msg = new Message (sentfolder);
try {
String [] v = splitString (toField.getText (), ',', false);
toList = new Address [v.length];
for (int i = 0; i <v.length i + +)
{
toList [i] = new Address (v [i], "");
}
} Catch (AddressException e) {System.out.println (e.toString ());}
msg.addRecipients (Message.RecipientType.TO, toList);
msg.setSubject (subjectField.getText ());
msg.setContent (msgField.getText ());
msg.setFrom (ad);
if (toField.getText().compareTo("") == 0 | | fromField.getText().compareTo("")==0)
{
Dialog.alert ("ERROR: \ n Lack mail recipient \ no sender");
}
else
{
Transport.send (msg);
Dialog.alert ("the mail was sent");
subjectField.setText ("");
msgField.setText ("");
}
} Catch (MessagingException e) {
System.out.println (e.getMessage ());
Dialog.alert ("No mail was sent");
}
I try to use msg.setFrom (ad), but dosen't work, then i try using msg.setHeader ("FROM", "emailexample#gmail.com") an neither work.
Waiting for helps, Thanks.

hi try this it work fine,,
public void TextMailSend()
{
String htmlContent = " Name:"+Name+ "\n Common Name:"+cmn_nm +"\n Radious:"+radius+"\n Year:"+yr+"\n Latitude:"+lat +"\n Longitude :"+lng ;
Message msg = new Message();
try
{
final Address address = new Address("","");
Address[] addresses = {address};
msg.addRecipients(net.rim.blackberry.api.mail.Message.RecipientType.TO, addresses);
msg.setContent(htmlContent);
msg.setSubject("Subject");
Invoke.invokeApplication(Invoke.APP_TYPE_MESSAGES, new MessageArguments(msg));
//Dialog.inform("Mail send fully.");
}
catch (AddressException e)
{
e.printStackTrace();
System.out.println("AddressException -->"+e.getMessage());
}
catch (MessagingException e)
{
e.printStackTrace();
System.out.println("MessagingException -->"+e.getMessage());
}
}

Related

Search for users by Forgerock ClientSDK tools

All.
I'm trying to search for the users using ClientSDK tools of Forgerock OpenAM-12.0.0 by sunIdentityServerPPCommonNameSN.
Look my code.
I found out that I can search the users by AMIdentityRepository.searchIdentities of the filter argument.
However, I don't find out the format.
Please give me your help.
Regard.
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
// TODO Auto-generated method stub
try {
AuthContext ac = new AuthContext("/");
AuthContext.IndexType indexType =
AuthContext.IndexType.MODULE_INSTANCE;
String indexName = "DataStore";
ac.login(indexType, indexName);
Callback[] callback = ac.getRequirements();
for (int i =0 ; i< callback.length ; i++) {
if (callback[i] instanceof NameCallback) {
NameCallback name = (NameCallback) callback[i];
name.setName("amAdmin");
} else if (callback[i] instanceof PasswordCallback) {
PasswordCallback pass = (PasswordCallback) callback[i];
String password = "adAdmin00";
pass.setPassword(password.toCharArray());
}
}
ac.submitRequirements(callback);
if(ac.getStatus() == AuthContext.Status.SUCCESS){
SSOToken token = ac.getSSOToken();
AMIdentityRepository amIr = new AMIdentityRepository(token, "/");
// I want to search for the users by sunIdentityServerPPCommonNameSN;
String filter = "sunIdentityServerPPCommonNameSN=*";
IdSearchResults isr = amIr.searchIdentities(IdType.USER,
filter,
new IdSearchControl());
Set<AMIdentity> results = isr.getSearchResults();
if ((results != null) && !results.isEmpty()) {
IdSearchResults specialUsersResults =
amIr.getSpecialIdentities(IdType.USER);
results.removeAll(specialUsersResults.getSearchResults());
for (Iterator<AMIdentity> i = results.iterator();
i.hasNext(); ) {
AMIdentity amid = i.next();
System.out.println("dn: "+ amid.getDN());
System.out.println("realm: "+ amid.getRealm());
System.out.println("uid: "+ amid.getUniversalId());
System.out.println("type: "+ amid.getType());
}
}
}
} catch (AuthLoginException e) {
e.printStackTrace();
} catch (L10NMessageImpl e) {
e.printStackTrace();
} catch (IdRepoException e) {
e.printStackTrace();
}
}
You are strongly encouraged to use the ForgeRock REST APIs in preference to the Java SDK.
Have a look at the OpenAM developers guide http://openam.forgerock.org/doc/webhelp/dev-guide/rest-api-query-identity.html
The best alternative is to query the data store directly. For example, if you are using OpenDJ you could use the OpenDJ LDAP SDK, or the OpenDJ REST interface.

C++/CLI code doesn't enter .then part of the create_task function

This is the code that I have:
void MainPage::OnNavigatedTo(NavigationEventArgs^ e)
{
XTRACE(L"=========================================will start onNavigated ");
auto mediaCapture = ref new Windows::Media::Capture::MediaCapture();
m_mediaCaptureMgr = mediaCapture;
IAsyncAction ^asyncAction = m_mediaCaptureMgr->InitializeAsync();
try
{
create_task(asyncAction).then([this](task<void> initTask)
{
XTRACE(L"=========================================will start onNavigated 2");
try
{
initTask.get();
auto mediaCapture = m_mediaCaptureMgr.Get();
if (mediaCapture->MediaCaptureSettings->VideoDeviceId != nullptr && mediaCapture->MediaCaptureSettings->AudioDeviceId != nullptr)
{
String ^fileName;
fileName = VIDEO_FILE_NAME;
XTRACE(L"=================================Device initialized successful\n");
create_task(KnownFolders::VideosLibrary->CreateFileAsync(fileName, Windows::Storage::CreationCollisionOption::GenerateUniqueName))
.then([this](task<StorageFile^> fileTask)
{
XTRACE(L"=================================Create record file successful\n");
m_recordStorageFile = fileTask.get();
MediaEncodingProfile^ recordProfile = nullptr;
recordProfile = MediaEncodingProfile::CreateMp4(Windows::Media::MediaProperties::VideoEncodingQuality::Auto);
stream = ref new InMemoryRandomAccessStream();
return m_mediaCaptureMgr->StartRecordToStreamAsync(recordProfile, stream);
}).then([this](task<void> recordTask)
{
try
{
recordTask.get();
XTRACE(L"=================================Start Record successful\n");
}
catch (Exception ^e)
{
XTRACE(L"======ERRROR is : %d", e);
}
});
}
else
{
XTRACE(L"=================================No VideoDevice/AudioDevice Found\n");
}
XTRACE(L"=================================WILL EXIT \n");
}
catch (Exception ^ e)
{
XTRACE(L"============================================ERROR IS: %d\n", e);
}
}
);
}
catch (Exception ^ e)
{
XTRACE(L"============================================before create task ERROR IS: %d\n", e);
}
XTRACE(L"=================================SLEEP 20000====================================\n");
std::chrono::milliseconds dura(20000);
std::this_thread::sleep_for(dura);
XTRACE(L"=================================TIME ENDED====================================\n");
// stop device detection
try
{
XTRACE(L"=================================Stopping Record\n");
create_task(m_mediaCaptureMgr->StopRecordAsync())
.then([this](task<void> recordTask)
{
try
{
recordTask.get();
XTRACE(L"=================================Stop record successful: %d\n", stream->Size);
}
catch (Exception ^e)
{
XTRACE(L"=================================ERROR while stoping 2: %d\n", e);
}
});
}
catch (Exception ^e)
{
XTRACE(L"=================================ERROR try catch 3 stoping: %d\n", e);
}
CloseHandle(ghEvent);
// destruct the device manager
XTRACE(L"=====================================================================END\n");
}
In the log I see:
=========================================will start onNavigated
And then directly:
=====================================================================
=================================SLEEP 20000====================================
What is strange is that I had this code in a unittest and it worked, I created a new windows phone project with a UI and it doesn't work
Apparently it was because of the ThreadSleep:
std::chrono::milliseconds dura(20000);
std::this_thread::sleep_for(dura);
In the library project where I was working I was using a different sleep, provided by the library, and that would work. So this was the line that would cause the application to block itself.
I worked my way around this by including 2 buttons in the app, for the start and stop recording.

Use iXMLHttpRequest2 to download zip file

I am trying to port cocos2dx application for Windows phone 8. I am trying to use iXMLHTTPRequest class to perform Network calls in C++.
I am trying to download zip file using this but dont know what and where I am doing wrong. Here is my code which I am using, Please help me to figure out the issue and what I should do to make it working.
void HTTPRequest::sendRequest(){
m_cancelHttpRequestSource = cancellation_token_source();
// Set up the GET request parameters.
std::string s_str = std::string(urlString);
std::wstring wid_str = std::wstring(s_str.begin(), s_str.end());
const wchar_t* w_char = wid_str.c_str();
auto uri = ref new Uri( ref new String(w_char));
String ^temp = uri->AbsoluteUri;
auto token = m_cancelHttpRequestSource.get_token();
// Send the request and then update the UI.
onHttpRequestCompleted(m_httpRequest.GetAsync(uri, token));
}
void HTTPRequest::onHttpRequestCompleted(concurrency::task httpRequest)
{
httpRequest.then([this](task previousTask)
{
try
{
wstring response = previousTask.get();
if (m_httpRequest.GetStatusCode() == 200)
{
size_t strSize;
FILE* fileHandle;
auto local = Windows::Storage::ApplicationData::Current->LocalFolder;
auto localFileNamePlatformString = local->Path + "\\test1.zip";
// Create an the xml file in text and Unicode encoding mode.
if ((fileHandle = _wfopen(localFileNamePlatformString->Data(), L"wb")) == NULL) // C4996
// Note: _wfopen is deprecated; consider using _wfopen_s instead
{
wprintf(L"_wfopen failed!\n");
return(0);
}
// Write a string into the file.
strSize = wcslen(response.c_str());
if (fwrite(response.c_str(), sizeof(wchar_t), strSize, fileHandle) != strSize)
{
wprintf(L"fwrite failed!\n");
}
// Close the file.
if (fclose(fileHandle))
{
wprintf(L"fclose failed!\n");
}
}
else
{
// The request failed. Show the status code and reason.
wstringstream ss;
ss << L"The server returned "
<< m_httpRequest.GetStatusCode()
<< L" ("
<< m_httpRequest.GetReasonPhrase()
<< L')';
//String ^responseText = ref new String(ss.str().c_str());
m_delegate->parserError(requestType->getCString(), "Print Status Code later");
}
}
catch (const task_canceled&)
{
// Indicate that the operation was canceled.
//String ^responseText = "The operation was canceled";
m_delegate->parserError(requestType->getCString(), "Operation has canceled");
}
catch (Exception^ e)
{
// Indicate that the operation failed.
//String ^responseText = "The operation failed";
m_delegate->parserError(requestType->getCString(), "The operation failed");
// TODO: Handle the error further.
(void)e;
}
}, task_continuation_context::use_current());
}

Problems reading from Microsoft Messaging Queues in C#

I have problems reading from my MSMQ. When I write to the queue, it works perfectly, but when I try to read that message from the queue, I get the following exception: "The queue does not exist or you do not have sufficient permissions to perform the operation." The queue does exists, and I have full permissions on the machine and queue. Here is my code:
public string path = #".\private$\";
public void WriteToQueue(string QueueName, object messageObject)
{
try
{
path = path + QueueName;
MessageQueue msmq = null;
if (!MessageQueue.Exists(path))
{
msmq = MessageQueue.Create(path);
}
else
{
msmq = new MessageQueue(path);
}
msmq.Formatter = new XmlMessageFormatter(new Type[] { typeof(string)});
msmq.Send(messageObject);
msmq.Close();
}
catch (MessageQueueException ex)
{
System.ArgumentException argEx = neArgumentException(ex.ToString());
throw argEx;
}
path = #".\private$\";
}
public string ReadQueue(string QueueName)
{
try
{
path = path + QueueName;
MessageQueue msmq = new MessageQueue(path);
string msg;
msmq.Formatter = new XmlMessageFormatter(new Type[] { typeof(string)});
msg = msmq.Receive().Body.ToString(); //exception is thrown here
path = #".\private$\";
return msg;
}
catch (Exception ex)
{
return null;
}
}
can the problem maybe be with reading it as type of string? Maybe not in the right format?
Try this:
public string path = ".\\private$\\";
'#' doesn't work for me too.

Is it possible to use IMAP Query Terms in Javamail with GMail?

I am trying to programmatically retrieve the Call Log messages that are backup up from my android phone by a little application called SMSBackup (highly recommended).
What I want to do is to be able to retrieve the call logs for a particular day. I have tried the following program, using JavaMail:
public List<CallLogEntry> getCallLog(String username, String password, Date date, TimeZone tz) {
Store store = null;
try {
store = MailUtils.getGmailImapStore(username, password);
Folder folder = store.getDefaultFolder();
if (folder == null)
throw new Exception("No default folder");
Folder inboxfolder = folder.getFolder("Call log");
if (inboxfolder == null)
throw new Exception("No INBOX");
inboxfolder.open(Folder.READ_ONLY);
Date fromMidnight = new Date(TimeUtils.fromMidnight(date.getTime(), tz));
Date toMidnight = new Date(TimeUtils.toMidnight(date.getTime(), 0, tz));
SentDateTerm fromTerm = new SentDateTerm(SentDateTerm.GT, fromMidnight);
SentDateTerm toTerm = new SentDateTerm(SentDateTerm.LT, toMidnight);
AndTerm searchTerms = new AndTerm(fromTerm, toTerm);
Message[] msgs = inboxfolder.search(searchTerms);
FetchProfile fp = new FetchProfile();
fp.add("Subject");
fp.add("Content");
fp.add("From");
fp.add("SentDate");
inboxfolder.fetch(msgs, fp);
List<CallLogEntry> callLog = new ArrayList<CallLogEntry>();
for (Message message : msgs) {
CallLogEntry entry = new CallLogEntry();
entry.subject = message.getSubject();
entry.body = (String) message.getContent();
callLog.add(entry);
}
inboxfolder.close(false);
store.close();
return callLog;
} catch (NoSuchProviderException ex) {
ex.printStackTrace();
} catch (MessagingException ex) {
ex.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (store != null)
store.close();
} catch (MessagingException ex) {
ex.printStackTrace();
}
}
return null;
}
My two utility methods (fromMidnight / toMidnight):
public static final long fromMidnight(long time, TimeZone tz) {
Calendar c = Calendar.getInstance(tz);
c.setTimeInMillis(time);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 1);
return c.getTimeInMillis();
}
public static final long toMidnight(long time, int nDays, TimeZone tz) {
Calendar c = Calendar.getInstance(tz);
c.setTimeInMillis(time + nDays*MILLIS_IN_DAY);
c.set(Calendar.HOUR_OF_DAY, 23);
c.set(Calendar.MINUTE, 59);
c.set(Calendar.SECOND, 59);
c.set(Calendar.MILLISECOND, 999);
return c.getTimeInMillis();
}
However, for some reason:
while eventually executing, it takes about 3 minutes to complete
I'm getting back the entire Call log, i.e. the entire content of the "Call Log" folder in my mailbox
What am I missing?
The main thing that you're missing is that the underlying IMAP SEARCH syntax supports only dates, not date-times. So your query will result in JavaMail issuing the command:
A001 SEARCH SENTBEFORE 16-JAN-2011 SENTSINCE 16-JAN-2011 ALL
(Put a breakpoint in IMAPProtocol.issueSearch() to see this.)
GMail appears to freak out on this query, which logically cannot match any messages. Try switching your logic to a single term using SentDateTerm.EQ (which maps to SENTON) and it should work:
SentDateTerm term = new SentDateTerm(SentDateTerm.EQ, date.getTime());
Message[] msgs = inboxfolder.search(term);

Resources