Thursday 9 June 2016

File Upload using Spring RestFul service

File Upload using Spring RestFul service

In this blow we will try to upload file file using Spring RestFul service.

First we need to register a bean in spring configuration XMl file for MultipartResolver that Spring support for uploading.
Here we have used CommonsMultipartResolver provided by spring framework to upload a file

Example:
<bean id="multipartResolver"              class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
p:defaultEncoding="utf-8"/>

Now create a controller and annotating with proper path.
Example:
@RequestMapping(value = "/image/ imageid/{imageid}", method = RequestMethod.POST)
  public String imageUpload(HttpServletRequest request,
      @RequestParam("imagefile") MultipartFile file) throws IOException {    
    InputStream stream = file.getInputStream();
            String fileName = file.getOriginalFilename();          
            System.out.println(“File name: “ + fileName);
            /*
            Now you have InputStream, file name and other information available so, you can save where you want
            */
    return "SUCCESS";
  }


To the created service we can test it using Postmaster app plugin of Chrome.


Consuming Web service in Java

Consume Web service using HttpURLConnection
We can call Web services method in java using classes URL and HttpURLConnection.
And can be used with Android to consume web services 
URL: Class URL represents a Uniform Resource Locator, a pointer to a "resource" on the World Wide Web. A resource can be something as simple as a file or a directory, or it can be a reference to a more complicated object, such as a query to a database or to a search engine.

HttpURLConnection: The abstract class URLConnection is the superclass of all classes that represent a communications link between the application and a URL. Instances of this class can be used both to read from and to write to the resource referenced by the URL. In general, creating a connection to a URL is a multistep process:
 
Method name:
openConnection():Manipulate parameters that affect the connection to the remote resource.

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

import org.json.JSONException;
import org.json.JSONObject;

public class HttpServiceHandler {
    URL url;
    HttpURLConnection connection;
    DataOutputStream dataOutputStrea;

    public static void main(String[] args) {
       String path = "http://localhost:90/testmethod/postdata";
       String method = "POST";
      
       try {
           HttpServiceHandler serviceHandler= new HttpServiceHandler(path, method);
           serviceHandler.setParameter(serviceHandler.getJson());
           System.out.println(serviceHandler.getResponse());
       } catch (Exception e) { 
           e.printStackTrace();
       }
    }
   
    public HttpServiceHandler(String requestUrl, String methodType) throws IOException{
       url = new URL(requestUrl);
       connection = (HttpURLConnection) url.openConnection(); 
       connection.setDoOutput(true);
       connection.setDoInput(true);
       connection.setInstanceFollowRedirects(false);
       connection.setRequestMethod(methodType);
       connection.setRequestProperty("Content-Type", "application/json");
       connection.setRequestProperty("charset", "utf-8");
       connection.setUseCaches (false);
      
       dataOutputStrea = new DataOutputStream(connection.getOutputStream ());
    }
   
    public void setParameter(JSONObject queryParameter) throws IOException{
       dataOutputStrea.writeBytes(queryParameter.toString());
       dataOutputStrea.flush();
       dataOutputStrea.close();
    }
   
    public String getResponse() throws IOException {
       StringBuilder response = new StringBuilder();
       int responseCode = connection.getResponseCode();

       if (responseCode == HttpsURLConnection.HTTP_OK) {
           String line;
           BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
           while ((line = br.readLine()) != null) {
              response.append(line);
           }
       } else {
           response.append("");
       }
       return response.toString();
    }
   
   
    private JSONObject getJson() throws JSONException{
       JSONObject jsonParam = new JSONObject();
       jsonParam.put("Username", "user1");
       jsonParam.put("Pasword", "123456");
       return jsonParam;
    }
}








Wednesday 2 March 2016

JAVA Swing: Custom JTextField


In this blow we are will design the custom JTextFields like:
1. RoundedCorner JTextField,
2. Image Background JTextField
3. JtextField with Hint text.

1. Rounded Corner TextField

import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Insets;

import javax.swing.JComponent;
import javax.swing.border.AbstractBorder;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.metal.MetalTextFieldUI;

public class RoundedCornerTextFieldUI extends MetalTextFieldUI {
    private final static int ARC_WIDTH = 5;
    private final static int ARC_HEIGHT = 5;
    private final static int x = 0;
    private final static int y = 0;
    private final static int BORDER_TOP = 4;
    private final static int BORDER_BOTTOM = 4;
    private final static int BORDER_LEFT = 4;
    private final static int BORDER_RIGHT = 4;

