Saturday 29 June 2013

OCJP Latest Dumps

Hi All,
Many people on internet are looking for latest and valid Java SE 1.6 dumps.
On this post, I am sharing valid and latest dumps.
Click Here to download.
Please provide feedback after taking exams about the dumps.

Cheers !!

Question - 2

Give the code. What is the result?
class Hotel {
    public int bookings;
    public void book() {
        bookings++;
    }
}

public class SuperHotel extends Hotel {

    public void book() {
        bookings--;
    }
    
    public void book(int size) {
        book();
        super.book();
        bookings += size;
    }
    
    public static void main(String args[]) {
        SuperHotel hotel = new SuperHotel();
        hotel.book(2);
        System.out.print(hotel.bookings);
    }
}
 
(Correct Answer)

Wednesday 26 June 2013

Question - 1

Que:  Given a class Repetition:
1. package utils;
2.
3. public class Repetition {
4. public static String twice(String s) { return s + s; }
5. }
and given another class Demo:
1. // insert code here
2.
3. public class Demo {
4. public static void main(String[] args) {
5. System.out.println(twice("pizza"));
6. }
7. }
Which code should be inserted at line 1 of Demo.java to compile and run Demo to print "pizzapizza"?
A. import utils.*;
B. static import utils.*;
C. import utils.Repetition.*;
D. static import utils.Repetition.*;
E. import utils.Repetition.twice();
F. import static utils.Repetition.twice;
G. static import utils.Repetition.twice;

Answer: F

Tuesday 25 June 2013

MongoDB Get names of all keys in collection

mr = db.runCommand({ 

 "mapreduce" : "things", 

 "map" : function() {

   for (var key in this) { 

         emit(key, null); } },

 "reduce" : function(key, stuff) { 

  return null; }, "out": "things" + "_keys" })

Then run distinct on the resulting collection so as to find all the keys:

db[mr.result].distinct("_id") ["foo", "bar", "baz", "_id", ...]

Friday 21 June 2013

Fetch Image Using Ajax

Introduction

One of the unsung heros in the HTML5 universe is XMLHttpRequest. Strictly speaking XHR2 isn't HTML5. However, it's part of the incremental improvements browser vendors are making to the core platform. I'm including XHR2 in our new bag of goodies because it plays such an integral part in today's complex web apps.
Turns out our old friend got a huge makeover but many folks are unaware of its new features. XMLHttpRequest Level 2 introduces a slew of new capabilities which put an end to crazy hacks in our web apps; things like cross-origin requests, uploading progress events, and support for uploading/downloading binary data. These allow AJAX to work in concert with many of the bleeding edge HTML5 APIs such as File System API, Web Audio API, and WebGL.

Fetching data

Fetching a file as a binary blob has been painful with XHR. Technically, it wasn't even possible. One trick that has been well documented involves overriding the mime type with a user-defined charset as seen below.

$('#linkImg').click(function(e){
                            e.preventDefault();
                            alert("hi");
                            var xhr = new XMLHttpRequest();
                            xhr.open('GET', '/users/exportA', true);
                            xhr.responseType = 'blob';

                            xhr.onload = function(e) {
                            if (this.status == 200) {
                            var blob = this.response;

                            var img = document.createElement('img');
                            img.onload = function(e) {
                            window.URL.revokeObjectURL(img.src); // Clean up after yourself.
                            };
                            img.src = window.URL.createObjectURL(blob);
                            document.body.appendChild(img);

                            }
                            };

                            xhr.send();
                            });

My Controller Code:

 @RequestMapping(value = "/users/exportA")
    @ResponseBody
    public void exportA(HttpServletResponse response)
            throws FileNotFoundException, IOException {

        response.setHeader("Content-Disposition", "inline;filename=Desert.jpg");

        OutputStream out = response.getOutputStream();
        response.setContentType("blob");
        FileCopyUtils.copy(new BufferedInputStream(new FileInputStream(
                "C:\\Users\\Public\\Pictures\\Sample Pictures\\Desert.jpg")), out);

        out.flush();
        out.close();
    }

Require: jquery.min.js (Latest Version)


Wednesday 19 June 2013

Export MongoDB "Database" in JAVA

public class TempMongoExportDB {

public void mongoExport()
throws IOException {

String command = "mongodump -db tree -o c:\\backup";
Process p = Runtime.getRuntime().exec(command);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(
p.getInputStream()));

BufferedReader stdError = new BufferedReader(new InputStreamReader(
p.getErrorStream()));

// read the output from the command
String s = "";

while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}

while ((s = stdError.readLine()) != null) {
System.out.println("Std ERROR : " + s);
}

}

public static void main(String[] args) throws IOException {

TempMongoExportDB tempMongoExportDB = new TempMongoExportDB();
tempMongoExportDB.mongoExport();

}

}

Wednesday 12 June 2013

Third example: RequestEntityMethodArgumentResolver

 For CRUD operations, a PUT request to a URL is common and usually overwrites the entire object. In our case however, this is not possible: some object properties are read-only, and others can only be written if the object has a certain status. So what we need is a _partial_ update.
And although it is usually possible to omit fields from the request body, this does not do what we want. What happens is for missing fields, use the default value from the constructor. But what we want is: for missing fields, to not change the value in the database.
We’ve created an annotation @RequestEntity to handle these parameters. Like @PathEntity, a URL template is tied to a domain entity, but now the request body is used to update the (detached) record. An example usage would be:


This controller method now only has to call the service method that updates the database. The code looks like this:


CRUD applications

The provided examples show the building blocks to reduce a CRUD application to almost no code beyond searching:
Create
The @RequestBody annotation combined with @Valid (see the first example) ensure that the controller only needs to save the record.
Read
The @PathEntity annotation in the second example already provides a loaded record, so the controller can simply return it. Only returning multiple records (i.e. searches) requires more code.
Update
The @RequestEntity annotation in the third example provides a detached, updated and optionally validated record. This includes partial updates The controller method only has to save it.
Delete
The @PathEntity annotation provides a record, so it can simply be removed.
As you can see, this means that implementing CRUD has become as trivial as calling your persistence layer. And as an added bonus, the more complex use cases are now also easier to implement: only the call to your business method is needed.

Conclusion


The examples in this article show that it is easy to extend the default Spring functionality to extract any information you want from the request. You can augment the existing functionality with, for example, JSR-303 validations. Or you can completely roll your own solution, including merging the request information with existing data. Combined with the generic Spring concept that any REST call is a method invocation, anything is possible. Your business needs are in control, not the technology.

Second example: PathEntityMethodArgumentResolver

 Another thing we encounter regularly, is that we want to issue a POST request to a URL to execute an action on a domain object. As we prefer not to repeat the code to retrieve the domain object, we’ve created an annotation @PathEntity so we can do this:


Granted, we could also do this by overriding the Spring ConversionService, but as we’ll see in the next example this approach has it’s advantages. The code for the @PathEntity annotation and the PathEntityMethodArgumentResolver to handle it is this:


And this is the class to resolve parameters annotated with @PathEntity:


Registering this MethodHandlerArgumentResolver is as usual:


With these two classes in place, we can identify our domain objects with our REST resources (URL’s). When the controller method is invoked, we have an instance of the domain entity the URL represents. Note that outside a transaction, this entity is a detached entity (this is prescribed by the JPA specification). So we still need to call EntityManager.merge(Object) to persist any changes.