Reading/Writing Files using FileChannel

Posted on

6db3a-download

There are multiple ways to reading/writing a file in Java. Usually, we used java.lang.IO package to read/write a file but as my last experience with copying a large file size (>256 MB ) into some other file location or on a network.

 

As we also tried to used java.lang.io package to get this job done but we were unable to copy the file in a Network location, there were performance issues.

http://stackoverflow.com/questions/1605332/java-nio-filechannel-versus-fileoutputstream-performance-usefulness

And finally, I got an alternative way to copy a file into a Network location  i.e FileChannel . its provide a better performance than InputStream/OutputStream.

Some interesting points about java.nio or FileChannel:-

  1. it’s a buffer-oriented, means- same Buffer is used to reading / writing so you can move back or forth in the Buffer as you need to.  usee flip() method to get the pointer to next position.
  2. It’s a non-blocking, i.e means a Thread request to reading data from Channel then only get what is currently available in a buffer, if data is not available then rather than blocking until data get available in buffer, Thread goes on and do something else in meantime. The same is true for non-blocking writing. A thread can request that some data be written to a channel, but not wait for it to be fully written. The thread can then go on and do something else in the mean time.
  3. Concurrent processing can be done in FileChannel which is safe for use.
  4. Channels can be read and written asynchronously.

Below example demonstrated how to write into a file using FileChannel.


 import java.io.File;
        import java.io.FileNotFoundException;
        import java.io.IOException;
        import java.io.RandomAccessFile;
        import java.nio.ByteBuffer;
        import java.nio.channels.FileChannel;
        import java.nio.channels.WritableByteChannel;
        
        /**
         * Created by kumajye on 10/01/2017.
         */
        public class FileChannelTest {
            // This is a Filer location where write operation to be done.
            private static final String FILER_LOCATION = "C:\\documents\\test";
            // This is a text message that to be written in filer location file.
            private static final String MESSAGE_WRITE_ON_FILER = "Operation has been committed.";
        
            public static void main(String[] args) throws FileNotFoundException {
                // Initialized the File and File Channel
                RandomAccessFile randomAccessFileOutputFile = null;
                FileChannel outputFileChannel = null;
                try {
                    // Create a random access file with 'rw' permission..
                    randomAccessFileOutputFile = new RandomAccessFile(FILER_LOCATION + File.separator + "readme.txt", "rw");
                    outputFileChannel = randomAccessFileOutputFile.getChannel();
                    //Read line of code one by one and converted it into byte array to write into FileChannel.
                    final byte[] bytes = (MESSAGE_WRITE_ON_FILER + System.lineSeparator()).getBytes();
                    // Defined a new buffer capacity.
                    ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
                    // Put byte array into butter array.
                    buffer.put(bytes);
                    // its flip the buffer and set the position to zero for next write operation.
                    buffer.flip();
                    /**
                     * Writes a sequence of bytes to this channel from the given buffer.
                     */
                    outputFileChannel.write(buffer);
                    System.out.println("File Write Operation is done!!");
        
                } catch (IOException ex) {
                    System.out.println("Oops Unable to proceed file write Operation due to ->" + ex.getMessage());
                } finally {
                    try {
                        outputFileChannel.close();
                        randomAccessFileOutputFile.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
        
                }
        
            }
        
        }


Advertisements

Difference between Association,Aggregation,Composition and Inheritance

Posted on

via Difference between Association,Aggregation,Composition and Inheritance

Building ReactJS Example with Event Handling

Posted on

Here is another simple example of ReactJS in which bunch of CommentBox components has been created and wrapped into a Board layer which is also a React Component and therefore events are binding to Save & Edit button under CommentBox component.

Set of comments text is initialized in parent Component i.e Board and each comment text is getting rendered into CommentBox Component by iteration.

Here is complete code:-

                <!DOCTYPE html>
        <html>

        <head>
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width">
            <title></title>
        </head>

        <body>
            <div id="content"></div>
            <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
            <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.js"></script>
            
            <script type="text/babel">

                class CommentBox extends React.Component{
                constructor(props){
                    super(props);
                    this.state = {
                    editable : false
                    };
                }

                save(event){
                    this.props.updateCommentText(this.refs.commentTxt.value,this.props.index);
                    this.setState({
                        editable:false
                    })
                }
                remove(){
                    this.props.removeCommentText(this.props.index);
                    
                }
                edit(){
                    this.setState({
                        editable:true
                    })
                }
                renderForm(){
                    return (
                    <div className="row">
                        <div><textArea ref="commentTxt" name="commentBox" defaultValue={this.props.children}></textArea></div>
                        <button type="button" className="btn btn-danger" onClick={this.save.bind(this)}>Save</button>
                    </div>
                    );
                }
                renderHtml(){  
                    return (
                        <div className="row">
                        <div>{this.props.children}</div>    
                        <button type="button" className="btn btn-danger" onClick={this.edit.bind(this)}>Edit</button>
                        <button type="button" className="btn btn-success" onClick={this.remove.bind(this)}>Remove</button>
                        </div>
                    );
                }

                render() {
                    if(this.state.editable){
                        return this.renderForm(this);
                    }else{
                        return this.renderHtml(this);
                    }
                }
                }

            class Board extends React.Component{
                constructor(props){
                    super(props);
                    this.state ={
                        comments:[
                            'Techical Comments',
                            'Wordpress Comments',
                            'Facebook Comments'
                        ]
                    }
                }
                updateComment(text,i){
                    console.log("Saving Comment..."+text+" index ["+i+"]")
                    var arr = this.state.comments;
                    arr[i] = text;
                    this.setState({comments:arr})
                }
                removeComment(i){
                    console.log("Removing Comment..." + "index ["+i+"]")
                    var arr = this.state.comments;
                    arr.splice(i,1);
                    console.log("After removing a record :"+arr)
                    this.setState({comments:arr});
                }    

                eachComment(text,i){
                    return (
                                <CommentBox key={i} index={i} updateCommentText={this.updateComment.bind(this)}  removeCommentText={this.removeComment.bind(this)}> {text}</CommentBox> 
                            );
                }

                render(){
                    return(
                        <div className="container-fluid">{
                        this.state.comments.map(this.eachComment.bind(this))
                        }
                        </div>
                    );
                }
            } 
            ReactDOM.render(
                <Board />
                , document.getElementById('content'))
            </script>
        </body>

        </html>

Building First ReactJS Example

Posted on Updated on

 

 

Below is sample example of ReactJS in which a counter variable is an increment or decrement by 1 on onClick event that is binding with a button.

Here is a complete example.

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title></title>
  </head>
  <body>
    <div id="content"></div>

    <script src="https://fb.me/react-0.14.7.js"></script>
    <script src="https://fb.me/react-dom-0.14.7.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.min.js"></script>
    
    
    <script type="text/babel">

        class CounterValue extends React.Component{
        constructor(props){
            super(props);
            this.state = {
            counter : 0
            };
        }

        onIncrementClickHandler() {
            this.setState({counter:this.state.counter +1})
        }

        onDecrementClickHandler() {
            if(this.state.counter == 0 ){
                return;
            }else{
             this.setState({counter:this.state.counter -1})
            }
        }
        render() {
            return (
            <div>
                <input type="button" onClick={this.onIncrementClickHandler.bind(this)} value="Increment"/>
                <input type="button" onClick={this.onDecrementClickHandler.bind(this)} value="Declement"/>
                <div>Counter value is  : {this.state.counter}</div>
                </div>
            );
        }
        }

      ReactDOM.render(<CounterValue />, document.getElementById('content'))
    </script>
  </body>
</html>

Command Design Pattern

Posted on Updated on

Command pattern is a behavioral design pattern in which an object is used to encapsulate all information needed to perform an action or trigger an event at a later time.

  1.  Decouple the caller and receiver call so the caller doesn’t know about receiver or receiver doesn’t know about a caller, they are communicating with Command layer.
  2. Allows requests to be encapsulated as objects, thereby allowing clients to be parametrized with different requests.
  3. delegates a request to a command object instead of implementing a particular request directly.

Key Points:-

Client – creates a ConcreteCommand object and sets its receiver.
Invoker – Asks the command to carry out the request;
Command – it is performing as “tokens” that are created by one client that knows what need to be done and passed to another client that has the resources for doing it.
Receiver –  knows how to perform the operations;

Below is snippet code for Command Design Pattern.

Command.Java – Here, Command decouples the object that invokes the operation from the one that knows how to perform it

package com.design.db;

public interface Command {
    Task submit();
}

DBSaveCommand.Java

package com.design.db;

public class DBSaveCommand implements Command {

    private final Object toBeObject;
    private final Class<?> persistCollection;
    private Receiver receiver = new DBProcessor();

    public DBSaveCommand(Class<?> persistCollection, Object object) {
        this.persistCollection = persistCollection;
        this.toBeObject = object;
    }

    @Override
    public Task submit() {
        try {
            this.receiver.save(this.persistCollection, this.toBeObject);
        } catch (Exception e) {
            return () -> e.getMessage();
        }
        return () -> new String("Save");
    }
}


DBRemoveCommand.Java

package com.design.db;

public class DBRemoveCommand implements Command {

    private final Object toBeObject;
    private final Class<?> persistCollection;
    private Receiver receiver = new DBProcessor();

    public DBRemoveCommand(Class<?> persistCollection, Object object) {
        this.persistCollection = persistCollection;
        this.toBeObject = object;
    }

    @Override
    public Task submit() {
        try {
            this.receiver.remove(this.persistCollection, this.toBeObject);
        } catch (Exception e) {
            return () -> e.getMessage();
        }
        return () -> new String("Delete");
    }
}


DBFetchByIdCommand.Java

package com.design.db;

public class DBFetchByIdCommand implements Command {

    private final Long toBeObject;
    private final Class<?> persistCollection;
    private Receiver receiver = new DBProcessor();

    public DBFetchByIdCommand(Class<?> persistCollection, Long object) {
        this.persistCollection = persistCollection;
        this.toBeObject = object;
    }

    @Override
    public Task submit() {
        try {
            return () -> this.receiver.fetchById(this.persistCollection, this.toBeObject);
        } catch (Exception e) {
            return () -> e.getMessage();
        }
    }
}

DBFetchAllCommand.Java

package com.design.db;

public class DBFetchAllCommand implements Command {
    private final Class<?> persistCollection;
    private Receiver receiver = new DBProcessor();

    public DBFetchAllCommand(Class<?> persistCollection) {
        this.persistCollection = persistCollection;
    }

    @Override
    public Task submit() {
        try {
            return () -> this.receiver.fetchAll(this.persistCollection);
        } catch (Exception e) {
            return () -> e.getMessage();
        }
    }
}

Receiver.Java

package com.design.db;

import java.util.Collection;

public interface Receiver {

    void save(Class<?> persistCollection, Object object);

    void remove(Class<?> persistCollection, Object object);

    Object fetchById(Class<?> persistCollection, Long id);

    Collection<?> fetchAll(Class<?> persistCollection);
}



DBRequestProcessor.Java – All the operation are perform here and only Command knows about the receiver and invokes the method of a receiver that is passed on through parameters.

package com.design.db;

import java.util.Collection;
import java.util.Collections;

public class DBRequestProcessor implements Receiver {


    @Override
    public void save(Class<?> persistCollection, Object object) {
        System.out.println("Entity Save");
    }

    @Override
    public void remove(Class<?> persistCollection, Object object) {
        System.out.println("Entity Removed");
    }

    @Override
    public Object fetchById(Class<?> persistCollection, Long id) {
        return id;
    }

    @Override
    public Collection fetchAll(Class<?> persistCollection) {
        return Collections.EMPTY_LIST;
    }
}

Invoker.Java

package com.design.db;

public interface Invoker {
    Task invoke(Command command);
}


DBCommandInvoker.Java – Invoker only know how to execute the Command and unknown about their concrete implementation of Command Interface.

package com.design.db;

public class DBCommandInvoker implements Invoker {


    public DBCommandInvoker() {
    }

    @Override
    public Task invoke(Command command) {
        return command.submit();
    }
}

Task.Java

package com.design.db;

public interface Task<T> {
    T get();
}


SqlRepository.Java :- This is Client here, which decides which command to be executed. to execute the Command, it passes to invoker object i.e DBCommandInvoker.

package com.design.db;

import java.util.Collection;

public class SqlRepository {

    private Invoker dbCommandInvoker = new DBCommandInvoker();

    public void save(Class zlass, Object payload) {
        dbCommandInvoker.invoke(new DBSaveCommand(zlass, payload));
    }

    public void remove(Class zlass, Long id) {
        dbCommandInvoker.invoke(new DBRemoveCommand(zlass, id));
    }

    public Object fetchById(Class zlass, Long id) {
        return dbCommandInvoker.invoke(new DBFetchByIdCommand(zlass, id)).get();
    }

    public Collection fetchAll(Class zclass) {
        return (Collection) dbCommandInvoker.invoke(new DBFetchAllCommand(zclass)).get();
    }
}


Setup React JS with NodeJS and Visual Studio Code

Posted on Updated on

Before getting started with first React JS example, download Visual Studio Code Editor that help you configure and better guidance of developing a React JS application.

Download & Install Visual Studio Code from here.
Download and install Node.Js from here.

Once the installation is done then create a root folder where do you want to set up a React JS Project.

>>cd d:
>>mkdir React
>>cd React
>>npm install –g create-react-app
>>create-react-app my-first-app
>>cd my-first-app
>>npm start

Once all step’s done successfully then the my-first-app folder will be created in your root folder React, go inside this folder and you will see all dependencies JS and related configuration files will be placed here.

Next, Open Visual Studio Code and Open project from File-> Open Folder

 

Then open http://localhost:3000/ to see your app.

Sort Array of String by their counts in Java 8

Posted on

Here, we will see how to sort an array base on elements occurrences in Java 8.

Suppose we got a city list containing duplicate city as well like below.

"Delhi,Agra,Bihar,UP,Delhi,Agra,Bihar,UP,Delhi,Bihar,Delhi,Agra,Delhi";

First, we have to do aggregation on city name by applying groupBy function, count their occurrence and return a Map.

 String cities = "Delhi,Agra,Bihar,UP,Delhi,Agra,Bihar,UP,Delhi,Bihar,Delhi,Agra,Delhi";
        
 TreeMap<String, Long> groupByCitiesMap = Stream.of(cities.split(","))
                .collect(Collectors.groupingBy(s -> s, TreeMap::new, Collectors.counting()));
 System.out.println(groupByCitiesMap);

This will return a TreeMap of sorted by City (natural sorting) that containing unique city name as key and their counts as in value.

{Agra=3, Bihar=3, Delhi=5, Uttar Pradesh=2}

OR

We can do it old fashion without using Stream.

TreeMap<String, CityReport> treeMap = new TreeMap();
for (String city : cities.split(",")) {
    CityReport cityReport = new CityReport(city);
    if (treeMap.containsKey(city)) {
        treeMap.computeIfPresent(city, (key, val) -> {val.counter+=1;return val;});
    } else {
        treeMap.put(city, cityReport);
    }
}

This will return a Map that containing unique city name as key and CityReport as value containing city name and count.

{Agra=CityReport{city=’Agra’, counter=3}, Bihar=CityReport{city=’Bihar’, counter=3}, Delhi=CityReport{city=’Delhi’, counter=5}, UP=CityReport{city=’UP’, counter=2}}

and Finally, need to be sorted out by City count and City name. so here we do so…

List<CityReport> sortedCityReport = treeMap.values().stream().sorted(new ComparatorFilter(new ComparatorByNumber(),new ComparatorByName())).collect(Collectors.toList());

System.out.println("Sort By Count first then City Name "+ sortedCityReport);

Output:

Sort By Count first then City Name [CityReport{city=’UP’, counter=2}, CityReport{city=’Agra’, counter=3}, CityReport{city=’Bihar’, counter=3}, CityReport{city=’Delhi’, counter=5}]

Rest of code is below:-

ComparatorFilter.Java :- Sorting by chain of comparator ( by count and name )  over the Collection.

static class ComparatorFilter implements Comparator<CityReport> {

    private final List<Comparator<CityReport>> comparators;

    ComparatorFilter(Comparator<CityReport>... comparators) {
        this.comparators = Arrays.asList(comparators);
    }

    @Override
    public int compare(CityReport o1, CityReport o2) {
        for (Comparator c : this.comparators) {
            int val = c.compare(o1, o2);
            if (val != 0) {
                return val;
            }
        }
        return 0;
    }
}

ComparatorByName.Java – Sorting by City Name

static class ComparatorByName implements Comparator<CityReport> {

    @Override
    public int compare(CityReport o1, CityReport o2) {
        return o1.city.compareTo(o2.city);
    }
}

ComparatorByNumber.Java – sorting by count number.

static class ComparatorByNumber implements Comparator<CityReport> {

    @Override
    public int compare(CityReport o1, CityReport o2) {
        return (int) (o1.counter - o2.counter);
    }
}

CityReport Model Class –


class CityReport {
String city;
Long counter;

public CityReport(String city) {
    this.city = city;
    this.counter = 1L;
}


@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    CityReport that = (CityReport) o;
    return Objects.equals(city, that.city);
}

@Override
public int hashCode() {

    return Objects.hash(city);
}

@Override
public String toString() {
    return "CityReport{" +
            "city='" + city + '\'' +
            ", counter=" + counter +
            '}';
}
}

