JavaDB error 'Schema 'ROOT' does not exist' - glassfish

I am new to Java Server Faces and JavaDB. I am struggling to connect due to my database due to an error stating "Schema 'ROOT' does not exist". I'm pulling my hair out over this and I know it must be something simple. I did not set a username or password for the database "guest_book". The database exists under the APP schema. The managed bean is coded as follows..
package com.jsf;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.annotation.Resource;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.sql.DataSource;
import javax.sql.rowset.CachedRowSet;
/**
*
* #author pctdeveloper7
*/
#ManagedBean(name="guestbean")
#SessionScoped
public class GuestBookBean {
private String date;
private String fname;
private String lname;
private String email;
private String message;
#Resource( name="jdbc/guest_book" )
DataSource ds;
/**
* Creates a new instance of NewJSFManagedBean
*/
public GuestBookBean() {
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
//return a resultset of entries
public ResultSet getEntries() throws SQLException{
//Check if was injected by the server
if(ds == null)
throw new SQLException("Unable to obtain datsource");
//get connection from datapool
Connection conn = ds.getConnection("root","root");
//check if connection was successful
if(conn==null)
throw new SQLException("Unable to connect to DataSource");
try{
//Create a prepared statement to insert a new address book entry
PreparedStatement getMessages = conn.prepareStatement("Select * " +
"FROM MESSAGES ORDER BY lname, fname");
CachedRowSet rowset= new com.sun.rowset.CachedRowSetImpl();
rowset.populate(getMessages.executeQuery());
return rowset;
} finally{
conn.close(); //return connection to pool
}
}//End getEntries
//Save a new guestbook message
public String save() throws SQLException{
//Check if was injected by the server
if(ds == null)
throw new SQLException("Unable to obtain datsource");
//get connection from datapool
Connection conn = ds.getConnection();
//check if connection was successful
if(conn==null)
throw new SQLException("Unable to connect to DataSource");
try{
//create a preparedStatement to insert a new guestbook entry
PreparedStatement insertEntry = conn.prepareStatement("INSERT INTO"+
"messages values( ?, ?, ?, ?, ?)");
//define prepared statements arguements
insertEntry.setString(1, fname);
insertEntry.setString(2, lname);
insertEntry.setString(3, email);
insertEntry.setString(4, message);
insertEntry.setString(5, date);
insertEntry.executeUpdate();// insert the new entry
return "index"; //go back to the index page
}finally{
conn.close();//return connection to the pool
}
}//END Save()
}
The SQL used to create the database is as follows..
create table messages
(
fname varchar(25),
lname varchar(35),
email varchar(50),
message varchar(300),
"DATE" varchar(11)
);
Insert into messages
values('Jared', 'Rainey', 'jared.rainey.it#gmail.com', 'Hi!', '10-12-1982');
The connection pool is named GuestBookPool and the datasource is jdbc/guest_book. I didn't set passwords or username for anything and it was all created under the APP schema from what I understand. Any help would be greatly appreciated!

Instead of #ManagedBean(name="guestbean");
try #ManagedBean(name="guestbean", schema="APP"); or whatever your schema is.

If you are using JSF you can connect the to the database by creating an ApplicationContext in your Web-INF folder shown in project.
Create a singleton bean of you desired datasource.
The method that you are using is not a preferred one.
By the way, to help you more, may I ask which database you are using? Oracle, postgres, Access etc.?

Related

Read data from database using UDF in pig

I have requirement to read data from a database and analyse the data using pig.
I have written a UDF in java Referring following link
register /tmp/UDFJars/CassandraUDF_1-0.0.1-SNAPSHOT-jar-with-dependencies.jar;
A = Load '/user/sampleFile.txt' using udf.DBLoader('10.xx.xxx.4','username','password','select * from customer limit 10') as (f1 : chararray);
DUMP A;
package udf;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.mapreduce.InputFormat;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.pig.LoadFunc;
import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigSplit;
import org.apache.pig.data.Tuple;
import org.apache.pig.data.TupleFactory;
import com.data.ConnectionCassandra;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session;
public class DBLoader extends LoadFunc {
private final Log log = LogFactory.getLog(getClass());
Session session;
private ArrayList mProtoTuple = null;
private String jdbcURL;
private String user;
private String pass;
private int count = 0;
private String query;
ResultSet result;
List<Row> rows;
int colSize;
protected TupleFactory mTupleFactory = TupleFactory.getInstance();
public DBLoader() {
}
public DBLoader(String jdbcURL, String user, String pass, String query) {
this.jdbcURL = jdbcURL;
this.user = user;
this.pass = pass;
this.query = query;
}
#Override
public InputFormat getInputFormat() throws IOException {
log.info("Inside InputFormat");
// TODO Auto-generated method stub
try {
return new TextInputFormat();
} catch (Exception exception) {
log.error(exception.getMessage());
log.error(exception.fillInStackTrace());
throw new IOException();
}
}
#Override
public Tuple getNext() throws IOException {
log.info("Inside get Next");
Row row = rows.get(count);
if (row != null) {
mProtoTuple = new ArrayList<Object>();
for (int colNum = 0; colNum < colSize; colNum++) {
mProtoTuple.add(row.getObject(colNum));
}
} else {
return null;
}
Tuple t = mTupleFactory.newTuple(mProtoTuple);
mProtoTuple.clear();
return t;
}
#Override
public void prepareToRead(RecordReader arg0, PigSplit arg1) throws IOException {
log.info("Inside Prepare to Read");
session = null;
if (query == null) {
throw new IOException("SQL Insert command not specified");
}
if (user == null || pass == null) {
log.info("Creating Session with user name and password as: " + user + " : " + pass);
session = ConnectionCassandra.connectToCassandra1(jdbcURL, user, pass);
log.info("Session Created");
} else {
session = ConnectionCassandra.connectToCassandra1(jdbcURL, user, pass);
}
log.info("Executing Query " + query);
result = session.execute(query);
log.info("Query Executed :" + query);
rows = result.all();
count = 0;
colSize = result.getColumnDefinitions().asList().size();
}
#Override
public void setLocation(String location, Job job) throws IOException {
log.info("Inside Set Location");
try {
FileInputFormat.setInputPaths(job, location);
} catch (Exception exception) {
log.info("Some thing went wrong : " + exception.getMessage());
log.debug(exception);
}
}
}
Above is my pig script and java code.
Here /user/sampleFile.txt is a dummy file with no data.
I am getting following exception:
Pig Stack Trace
ERROR 1066: Unable to open iterator for alias A
org.apache.pig.impl.logicalLayer.FrontendException: ERROR 1066: Unable to open iterator for alias A
at org.apache.pig.PigServer.openIterator(PigServer.java:892)
at org.apache.pig.tools.grunt.GruntParser.processDump(GruntParser.java:774)
at org.apache.pig.tools.pigscript.parser.PigScriptParser.parse(PigScriptParser.java:372)
at org.apache.pig.tools.grunt.GruntParser.parseStopOnError(GruntParser.java:198)
at org.apache.pig.tools.grunt.GruntParser.parseStopOnError(GruntParser.java:173)
at org.apache.pig.tools.grunt.Grunt.exec(Grunt.java:84)
at org.apache.pig.Main.run(Main.java:484)
at org.apache.pig.Main.main(Main.java:158)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.hadoop.util.RunJar.run(RunJar.java:221)
at org.apache.hadoop.util.RunJar.main(RunJar.java:136)
Caused by: java.io.IOException: Job terminated with anomalous status FAILED
at org.apache.pig.PigServer.openIterator(PigServer.java:884)
... 13 more
Vivek! Do you even get in prepareToRead? (I see you did some logging, so it would be nice to know what you actually have in log) Also it would be really great to provide full stacktrace as I see you don't have full underlying exception.
Just some thoughts - I never tried writing a LoadFunc without implementing my own InputFormat and RecordReader - TextInputFormat checks for file existence and it's size (and creates a number of InputSplits based on file size(s)), so if your dummy file is empty there is a big possibility that no InputSplits are produced or zero-length InputSplit is produced. As it has zero-length it may cause pig to throw that exception. So the good suggestion is to implement own InputFormat (it's actually pretty easy). Also just as a fast try - try
set pig.splitCombination false
Probably it won't help, but it's easy to try.

