Tuesday, March 25, 2014

Java IO Tutorial - file read / write

Commonly Used Methods for Small Files

Reading All Bytes or Lines from a File

If you have a small-ish file and you would like to read its entire contents in one pass, you can use the readAllBytes(Path) or readAllLines(Path, Charset) method. These methods take care of most of the work for you, such as opening and closing the stream, but are not intended for handling large files. The following code shows how to use the readAllBytes method:

Path file = ...;
byte[] fileArray;
fileArray = Files.readAllBytes(file);

Writing All Bytes or Lines to a File

The following code snippet shows how to use a write method.

Path file = ...;
byte[] buf = ...;
Files.write(file, buf);


Original tutorial is locate here: http://docs.oracle.com/javase/tutorial/essential/io/file.html

Thursday, March 20, 2014

junit: Header line for each test

This code will print nice junit header line. You could put the code in base class of your tests.

    @Rule public TestName name = new TestName();
   
    @Before
    public void before(){
        System.out.println("\n\n========================================= " + this.getClass().getSimpleName() + " -> " + name.getMethodName() +  "() ==================================\n");
    }



Getting last element in Hibernate's repository by annotations

Getting last element in hibernate is useful for integration testing, where you have to ensure some object is stored in database, for example.

Using Hibernate SQL.

Code:
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.jpa.repository.Query;

public interface MyObjectRepository extends CrudRepository<MyObject, Long> {
 
  @Query("FROM com.yourcompany.zzz.MyObject c WHERE (c.id) IN (select max(id) from com.yourcompany.zzz.MyObject)")
  MyObject getLastOne();   
 
}



It returns null, when there are no elements in table (do not throw an exception).

Tuesday, March 11, 2014

Wednesday, March 5, 2014

Jackson deserialization in controller

Here is an example for deserialize JSON data from string placed in the body of the request.

Here are clear (not-working) and work-around.

Workaround:


    @RequestMapping(
        value = "/add_venue_raw",
//        method = RequestMethod.POST, // if you like
        produces="application/json",
        consumes={"application/json"}
    )
    @ResponseBody
    public String addVenueRaw( @RequestBody String body ) throws IOException {
        log.info( "received body: " + body );


        ObjectMapper mapper = new ObjectMapper();
        Venue x = mapper.readValue( body, Venue.class );
        log.info( "obj.toString() = " + x.toString() );


        return "{\"status\":\"no warnings
\"}";
    }


Clear but not working way

    @RequestMapping(
        value = "/add_venue_buggy",
        method = RequestMethod.POST,
        consumes={"application/json"},
//        produces="application/json;charset=utf-8"
        produces="application/json"
    )
    @ResponseBody
    public String addVenue( @RequestBody VenuePhoto venue ) {
// this DO NOT works!!!!!!!!!!!!!!!!!!!!
        return "{}";
    }

   


Deserialize as map