Angular Filter

Posted on Updated on

 

 

 

 

What is Filter in AngularJS?

Filters are used for formatting data displayed to the user. They can be used in view templates, controllers or services. AngularJS comes with a collection of built-in filters as given below, but it is easy to define your own as well.

The general syntax in templates is as follows:

{{ expression [| filter_name[:parameter_value] ... ] }}

Build-in AngularJS filter

Name Description
filter Selects a subset of items from array and returns it as a new array.
currency Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default symbol for current locale is used.
number Formats a number as text.
date Formats date to a string based on the requested format.
json Allows you to convert a JavaScript object into JSON string.
lowercase Converts string to lowercase.
uppercase Converts string to uppercase.
limitTo Creates a new array or string containing only a specified number of elements. The elements are taken from either the beginning or the end of the source array, string or number, as specified by the value and sign (positive or negative) of limit. Other array-like objects are also supported (e.g. array subclasses, NodeLists, jqLite/jQuery collections etc). If a number is used as input, it is converted to a string.
orderBy Returns an array containing the items from the specified collection, ordered by a comparator function based on the values computed using the expression predicate.

Currency Filter Example :-

In HTML Template Binding
{{ currency_expression | currency : symbol : fractionSize}}
In JavaScript
$filter('currency')(amount, symbol, fractionSize)
Snippet example here:-



