JNEXT JAVA GROUPS
Tuesday 8 September 2015
Tuesday 30 September 2014
Image Upload Using servlet /Store image in data base
Image (Photo) Upload Using Java Servlet and JSP
Please Download below jar File:
Java Class: UploadFile .class
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UploadFile extends HttpServlet {
private static final String upload="upload";
private static final int thread =1024*1024*3;
private static final int filesize=1024*1024*40;
private static final int reqsize=1024*1024*50;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
if(!ServletFileUpload.isMultipartContent(req)){
System.out.println(" please select file ");
}
else{
DiskFileItemFactory factory= new DiskFileItemFactory();
factory.setSizeThreshold(thread);
factory.setRepository(new File(System.getProperty("java.io.temdir")));
ServletFileUpload fileUpload= new ServletFileUpload(factory);
fileUpload.setSizeMax(reqsize);
fileUpload.setFileSizeMax(filesize);
String path=getServletContext().getRealPath("")+File.separator+upload;
File file= new File(path);
if(!file.exists()){
file.mkdir();
}
try{
List list=fileUpload.parseRequest(req);
Iterator iter=list.iterator();
// iterates over form's fields
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
// processes only fields that are not form fields
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
String filePath =upload+File.separator+fileName;
File storeFile = new File(filePath);
// saves the file on disk
item.write(storeFile);
}
}
}
catch (Exception e) {
// TODO: handle exception
}
}
}
}
JSP Page: index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
Insert title here
select File :
web.xml
UploadFile
index.jsp
uplaod
Uploadfile
uplaod
/upload
Please Download below jar File:
- commons-fileupload-1.2.2.jar
- commons-io-2.5-20121102.152256-3.jar
Java Class: UploadFile .class
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UploadFile extends HttpServlet {
private static final String upload="upload";
private static final int thread =1024*1024*3;
private static final int filesize=1024*1024*40;
private static final int reqsize=1024*1024*50;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
if(!ServletFileUpload.isMultipartContent(req)){
System.out.println(" please select file ");
}
else{
DiskFileItemFactory factory= new DiskFileItemFactory();
factory.setSizeThreshold(thread);
factory.setRepository(new File(System.getProperty("java.io.temdir")));
ServletFileUpload fileUpload= new ServletFileUpload(factory);
fileUpload.setSizeMax(reqsize);
fileUpload.setFileSizeMax(filesize);
String path=getServletContext().getRealPath("")+File.separator+upload;
File file= new File(path);
if(!file.exists()){
file.mkdir();
}
try{
List list=fileUpload.parseRequest(req);
Iterator iter=list.iterator();
// iterates over form's fields
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
// processes only fields that are not form fields
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
String filePath =upload+File.separator+fileName;
File storeFile = new File(filePath);
// saves the file on disk
item.write(storeFile);
}
}
}
catch (Exception e) {
// TODO: handle exception
}
}
}
}
JSP Page: index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
select File :
web.xml
Friday 8 August 2014
how to send multiple image by using java Bluetooth
Send File Multiples Device
Download List Of Jar File:
Download List Of Jar File:
- bluecover-2.1.1
- commons-io-1.3.2
Now create Couple of java class.
1)UI Class:
public class UIDemo extends JDialog implements ActionListener{
private JTextArea jTextArea;
private JList jList;
private DialogListener listener;
private Object[] items;
private JLabel statusLabel;
private static JFileChooser fileChooser = new JFileChooser();
public MyDialog(String title, Object [] items , DialogListener listener ) {
super.setTitle(title);
this.listener = listener;
this.setSize(500,300);
jList = new JList();
if(items==null){
items = new Object[0];
}
jList.setListData(items);
this.items = items;
JScrollPane jScrollPane = new JScrollPane(jList);
jScrollPane.setSize(255,5);
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(jScrollPane,BorderLayout.WEST);
jTextArea = new JTextArea("Enter message ");
this.getContentPane().add(jTextArea,BorderLayout.CENTER);
JButton ffile= new JButton("Browse");
ffile.addActionListener(this);
this.getContentPane().add(ffile,BorderLayout.EAST);
JButton jButton = new JButton("Send");
jButton.addActionListener(this);
this.getContentPane().add(jButton,BorderLayout.SOUTH);
statusLabel = new JLabel("Started");
fileChooser.setMultiSelectionEnabled(true);
fileChooser.setCurrentDirectory(new File("path (D:/jnext/.....)"));
fileChooser.setBounds(50,50,400,400);
this.getContentPane().add(statusLabel,BorderLayout.NORTH);
setLocationRelativeTo(null);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.show();
}
public void addItem(Object item){
Object [] newitems = new Object[items.length+1];
for (int i = 0; i < items.length; i++) {
newitems[i] = items[i];
}
newitems[newitems.length-1] =item;
items = newitems;
jList.setListData(newitems);
}
public void setStatus(String text){
statusLabel.setText(text);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("Send")){
Object [] selectedItems = jList.getSelectedValues();
String message = jTextArea.getText();
Point a=fileChooser.getLocation();
File f=fileChooser.getSelectedFile();
System.out.println(f.getAbsolutePath()+" path :");
System.out.println(" first file");
System.out.println("project data "+a);
listener.sendPressed(selectedItems, f.getAbsolutePath(),this);
}
else{
fileChooser.showDialog(null,
"File Chooser");
}
}
public interface DialogListener{
public void sendPressed(Object [] selectedItems, String message,MyDialog dialog);
}
}
2) BTDevice :
public class BTDevice {
private String name;
private String BTURL;
public BTDevice(String name,String BTURL) {
this.name=name;
this.BTURL=BTURL;
}
@Override
public String toString() {
return name;
}
public String getBTURL() {
return BTURL;
}
}
3)BTMessageSender class :
public class BTMessageSender {
public static boolean sendMessage(String deviceBTURL, String message, MyDialog dialog){
// we assume that the given device already has the service
try{
System.out.println("Connecting to " + deviceBTURL);
dialog.setStatus("Connecting to " + deviceBTURL);
ClientSession clientSession =
(ClientSession) Connector.open(deviceBTURL);
HeaderSet hsConnectReply = clientSession.connect(null);
if (hsConnectReply.getResponseCode() != ResponseCodes.OBEX_HTTP_OK) {
System.out.println("Failed to connect");
dialog.setStatus("Failed to connect");
return false;
}
HeaderSet hsOperation = clientSession.createHeaderSet();
hsOperation.setHeader(HeaderSet.NAME, "jnext.text");
hsOperation.setHeader(HeaderSet.TYPE, "text");
Operation putOperation = clientSession.put(hsOperation);
// 4. send the data to the device
File f= new File(message);
InputStream is= new FileInputStream(f);
byte bk[]=IOUtils.toByteArray(is);
// File imgPath = new File(ImageName);
BufferedImage bufferedImage = ImageIO.read(f);
// get DataBufferBytes from Raster
WritableRaster raster = bufferedImage .getRaster();
DataBufferByte data = (DataBufferByte) raster.getDataBuffer();
// text message
// byte arydata[] = message.getBytes("iso-8859-1");
byte arydata[] =data.getData();
System.out.println(" total size "+arydata.length);
OutputStream os = putOperation.openOutputStream();
os.write(bk);
os.close();
putOperation.close();
clientSession.disconnect(null);
clientSession.close();
}
catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
}
4)BTServicesSearcher class :
public class BTServicesSearcher {
static String tempDeviceName;
private static MyDialog dialog;
private static RemoteDeviceDiscoverer remoteDeviceDiscoverer;
static final UUID OBEX_OBJECT_PUSH = new UUID(0x1105);
public static final Vector serviceFound = new Vector();
public static void main(String[] args) throws IOException, InterruptedException {
dialog = new MyDialog("Bluetooth multi-sender",null, new DevicesDialogListener());
remoteDeviceDiscoverer = new RemoteDeviceDiscoverer();
// First run RemoteDeviceDiscovery and use discovered device
dialog.setStatus("Searching devices, please wait..");
remoteDeviceDiscoverer.searchDevices();
serviceFound.clear();
UUID serviceUUID = OBEX_OBJECT_PUSH;
if ((args != null) && (args.length > 0)) {
serviceUUID = new UUID(args[0], false);
}
final Object serviceSearchCompletedEvent = new Object();
DiscoveryListener listener = new DiscoveryListener() {
public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
}
public void inquiryCompleted(int discType) {
}
public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
for (int i = 0; i < servRecord.length; i++) {
String url = servRecord[i].getConnectionURL(ServiceRecord.AUTHENTICATE_NOENCRYPT, false);
if (url == null) {
continue;
}
serviceFound.add(url);
DataElement serviceName = servRecord[i].getAttributeValue(0x0100);
if (serviceName != null) {
System.out.println("service " + serviceName.getValue() + " found " + url);
} else {
System.out.println("service found " + url);
}
dialog.addItem(new BTDevice(tempDeviceName,url));
}
}
public void serviceSearchCompleted(int transID, int respCode) {
System.out.println("service search completed!");
synchronized(serviceSearchCompletedEvent){
serviceSearchCompletedEvent.notifyAll();
}
}
};
UUID[] searchUuidSet = new UUID[] { serviceUUID };
int[] attrIDs = new int[] {
0x0100 // Service name
};
int size = remoteDeviceDiscoverer.getDevicesDiscovered().size();
dialog.setStatus(size + " devices found. Now checking which is supported.");
for(Enumeration en = remoteDeviceDiscoverer.getDevicesDiscovered().elements(); en.hasMoreElements(); ) {
RemoteDevice btDevice = (RemoteDevice)en.nextElement();
synchronized(serviceSearchCompletedEvent) {
String friendlyName = "";
try{
friendlyName = btDevice.getFriendlyName(false);
tempDeviceName = friendlyName;
}
catch (Exception e) {
System.out.println("(dont know the name)");
tempDeviceName = null;
}
System.out.println("search services on " + btDevice.getBluetoothAddress() + " " + friendlyName);
LocalDevice.getLocalDevice().getDiscoveryAgent().searchServices(attrIDs, searchUuidSet, btDevice, listener);
serviceSearchCompletedEvent.wait();
}
}
dialog.setStatus("Search finished. Send a message");
}
}
5)DevicesDialogListener class :
public class DevicesDialogListener implements DialogListener {
@Override
public void sendPressed(Object[] selectedItems, String message,MyDialog dialog) {
System.out.println(""+message);
for (Object item : selectedItems) {
BTMessageSender.sendMessage(((BTDevice)item).getBTURL(),message, dialog);
}
}
}
6)RemoteDeviceDiscoverer class :
public class RemoteDeviceDiscoverer {
private final Vector devicesDiscovered = new Vector();
public void searchDevices() throws IOException, InterruptedException {
final Object inquiryCompletedEvent = new Object();
devicesDiscovered.clear();
DiscoveryListener listener = new DiscoveryListener() {
public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
System.out.println("Device " + btDevice.getBluetoothAddress() + " found");
devicesDiscovered.addElement(btDevice);
try {
System.out.println(" name " + btDevice.getFriendlyName(false));
} catch (IOException cantGetDeviceName) {
}
}
public void inquiryCompleted(int discType) {
System.out.println("Device Inquiry completed!");
synchronized(inquiryCompletedEvent){
inquiryCompletedEvent.notifyAll();
}
}
public void serviceSearchCompleted(int transID, int respCode) {
}
public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
}
};
synchronized(inquiryCompletedEvent) {
boolean started = LocalDevice.getLocalDevice().getDiscoveryAgent().startInquiry(DiscoveryAgent.GIAC, listener);
if (started) {
//wait for device inquiry to complete
inquiryCompletedEvent.wait();
System.out.println(devicesDiscovered.size() + " device(s) found");
}
}
}
public Vector getDevicesDiscovered() {
return devicesDiscovered;
}
}
Note: Application start on UI class.
How to connect java to mysql server by using jdbc
Java With Mysql Database connectivity
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306","root","root");
System.out.println("welcome to jnext : mysql database connect: "+connection);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306","root","root");
System.out.println("welcome to jnext : mysql database connect: "+connection);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
contace me :ghorivipul97@gmail.com
How to use session in java
Login With Java Session /How Use session object in java ???
public class CheckLogin {
public void checkValid(UserDetail bean){
String sql="SELECT * FROM tablename WHERE user=?";
Connection con=DBcon.getConnection(); //singleton database object
try {
PreparedStatement pstm=con.prepareStatement(sql);
pstm.setInt(1,"jnext");//username
ResultSet rs=pstm.executeQuery(); //execute query
if(rs.next()){
System.out.println("WEL-COME jnext Development : ");
HttpSession session=req.getSession(true); // session start for new user
session.setAttribute("ky", "jnext"); // set user name on session scope
RequestDispatcher rd;
rd=req.getRequestDispatcher("abc.jsp"); // redirect after login page
rd.forward(req, resp);
}
} catch (SQLException e) {
System.out.println("sql exception please check sql query");
e.printStackTrace(); //print exception
}
}
}
}
public class CheckLogin {
public void checkValid(UserDetail bean){
String sql="SELECT * FROM tablename WHERE user=?";
Connection con=DBcon.getConnection(); //singleton database object
try {
PreparedStatement pstm=con.prepareStatement(sql);
pstm.setInt(1,"jnext");//username
ResultSet rs=pstm.executeQuery(); //execute query
if(rs.next()){
System.out.println("WEL-COME jnext Development : ");
HttpSession session=req.getSession(true); // session start for new user
session.setAttribute("ky", "jnext"); // set user name on session scope
RequestDispatcher rd;
rd=req.getRequestDispatcher("abc.jsp"); // redirect after login page
rd.forward(req, resp);
}
} catch (SQLException e) {
System.out.println("sql exception please check sql query");
e.printStackTrace(); //print exception
}
}
}
}
contace me :ghorivipul97@gmail.com
Array Index out of bound Exception
import java.util.ArrayList;
public class Jnext_Demo {
public static void main(String[] args) {
ArrayList
//now ADD data in array list 2 string insert in array list
data.add("java"); // 0 index
data.add("android"); // 1 index
// now Display data with index 3
System.out.println(data.get(3));
}
}
Check screen short for java class.
Output Screen
IF you have more Query ,Write comment blow
Subscribe to:
Posts (Atom)