    public static ComponentUI createUI(JComponent jComponent) {
       return new RoundedCornerTextFieldUI();
    }

    public void installUI(JComponent jComponent) {
       super.installUI(jComponent);
       jComponent.setBorder(new RoundedBorder());
       jComponent.setOpaque(false);
    }

    protected void paintSafely(Graphics graphics) {
       JComponent component = getComponent();
       if (!component.isOpaque()) {
           graphics.setColor(component.getBackground());
           graphics.fillRoundRect(x, y, component.getWidth()-1, component.getHeight()-1, ARC_WIDTH, ARC_HEIGHT);
       }
       super.paintSafely(graphics);
    }

    private static class RoundedBorder extends AbstractBorder {
       private static final long serialVersionUID = 1L;

       public void paintBorder(Component coponent, Graphics graphics, int x, int y, int width, int height) {
           Color oldColor = graphics.getColor();
           graphics.setColor(Color.gray);
           graphics.drawRoundRect(x, y, width-1, height-1, ARC_WIDTH, ARC_HEIGHT);
           graphics.setColor(oldColor);
       }

       public Insets getBorderInsets(Component c) {
           return new Insets(BORDER_TOP, BORDER_LEFT, BORDER_BOTTOM, BORDER_RIGHT);
       }

    }

}



2. Image Background and Hint Text TextField

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;

import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JTextField;

public class HintBGImageTextField extends JTextField {

    private static final long serialVersionUID = 1L;
    private static final Font focusGainFont = new Font("Courier New", Font.PLAIN, 12);
    private static final Font focusLostFont = new Font("Courier New", Font.ITALIC, 12);
    private Image img;
    private HintBGImageTextField hintTextField;
   
    public HintBGImageTextField() {
       hintTextField = this;
    }
   
   @Override
    public void paintComponent(Graphics g) {
       g.drawImage(img, 0, 0, this);
       super.paintComponent(g);
    }
   
    public void setBackgroundImage(String imPath){
       img = new ImageIcon(imPath).getImage();
       setOpaque(false);
       new JComponent(){
           private static final long serialVersionUID = 1L;

           @Override
           public void paintComponent(Graphics g) {
              super.paintComponent(g);
           }
       };
    }
   
    public void setHint(String hint){
       hintTextField.setText(hint);
       hintTextField.setFont(focusLostFont);
       hintTextField.setForeground(Color.GRAY);
       hintTextField.addFocusListener(new FocusAdapter() {

            @Override
            public void focusGained(FocusEvent e) {
                if (hintTextField.getText().equals(hint)) {
                    hintTextField.setText("");

                } else {
                    hintTextField.setText(getText());
                }
                hintTextField.setFont(focusGainFont);
                hintTextField.setForeground(Color.BLACK);
            }

            @Override
            public void focusLost(FocusEvent e) {
                if ( hintTextField.getText().equals(hint) || getText().length() == 0) {
                    hintTextField.setText(hint);
                    hintTextField.setFont(focusLostFont);
                    hintTextField.setForeground(Color.GRAY);
                } else {
                    hintTextField.setText(getText());
                    hintTextField.setFont(focusGainFont);
                    hintTextField.setForeground(Color.BLACK);
                }
            }
        });
    }

}


3. Main Class

import javax.swing.JFrame;
import javax.swing.JTextField;

public class Main extends JFrame {
   
    public Main(){
       setDefaultCloseOperation(3);
       setSize(400, 350);
       setLayout(null);
      
           
       JTextField field = new JTextField();
       field.setBounds(5,35,200,25);
       field.setUI(new RoundedCornerTextFieldUI());
       add(field);
      
      
       HintBGImageTextField hintTextField  = new HintBGImageTextField();
       hintTextField.setBounds(5,65,200,25);
       hintTextField.setBackgroundImage("resources/textfield.png");
       hintTextField.setHint("Search...");
       add(hintTextField);
      
      
       setVisible(true);
       setResizable(false);
    }
   
    public static void main(String[] args) {
      
       Main main = new Main();
       main.setVisible(true);
    }
}


Image Folder path and Image




Output: