Pages

Saturday, June 25, 2011

JAVA Code Snippet

String.Format(for (int i = 0; i < names.length; i++) {
                    //out.println("
" + names[i]);
                    out.print(String.format("%s %s", "
", names[i])
);
                }



Enumeration
 Enumeration params = request.getParameterNames();
        while (params.hasMoreElements())
        {
// Get the next parameter name.
            String paramName = params.nextElement();






Reading Resource File
public void testParsLocalfile() {
        String resourceLocation="/examples/documents/ABC_Catalyst.xml";
        URL result = getClass().getResource(resourceLocation);
        InputStream stream=null;
        try {
            stream = result.openStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        assertTrue("File is not exists", stream!=null);
   
        try {
            stream.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


Uploading files

InputStream in = request.getInputStream();

// The file is always saved with the same name (just for this demo).
String path =this.getServletContext().getRealPath("/tmp/uploaded_file.txt");
OutputStream fileOut = new BufferedOutputStream(
new FileOutputStream(path));
// Create a buffer for reading bytes from the input stream.
byte[] buff = new byte[4096];
int len;

// Read bytes from the input stream, and write them to the file.
while ((len = in.read(buff)) > 0)
{
fileOut.write(buff, 0, len);
}
fileOut.close();

Saturday, June 18, 2011

MVC JNSON

// 
public ActionResult GetContactsJSON(string id)
{
if (string.IsNullOrEmpty(id))
{
return Json(_ctx.Contacts.OrderBy(cnt => cnt.FirstName).Take(100).ToList(), JsonRequestBehavior.AllowGet);
}
else
{

return Json(_ctx.Contacts.Where(cnt => cnt.FirstName.StartsWith(id)).OrderBy(cnt => cnt.FirstName).Take(100).ToList(), JsonRequestBehavior.AllowGet);

}
}
public ActionResult GetContactJSON(int id)
{

return Json(_ctx.Contacts.SingleOrDefault(cnt => cnt.ContactID == id), JsonRequestBehavior.AllowGet);

}

JSON webservice

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using Cli.Lsp.Web2Services.RatingService.Bll.Adapters;

///

/// Summary description for RatingService_JSONP
///

[WebService(Namespace = "http://ws.cli.det.nsw.edu.au/ns/Web2Services/RattingService",
           Description = "Ratting service, this service will be plugable in any application, to support rating with comments, including reports and summaries")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class RatingService_JSONP : RatingService
{
    [WebMethod, ScriptMethod(UseHttpGet= true)]
    public override int GetNoOfLiked(int applicationID, string applicationItemID)
    {
        return RateServiceAdapter.GetNoOfLiked(applicationID, applicationItemID);
    }
   
    [WebMethod, ScriptMethod(UseHttpGet = true)]
    public override void Rate(int applicationID, string applicationItemID, int rate, string comment, string userID)
    {
         RateServiceAdapter.LightRate(applicationID, applicationItemID, rate, comment, userID);

    }
    [WebMethod(Description = @"Sample Please remove it")]
    [ScriptMethod(UseHttpGet=true)]
    public string[] Sample()
    {
        return new string[] { "AAA", "BBB", "CCC", "DDD" };
    }

}

Simple JSP code

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
      pageEncoding="ISO-8859-1"
      import="de.vogella.wtp.jsp.controller.*,java.util.*"%>
DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Show all namestitle>
head>
<body>

      <form method="GET" action='HomeController' name="showall">
            <table>
                  <%
                        ArrayList users = new ArrayList();
                        if (request.getSession(true).getValue("users") instanceof ArrayList) {
                              users = (ArrayList) request.getSession(true).getValue("users");
                        }
                        for (User user : users) {
                  %>
                  <tr>
                        <td><input type="checkbox" name="<%=user.getID()%>" />
                        td>
                        <td><%=user.getFirstName()%>td>
                        <td><%=user.getLastName()%>td>
                  tr>

                  <%
                        }
                        ;
                  %>

            table>

            <p>
                  <input type="submit" name="delete" value="delete" />  <input
                        type="submit" name="edit" value="edit" />  <input type="reset"
                        value="reset" />
            p>
      form>



body>
html>

Simple AWT Java Application

//MyFirstUI.java
package ui;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;


public class MyFirstUI extends JFrame implements ActionListener{

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    private JCheckBox checkbox;
    private JTextField firstName;
    private JTextField lastName;

    public MyFirstUI() {

        // Lets make it look nice
        // This you can ignore / delete if you don't like it
        // try {
        // for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
        // if ("Nimbus".equals(info.getName())) {
        // UIManager.setLookAndFeel(info.getClassName());
        // break;
        // }
        // }
        // } catch (Exception e) {
        // e.printStackTrace();
        // }

        setTitle("My First UI");

        // We create a panel which will hold the UI components
        JPanel pane = new JPanel(new BorderLayout());
        // We always have two UI elements (columns) and we have three rows
        int numberOfRows = 3;
        int numberOfColumns = 2;
        pane.setLayout(new GridLayout(numberOfRows, numberOfColumns));

        // create and attach buttons
        // create a label and add it to the main window
        JLabel firstNamelabel = new JLabel(" Firstname: ");
        pane.add(firstNamelabel);
        firstName = new JTextField();
        pane.add(firstName);

        JLabel lastNamelabel = new JLabel(" Lastname: ");
        pane.add(lastNamelabel);
        lastName = new JTextField();
        pane.add(lastName);

        JButton sayHello = new JButton("Say something");
        pane.add(sayHello);

        checkbox = new JCheckBox("Nice");
        pane.add(checkbox);

        // Add the pane to the main window
        getContentPane().add(pane);

        // Pack will make the size of window fitting to the compoents
        // You could also use for example setSize(300, 400);
        pack();

        // Set a tooltip for the button
        sayHello.setToolTipText("This button will say something really nice of something bad");
        // sayHello need to do something
        sayHello.addActionListener(this);
    }
    public void actionPerformed(ActionEvent e) {
        if (!checkbox.isSelected()) {
            JOptionPane.showMessageDialog(null, "I don't like you, "
                    + firstName.getText() + " " + lastName.getText() + "!");
        } else {
            JOptionPane.showMessageDialog(null, "How are you, "
                    + firstName.getText() + " " + lastName.getText() + "?");
        }
    }


}

//MainTester.java
package test;

import ui.MyFirstUI;

public class MainTester {
    public static void main(String[] args) {
        MyFirstUI view = new MyFirstUI();
        view.setVisible(true);
    }
}