Deserialize body data as map and return the same body (useful for tests):
    @RequestMapping(
        value = "/add_venue_raw",
//        method = RequestMethod.POST,
        produces="application/json",
        consumes={"application/json"}
    )
    @ResponseBody
    public String addVenueRaw( @RequestBody String body ) throws IOException {

        log.info( "received body: " + body );
       
        Map<String, String> map = new HashMap<String, String>();
        ObjectMapper mapper = new ObjectMapper();

        try {
            //convert JSON string to Map
            map = mapper.readValue(body,
                new TypeReference<HashMap<String, String>>() {
                });


            System.out.println(map);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return map.toString();
    }


Blank template JavaScript application for JSON requests

Blank template application for JSON requests with and without body:

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>My Blank JS / jQuery app - jsFiddle demo by jorooo</title>
 
  <script type='text/javascript' src='http://code.jquery.com/jquery-latest.js'></script>
  <!--link rel="stylesheet" type="text/css" href="/css/result-light.css"-->
  <script type='text/javascript' src="http://code.jquery.com/mobile/latest/jquery.mobile.min.js"></script>
  <link rel="stylesheet" type="text/css" href="http://code.jquery.com/mobile/latest/jquery.mobile.min.css">
     
  <style type='text/css'>
   
  </style>
</head>
<body>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
    $("#alert").bind("click", function(event) {
        alert('alert called');
    }); 

    $("#call_json_with_body").bind("click", function(event) {
        $.ajax({
            success: function( data ){
                alert("success");
                alert('success, data received is ' + JSON.stringify(data));
            },
            error: function( jqXHR, textStatus, errorThrown ){
                alert( "error  while making ajax call. Error parameters are, " +
                    "\ntextStatus: " + textStatus +
                    ";\n errorThrown: " + errorThrown +
                    ";\n jqXHR: " + JSON.stringify(jqXHR) );
            },
            beforeSend: function(req) {
                req.setRequestHeader("Accept", "application/json");
                req.setRequestHeader("Content-Type","application/json");
            },       
            dataType: 'json',
            data: JSON.stringify( {"zzz":"222"} ),
            type: 'POST',
            cache: false,
            url: "http://localhost:8080/add_venue_raw",
          }
        );   
    }); 
    $("#call_json_without_body").bind("click", function(event) {
        $.ajax({
            success: function( data ){
                alert("x");
                alert('success, data received is ' + JSON.stringify(data) );
            },
            error: function( jqXHR, textStatus, errorThrown ){
                alert( "error  while making ajax call. Error parameters are, " +
                    "\ntextStatus: " + textStatus +
                    ";\n errorThrown: " + errorThrown +
                    ";\n jqXHR: " + JSON.stringify(jqXHR) );
            },
            type: 'GET',
            cache: false,
            url: "http://localhost:8080/user/1",
          }
        );   
    }); 
});//]]> 

</script>

  <div data-role="page" id="p1">
    <div  data-role="header"><h1>Header</h1></div>
   
    <div  data-role="content">
        <h5>If the script is running from a file:/// URL you could experience some issues. It's best not to do AJAX requests from file URLs, because they are treated inconsistently. Chrome, for example, entirely disallows them. Firefox also.</h5>
        <a href="#" id="call_json_without_body" data-role="button">JSON request without body</a><br/>
        <a href="#" id="call_json_with_body" data-role="button">JSON request with body</a><br/>
        <a href="#" id="alert" data-role="button">Show alert</a>
    </div>
   
    <div  data-role="footer"><h4>Footer</h4></div>
</div>

 
</body>
</html>





static root folder for maven projects

Static files could be copied here:
<maven-project-root>\src\main\webapp\resources

They are accessed on server on URL:
<server_address>/resources

Example:
<maven-project-root>\src\main\webapp\resources\x.txt
could be accessed on
http://localhost:8080/resources/x.txt

In come cases, the content changes are actualized without server restart. For example with:
mvn jetty:run

Tuesday, March 4, 2014

jQuery Mobile blank app with dummy CSS / JavaScript sections

Code below could be used as template for kick-start application.

Code:


<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>My Blank JS / jQuery app - demo</title>
 
  <script type='text/javascript' src='http://code.jquery.com/jquery-latest.js'></script>
  <link rel="stylesheet" type="text/css" href="/css/result-light.css">
      <script type='text/javascript' src="http://code.jquery.com/mobile/latest/jquery.mobile.min.js"></script>
      <link rel="stylesheet" type="text/css" href="http://code.jquery.com/mobile/latest/jquery.mobile.min.css">
     
  <style type='text/css'>
   
  </style>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
    $("#add").bind("click", function(event) {
        alert('clicked');
    }); 

});//]]> 

</script>


</head>
<body>
  <div data-role="page" id="p1">
    <div  data-role="header"><h1>Header</h1></div>
   
    <div  data-role="content">
        <a href="#" id="add" data-role="button">Click Me</a>
    </div>
   
    <div  data-role="footer"><h4>Footer</h4></div>
</div>

 
</body>
</html>