Currency : {{currencyValue}} Filter with Currency Symbol and Fraction : {{1234.1324 | currency : "USD$" :4}}

Currency : {{currencyValue}} Filter with Fraction : {{currencyValue | currency : 4}}
<hr/>		


Date filter example :

In HTML Template Binding
{{ date_expression | date : format : timezone}}
In JavaScript
$filter('date')(date, format, timezone)
Snippet example here:-


 Date : {{todayDate}} Filter with medium date format : {{dateInTimestamp | date:'medium'}}
 
 Date : {{todayDate}} Filter with full date format : {{dateInTimestamp | date: fullDate}}
 
 Date : {{todayDate}} Filter format date : {{dateInTimestamp | date:'yyyy-MM-dd HH:mm:ss Z'}}
 <hr/> 


Number filter example :

In HTML Template Binding
{{ number_expression | number : fractionSize}}
In JavaScript
$filter('number')(number, fractionSize)
Snippet example here:-
Number : {{numberValue}} Filter with Fraction 3 : {{numberValue | number:3}}

Json filter example :

In HTML Template Binding
{{ json_expression | json : spacing}}
In JavaScript
$filter('json')(object, spacing)
Snippet example here:-


 JSON : {{JSONValue}} Filter : {{JSONValue | json}}
 
 JSON : {{JSONValue}} Filter with spacing : {{JSONValue | json :10}}
 <hr/> 


Uppercase and Lowercase filter example :

In HTML Template Binding
{{ lowercase_expression | lowercase}}
{{ uppercase_expression | uppercase}}
In JavaScript
$filter('lowercase')()
$filter('uppercase')()
Snippet example here:-


 Name Value is {{name}}
 
 Upper Case : {{name | uppercase}}
 
 Lower Case : {{name | lowercase}}
 <hr/> 


 filter example :

In HTML Template Binding
{{ filter_expression | filter : expression : comparator : anyPropertyKey}}
In JavaScript
$filter('filter')(array, expression, comparator, anyPropertyKey)
Snippet example here:-
<p>
	<p>
		Search : <input type="text" ng-model="searchQuery"/> 
	</p>
	<table border="1">
		<tr>
			<th>ID</th>
			<th>Type</th>
		</tr>
		<tr ng-repeat="item in listOfItem | filter : searchQuery">
			<td>{{item.id}}</td>
			<td>{{item.type}}</td>
		</tr>
	</table>
	<hr/>	
</p>

How to Create custom filter?

Writing your own filter is very easy: just register a new filter factory function with your module. Internally, this uses the filterProvider. This factory function should return a new filter function which takes the input value as the first argument. Any filter arguments are passed in as additional arguments to the filter function.

angular.module("myApp",[]).filter('reverse', function() {
 return function(input, uppercase) {
 input = input || '';
 var out = '';
 for (var i = 0; i < input.length; i++) {
 out = input.charAt(i) + out;
 }
 // conditional based on optional argument
 if (uppercase) {
 out = out.toUpperCase();
 }
 return out;
 };
})</pre>