Java txt to sqlite database data transfer how can be faster

I wrote a java program about transfering a txt file to a sqlite db but it takes really more time there are about 83000 data (200 data takes about 1 minute).
how can i increase transfering speed. İ tried adding arraylist than get but its not change
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;
public class NewMain {
public static Connection connect() {
Connection conn = null;
try {
String url1 = "jdbc:sqlite:c:/Users/sozdemir/Desktop/sozluk.db";
conn = DriverManager.getConnection(url1);
String sql1 = "CREATE TABLE IF NOT EXISTS KELIMELER (Kelime PRIMARYKEY NOT NULL);";
Statement s = conn.createStatement();
s.execute(sql1);
} catch (Exception e) {
System.out.println(e.getMessage());
}
return conn;
}
public void Verigir(String kelime){
String sql = "INSERT INTO KELIMELER (kelime) VALUES(?)";
try (Connection conn = this.connect();
PreparedStatement statement = conn.prepareStatement(sql)
){
statement.setString(1, kelime);
statement.executeUpdate();
} catch (Exception e) {
}
}
public static void main(String[] args) throws IOException {
/* connect();*/
NewMain app = new NewMain();
String kelime = null;
BufferedReader in = null;
int adet;
adet= 0;
in = new BufferedReader(new FileReader("C://Users//sozdemir//Desktop//ozluk.txt"));
while ((kelime=in.readLine()) !=null) {
app.Verigir(kelime);
adet +=1;
System.out.println(81742 - adet);
}
}
}
Some hints:
Use a single prepareStatement
Put everything inside a transaction
Use PRAGMA synchronous = OFF and PRAGMA journal_mode = OFF
This will give you very fast inserts.

