Wednesday, October 16, 2013
Monday, October 14, 2013
How to send an email using Java API & Gmail account
Below blog explains about sending an email using Gmail email address as from email and Java API
Below is the sample code snippet to send email using Java Mail API.
Download the Java Mail Jar and set in class path
Here is the link to download java-mail.jar http://www.oracle.com/technetwork/java/index-138643.html
/**
* De limit the toEmail List
* Authenticate
* @param msg
* @param subject
* @param toEmail
* @param fromEmail
* @return
* @throws Exception
*/
public static String sendEmail(String msg, String subject, String toEmail, String fromEmail)
throws Exception
{
String toEmails[] = toEmail.split(",");
System.out.println("TO:::FROM:::SUBJ:::BODY:::" + toEmail + "-" + fromEmail + "-" + subject + "-" + msg);
Session session = setSessionAuthentication();
InternetAddress from = new InternetAddress(fromEmail);
InternetAddress to[] = new InternetAddress[toEmails.length];
for (int c = 0; c < toEmails.length; c++)
{
to[c] = new InternetAddress(toEmails[c]);
}
MimeMessage message = new MimeMessage(session);
message.setFrom(from);
message.addRecipients(Message.RecipientType.TO, to);
message.setSubject(subject);
message.setText(msg);
Transport.send(message);
// msg="OK Msg Posted Successfully";
return "EMail Sent Successfully";
}
/**
*
* @return
* @throws Exception
*/
public static Session setSessionAuthentication()
throws Exception
{
final String username = "FM@gmail.com";
final String password = "GMAIL PASSWORD";
//Using SSL
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
// USING TLS
// Properties props = new Properties();
// props.put("mail.smtp.auth", "true");
// props.put("mail.smtp.starttls.enable", "true");
// props.put("mail.smtp.host", "smtp.gmail.com");
// props.put("mail.smtp.port", "587");
props.put("mail.debug", "true");
MailSSLSocketFactory sf = null;
try
{
sf = new MailSSLSocketFactory();
}
catch (GeneralSecurityException e1)
{
e1.printStackTrace();
}
sf.setTrustAllHosts(true);
props.put("mail.smtp.ssl.socketFactory", sf);
Session session = Session.getInstance(props, new javax.mail.Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(username, password);
}
});
return session;
}
Tuesday, October 8, 2013
Oracle ADF Cheat Sheet
// print the roles of the current user
for ( String role : ADFContext.getCurrent().getSecurityContext().getUserRoles() ) {
System.out.println(”role “+role);
}
for ( String role : ADFContext.getCurrent().getSecurityContext().getUserRoles() ) {
System.out.println(”role “+role);
}
// get the ADF security context and test if the user has the role users
SecurityContext sec = ADFContext.getCurrent().getSecurityContext();
if ( sec.isUserInRole(”users”) ) {
}
// is the user valid
public boolean isAuthenticated() {
return ADFContext.getCurrent().getSecurityContext().isAuthenticated();
}
// return the user
public String getCurrentUser() {
return ADFContext.getCurrent().getSecurityContext().getUserName();
}
SecurityContext sec = ADFContext.getCurrent().getSecurityContext();
if ( sec.isUserInRole(”users”) ) {
}
// is the user valid
public boolean isAuthenticated() {
return ADFContext.getCurrent().getSecurityContext().isAuthenticated();
}
// return the user
public String getCurrentUser() {
return ADFContext.getCurrent().getSecurityContext().getUserName();
}
// get the binding container
BindingContainer bindings = BindingContext.getCurrent().getCurrentBindingsEntry();
BindingContainer bindings = BindingContext.getCurrent().getCurrentBindingsEntry();
// get an ADF attributevalue from the ADF page definitions
AttributeBinding attr = (AttributeBinding)bindings.getControlBinding(”test”);
attr.setInputValue(”test”);
AttributeBinding attr = (AttributeBinding)bindings.getControlBinding(”test”);
attr.setInputValue(”test”);
// get an Action or MethodAction
OperationBinding method = bindings.getOperationBinding(”methodAction”);
method.execute();
List errors = method.getErrors();
OperationBinding method = bindings.getOperationBinding(”methodAction”);
method.execute();
List errors = method.getErrors();
method = bindings.getOperationBinding(”methodAction”);
Map paramsMap = method.getParamsMap();
paramsMap.put(”param”,”value”) ;
method.execute();
Map paramsMap = method.getParamsMap();
paramsMap.put(”param”,”value”) ;
method.execute();
// Get the data from an ADF tree or table
DCBindingContainer dcBindings = (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
DCBindingContainer dcBindings = (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
FacesCtrlHierBinding treeData = (FacesCtrlHierBinding)bc.getControlBinding(”tree”);
Row[] rows = treeData.getAllRowsInRange();
Row[] rows = treeData.getAllRowsInRange();
// Get a attribute value of the current row of iterator
DCIteratorBinding iterBind= (DCIteratorBinding)dcBindings.get(”testIterator”);
String attribute = (String)iterBind.getCurrentRow().getAttribute(”field1″);
DCIteratorBinding iterBind= (DCIteratorBinding)dcBindings.get(”testIterator”);
String attribute = (String)iterBind.getCurrentRow().getAttribute(”field1″);
// Get the error
String error = iterBind.getError().getMessage();
String error = iterBind.getError().getMessage();
// refresh the iterator
bindings.refreshControl();
iterBind.executeQuery();
iterBind.refresh(DCIteratorBinding.RANGESIZE_UNLIMITED);
bindings.refreshControl();
iterBind.executeQuery();
iterBind.refresh(DCIteratorBinding.RANGESIZE_UNLIMITED);
// Get all the rows of a iterator
Row[] rows = iterBind.getAllRowsInRange();
TestData dataRow = null;
for (Row row : rows) {
dataRow = (TestData)((DCDataRow)row).getDataProvider();
}
Row[] rows = iterBind.getAllRowsInRange();
TestData dataRow = null;
for (Row row : rows) {
dataRow = (TestData)((DCDataRow)row).getDataProvider();
}
// Get the current row of a iterator , a different way
FacesContext ctx = FacesContext.getCurrentInstance();
ExpressionFactory ef = ctx.getApplication().getExpressionFactory();
ValueExpression ve = ef.createValueExpression(ctx.getELContext(), “#{bindings.testIter.currentRow.dataProvider}”, TestHead.class);
TestHead test = (TestHead)ve.getValue(ctx.getELContext());
FacesContext ctx = FacesContext.getCurrentInstance();
ExpressionFactory ef = ctx.getApplication().getExpressionFactory();
ValueExpression ve = ef.createValueExpression(ctx.getELContext(), “#{bindings.testIter.currentRow.dataProvider}”, TestHead.class);
TestHead test = (TestHead)ve.getValue(ctx.getELContext());
// Get a session bean
FacesContext ctx = FacesContext.getCurrentInstance();
ExpressionFactory ef = ctx.getApplication().getExpressionFactory();
ValueExpression ve = ef.createValueExpression(ctx.getELContext(), “#{testSessionBean}”, TestSession.class);
TestSession test = (TestSession)ve.getValue(ctx.getELContext());
FacesContext ctx = FacesContext.getCurrentInstance();
ExpressionFactory ef = ctx.getApplication().getExpressionFactory();
ValueExpression ve = ef.createValueExpression(ctx.getELContext(), “#{testSessionBean}”, TestSession.class);
TestSession test = (TestSession)ve.getValue(ctx.getELContext());
// main jsf page
DCBindingContainer dc = (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
// taskflow binding
DCTaskFlowBinding tf = (DCTaskFlowBinding)dc.findExecutableBinding(”dynamicRegion1″);
// pagedef of a page fragment
JUFormBinding form = (JUFormBinding) tf.findExecutableBinding(”regions_employee_regionPageDef”);
// handle to binding container of the region.
DCBindingContainer dcRegion = form;
DCBindingContainer dc = (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
// taskflow binding
DCTaskFlowBinding tf = (DCTaskFlowBinding)dc.findExecutableBinding(”dynamicRegion1″);
// pagedef of a page fragment
JUFormBinding form = (JUFormBinding) tf.findExecutableBinding(”regions_employee_regionPageDef”);
// handle to binding container of the region.
DCBindingContainer dcRegion = form;
// return a methodexpression like a control flow case action or ADF pagedef action
private MethodExpression getMethodExpression(String name) {
Class [] argtypes = new Class[1];
argtypes[0] = ActionEvent.class;
FacesContext facesCtx = FacesContext.getCurrentInstance();
Application app = facesCtx.getApplication();
ExpressionFactory elFactory = app.getExpressionFactory();
ELContext elContext = facesCtx.getELContext();
return elFactory.createMethodExpression(elContext,name,null,argtypes);
}
private MethodExpression getMethodExpression(String name) {
Class [] argtypes = new Class[1];
argtypes[0] = ActionEvent.class;
FacesContext facesCtx = FacesContext.getCurrentInstance();
Application app = facesCtx.getApplication();
ExpressionFactory elFactory = app.getExpressionFactory();
ELContext elContext = facesCtx.getELContext();
return elFactory.createMethodExpression(elContext,name,null,argtypes);
}
//
RichCommandMenuItem menuPage1 = new RichCommandMenuItem();
menuPage1.setId(”page1″);
menuPage1.setText(”Page 1″);
menuPage1.setActionExpression(getMethodExpression(”page1″));
RichCommandMenuItem menuPage1 = new RichCommandMenuItem();
menuPage1.setId(”page1″);
menuPage1.setText(”Page 1″);
menuPage1.setActionExpression(getMethodExpression(”page1″));
RichCommandButton button = new RichCommandButton();
button.setValueExpression(”disabled”,getValueExpression(”#{!bindings.”+item+”.enabled}”));
button.setId(item);
button.setText(item);
MethodExpression me = getMethodExpression(”#{bindings.”+item+”.execute}”);
button.addActionListener(new MethodExpressionActionListener(me));
footer.getChildren().add(button);
button.setValueExpression(”disabled”,getValueExpression(”#{!bindings.”+item+”.enabled}”));
button.setId(item);
button.setText(item);
MethodExpression me = getMethodExpression(”#{bindings.”+item+”.execute}”);
button.addActionListener(new MethodExpressionActionListener(me));
footer.getChildren().add(button);
// get a value
private ValueExpression getValueExpression(String name) {
FacesContext facesCtx = FacesContext.getCurrentInstance();
Application app = facesCtx.getApplication();
ExpressionFactory elFactory = app.getExpressionFactory();
ELContext elContext = facesCtx.getELContext();
return elFactory.createValueExpression(elContext, name, Object.class);
}
// an example how to use this
RichInputText input = new RichInputText();
input.setValueExpression(”value”,getValueExpression(”#{bindings.”+item+”.inputValue}”));
input.setValueExpression(”label”,getValueExpression(”#{bindings.”+item+”.hints.label}”));
input.setId(item);
panelForm.getChildren().add(input);
private ValueExpression getValueExpression(String name) {
FacesContext facesCtx = FacesContext.getCurrentInstance();
Application app = facesCtx.getApplication();
ExpressionFactory elFactory = app.getExpressionFactory();
ELContext elContext = facesCtx.getELContext();
return elFactory.createValueExpression(elContext, name, Object.class);
}
// an example how to use this
RichInputText input = new RichInputText();
input.setValueExpression(”value”,getValueExpression(”#{bindings.”+item+”.inputValue}”));
input.setValueExpression(”label”,getValueExpression(”#{bindings.”+item+”.hints.label}”));
input.setId(item);
panelForm.getChildren().add(input);
// catch an exception and show it in the jsf page
catch(Exception e) {
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), “”);
FacesContext.getCurrentInstance().addMessage(null, msg);
}
catch(Exception e) {
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), “”);
FacesContext.getCurrentInstance().addMessage(null, msg);
}
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_WARN, msgHead , msgDetail);
facesContext.addMessage(uiComponent.getClientId(facesContext), msg);
facesContext.addMessage(uiComponent.getClientId(facesContext), msg);
// reset all the child uicomponents
private void resetValueInputItems(AdfFacesContext adfFacesContext,
UIComponent component){
List<UIComponent> items = component.getChildren();
for ( UIComponent item : items ) {
private void resetValueInputItems(AdfFacesContext adfFacesContext,
UIComponent component){
List<UIComponent> items = component.getChildren();
for ( UIComponent item : items ) {
resetValueInputItems(adfFacesContext,item);
if ( item instanceof RichInputText ) {
RichInputText input = (RichInputText)item;
if ( !input.isDisabled() ) {
input.resetValue() ;
adfFacesContext.addPartialTarget(input);
};
} else if ( item instanceof RichInputDate ) {
RichInputDate input = (RichInputDate)item;
if ( !input.isDisabled() ) {
input.resetValue() ;
adfFacesContext.addPartialTarget(input);
};
}
}
}
RichInputText input = (RichInputText)item;
if ( !input.isDisabled() ) {
input.resetValue() ;
adfFacesContext.addPartialTarget(input);
};
} else if ( item instanceof RichInputDate ) {
RichInputDate input = (RichInputDate)item;
if ( !input.isDisabled() ) {
input.resetValue() ;
adfFacesContext.addPartialTarget(input);
};
}
}
}
// redirect to a other url
ExternalContext ectx = FacesContext.getCurrentInstance().getExternalContext();
HttpServletResponse response = (HttpServletResponse)ectx.getResponse();
String url = ectx.getRequestContextPath()+”/adfAuthentication?logout=true&end_url=/faces/start.jspx”;
ExternalContext ectx = FacesContext.getCurrentInstance().getExternalContext();
HttpServletResponse response = (HttpServletResponse)ectx.getResponse();
String url = ectx.getRequestContextPath()+”/adfAuthentication?logout=true&end_url=/faces/start.jspx”;
try {
response.sendRedirect(url);
} catch (Exception ex) {
ex.printStackTrace();
}
response.sendRedirect(url);
} catch (Exception ex) {
ex.printStackTrace();
}
// PPR refresh a jsf component
AdfFacesContext.getCurrentInstance().addPartialTarget(UIComponent);
AdfFacesContext.getCurrentInstance().addPartialTarget(UIComponent);
// find a jsf component
private UIComponent getUIComponent(String name) {
FacesContext facesCtx = FacesContext.getCurrentInstance();
return facesCtx.getViewRoot().findComponent(name) ;
}
private UIComponent getUIComponent(String name) {
FacesContext facesCtx = FacesContext.getCurrentInstance();
return facesCtx.getViewRoot().findComponent(name) ;
}
// get the adf bc application module
private OEServiceImpl getAm(){
FacesContext fc = FacesContext.getCurrentInstance();
Application app = fc.getApplication();
ExpressionFactory elFactory = app.getExpressionFactory();
ELContext elContext = fc.getELContext();
ValueExpression valueExp =
elFactory.createValueExpression(elContext, “#{data.OEServiceDataControl.dataProvider}”,
Object.class);
return (OEServiceImpl)valueExp.getValue(elContext);
}
private OEServiceImpl getAm(){
FacesContext fc = FacesContext.getCurrentInstance();
Application app = fc.getApplication();
ExpressionFactory elFactory = app.getExpressionFactory();
ELContext elContext = fc.getELContext();
ValueExpression valueExp =
elFactory.createValueExpression(elContext, “#{data.OEServiceDataControl.dataProvider}”,
Object.class);
return (OEServiceImpl)valueExp.getValue(elContext);
}
// change the locale
Locale newLocale = new Locale(this.language);
FacesContext context = FacesContext.getCurrentInstance();
context.getViewRoot().setLocale(newLocale);
Locale newLocale = new Locale(this.language);
FacesContext context = FacesContext.getCurrentInstance();
context.getViewRoot().setLocale(newLocale);
// get the stacktrace of a not handled exception
private ControllerContext cc = ControllerContext.getInstance();
private ControllerContext cc = ControllerContext.getInstance();
public String getStacktrace() {
if ( cc.getCurrentViewPort().getExceptionData()!=null ) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
cc.getCurrentViewPort().getExceptionData().printStackTrace(pw);
return sw.toString();
}
return null;
}
if ( cc.getCurrentViewPort().getExceptionData()!=null ) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
cc.getCurrentViewPort().getExceptionData().printStackTrace(pw);
return sw.toString();
}
return null;
}
// get the selected rows from a table component
RowKeySet selection = resultTable.getSelectedRowKeys();
Object[] keys = selection.toArray();
List<Long> receivers = new ArrayList<Long>(keys.length);
for ( Object key : keys ) {
User user = modelFriends.get((Integer)key);
}
RowKeySet selection = resultTable.getSelectedRowKeys();
Object[] keys = selection.toArray();
List<Long> receivers = new ArrayList<Long>(keys.length);
for ( Object key : keys ) {
User user = modelFriends.get((Integer)key);
}
// get selected Rows of a table 2
for (Object facesRowKey : table.getSelectedRowKeys()) {
table.setRowKey(facesRowKey);
Object o = table.getRowData();
JUCtrlHierNodeBinding rowData = (JUCtrlHierNodeBinding)o;
Row row = rowData.getRow();
Test testRow = (Test)((DCDataRow)row).getDataProvider() ;
}
for (Object facesRowKey : table.getSelectedRowKeys()) {
table.setRowKey(facesRowKey);
Object o = table.getRowData();
JUCtrlHierNodeBinding rowData = (JUCtrlHierNodeBinding)o;
Row row = rowData.getRow();
Test testRow = (Test)((DCDataRow)row).getDataProvider() ;
}
Oracle ADF – Best Practices
- Do not use invokeAction in pageDef because will be executed several times. Use instead a task flow with a method call in front. Also, using this approach, we can reuse the page in other task flows.
- Do not create view criterias containing the name of the view since the name of the view could be changed and then also, the criteria name should be changed.
- Use unbounded tasks only for pages or bounded task flows available as bookmarks.
- Do not use unbounded task flows for the following operations: create, update and delete. Should be used only for read operations.
- Do not add service methods in the application model that are dependent of the view iterators (default iterators). Use instead standard operations like: CreateWithParams, ExecuteWithParams, etc.
- Create secondary iterators for views in the service methods. Do not use default iterators because are the same used in the view layer.
- Do not add HTML in JSF. Use instead styles and/or CSS for available ADF components.
- Try to not use the view’s attributes in the WHERE clause for filtering. Use instead default criterias for each view instance from the application model.
- Do not use two services layers separately with different database connections to the same database if is not needed. Use instead nested application models.
- Always use the scope prefix for any accessed memory variables (requestScope, backingBeanScope, viewScope, pageFlowScope, sessionScope, applicationScope, backingBeanScope).
- Put the Cancel operation in af:subform and with immediate=true, in order to ignore the validations of other input fields which have immediate=true.
- In the context of fragment based task flows, use viewScope in preference to request scope for a more predictable behavior within the context of the sub-flow that contains the fragments
- Task flows should always contain an activity marked as an exception handler. This activity does not have to be a view activity it can be a method or router (our preferred approach) with control flow rules to subsequent activities.
- Use SetPropertyListener instead of SetActionListener (was deprecated in 11g).
- Do not combine view accessors with data model master-detail because accessor attributes create distinct row sets based on an internal view object other than that from detail.
- When a view criteria is applied programmatically in a business method from the application model later the view criteria must be removed.
- Try to use data model master-detail only for composite relations.
- For performance increase you can tune the view instance from the application model in order to get from DB more than one row once. By default is 1.
Subscribe to:
Posts (Atom)