Showing posts with label Java Tutorial. Show all posts
Showing posts with label Java Tutorial. Show all posts

WordPress – Allow Contributors to Add / Upload Media

In WordPress by default the Add Media functionality (called Capability in wordpress terms) is disabled for users with Contributor role. If you are hosting multiuser wordpress site where users with contributor roles logs in and update their post, they would not be able to add images / medias. That’s quite annoying. The user who is editing a post must be able to add supported media for their post.


Check below screenshot. The current user has “Contributor” role. Hence she is not able to view Add media button.


wordpress-contributor-add-media-disabled


Now to overcome this there is a simple trick. By using WordPress’s add_cap method we can add different capabilities to user. So we can add upload_files capability to a Contributor using this method.


Add following code in functions.php file of your current wordpress theme.



//Allow Contributors to Add Media
if ( current_user_can('contributor') && !current_user_can('upload_files') )
add_action('admin_init', 'allow_contributor_uploads');

function allow_contributor_uploads() {
$contributor = get_role('contributor');
$contributor->add_cap('upload_files');
}

Now logout and login again using a user with contributor role. Ta’da.. Add media button is visible now.


wordpress-contributor-add-media-option-enabled


Use this simple trick to make Add media button visible for contributors on your wordpress site. I think this simple trick will help those who have contributors on their site.


The post WordPress – Allow Contributors to Add / Upload Media appeared first on ViralPatel.net.








via ViralPatel.net http://ift.tt/1CO56nL

Excel Macro: Evaluating Formulas Dynamically

In this post, we will see how excel formulas can be picked-up dynamically in excel macros. This tutorial also covers applying cell formats dynamically.


Lets consider the following example. For data setup, we open a new excel file and create a worksheet named “Data” in it. We set up the following sample data set in this sheet.


Data_Before


The requirement is to write a macro which will populate additional columns based on some calculations (apply formulas on the existing data cells) for all the rows present. So, the result would look something like:


Data_After


The following processing has been done:



' Two new columns “Full Name” and “Bonus” have been added.

' The value for “Full name” has been computed based on following formula:
IF(C2 = "M", "Mr ","Mrs ") & A2 & " " &B2

' The value for “Bonus” has been calculated based on the following formula:
(D2 * 12) * (10/100)
where the bonus is 10% of the annual salary.

' A specific formatting has been applied to the bonus value.

' The values have been computed for the whole range of data ( 9 rows in this case).


The task is to achieve this whole processing via an excel macro. Further, we will try to keep all the aspects as dynamic as possible. For this, we create another worksheet named “Config” and populate the following data in it:


Config_Formula


So, each formula being used in the calculation is mentioned as a configuration in this new sheet. Also, the bonus value has been mentioned as 10% (It can also be made a configuration item where we read it from another cell). Please note that the formula contains 2nd row references. We will shortly see the reason for that.


Save this workbook as “dynamic_macro.xlsm”. The extension “.xlsm” is used for macro enabled workbooks.


Now that we are done defining the problem statement and doing the required data setup, let’s move on to writing the macro. Under the “Developer” tab in Menu, click on “Macros”. The following dialogue box will open, just put a macro name and click on “create”.


Macro_Image


Once you click on “create” button, it will open a VB editor where the coding can be done:


Macro_Code


Simply copy-paste the below code in the above editor:



