Showing posts with label Spring. Show all posts
Showing posts with label Spring. Show all posts

Wednesday, 13 April 2016

Autowire Logger Object In Spring

You could do it with a @Qualifier annotation. Of course that means that you have added Loggerobjects to your application context already.
Importing this config into your application context would allow you to do that:
@Configuration
public class LoggerConfig {
    @Bean
    public Logger myClassLogger() {
        return LoggerFactory.getLogger(MyClass.class);
    }

    @Bean
    public Logger myOtherClassLogger() {
        return LoggerFactory.getLogger(MyOtherClass.class);
    }
}
And then in your classes that uses the Logger:
@Component
public class MyClass {
    @Autowired
    @Qualifier("myClassLogger")
    private Logger logger;

    //...
}

@Component
public class MyOtherClass {
    @Autowired
    @Qualifier("myOtherClassLogger")
    private Logger logger;

    //...
}

Wednesday, 2 October 2013

How would I do $push using MongoRepository in Spring Data?

Yes, you must implement a custom method on the repository and your push method would be something like this :


public class FooRepositoryImpl implements
    AppointmentWarehouseRepositoryCustom {

    @Autowired
    protected MongoTemplate mongoTemplate;

    public void pushMethod(String objectId, Object... events) {
        mongoTemplate.updateFirst(
            Query.query(Criteria.where("id").is(objectId)), 
            new Update().pushAll("events", events), Foo.class);
    }
}
You can do this but I ran into an issue where the "_class" field wasn't being preserved. 
The pushed object itself was run through the configured converter but for some reason the "_class" field of that pushed object wasn't written. 
However, if I injected the converter and wrote the object to a DBObject myself, then the "_class" field was preserved and written. The thus becomes:

public class FooRepositoryImpl implements
AppointmentWarehouseRepositoryCustom {

@Autowired
protected MongoTemplate mongoTemplate;

public void pushMethod(String objectId, Object event) {
    DBObject eventObj = new BasicDBObject();
    converter.write(event, eventObj);
    mongoTemplate.updateFirst(
        Query.query(Criteria.where("id").is(objectId)), 
        new Update().push("events", eventObj), Foo.class);
  }
}

Thursday, 4 July 2013

Multiple File Uploading With Spring

//#####################################Screen Shot









//##################################### Maven Dependency

<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>

<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>

//##################################### Jsp Code

 <script type="text/javascript" src="http://www.technicalkeeda.com/js/javascripts/plugin/jquery.js"></script>
<script type="text/javascript">
var i=1;
$(document).ready(function(){
$('#add').click(function(){
$('#files').append('<input type="file" name="file['+i+']"/><br>');
i++;
});
$('#upload').click(function(){
$('#files').append('<input type="hidden" name="count" value='+i+'>');
console.log(i);
});
});
</script>

 -------------------------------------------------------------------------------------------------

<p>Click Add Button To Browse More Files</p>
<form action="uploadMultipleFiles" enctype="multipart/form-data" method="post">
<div id="files">
<input type="file" name="file[0]" />
<input type="submit" value="upload" id="upload"/>
<input type="button" id="add" value="Add" /><br>
</div>
</form>


//##################################### Controller Code

 @RequestMapping("/uploadMultipleFiles")
public String uploadFiles(HttpServletRequest request) throws IOException{

System.out.println("inside upload multiple files..");
int total=Integer.parseInt(request.getParameter("count"));
//System.out.println(total);
MultipartHttpServletRequest req=(MultipartHttpServletRequest)request;
for(int i=0;i<total;i++){
MultipartFile files=req.getFile("file["+i+"]");
String filenameToCreate="D:\\harsh.patel\\SpringFileUpload\\UploadedFiles\\"+files.getOriginalFilename();
System.out.println(filenameToCreate);
File file = new File(filenameToCreate);
FileUtils.writeByteArrayToFile(file, files.getBytes());
}
System.out.println("after upload multiple files");
return "result";

}
 

Simple File Upload in Spring



//##################################### Maven Dependency

<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>

<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>

//##################################### Jsp Code

<form action="uploadRequest" enctype="multipart/form-data" method="post">
<input type="file" id="file" name="file"/>
<input type="submit" value="upload" />
</form>

//######################################  Controller Code
@RequestMapping("uploadRequest")
public String upload(HttpServletRequest request) throws IOException{
System.out.println("inside upload");
MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
MultipartFile files = req.getFile("file");
String filenameToCreate="Path Up to Folder\\"+files.getOriginalFilename();
//(Don't forgot to put \\ )
System.out.println(filenameToCreate);
File file = new File(filenameToCreate);
FileUtils.writeByteArrayToFile(file, files.getBytes());
System.out.println("after upload");
return "result";
}

Get all error message of hibernate annotation in Map (Field,Error Message)


import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.constraints.NotNull;

import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "user")
public class User1 extends AbstractDocument {

public User1() {

}

public User1(String displayName, String username, String password) {
this.displayName = displayName;
this.username = username;
this.password = password;
}

@NotNull
@NotBlank
@NotEmpty
@Length(min = 6, max = 8)
private String displayName;

@NotNull
@NotBlank
@NotEmpty
@Length(min = 6, max = 8)
private String username;

@NotNull
@NotBlank
@NotEmpty
@Email
@Length(min = 6, max = 8)
private String password;

public String getDisplayName() {
return displayName;
}

public void setDisplayName(String displayName) {
this.displayName = displayName;
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

@Override
public String toString() {
return "User [displayName=" + displayName + ", username=" + username
+ ", password=" + password + ", toString()=" + super.toString()
+ "]";
}

public static void main(String[] args) {

User1 user = new User1("", "", "qqq");

ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();

Set<ConstraintViolation<User1>> constraintViolations = validator
.validate(user);

System.out.println("size:" + constraintViolations.size());

Map<String, String> map = new HashMap<String, String>();

for (ConstraintViolation<User1> obj : constraintViolations) {

String key = obj.getPropertyPath().toString();

if (!map.containsKey(key)) {
map.put(key, obj.getMessage());
} else {
map.put(key, map.get(key) + "," + obj.getMessage());
}
}
System.out.println(map);

}

}

OUTPUT:

size:6
{password=not a well-formed email address,length must be between 6 and 8, username=may not be empty,length must be between 6 and 8, displayName=length must be between 6 and 8,may not be empty}


Wednesday, 3 July 2013

XML Code For @JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)

<mvc:annotation-driven>
  <mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="objectMapper">
 <bean class="org.codehaus.jackson.map.ObjectMapper">
<property name="serializationInclusion">
<value type="org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion">NON_NULL</value>
</property>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>

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, 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.