Write object as blob via BinaryStream in Java SQLite update - NOT NULL constraint violation

I'm trying to write an object into a database as a blob, but I'm getting java.sql.SQLException: [SQLITE_CONSTRAINT] Abort due to constraint violation (NOT NULL constraint failed: table_name.blob).
Initially, I tried creating the blob as a SerialBlob and setting it on a PreparedStatement with setBlob, but I got java.sql.SQLException: not implemented by SQLite JDBC driver. So, guided by this answer, I tried to create an inputStream for the object, and set that as the binary stream.
I don't know why the database believes that the constraint is being violated - in the tests below, testStreamContentNotNull passes, but testDatabaseWrite throws the aforementioned SQLException.
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;
import org.junit.Test;
public class StackOverflowTest {
private static final String testStringToBeWrittenAsBlob = "abcdef";
#Test
public void testStreamContentNotNull() {
try {
try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
try (ObjectOutputStream oos = new ObjectOutputStream(bos)) {
oos.writeObject(testStringToBeWrittenAsBlob);
oos.flush();
oos.close();
try (ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray())) {
try (ObjectInputStream ois = new ObjectInputStream(bis)) {
assertThat((String)ois.readObject()).isEqualTo(testStringToBeWrittenAsBlob);
}
}
}
}
} catch (Exception e) {
fail();
}
}
#Test
public void testDatabaseWrite() {
Connection c = null;
Statement stmt = null;
String sql = null;
try {
// Initialize the connection
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite::memory:");
c.setAutoCommit(false);
// Create the table
stmt = c.createStatement();
sql = "CREATE TABLE table_name " +
"(id INT PRIMARY KEY NOT NULL," +
"blob BLOB NOT NULL)";
stmt.executeUpdate(sql);
c.commit();
stmt.close();
// Table has been created - now write to it
sql = "INSERT INTO table_name (id, blob) VALUES (?, ?)";
PreparedStatement p_stmt = c.prepareStatement(sql);
try(ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
try(ObjectOutputStream oos = new ObjectOutputStream(bos)) {
oos.writeObject(testStringToBeWrittenAsBlob);
oos.flush();
oos.close();
try (ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray())) {
try (ObjectInputStream ois = new ObjectInputStream(bis)) {
p_stmt.setString(1, "test-id");
p_stmt.setBinaryStream(2, ois);
p_stmt.execute(); // <--- This is where the exception is thrown
c.commit();
}
}
}
}
c.close();
} catch (Exception e) {
fail();
}
}
}
For anyone who finds this question, thanks to this post I got it to work by just reading from the ByteArrayOutputStream::toBytes - i.e. the following test passes:
#Test
public void testDatabaseWriteAsBytes() {
Connection c = null;
Statement stmt = null;
String sql = null;
try {
// Initialize the connection
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite::memory:");
c.setAutoCommit(false);
// Create the table
stmt = c.createStatement();
sql = "CREATE TABLE table_name " +
"(id INT PRIMARY KEY NOT NULL," +
"blob BLOB NOT NULL)";
stmt.executeUpdate(sql);
c.commit();
stmt.close();
// Table has been created - now write to it
sql = "INSERT INTO table_name (id, blob) VALUES (?, ?)";
PreparedStatement p_stmt = c.prepareStatement(sql);
try(ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
try(ObjectOutputStream oos = new ObjectOutputStream(bos)) {
oos.writeObject(testStringToBeWrittenAsBlob);
oos.flush();
oos.close();
p_stmt.setString(1, "test-id");
p_stmt.setBytes(2, bos.toByteArray());
p_stmt.execute(); // <--- No exception here now!
c.commit();
}
}
String selectSql = "SELECT blob FROM table_name WHERE id='test-id'";
Statement selectStatement = c.createStatement();
ResultSet resultSet = selectStatement.executeQuery(selectSql);
if (resultSet.next()) {
try (ObjectInputStream ois = new ObjectInputStream(resultSet.getBinaryStream(1))) {
assertThat((String)ois.readObject()).isEqualTo(testStringToBeWrittenAsBlob);
}
} else {
fail("Nothing in result set");
}
c.close();
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
but I'm keeping this question open because I still don't know why this failed in the first place.

testNg Factory, DataProvider reading from excel sheet, tests pass only with instance with last row parameters, others get NPE

I am using factory with data provider reading my data from an excel sheet. The issue is that my tests are passing when the last row from the excel sheet is provided through data providers. Preceding rows are giving me NPE.
I am pasting my code here. Thanks for taking a look.
Here is my factory class:
//Factory test class
public class testFactory {
#Factory(dataProviderClass=dataProvider.MyDataProvider.class,dataProvider="userDataProvider")
public Object[] factoryMethod(String email,String password,String firstName, String lastName) {
TestFaceBookUsingExcelSheetAsDataProvider instance = new TestFaceBookUsingExcelSheetAsDataProvider(email,password,firstName, lastName);
return new Object[] { instance };
}
}
This is my data provider class
//Data Provider class
public class MyDataProvider {
#DataProvider(name = "userDataProvider")
public static Object[][] getUserData() {
return ExcelUtils.fileDataProvider("user");//TODO: currently this value is not in use, hard coded in method
}
}
Here is the method which my data provider class method is calling to read data from excel sheet
//Utility Class's helper method to read test data from excel sheet
//#DataProvider(name = "fileDataProvider")
public static Object[][] fileDataProvider(String sheetName) { //TODO: sheetname
try {
//ExcelUtils.setExcelFile(Constant.Path_TestData + Constant.File_TestData,"user");
System.out.println(Constant.Path_TestData + Constant.File_TestData); //TODO
//XSSFWorkbook workbook = new XSSFWorkbook(Constant.Path_TestData + Constant.File_TestData);
XSSFWorkbook workbook = new XSSFWorkbook("<path_to_file>\\TestData.xlsx");
XSSFSheet sheet = workbook.getSheet("user");
Iterator<Row> rowIterator = sheet.iterator();
ArrayList<ArrayList<String>> rowdata = new ArrayList<ArrayList<String>>();
boolean isHeader = true;
while (rowIterator.hasNext()) {
ArrayList<String> columndata = new ArrayList<String>();
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
if (row.getRowNum() > 0) { // To filter column headings
isHeader = false;
if(cell.getCellType() == org.apache.poi.ss.usermodel.Cell.CELL_TYPE_NUMERIC) {
columndata.add(cell.getNumericCellValue() + "");
} else if (cell.getCellType() == org.apache.poi.ss.usermodel.Cell.CELL_TYPE_STRING) {
columndata.add(cell.getStringCellValue());
} else if (cell.getCellType() == org.apache.poi.ss.usermodel.Cell.CELL_TYPE_BOOLEAN) {
columndata.add(cell.getBooleanCellValue() + "");
}
}
}
if (isHeader == false ) {
rowdata.add(columndata); // to make sure we don't add an empty array for header row
}
}
workbook.close();
String[][] return_array = new String[rowdata.size()][];
for (int i = 0; i < rowdata.size(); i++) {
ArrayList<String> row = rowdata.get(i);
return_array[i] = row.toArray(new String[row.size()]);
}
return return_array;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
And this, finally, is my test code
//My testclass
package test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import pgFactory.fb.HomePage;
import pgFactory.fb.LandingPage;
import pgFactory.fb.TimeLine;
public class TestFaceBookUsingExcelSheetAsDataProvider {
// Constructor to be called from factory class
public TestFaceBookUsingExcelSheetAsDataProvider(String email, String password, String firstName, String lastName) {
this.email = email;
this.password = password;
this.firstName = firstName;
this.lastName = lastName;
}
// class variables to be used in the tests
WebDriver driver;
LandingPage lp;
HomePage hp;
TimeLine tl;
// Variables from data provider which in turn is reading from excel sheet
private String email = null;
private String password = null;
private String firstName = null;
private String lastName = null;
#Override
public String toString()
{
return this.email+ " " + this.password + " " + this.firstName + " " + this.lastName;
}
#BeforeTest
public void setup() {
// Driver
driver = new FirefoxDriver();
// Pages
lp = new LandingPage(driver).get();
hp = new HomePage(driver).get();
tl = new TimeLine(driver).get();
}
// Test methods
#Test()
public void testLogin() {
lp.login(email, password);
// Assert that after login you will see your home page
Assert.assertEquals(hp.getUserLeftNavName().getAttribute("innerHTML"), firstName + " " + lastName,
"The full name is not correct on the left side user navigation frame");
Assert.assertEquals(hp.getUserUpperNavName().getAttribute("innerHTML"), firstName,
"The first is not correct on the upper user navigation bar");
hp.logOut();
}
#Test
public void testMyPage() {
lp.login(email, password);
hp.getUserLeftNavName().click();
String name = (new WebDriverWait(driver, 5))
.until(ExpectedConditions.presenceOfElementLocated(By.id("fb-timeline-cover-name"))).getText();
Assert.assertEquals(name, firstName + " " + lastName, "The fullname on timeline cover is not correct");
hp.logOut();
}
#AfterTest
public void teardown() {
driver.quit();
}
}
BTW, I am learning selenium by automating a few tests on facebook page. So, if I am making a silly mistake, please be patient with me.
I found the solution by debugging the code. The issue is when factory is used then I don't have any control over the BeforeTest annotated methods. These are not being run before tests start to execute. So, NPE is thrown because my pageObject is not instantiated yet.
Workaround. I annotated setup method with #Test and made other tests dependent on this test and it worked like a charm. Its not the best solution because now I have to make every existing and future tests with this dependsOnMethods parameter in annotation.
If you know of a better solution, please reply.

How to read emails from outlook [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this question
recently I started a task to retrieve the emails on the exchange server using javamail API. However, sometimes I can not fetch any mails because outlook client synchronises with the mail server and those emails are therefore removed from the server.
Is there any way to ensure that I can fetch all new emails no matter before or after outlook synchronization. Or I should try to connect to outlook, if so, is there any available free API? Thank you.
Isn't is possible to configure outlook to leave a copy of the messages on the server? I really do not think connection to outlook is the way to go.
I have the solution to read emails from outlook.
We need to give username, password, domain and exchange address: https://webmail.**companynameXYZ**.com/ews/exchange.asmx.
following is the code .... I have used this from some purpose, to download attachments from undread mails and making it as read after downloading.
NOTE: we need DLL Microsoft.Exchange.WebServices.dll to be downloaded
CODE in C#:
string _username = string.Empty;
string _password = string.Empty;
string _domain = "us";
string _exchange = string.Empty;
_username = ConfigurationSettings.AppSettings["Username"].ToString();
_password = ConfigurationSettings.AppSettings["Pasword"].ToString();
_exchange = ConfigurationSettings.AppSettings["MailServer"].ToString();
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
// service.AutodiscoverUrl("maxdatafeeds#maritz.com");
service.Url = new Uri(_exchange);
service.Credentials = new WebCredentials(_username, _password, _domain);
FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, new ItemView(10));
int attachmentCount = 0;
foreach (Item item in findResults.Items)
{
// Bind to an existing message item, requesting its Id property plus its attachments collection.
EmailMessage message = EmailMessage.Bind(service, item.Id);
//read only unread mails and has attachemnts to it.
if ((!message.IsRead) && message.HasAttachments )
{
Console.WriteLine(item.Subject);
#region Iterate through the attachments collection and load each attachment.
foreach (Microsoft.Exchange.WebServices.Data.Attachment attachment in message.Attachments)
{
if (attachment is FileAttachment)
{
FileAttachment fileAttachment = attachment as FileAttachment;
attachmentCount++;
// Load the file attachment into memory and print out its file name.
fileAttachment.Load();
Console.WriteLine("Attachment name: " + fileAttachment.Name);
//create Attachments-folder if not exists.
if (!Directory.Exists(#"C:\Attachments\"))
{
Directory.CreateDirectory(#"C:\Attachments\");
}
// Load attachment contents into a file.
fileAttachment.Load("C:\\attachments\\" + fileAttachment.Name);
}
else // Attachment is an item attachment.
{
// Load attachment into memory and write out the subject.
ItemAttachment itemAttachment = attachment as ItemAttachment;
itemAttachment.Load();
Console.WriteLine("Subject: " + itemAttachment.Item.Subject);
}
}//for inner
#endregion
//mark as READ
message.IsRead = true;
message.Update(ConflictResolutionMode.AlwaysOverwrite);
Console.WriteLine("------------------------");
}//if
}//for outer
Microsoft team has created EWS-Java-Api (a java implementation) as an alternative to Microsoft.Exchange.WebServices.dll for C# implementation, and nice thing is its open sourced:
Link: https://github.com/OfficeDev/ews-java-api/wiki
JAVA Code:
package EWSGetDetailsOffice365;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import microsoft.exchange.webservices.data.Appointment;
import microsoft.exchange.webservices.data.AppointmentSchema;
import microsoft.exchange.webservices.data.CalendarFolder;
import microsoft.exchange.webservices.data.CalendarView;
import microsoft.exchange.webservices.data.EmailMessage;
import microsoft.exchange.webservices.data.ExchangeService;
import microsoft.exchange.webservices.data.ExchangeVersion;
import microsoft.exchange.webservices.data.FindItemsResults;
import microsoft.exchange.webservices.data.Folder;
import microsoft.exchange.webservices.data.IAutodiscoverRedirectionUrl;
import microsoft.exchange.webservices.data.Item;
import microsoft.exchange.webservices.data.ItemId;
import microsoft.exchange.webservices.data.ItemSchema;
import microsoft.exchange.webservices.data.ItemView;
import microsoft.exchange.webservices.data.PropertySet;
import microsoft.exchange.webservices.data.SearchFilter;
import microsoft.exchange.webservices.data.ServiceLocalException;
import microsoft.exchange.webservices.data.WebCredentials;
import microsoft.exchange.webservices.data.WellKnownFolderName;
public class MSExchangeEmailService {
public static class RedirectionUrlCallback implements IAutodiscoverRedirectionUrl {
public boolean autodiscoverRedirectionUrlValidationCallback(String redirectionUrl) {
return redirectionUrl.toLowerCase().startsWith("https://");
}
}
private static ExchangeService service;
private static Integer NUMBER_EMAILS_FETCH =5; // only latest 5 emails/appointments are fetched.
/**
* Firstly check, whether "https://webmail.xxxx.com/ews/Services.wsdl" and "https://webmail.xxxx.com/ews/Exchange.asmx"
* is accessible, if yes that means the Exchange Webservice is enabled on your MS Exchange.
*/
static{
try{
service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
//service.setUrl(new URI("https://webmail.xxxx.com/ews/Exchange.asmx"));
}catch (Exception e) {
e.printStackTrace();
}
}
/**
* Initialize the Exchange Credentials.
* Don't forget to replace the "USRNAME","PWD","DOMAIN_NAME" variables.
*/
public MSExchangeEmailService() {
service.setCredentials(new WebCredentials("abc#domain.com", "1234"));
try {
service.autodiscoverUrl("dhananjayk#sysmind.com", new RedirectionUrlCallback());
} catch (Exception ex) {
Logger.getLogger(MSExchangeEmailService.class.getName()).log(Level.SEVERE, null, ex);
}
service.setTraceEnabled(true);
}
/**
* Reading one email at a time. Using Item ID of the email.
* Creating a message data map as a return value.
*/
public Map readEmailItem(ItemId itemId){
Map messageData = new HashMap();
try{
Item itm = Item.bind(service, itemId, PropertySet.FirstClassProperties);
EmailMessage emailMessage = EmailMessage.bind(service, itm.getId());
messageData.put("emailItemId", emailMessage.getId().toString());
messageData.put("subject", emailMessage.getSubject().toString());
messageData.put("fromAddress",emailMessage.getFrom().getAddress().toString());
messageData.put("senderName",emailMessage.getSender().getName().toString());
Date dateTimeCreated = emailMessage.getDateTimeCreated();
messageData.put("SendDate",dateTimeCreated.toString());
Date dateTimeRecieved = emailMessage.getDateTimeReceived();
messageData.put("RecievedDate",dateTimeRecieved.toString());
messageData.put("Size",emailMessage.getSize()+"");
messageData.put("emailBody",emailMessage.getBody().toString());
}catch (Exception e) {
e.printStackTrace();
}
return messageData;
}
/**
* Number of email we want to read is defined as NUMBER_EMAILS_FETCH,
*/
public List readEmails(){
List msgDataList = new ArrayList();
try{
Folder folder = Folder.bind( service, WellKnownFolderName.Inbox );
FindItemsResults<Item> results = service.findItems(folder.getId(), new ItemView(NUMBER_EMAILS_FETCH));
int i =1;
for (Item item : results){
Map messageData = new HashMap();
messageData = readEmailItem(item.getId());
System.out.println("\nEmails #" + (i++ ) + ":" );
System.out.println("subject : " + messageData.get("subject").toString());
System.out.println("Sender : " + messageData.get("senderName").toString());
msgDataList.add(messageData);
}
}catch (Exception e) {
e.printStackTrace();
}
return msgDataList;
}
/**
* Reading one appointment at a time. Using Appointment ID of the email.
* Creating a message data map as a return value.
*/
public Map readAppointment(Appointment appointment){
Map appointmentData = new HashMap();
try {
appointmentData.put("appointmentItemId", appointment.getId().toString());
appointmentData.put("appointmentSubject", appointment.getSubject());
appointmentData.put("appointmentStartTime", appointment.getStart()+"");
appointmentData.put("appointmentEndTime", appointment.getEnd()+"");
//appointmentData.put("appointmentBody", appointment.getBody().toString());
} catch (ServiceLocalException e) {
e.printStackTrace();
}
return appointmentData;
}
/**
*Number of Appointments we want to read is defined as NUMBER_EMAILS_FETCH,
* Here I also considered the start data and end date which is a 30 day span.
* We need to set the CalendarView property depending upon the need of ours.
*/
public List readAppointments(){
List apntmtDataList = new ArrayList();
Calendar now = Calendar.getInstance();
Date startDate = Calendar.getInstance().getTime();
now.add(Calendar.DATE, 30);
Date endDate = now.getTime();
try{
CalendarFolder calendarFolder = CalendarFolder.bind(service, WellKnownFolderName.Calendar, new PropertySet());
CalendarView cView = new CalendarView(startDate, endDate, 5);
cView.setPropertySet(new PropertySet(AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.End));// we can set other properties as well depending upon our need.
//FindItemsResults appointments = calendarFolder.findAppointments(cView);
FindItemsResults<Appointment> appointments = calendarFolder.findAppointments(cView);
System.out.println("|------------------> Appointment count = " + appointments.getTotalCount());
int i =1;
//List appList = appointments.getItems();
for (Appointment appointment : appointments.getItems()) {
System.out.println("\nAPPOINTMENT #" + (i++ ) + ":" );
Map appointmentData = new HashMap();
appointmentData = readAppointment(appointment);
System.out.println("subject : " + appointmentData.get("appointmentSubject").toString());
System.out.println("On : " + appointmentData.get("appointmentStartTime").toString());
apntmtDataList.add(appointmentData);
}
}catch (Exception e) {
e.printStackTrace();
}
return apntmtDataList;
}
public static void getAllMeetings() throws Exception {
try {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date startDate = formatter.parse("2016-01-01 00:00:00");
SearchFilter filter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.LastModifiedTime,startDate);
FindItemsResults<Item> findResults = service.findItems(WellKnownFolderName.Calendar, filter, new ItemView(1000));
System.out.println("|------------------> meetings count = " + findResults.getTotalCount());
for (Item item : findResults.getItems())
{
Appointment appt = (Appointment)item;
//appt.setStartTimeZone();
System.out.println("TimeZone====="+appt.getTimeZone());
System.out.println("SUBJECT====="+appt.getSubject());
System.out.println("Location========"+appt.getLocation());
System.out.println("Start Time========"+appt.getStart());
System.out.println("End Time========"+appt.getEnd());
System.out.println("Email Address========"+ appt.getOrganizer().getAddress());
System.out.println("Last Modified Time========"+appt.getLastModifiedTime());
System.out.println("Last Modified Time========"+appt.getLastModifiedName());
System.out.println("*************************************************\n");
}
} catch (Exception exp) {
exp.printStackTrace();
}
}
public static void main(String[] args) {
MSExchangeEmailService msees = new MSExchangeEmailService();
//msees.readEmails();
//msees.readAppointments();
try {
msees.getAllMeetings();
} catch (Exception ex) {
Logger.getLogger(MSExchangeEmailService.class.getName()).log(Level.SEVERE, null, ex);
}
}
}