' Function to return string based on the integer value passed for columns (For Ex: AA, A, HR etc.)
Function ColLtr(iCol As Integer) As String
If iCol > 0 And iCol <= Columns.Count Then
ColLtr = Evaluate("substitute(address(1, " & iCol & ", 4), ""1"", """")")
End If
End Function

' Main procedure for the processing
Sub calculate_fields()
' Defining the worksheet names
strData = "Data"
srtConfig = "Config"

' Getting the worksheet handle
Set wsData = ThisWorkbook.Worksheets(strData)
Set wsConfig = ThisWorkbook.Worksheets(srtConfig)

' Activating the "Data" worksheet
wsData.Activate

' Getting the row / column count of existing data.
dataRowCount = wsData.UsedRange.Rows.Count
dataColCount = wsData.UsedRange.Columns.Count

' Getting the formula row count in "Config" worksheet, substracting 1 for the header records
formulaRowCount = wsConfig.Range("A1").End(xlDown).Row - 1

' Looping through the config rows count. In this setup, these are the columns to be computed
For i = 1 To formulaRowCount
' Copy the column header name from column "B"
Cells(1, dataColCount + i) = wsConfig.Range("B" & (i + 1)).Value

' Get the column format (if any)
colFormat = wsConfig.Range("D" & (i + 1)).Value

' Applying the formula to the 2nd row after the actual column count in the "Data" worksheet
Range(ColLtr(dataColCount + i) & "2").Formula = "=" & Replace(wsConfig.Range("C" & (i + 1)).Value, "", """")

' Apply the formatting (if specified)
If colFormat "" Then
' Replace any " in the format value with ""
colFormat = Replace(colFormat, """", """""")
Range(ColLtr(dataColCount + i) & "2").NumberFormat = colFormat
End If

' Noting the range start value
If i = 1 Then
strCopyStart = ColLtr(dataColCount + i)
End If

' Noting the range end value
If i = formulaRowCount Then
strCopyEnd = ColLtr(dataColCount + i)
End If
Next i

' Selecting the range for which the formulas have been applied
Range(strCopyStart & "2:" & strCopyEnd & "2").Select

' Using Autofill to apply formula to all the records
copyRange = strCopyStart & "2:" & strCopyEnd & (dataRowCount)
Selection.AutoFill Destination:=Range(copyRange), Type:=xlFillDefault

' Finally, save the workbook
ThisWorkbook.Save

End Sub

Once done, save the code changes. It will take you back to the following screen where you can just select and run the macro.

Macro_Run


Let’s now go through the code and try to understand the functionality.


The generic function “ColLtr” is useful to get the cell in lettered format. For Ex:



5 will return E
27 will return AA
55 will return BC and so on

In the main procedure, we defined the worksheets name, got their handles and activated the “Data” worksheet. The “UsedRange” property has been used to get the rows and columns count.



dataRowCount = wsData.UsedRange.Rows.Count
dataColCount = wsData.UsedRange.Columns.Count

Every Worksheet object has a UsedRange property that returns a Range object representing the area of a worksheet that is being used. The UsedRange property represents the area described by the farthest upper-left and farthest lower-right nonempty cells in a worksheet and includes all cells in between. Because the test data in our case is continuous, it can be used directly to get the count.


You might use the UsedRange property together with the SpecialCells method to return a Range object representing all cells in a worksheet of a specified type. For example, the following code returns a Range object that includes all the cells in the active worksheet that contain a formula:



Dim rngFormulas As Excel.Range
Set rngFormulas = ActiveSheet.UsedRange.SpecialCells(xlCellTypeFormulas)

On the next line, a different property “Range.End” has been used to get the row count.



formulaRowCount = wsConfig.Range("A1").End(xlDown).Row - 1

This property returns a Range object that represents the cell at the end of the region that contains the source range. The generic syntax for this property is:



expression.End(Direction)

Where, expression is a variable that represents a Range object. The parameter “Direction” mentions the direction in which to move. The valid values are:



xlDown ' Down
xlToLeft ' To Left
xlToRight ' To Right
xlUp ' Up

Once the formula count is there, we just loop that many times to get the additional columns created. Within the loop, the column header has been copied as mentioned in the “Config” worksheet by using the “Range.Value” property:



Cells(1, dataColCount + i) = wsConfig.Range("B" & (i + 1)).Value

Similarly, the format which has to be applied to this new column is fetched.


Now, this is the most interesting part of the code where we apply the formula to column:



' Applying the formula to the 2nd row after the actual column count in the "Data" worksheet
Range(ColLtr(dataColCount + i) & "2").Formula = "=" & Replace(wsConfig.Range("C" & (i + 1)).Value, "", """")

Here, the “Range.Formula” property is used. If the cell contains a constant, this property returns the constant. If the cell is empty, this property returns an empty string. If the cell contains a formula, the Formula property returns the formula as a string in the same format that would be displayed in the formula bar (including the equal sign (=)).


So, to set formula for this cell, we prefix the formula value which is picked from the “Config” by “=”. Also note that double quotes in the actual formula has to be escaped to preserve it. In case any change in formula is required, we just need to update the details on “Config” worksheet and the changes will reflect automatically with the next run.


The format, if any, is then applied to the cell. Again, because we are reading this format from “Config”, the double quotes have to be escaped.



' Apply the formatting (if specified)
If colFormat "" Then
' Replace any " in the format value with ""
colFormat = Replace(colFormat, """", """""")
Range(ColLtr(dataColCount + i) & "2").NumberFormat = colFormat
End If

The “Range.NumberFormat” property has been used for doing that. This property returns or sets a Variant value that represents the format code for the object. The format code is the same string as the Format Codes option in the Format Cells dialog box. Here are few more examples:



Worksheets("Sheet1").Range("B13").NumberFormat = "General" ' 35332
Worksheets("Sheet1").Rows(5).NumberFormat = "[$-409]m/d/yy h:mm AM/PM;@" ' 5/2/2014 12:00:00 AM
Worksheets("Sheet1").Columns("C"). _
NumberFormat = "$#,##0.00_);[Red]($#,##0.00)" ' USD 45,123,234.00

Finally, the whole range of the new columns have been selected (2nd row as the 1st one is just header) and applied to all the rows.



' Using Autofill to apply formula to all the records
copyRange = strCopyStart & "2:" & strCopyEnd & (dataRowCount)
Selection.AutoFill Destination:=Range(copyRange), Type:=xlFillDefault

I hope you have found this post useful. Although there are several other ways in VB to accomplish the same tasks, what I have tried here is to provide a working solution for a particular use case which can be generalised based on requirements. As some of you must have already noticed, I haven’t bothered to make this macro re-runnable. But that can be easily achieved; in my use case, I was refreshing the whole data from other workbook before running the macro.


References:

http://ift.tt/1ENF8Qb


The post Excel Macro: Evaluating Formulas Dynamically appeared first on ViralPatel.net.








via ViralPatel.net http://ift.tt/1ENF6YF

Getting Started With Yeoman (Introduction to Yeoman)

yeoman-logo

Yeoman is a Node module to automate your front-end project build process, so that all we as a developer only need to worry about is to code and test. Think of it as a Maven for your next JS based project. It does scaffolding of your project, manage your dependencies and then does the building. To perform these tasks, Yeoman is made up of three tools:



  • yo: For scaffolding the application. That means you don’t worry about creating all those directory structures, writing basic JS file to get a project up and running. It magically creates all directory as per industry best practice, along with executable code to get the application up.

  • bower: Managing all JS/CSS based dependencies. So next time when you need to include UI-Router in your angular JS application, instead of manually downloading the latest JS file, just update the bower config file and run bower install command.

  • grunt: Building the project to make it production ready. This may include running JSHint, Test Cases, Minifying your JS, CSS files, Uglifying JS files and many other plugin based features.


Let’s Get Started


Since Yeoman comes as a Node module, before we can install Yeoman make sure you have Node installed on your system. If not, it’s a good time to install Node as most of industries front-end framework are now available as a Node Module, and it’s really easy to install new modules once you have Node. To install Node, just go to http://nodejs.org/ and follow the Install instruction.


Back to Business


Assuming you now have Node and Node Package Manager (NPM) installed (NPM automatically gets installed along with Node), let’s install Yeoman. To do so use below command:



npm install -g yo

or if you don’t have sufficient permission, you may need to run it using sudo:



sudo npm install -g yo

SideNote: If you are behind a proxy, you might need to first configure npm



npm set config proxy http://ift.tt/1sxkaRC
npm set config https-proxy http://ift.tt/1sxkaRF

After installation, before you can scaffold the application we need to install Yeoman Generators. Yeoman scaffolds different types of application through different Generator (which again are distributed through npm). So for example, if you want to start a AngularJs application you will install generator-angular using npm. There are many Official and Community based generators available, or if you don’t find one which you need… you can create a Generator of your own.


Let’s create a simple AngularJs and Twitter Bootstrap based application


First, install Angular-Bootstrap Generator:



npm install -g generator-angular-bootstrap

You will see many GET and REDIRECT requests. On completion, you will see a message like below:



generator-angular-bootstrap@0.4.3 /usr/local/lib/node_modules/generator-angular-bootstrap
├── semver@2.3.1
├── bluebird@2.2.2
├── needle@0.7.2 (qs@0.6.6, iconv-lite@0.4.3)
└── yeoman-generator@0.17.1 (dargs@0.1.0, github-username@0.1.1, diff@1.0.8, class-extend@0.1.1, rimraf@2.2.8, text-table@0.2.0, chalk@0.4.0, mime@1.2.11, async@0.9.0, isbinaryfile@2.0.1, debug@1.0.3, nopt@3.0.1, grouped-queue@0.3.0, shelljs@0.3.0, mkdirp@0.5.0, glob@4.0.4, findup-sync@0.1.3, underscore.string@2.3.3, iconv-lite@0.2.11, download@0.1.18, file-utils@0.2.0, request@2.37.0, lodash@2.4.1, gruntfile-editor@0.1.1, cheerio@0.17.0, inquirer@0.5.1)

All Set! Create Yeoman Project


Ok great, we have Yeoman! and we have its AngularJs-Bootstrap Generator! Let’s kick-start our project.

Create a project directory, name it ‘YoProject’.



mkdir YoProject
cd YoProject

In this new directory, just execute below “yo” command:



yo angular-bootstrap

During executing of above command, Yeoman will ask you couple of questions required to set up your project. I answered them as below:



[?] What version of angular would you like to use? 1.3.0-beta.15
[?] Which official angular modules would you need? animate, resource, route
[?] Any third-party component you might require? twbs/bootstrap (3.2.0), fortawesome/font-awesome (4.1.0), angular-ui/ui-router (0.2.10)
[?] What build system would I use? grunt
[?] Should I set up one of those HTML preprocessors for you? none
[?] Should I set up one of those JS preprocessors for you? none
[?] Should I set up one of those CSS preprocessors for you? sass
[?] Would you want me to support old versions of Internet Explorer (eg. before IE9)? no
[?] What's the base name of your project? YoProject

After answering all question, it will download required libraries and scaffold the application. Once done check the directory content, you will see that every thing you need to get started is already there.



aadi@ubuntu:~/eclipse_ws/YoProject$ tree .
.
+-- app
¦ +-- index.html
¦ +-- scripts
¦ ¦ +-- app.js
¦ ¦ +-- controllers
¦ ¦ ¦ +-- main.js
¦ ¦ +-- directives
¦ ¦ ¦ +-- sample.js
¦ ¦ +-- filters
¦ ¦ ¦ +-- sample.js
¦ ¦ +-- services
¦ ¦ +-- sample.js
¦ +-- styles
¦ ¦ +-- main.css
¦ +-- views
¦ +-- contact.html
¦ +-- features.html
¦ +-- home.html
¦ +-- partials
¦ +-- footer.html
¦ +-- header.html
+-- bower.json
+-- Gruntfile.js
+-- npm-debug.log
+-- package.json
+-- README.md

9 directories, 17 files

Once your application is created, install bower dependencies using:



bower install

These dependencies are downloaded under app/bower_components directory. Next, you can run below grunt command to include these dependencies in index.html file.



aadi@ubuntu:~/eclipse_ws/YoProject$ grunt bowerInstall
Running "bowerInstall:app" (bowerInstall) task
app/index.html modified.

Done, without errors.

This command updates the index.html file to include all the dependencies. After change, my index.html file has these new lines:



....
<!-- build:css styles/components.min.css -->
<!-- bower:css -->
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css" />
<link rel="stylesheet" href="bower_components/font-awesome/css/font-awesome.css" />
<!-- endbower -->
<!-- endbuild -->
....
<!-- build:js scripts/components.min.js -->
<!-- bower:js -->
<script src="bower_components/jquery/dist/jquery.js"></script>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-ui-router/release/angular-ui-router.js"></script>
<script src="bower_components/angular-animate/angular-animate.js"></script>
<script src="bower_components/angular-resource/angular-resource.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
<!-- endbower -->
....

You can now open up ‘app/index.html’ in browser and see application is up and running and you are all set to start making changes.

You may take a look at the code generated using above steps on GitHub.


To cut-short above process, we first installed Yeoman and its angular-bootstrap Generator. Then we scaffolded the application using ‘yo angular-bootstrap’, installed its dependencies using ‘bower install’ and then built is using ‘grunt bowerInstall’. Once familiar, this process becomes very easy to kickstart and maintain projects as compared to downloading individual dependencies and updating index.html each time.


There are many interesting and powerful generator available which can build and manage not only client side of application but also full application stack. For example, an application with Stack as ‘Twitter Bootstap – AngularJs – NodeJs – ExpressJS – MongooseJs – MongoDB’ can be generated using a popular community generator: generator-angular-fullstack


That’s it, hope that was helpful!


The post Getting Started With Yeoman (Introduction to Yeoman) appeared first on ViralPatel.net.








via ViralPatel.net http://ift.tt/1sxk9gy

Navigating Spring Security from thick Client to REST Webservice

When a Web Service is protected by Spring security, and we try to access that Web Service, we are presented with a login page to enter our credentials. After we provide our credentials, this information is stored as part of the session and sent back and forth between the browser and the server in a cookie.


However this is not the way it works with a non-browser, standalone client (like a mobile app) – for obvious reasons.


This note describes a thick client. User requires to login into the thick client. On successful authentication the user’s credentials are stored with the client. When the client accesses the Web Service, the web server responds to the client with the login page. Then the client presents the credentials, and submits it back to the web server.


Thus accessing a Web Service secured by Spring Security is a two-step process.


This note primarily describes the client. Some server-side config files are shown for information.


Follows are relevant code snippets for this scenario.


Comments are provided in bold.


On the Server side


Follows are some standard code snippets to secure a URL pattern with Spring Security with a username and password. Please refer to Spring Security documentation for detailed instructions and samples.


In web.xml



<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/mvc-dispatcher-servlet.xml,
/WEB-INF/spring-security.xml
</param-value>
</context-param>

……..
……..

<!-- Spring Security -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>


In spring-security.xml



<beans:beans xmlns="http://ift.tt/1gJEsAP;
xmlns:beans="http://ift.tt/GAfaRz;
xmlns:xsi="http://ift.tt/Atvu06;
xsi:schemaLocation="http://ift.tt/GArMu6

http://ift.tt/QEDs1e


http://ift.tt/1c8inpe


http://ift.tt/1igcnCk;

<!--Web Services with the pattern “/rest/vp/” will be secured -->
<http auto-config="true">
<intercept-url pattern="/rest/vp/**" access="ROLE_USER" />
</http>


<!—The username and password to be provided is “vpUser” and “vp123” -->
<authentication-manager>
<authentication-provider>
<user-service>
<user name="vpUser" password="vp123" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>

</beans:beans>

In mvc-dispatcher-servlet.xml



<beans xmlns="http://ift.tt/GAfaRz;
xmlns:context="http://ift.tt/GAfaRB;
xmlns:mvc="http://ift.tt/1gSwL9o; xmlns:xsi="http://ift.tt/Atvu06;
xsi:schemaLocation="

http://ift.tt/GArMu6


http://ift.tt/QEDs1e


http://ift.tt/GArMu7


http://ift.tt/QEDs1k


http://ift.tt/1bHqwjR


http://ift.tt/1gVzA7d;

<context:component-scan base-package="com.devices.middleware.webservice" />

<mvc:annotation-driven />

</beans>

On the Mobile Client side



// This is the object that we will populate from the JSON object
//returned by the Web Service
List<AlarmBean> alarmBeanList = new ArrayList<AlarmBean>();


// The username and password authenticated to the client, and required for
//the Web Service
//String urlParameters=
// "j_username="+userBean.getUsername()+"&j_password="+userBean.getPassword();
String urlParameters="j_username="+”vpUser” +"&j_password="+”vp123”;


// When Spring Security presents the login page, that page gets submitted to this link.
// i.e. - /j_spring_security_check
String strSpringAuthURL = "http://hostname/j_spring_security_check";



//This is the REST Web Service to be invoked
String strWebSvc = "http://hostname/rest/vp/alarm/11";


try {

// Create the URL object with the Web Service url
URL url = new URL(strWebSvc);

System.out.println("strWebSvc "+strWebSvc);

// Invoke the URL
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();

conn.setDoOutput(true);
conn.setDoInput(true);

conn.setInstanceFollowRedirects(false);
// ************* IMP *************
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
conn.setUseCaches (false);




//HTTP Response codes are
// 200 is OK
// 302 is Redirect
// When the secured Web Service is requested, the web server directs
// to the login page and sends a 302 Response code

if (conn.getResponseCode() == 302) {


System.out.println(" Response code is " + conn.getResponseCode());

String newUrl = conn.getHeaderField("Location");

// Get the cookie. It has the value of the original Web Service URL.
//In a browser scenario, after successful authentication, it would’ve
//automatically re-directed to the WS URL
String cookies = conn.getHeaderField("Set-Cookie");



//conn = (HttpURLConnection) new URL(strSpringAuthURL +
// ";jsessionid=" + J_SESSION_ID).openConnection();
conn = (HttpURLConnection) new URL(strSpringAuthURL).openConnection();
//Pass on the cookie
conn.setRequestProperty("Cookie", cookies);
conn.setDoOutput(true);
conn.setDoInput(true);

conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("POST");
DataOutputStream wr1 = new DataOutputStream(conn.getOutputStream ());
//Pass on the credentials
wr1.writeBytes(urlParameters);
wr1.flush();
wr1.close();

//System.out.println("Redirect to URL : " + strSpringAuthURL
// + ";jsessionid=" + J_SESSION_ID);
System.out.println("Redirected to URL : " + strSpringAuthURL );
System.out.println("Response code from Spring Auth URL is " +
conn.getResponseCode());

//Get the Web Service URL from the http header
String strOrigWSUrl = conn.getHeaderField("Location");

String cookies1 = conn.getHeaderField("Set-Cookie");

//conn = (HttpURLConnection) new URL(strOrigWSUrl +
// ";jsessionid=" + J_SESSION_ID).openConnection();

// Connection is made to the original Web Service URL that we want
conn = (HttpURLConnection) new URL(strOrigWSUrl).openConnection();

// ************* IMP *************
// The cookies that we received after authentication is passed here again.
conn.setRequestProperty("Cookie", cookies1);

conn.setDoOutput(true);
conn.setDoInput(true);

conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
conn.setUseCaches (false);


System.out.println("Redirect to URL strOrigWSUrl : " + strOrigWSUrl);
// We get a 200 Response code now
System.out.println(" Response code 555 is " + conn.getResponseCode());

} //end-if for the condition where we checked if the Response code was 302

//if the response code was not 302 above at the “if” check for the response code,
//and was 200 (assumed, not checked here),
//code would’ve continued here-forward

// Reading the JSON output returned by the Web Service
// And populating the AlarmBean object
BufferedReader br = new BufferedReader(
new InputStreamReader((conn.getInputStream())));
String line;
while ((line = br.readLine()) != null) {
JSONArray jsa = new JSONArray(line);

for (int i = 0; i < jsa.length(); i++) {
JSONObject jo = (JSONObject) jsa.get(i);

AlarmBean alarmBean = new AlarmBean(jo
.getInt("alarmId"), jo.getString("timestamp"),
jo.getString("duration"), jo
.getString("meterName"), jo
.getString("alarmType"), jo
.getString("status"), jo
.getInt("dcId"), jo
.getInt("count"), jo
.getString("deviceId"), jo
.getInt("buildingId"), jo
.getBoolean("disabled"), jo
.getString("location"), jo
.getString("dc"), jo
.getString("buildingName"), jo
.getInt("acknowledgedBy"), jo
.getString("ackUserName"), jo
.getString("acknowledgedOn"), jo
.getString("thresholdValue"), jo
.getString("actualValue"));
alarmBeanList.add(alarmBean);

}


The post Navigating Spring Security from thick Client to REST Webservice appeared first on ViralPatel.net.








via ViralPatel.net http://ift.tt/1gWwD7N

HTML5 DataList Example

HTML5 Datalist is a new html tag shipped with HTML5 specification. HTML5 Datalist can be used to create a simple poor man’s Autocomplete feature for a webpage.


In this tutorial we will go through the basics of HTML5 Datalist tag and check some quick examples of autocomplete.


Introduction to HTML5 Datalist tag


As part of HTML5 specification a new tag <datalist> has been introduced. Using this tag, we can define a list of data which then can be used as list for an input box. We can create a simple Autocomplete feature using this tag.


html5-datalist-example


Consider a textbox to take country name input from user.


Syntax:



<input type="text" list="countries" name="mycountry" />

See how we used attribute list and pass a list of countries called ‘countries’. We can define this list of countries using datalist tag.



<datalist id="countries">
<option value="India">India</option>
<option value="United States">United States</option>
<option value="United Kingdom">United Kingdom</option>
<option value="Germany">Germany</option>
<option value="France">France</option>
</datalist>

So we created a list of countries using <datalist> tag. The id of datalist tag must match with the list attribute of the input box.


Demo


Below is the demo. Enter some text in the Country textbox and see how an autocomplete list appears below it.



Browser Compatibility


Not every browser out there supports html5 datalist for now. So far IE 10 and above, Firefox, Chrome and Opera 19 above supports html5 datalist tag. Safari doesn’t support datalist yet :(



















ChromeFirefox (Gecko)Internet ExplorerOperaSafari
3126.010.019.0

This might change in future. Check the latest compatibility matrix for HTML5 Datalist here http://ift.tt/V2Oe3G.


Backward Compatibility for HTML5 Datalist tag


As seen in above compatibility table, not all browser supports html5 datalist tag. If you are using datalist, the older browser will simply ignores the datalist tag and renders rest of the webpage. The textbox which is linked to datalist will remain just a textbox. No autocomplete will be added. Internet explorer 9 and below has unique way of parsing datalist. If you try to check above example in IE 9 or below you will see all the option values are simply printed on the page. To avoid this we can wrap the options in datalist tag with a select tag. For example:



<datalist id="countries">
<select>
<option value="India">India</option>
<option value="United States">United States</option>
<option value="United Kingdom">United Kingdom</option>
<option value="Germany">Germany</option>
<option value="France">France</option>
</select>
</datalist>

This can give user option to select from the list if autocomplete is not available. Check below screenshot.


html5-datalist-backward-compatibility


Here we simple let user enter the country name or they can select from the country list box. This way users have an option to select from the list if they want to.


This can be simply achieve by adding a select tag inside datalist and make it as if it’s a select box.


Demo:



Here we simply wrapped all options within select tag. The name of select tag must be same as that of textbox. So when the form is submitted the appropriate value is passed to server-side code.


This is crud way of doing backward compatibility. If you don’t want to add more javascripts to your page, you can use this simple technique.


There is a better way of adding datalist compatibility to browsers that aren’t yet supporting this feature. We call it Polyfills. It is a way to fallback functionality to older browsers.


Chris Coyier has written a nice library that polyfills the datalist capabilities into older/non-supportive browsers.


All we need to do is to check if our browser supports datalist of not. If not then simply includes the polyfill js library. Check out below example.


We use Modernizr to identify if browser supports html5 datalist, if not then we simply includes the polyfill javascript for datalist by Chris Coyier.



<!DOCTYPE html>
<html>
<head>
<script src="http://ift.tt/1bLNnMy;

<script>

// Safari reports success of list attribute, so doing ghetto detection instead
yepnope({
test : (!Modernizr.input.list || (parseInt($.browser.version) > 400)),
yep : [
'http://ift.tt/1kB95v4',
'http://ift.tt/1bLNpnP'
]
});
</script>
</head>
<body>
<input type="text" list="countries" name="mycountry" />

<datalist id="countries">
<option value="India">India</option>
<option value="United States">United States</option>
<option value="United Kingdom">United Kingdom</option>
<option value="Germany">Germany</option>
<option value="France">France</option>
</datalist>
</body>
</html>

Online Demo


View Demo


Download Source Code


html5-datalist.zip (5.4KB)


The post HTML5 DataList Example appeared first on ViralPatel.net.








via ViralPatel.net http://ift.tt/1kB961U

Auditing DML changes in Oracle

auditing sql in oracleWe are often faced with a situation when every DML change (Inserts/Updates/Deletes) made in Oracle/SQL tables must be audited. Banking Softwares and other similar applications have a strict requirement to maintain the audit trail of every single change made to the database.


The DML changes must be audited irrespective of whether it was made from the Front End, during a release, or directly by a production support person while serving a production ticket. Ever wondered how an audit trail of such large numbers tables in your database can be created. Especially when your application is ever-changing with new columns getting added, dropped or modified often.


Triggers in oracle often come handy when fulfilling audit requirements for your database. An audit trigger can be created on the table which will compare the old and new values of all the columns and in case of a difference will log the old record into an audit table. The audit table will have a similar structure to the main table with 3 additional columns AUDIT_BY, AUDIT_AT and AUDIT_ACTION.


Triggers will ensure that the audit trail is maintained irrespective of from where the database change was initiated. However creating such large number of audit tables and triggers manually can be a huge effort. In this article I will demonstrate how easily we can create audit tables and triggers in oracle for database of any size very easily and with very less effort.


Step 1 – Create some tables


Create some sample tables for which you would like to maintain the audit trail.



CREATE TABLE EMPLOYEE
(
EID NUMBER,
ENAME VARCHAR2 (40)
);

CREATE TABLE DEPARTMENT
(
DID NUMBER,
DNAME VARCHAR2 (40)
);

CREATE TABLE SALARY
(
EID NUMBER,
SALARY NUMBER
);

Step 2 – Create an exclude table


There will be always some tables which we would like to exclude from the audit. For example if the table is very huge, contains blob or images, or if the table is rarely modified we might not want to audit it. The exclude table will contain a list of such table which we would like to exclude from the audit.



CREATE TABLE EXCLUDE_FROM_AUDIT
(
TNAME VARCHAR2 (30) NOT NULL
);

In our example let us assume that we want to exclude the department table from the audit. We simply make an entry of this table in our exclude table.



INSERT INTO EXCLUDE_FROM_AUDIT (TNAME)
VALUES ('DEPARTMENT');

Step 3 – Create audit tables


Now comes the interesting part. We want to create audit tables that will hold the audit trail of all the tables in our database. This can be achieved with a simple procedure like below.



CREATE OR REPLACE PROCEDURE create_audit_tables (table_owner VARCHAR2)
IS
CURSOR c_tables (
table_owner VARCHAR2)
IS
SELECT ot.owner AS owner, ot.table_name AS table_name
FROM all_tables ot
WHERE ot.owner = table_owner
AND ot.table_name NOT LIKE 'AUDIT_%'
AND ot.table_name <> 'EXCLUDE_FROM_AUDIT'
AND NOT EXISTS
(SELECT 1
FROM exclude_from_audit efa
WHERE ot.table_name = efa.tname)
AND NOT EXISTS
(SELECT 1
FROM all_tables at
WHERE at.table_name = 'AUDIT_'||ot.table_name);

v_sql VARCHAR2 (8000);
v_count NUMBER := 0;
v_aud VARCHAR2 (30);
BEGIN
FOR r_table IN c_tables (table_owner)
LOOP
BEGIN
v_aud := 'AUDIT_'||r_table.table_name;
v_sql :=
'create table '
|| v_aud
|| ' as select * from '
|| r_table.owner
|| '.'
|| r_table.table_name
|| ' where 0 = 1';


DBMS_OUTPUT.put_line ('Info: ' || v_sql);

EXECUTE IMMEDIATE v_sql;

v_sql :=
'alter table '
|| v_aud
|| ' add ( AUDIT_ACTION char(1), AUDIT_BY varchar2(50), AUDIT_AT TIMESTAMP)';

DBMS_OUTPUT.put_line ('Info: ' || v_sql);

EXECUTE IMMEDIATE v_sql;

v_count := c_tables%ROWCOUNT;
EXCEPTION
WHEN OTHERS
THEN
DBMS_OUTPUT.put_line (
'ERR: Failed to create table '
|| v_aud
|| ' due to '
|| SQLERRM);
END;
END LOOP;

IF v_count = 0
THEN
DBMS_OUTPUT.put_line ('Info: No audit tables created');
ELSE
DBMS_OUTPUT.put_line ('Info: ' || v_count || ' audit tables created.');
END IF;
END;
/

After the above procedure is created execute it by passing the schema name (owner) of the schema where your main tables were created.



execute create_audit_tables('OWNER');

This will create audit tables corresponding to all main tables and with the additional columns like audit_on,audit_by and audit_action. The tables in the exclude table will be excluded.


Step 4 – Create audit triggers


I will first create a small helper function that will give me a comma separated list of columns of a given table (with a prefix if required)



create or replace FUNCTION get_columns_for_table (
table_owner VARCHAR2,
t_name VARCHAR2,
prefix VARCHAR2
) RETURN CLOB
IS
v_text CLOB;
BEGIN
FOR getrec IN (SELECT column_name
FROM all_tab_columns
WHERE table_name = t_name
AND owner = table_owner
AND data_type<>'BLOB')
LOOP
v_text := v_text
|| ','
|| prefix
|| getrec.column_name
|| CHR (10)
|| ' ';
END LOOP;

RETURN ltrim(v_text,',');
END;

Next create a helper function that will give us a comparison between the columns in case of table updates



create or replace function get_column_comparasion (
table_owner VARCHAR2,
t_name VARCHAR2
) RETURN CLOB
IS
v_text CLOB;
BEGIN
FOR getrec IN (SELECT column_name
FROM all_tab_columns
WHERE table_name = t_name
AND owner = table_owner
AND data_type<>'BLOB')
LOOP
v_text := v_text
|| ' or( (:old.'
|| getrec.column_name
|| ' <> :new.'
|| getrec.column_name
|| ') or (:old.'
|| getrec.column_name
|| ' IS NULL and :new.'
|| getrec.column_name
|| ' IS NOT NULL) or (:old.'
|| getrec.column_name
|| ' IS NOT NULL and :new.'
|| getrec.column_name
|| ' IS NULL))'
|| CHR (10)
|| ' ';
END LOOP;

v_text := LTRIM (v_text, ' or');
RETURN v_text;
END;

Next create the procedure that will create our audit triggers



CREATE OR REPLACE PROCEDURE create_audit_triggers (table_owner VARCHAR2)
IS
CURSOR c_tab_inc (
table_owner VARCHAR2)
IS
SELECT ot.owner AS owner, ot.table_name AS table_name
FROM all_tables ot
WHERE ot.owner = 'T288655'
AND ot.table_name NOT LIKE 'AUDIT_%'
AND ot.table_name <> 'EXCLUDE_FROM_AUDIT'
AND ot.table_name NOT IN (SELECT tname FROM exclude_from_audit);

v_query VARCHAR2 (32767);
v_count NUMBER := 0;
BEGIN
FOR r_tab_inc IN c_tab_inc (table_owner)
LOOP
BEGIN
-- Breaks down sql into 3 pieces. It's assumed each piece is not bigger then 32676 bytes
v_query :=
'CREATE OR REPLACE TRIGGER TRIGGER_'
|| r_tab_inc.table_name
|| ' AFTER INSERT OR UPDATE OR DELETE ON '
|| r_tab_inc.owner
|| '.'
|| r_tab_inc.table_name
|| ' FOR EACH ROW'
|| CHR (10)
|| 'DECLARE '
|| CHR (10)
|| ' v_user varchar2(30):=null;'
|| CHR (10)
|| ' v_action varchar2(15);'
|| CHR (10)
|| 'BEGIN'
|| CHR (10)
|| ' SELECT SYS_CONTEXT (''USERENV'', ''session_user'') session_user'
|| CHR (10)
|| ' INTO v_user'
|| CHR (10)
|| ' FROM DUAL;'
|| CHR (10)
|| ' if inserting then '
|| CHR (10)
|| ' v_action:=''INSERT'';'
|| CHR (10)
|| ' insert into AUDIT_'
|| r_tab_inc.table_name
|| '('
|| get_columns_for_table (r_tab_inc.owner,
r_tab_inc.table_name,
NULL)
|| ' ,AUDIT_ACTION,AUDIT_BY,AUDIT_AT)'
|| CHR (10)
|| ' values ('
|| get_columns_for_table (r_tab_inc.owner,
r_tab_inc.table_name,
':new.')
|| ' ,''I'',v_user,SYSDATE);'
|| CHR (10)
|| ' elsif updating then '
|| CHR (10)
|| ' v_action:=''UPDATE'';'
|| CHR (10)
|| ' if '
|| get_column_comparasion (r_tab_inc.owner, r_tab_inc.table_name)
|| ' then '
|| CHR (10)
|| ' insert into AUDIT_'
|| r_tab_inc.table_name
|| '('
|| get_columns_for_table (r_tab_inc.owner,
r_tab_inc.table_name,
NULL)
|| ' ,AUDIT_ACTION,AUDIT_BY,AUDIT_AT)'
|| CHR (10)
|| ' values ('
|| get_columns_for_table (r_tab_inc.owner,
r_tab_inc.table_name,
':new.')
|| ' ,''U'',v_user,SYSDATE);'
|| CHR (10)
|| ' end if;'
|| ' elsif deleting then'
|| CHR (10)
|| ' v_action:=''DELETING'';'
|| CHR (10)
|| ' insert into AUDIT_'
|| r_tab_inc.table_name
|| '('
|| get_columns_for_table (r_tab_inc.owner,
r_tab_inc.table_name,
NULL)
|| ' ,AUDIT_ACTION,AUDIT_BY,AUDIT_AT)'
|| CHR (10)
|| ' values ('
|| get_columns_for_table (r_tab_inc.owner,
r_tab_inc.table_name,
':old.')
|| ' ,''D'',v_user,SYSDATE);'
|| CHR (10)
|| ' end if;'
|| CHR (10)
|| 'END;';

DBMS_OUTPUT.put_line (
'CREATE TRIGGER '
|| REPLACE (r_tab_inc.table_name, 'TABLE_', 'TRIGGER_'));

DBMS_OUTPUT.put_line (v_query);

EXECUTE IMMEDIATE v_query;

DBMS_OUTPUT.put_line (
'Audit trigger '
|| REPLACE (r_tab_inc.table_name, 'TABLE_', 'TRIGGER_')
|| ' created.');

v_count := c_tab_inc%ROWCOUNT;
EXCEPTION
WHEN OTHERS
THEN
DBMS_OUTPUT.put_line (
'Failed to create audit trigger for '
|| r_tab_inc.owner
|| '.'
|| r_tab_inc.table_name
|| ' due to '
|| SQLERRM);
END;
END LOOP;

IF v_count = 0
THEN
DBMS_OUTPUT.put_line ('No audit triggers created');
END IF;
END;

Finally execute the procedure. This will create all the audit triggers.



EXECUTE CREATE_AUDIT_TRIGGERS('OWNER');

Step 5 – Test the auditing


Now execute a few DML scripts and notice that all changes made to our main tables get audited with appropriate action in the audit tables. Changes to department table will not be audited as we have excluded it.



insert into employee values(1,'John');

insert into employee values(2,'Smith');

insert into department values(1,'Sales');

insert into department values(2,'Purchase');

insert into salary values(1,5000);

insert into salary values(2,10000);

delete from employee where eid = 1;

update employee set ename = 'Raj' where eid = 2;

All tables will have a primary key which never changes. Using the primary key we can query our audit tables and get the entire audit trail when required. Instead of session user we can also set the user from the middle tier in the SYS_CONTEXT.


Here I demonstrated how with few simple procedures you can fulfil the audit requirement of your application. The concepts and scripts here are very small but quite powerful and can be used to create audit trail for any number of tables in your database.


The post Auditing DML changes in Oracle appeared first on ViralPatel.net.








via ViralPatel.net http://ift.tt/1e0ZXah

Java 8 Lambda Expressions Tutorial with Examples

Java is a first-class object-oriented language. With the exception of primitive data types, everything in Java is an object. Even an array is an Object. Every class creates instances that are objects. There is no way of defining just a function / method which stays in Java all by itself. There is no way of passing a method as argument or returning a method body for that instance.


Since the old days of Swing, we always had written anonymous classes if we wanted to pass some functionality to any method. For example the old event listener code used to look like:



someObject.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {

//Event listener implementation goes here...

}
});

Here we wanted to add some custom code to Mouse listener. We defined an anonymous inner class MouseAdapter and created its object. This way we passed some functionality to addMouseListener method.


In short, it is not easy to pass plain methods / functionalities in Java that can be passed as arguments. Due to this limitation Java 8 adds a brand new language level feature called Lambda Expressions.


Why Java needs Lambda Expressions?


Since its beginning, the Java language hasn’t evolved much if you ignore some of the features like Annotations, Generics etc. Mostly during its life Java always remained Object first language. After working with functional language like JavaScript, it becomes clear to one how Java enforce its strict object-oriented nature and strict typed on the source code. You see Functions are not important for Java. On their own they cannot live in Java world.


xkcd-functionalFunctions are first class citizens in a functional programming language. They exists on their own. You can assign them to a variable and pass them as arguments to other functions. JavaScript is one of the best example of an FP language. There are some good articles here and here that clearly describes the benefits of JavaScript as a functional language. A functional language provides very powerful feature called Closure that has quite a few advantages over traditional way of writing applications. A closure is a function or reference to a function together with a referencing environment — a table storing a reference to each of the non-local variables of that function. Closest thing that Java can provide to Closure is Lambda expressions. There is significant difference between a Closure and Lambda expression, but at least Lambda expression provides a good alternative to Closure.


In his quite sarcastic and funny blog post, Steve Yegge describes how Java world is strictly about Nouns. If you haven’t read his blog, go first read it. It’s funny, its interesting and it describe the exact reason why Java had to add Lambda expressions.


Lambda expression adds that missing link of functional programming to Java. Lambda expression let us have functions as first class citizen. Although this is not 100% correct, we will shortly see how Lambda expressions are not closures but they are as much close as we can get to closures. In languages that support first class functions, the type of the lambda expression would be a function; but in Java, the lambda expressions are represented as objects, and so they must be bound to a particular object type known as a functional interface. We will see in detail what Functional interface are.


Here is a nicely written article by Mario Fusco on Why we need Lambda Expression in Java. He explains why a modern programming language must have feature like closures.


Introduction to Lambda Expressions


lambda expressions in javaA lambda expression is an anonymous function (not 100% true for Java but lets assume it for time being). Simply put, it’s a method without a declaration, i.e., access modifier, return value declaration, and name.


It’s a shorthand that allows you to write a method in the same place you are going to use it. Especially useful in places where a method is being used only once, and the method definition is short. It saves you the effort of declaring and writing a separate method to the containing class.


Lambda expressions in Java is usual written using syntax (argument) -> (body). For example:



(arg1, arg2...) -> { body }

(type1 arg1, type2 arg2...) -> { body }

Following are some examples of Lambda expressions.



(int a, int b) -> { return a + b; }

() -> System.out.println("Hello World");

(String s) -> { System.out.println(s); }

() -> 42

() -> { return 3.1415 };


Structure of Lambda Expressions


Let’s check the structure of lambda expressions.



  • A lambda expression can have zero, one or more parameters.

  • The type of the parameters can be explicitly declared or it can be inferred from the context. e.g. (int a) is same as just (a)

  • Parameters are enclosed in parentheses and separated by commas. e.g. (a, b) or (int a, int b) or (String a, int b, float c)

  • Empty parentheses are used to represent an empty set of parameters. e.g. () -> 42

  • When there is a single parameter, if its type is inferred, it is not mandatory to use parentheses. e.g. a -> return a*a

  • The body of the lambda expressions can contain zero, one or more statements.

  • If body of lambda expression has single statement curly brackets are not mandatory and the return type of the anonymous function is the same as that of the body expression.

  • When there is more than one statement in body than these must be enclosed in curly brackets (a code block) and the return type of the anonymous function is the same as the type of the value returned within the code block, or void if nothing is returned.


What are Functional Interfaces


In Java, a Marker interface is an interface with no methods or fields declaration. In simple words, marker interface is an empty interface. Similarly, a Functional Interface is an interface with just one abstract method declared in it.


java.lang.Runnable is an example of a Functional Interface. There is only one method void run() declared in Runnable interface. Similarly ActionListener interface is also a Functional Interface. We use Anonymous inner classes to instantiate objects of functional interface. With Lambda expressions, this can be simplified.


Each lambda expression can be implicitly assigned to one of the interface called Functional interface. For example we can create Runnable interface’s reference from lambda expression like below:



Runnable r = () -> System.out.println("hello world");

This type of conversion is automatically taken care by compiler when we dont specify the functional interface. For example:



new Thread(
() -> System.out.println("hello world")
).start();

So in above code, compiler automatically deduced that lambda expression can be casted to Runnable interface from Thread class’s constructor signature public Thread(Runnable r) { }.


Few examples of lambda expressions and their functional interface:



Consumer<Integer> c = (int x) -> { System.out.println(x) };

BiConsumer<Integer, String> b = (Integer x, String y) -> System.out.println(x + " : " + y);

Predicate<String> p = (String s) -> { s == null };

@FunctionalInterface is a new interface added in Java 8 to indicate that an interface type declaration is intended to be a functional interface as defined by the Java Language Specification. Java 8 also declared number of Functional Interfaces that can be used by Lambda expressions. @FunctionalInterface can be used for compiler level errors when the interface you have annotated is not a valid Functional Interface.


Following is an example of custom defined Functional interface.



@FunctionalInterface
public interface WorkerInterface {

public void doSomeWork();

}

As its definition says, Functional Interfaces can have only one abstract method. If you try to add one more abstract method in it, it throws compile time error. For example:



@FunctionalInterface
public interface WorkerInterface {

public void doSomeWork();

public void doSomeMoreWork();

}

Error:



Unexpected @FunctionalInterface annotation
@FunctionalInterface ^ WorkerInterface is not a functional interface multiple
non-overriding abstract methods found in interface WorkerInterface 1 error

Once the Functional interface is defined, we can simply use it in our API and take advantage of Lambda expressions. For example:



//define a functional interface
@FunctionalInterface
public interface WorkerInterface {

public void doSomeWork();

}


public class WorkerInterfaceTest {

public static void execute(WorkerInterface worker) {
worker.doSomeWork();
}

public static void main(String [] args) {

//invoke doSomeWork using Annonymous class
execute(new WorkerInterface() {
@Override
public void doSomeWork() {
System.out.println("Worker invoked using Anonymous class");
}
});

//invoke doSomeWork using Lambda expression
execute( () -> System.out.println("Worker invoked using Lambda expression") );
}

}

Output:



Worker invoked using Anonymous class
Worker invoked using Lambda expression

Here we created our own Functional interface and used to with lambda expressions. execute() method can now take lambda expressions as argument.


Examples of Lambda Expression


Best way of learning about Lambda expressions is by examples. Following are few examples:


Thread can be initialized like following:



//Old way:
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Hello from thread");
}
}).start();

//New way:
new Thread(
() -> System.out.println("Hello from thread")
).start();

The event handling can be done with Java 8 using lambda expression. Following code we show both old and new way of adding ActionListener to a UI component.



//Old way:
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("The button was clicked using old fashion code!");
}
});

//New way:
button.addActionListener( (e) -> {
System.out.println("The button was clicked. From lambda expressions !");
});

Simple code to print all elements of given array. Note there is one more way of using lambda expression. In below example we use the usual way of creating lambda expression using arrow syntax and also we used a brand new double colon (::) operator that Java 8 has to convert a normal method into lambda expression.



//Old way:
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
for(Integer n: list) {
System.out.println(n);
}

//New way:
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
list.forEach(n -> System.out.println(n));


//or we can use :: double colon operator in Java 8
list.forEach(System.out::println);

In this example we use Predicate functional interface to create a test and print the elements that pass the test. This way you can provide the logic using lambda expression and do something based on it.



import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class Main {

public static void main(String [] a) {

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7);

System.out.println("Print all numbers:");
evaluate(list, (n)->true);

System.out.println("Print no numbers:");
evaluate(list, (n)->false);

System.out.println("Print even numbers:");
evaluate(list, (n)-> n%2 == 0 );

System.out.println("Print odd numbers:");
evaluate(list, (n)-> n%2 == 1 );

System.out.println("Print numbers greater than 5:");
evaluate(list, (n)-> n > 5 );

}

public static void evaluate(List<Integer> list, Predicate<Integer> predicate) {
for(Integer n: list) {
if(predicate.test(n)) {
System.out.println(n + " ");
}
}
}

}

Output:



Print all numbers: 1 2 3 4 5 6 7
Print no numbers:
Print even numbers: 2 4 6
Print odd numbers: 1 3 5 7
Print numbers greater than 5: 6 7

Some wizardry using Lambda expression to print square of each element of a list. Notice we used .stream() method to convert regular list into a steam. Java 8 added some awesome Stream APIs. java.util.stream.Stream interface comes with tons of useful methods which can be used along with lambda expression to do some voodoo. We passed a lambda expression x -> x*x to map() method which applies this to all elements of the stream. After that we use forEach to print the all elements of list.



//Old way:
List<Integer> list = Arrays.asList(1,2,3,4,5,6,7);
for(Integer n : list) {
int x = n * n;
System.out.println(x);
}

//New way:
List<Integer> list = Arrays.asList(1,2,3,4,5,6,7);
list.stream().map((x) -> x*x).forEach(System.out::println);

Given a list, sum the square of each element from this list. See how Lambda expression can be used to achieve this in a single statement. This is also a starters example on MapReduce. We used map() to square each element and then reduce() to reduce all elements into single number.



//Old way:
List<Integer> list = Arrays.asList(1,2,3,4,5,6,7);
int sum = 0;
for(Integer n : list) {
int x = n * n;
sum = sum + x;
}
System.out.println(sum);

//New way:
List<Integer> list = Arrays.asList(1,2,3,4,5,6,7);
int sum = list.stream().map(x -> x*x).reduce((x,y) -> x + y).get();
System.out.println(sum);

Difference between Lambda Expression and Anonymous class


One key difference between using Anonymous class and Lambda expression is the use of this keyword. For anonymous class ‘this’ keyword resolves to anonymous class, whereas for lambda expression ‘this’ keyword resolves to enclosing class where lambda is written.


Another difference between lambda expression and anonymous class is in the way these two are compiled. Java compiler compiles lambda expressions and convert them into private method of the class. It uses invokedynamic instruction that was added in Java 7 to bind this method dynamically. Tal Weiss has written a good blog on how Java compiles the lambda expressions into bytecode.


That’s All Folks


Mark Reinhold, Oracle’s Chief Architect, describes Lambda expressions as the single largest upgrade to the programming model ever — larger even than generics. And why not. It gives Java programmer the edge that it lacked compared to other functional programming languages. Along with other features like Virtual extension methods, Lambda expression can be utilized to write some really good code.


I hope this article gave a glimpse of what’s in the store for us in Java 8. Ciao :)


Image courtesy:



The post Java 8 Lambda Expressions Tutorial with Examples appeared first on ViralPatel.net.








via ViralPatel.net http://ift.tt/1b7jF4l

Java 8 Default Methods Tutorial

Java 8 Default MethodsInterfaces in Java always contained method declaration not their definitions (method body). There was no way of defining method body / definition in interfaces. This is because historically Java didn’t allow multiple inheritance of classes. It allowed multiple inheritance of interfaces as interface were nothing but method declaration. This solves the problem of ambiguity in multiple inheritance. Since Java 8 it is now possible to add method bodies in interfaces.


Java 8 has a new feature called Default Methods. It is now possible to add method bodies into interfaces!



public interface Math {

int add(int a, int b);

default int multiply(int a, int b) {
return a * b;
}
}

In above Math interface we added a method multiply with actual method body.


Why we need Default Methods?


Why would one want to add methods into Interfaces? We’ll it is because interfaces are too tightly coupled with their implementation classes. i.e. it is not possible to add a method in interface without breaking the implementor class. Once you add a method in interface, all its implemented classes must declare method body of this new method.


Since Java 8, things started getting ugly. A new feature Lambda was introduce which is cool. However it is not possible to use this feature in existing Java libraries such as java.util package. If you add a single method in interface List, it breaks everything. You need to add its implementation in every class that implements List interface. Imagine in real world how many custom classes would change.


So for backward compatibility, Java 8 cleverly added Default Methods.


Virtual Extension Methods


It added a new concept Virtual extension methods, or as they are often called defender methods, can now be added to interfaces providing a default implementation of the declared behavior. So existing interfaces can be augmented without compromising backward compatibility by adding extension methods to the interface, whose declaration would contain instructions for finding the default implementation in the event that implementors do not provide a method body. A key characteristic of extension methods is that they are virtual methods just like other interface methods, but provide a default implementation in the event that the implementing class does not provide a method body.


Consider following example:



interface Person {
//adds a java 8 default method
default void sayHello() {
System.out.println("Hello there!");
}
}

class Sam implements Person {

}

public class Main {

public static void main(String [] args) {

Sam sam = new Sam();

//calling sayHello method calls the method
//defined in interface
sam.sayHello();
}
}

Output:



Hello there!

In above code we added a defender method sayHello() in Person interface. So it was ok for class Sam to avoid declaring this methods body.


What about Multiple Inheritance?


Adding method definitions in interfaces can add ambiguity in multiple inheritance. isn’t it? Well, it does. However Java 8 handle this issue at Compile type. Consider below example:



interface Person {
default void sayHello() {
System.out.println("Hello");
}
}

interface Male {
default void sayHello() {
System.out.println("Hi");
}
}

class Sam implements Person, Male {

}

In this example we have same defender method sayHello in both interfaces Person and Male. Class Sam implements these interfaces. So which version of sayHello will be inherited? We’ll if you try to compile this code in Java 8, it will give following error.




class Sam inherits unrelated defaults for sayHello() from types Person and Male class Sam implements Person, Male { ^ 1 error


So that solves multiple inheritance problem. You cannot implement multiple interfaces having same signature of Java 8 default methods (without overriding explicitly in child class).


We can solve the above problem by overriding sayHello method in class Sam.



interface Person {
default void sayHello() {
System.out.println("Hello");
}
}

interface Male {
default void sayHello() {
System.out.println("Hi");
}
}

class Sam implements Person, Male {

//override the sayHello to resolve ambiguity
void sayHello() {

}
}

It is also possible to explicitly call method from child class to parent interface. Consider in above example you want to call sayHello method from Male interface when Sam.sayHello is called. You can use super keyword to explicitly call the appropriate method.



class Sam implements Person, Male {

//override the sayHello to resolve ambiguity
void sayHello() {
Male.super.sayHello();
}
}

Difference between default methods and abstract class


Ok, so far it looks good. In Java 8 we can have concrete methods within interfaces.. right.. So how it is different from Abstract classes? Remember an abstract class is a class that can not be instantiated (i.e. objects can not be created of) and which may contain method bodies. Default method in Java 8 looks similar to Abstract class isn’t it?


We’ll its different actually. Abstract class can hold state of object. It can have constructors and member variables. Whereas interfaces with Java 8 default methods cannot hold state. It cannot have constructors and member variables. You should still use Abstract class whenever you think your class can have state or you need to do something in constructor. Default method should be used for backward compatibility. Whenever you want to add additional functionality in an existing legacy interface you can use default methods without breaking any existing implementor classes.


Also abstract classes cannot be root classes in Lambda expression. What?… I know that’s confusing, but Lambda expressions are the reason why virtual extension methods were introduced in Java 8. When a lambda expression is evaluated, the compiler can infers it into the interface where default method is added.


The post Java 8 Default Methods Tutorial appeared first on ViralPatel.net.








via ViralPatel.net http://ift.tt/KLvp5h

Microsoft 365 (Office) Insider Preview Build 17715.20000 (Version 2406) Released, Here is What’s New and Fixed

UPDATE: Microsoft 365 Insider (previously known as Office Insider) Preview build 17715.20000 (version 2406) is available for download and in...