HTML binding here



<pre>

<div>
 <input ng-model="greeting" type="text">
 No filter: {{greeting}}
 Reverse: {{greeting|reverse}}
 Reverse + uppercase: {{greeting|reverse:true}}
 Reverse, filtered in controller: {{filteredGreeting}}
</div>


Complete Example here :-

<html ng-app="myApp">
<head>
	<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
</head>
<body ng-controller="filterController">
	<h1> Angular Build-in Filter Example </h1>
	<hr/>
	<p>
		Currency : {{currencyValue}} Filter with Currency Symbol and Fraction : {{currencyValue | currency : "USD$" :4}}
		<br/>
		Currency : {{currencyValue}} Filter with Fraction : {{currencyValue | currency : 4}}
		<hr/>	
	</p>	

<p>
	Date : {{todayDate}} Filter with medium date format : {{dateInTimestamp | date:'medium'}}
	<br/>
	Date : {{todayDate}} Filter with full date format : {{dateInTimestamp | date: fullDate}}
	<br/>
	Date : {{todayDate}} Filter format date : {{dateInTimestamp | date:'yyyy-MM-dd HH:mm:ss Z'}}
	<hr/>	
</p>

<p>
	Number : {{numberValue}} Filter with Fraction 3 : {{numberValue | number:3}}
	<hr/>	
</p>

<p>
	JSON : {{JSONValue}} Filter  : {{JSONValue | json}}
	<br/>
	JSON : {{JSONValue}} Filter with spacing : {{JSONValue | json :10}}
	<hr/>	
</p>

<p>
	Name Value is {{name}}
	<br/>
	Upper Case   : {{name | uppercase}}
	<br/>
	Lower Case   : {{name | lowercase}}
	<hr/>	
</p>

<p>
	<p>
		Search : <input type="text" ng-model="searchQuery"/> 
	</p>
	<table border="1">
		<tr>
			<th>ID</th>
			<th>Type</th>
		</tr>
		<tr ng-repeat="item in listOfItem | filter : searchQuery">
			<td>{{item.id}}</td>
			<td>{{item.type}}</td>
		</tr>
	</table>
	<hr/>	
</p>
<p>
<input ng-model="greeting" type="text"><br>
  No filter: {{greeting}}<br>
  Reverse: {{greeting|reverse}}<br>
  Reverse + uppercase: {{greeting|reverse:true}}<br>
  Reverse, filtered in controller: {{filteredGreeting}}<br>
</p>
</body>
<script type="text/javascript">
angular.module("myApp",[])
.controller("filterController",function($scope){
	$scope.todayDate = new Date();
	$scope.dateInTimestamp = $scope.todayDate.getTime();
	$scope.currencyValue = 1234.33;
	$scope.numberValue = 123.456789;
	$scope.JSONValue = "[{'key':'value'}]";
	$scope.name="Sample Angular Filter Example";
	$scope.listOfItem = [
			{ "id": "5001", "type": "None" },
			{ "id": "5002", "type": "Glazed" },
			{ "id": "5005", "type": "Sugar" },
			{ "id": "5007", "type": "Powdered Sugar" },
			{ "id": "5006", "type": "Chocolate with Sprinkles" },
			{ "id": "5003", "type": "Chocolate" },
			{ "id": "5004", "type": "Maple" }
		]
})
.filter('reverse', function() {
  return function(input, uppercase) {
    input = input || '';
    var out = '';
    for (var i = 0; i < input.length; i++) {
      out = input.charAt(i) + out;
    }
    // conditional based on optional argument
    if (uppercase) {
      out = out.toUpperCase();
    }
    return out;
  };
})
</script>

</html>