How to pass whole toolbar item into keybinding? - eclipse-rcp

I have A one RCP application which is run on the windows platform.in this application so many command in tool bar, So i want to assign one short cut key
to open one by one tool bar how to do this?
I have used key biding concept but, tool bar item = shortcut key happen , so i want only one key then how to do it possible?

You can't do this. A key binding is always bound to a single command.
If you want to do things in a sequence use a Wizard with multiple pages or something like that.
Using a cheat sheet to guide the user through the actions might be another way.

I have do it but different way. Whole toolbar item is passed via handler. I can share you code:
Forward Editor code:
package handler;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.handlers.HandlerUtil;
import rcp_demo.Editor.EmployeeEditor;
import rcp_demo.Editor.EmployeeEditorInput;
import rcp_demo.Editor.EnquiryEditor;
import rcp_demo.Editor.EnquiryEditorInput;
import rcp_demo.Editor.FoodDetailsEditor;
import rcp_demo.Editor.FoodDetailsEditorInput;
import rcp_demo.Editor.StaffdetailsEditor;
import rcp_demo.Editor.StaffdetailsEditorInput;
//Defauklt Editor ID
import rcp_demo.Editor.UserEditor;
import rcp_demo.Editor.UserEditorInput;
/**
* #author summet
*
*/
public class SwitchingHandler extends AbstractHandler {
/*
* (non-Javadoc)
*
* #see
* org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.
* ExecutionEvent)
*/
String tempEditorID = null;
#Override
public Object execute(ExecutionEvent event) throws ExecutionException {
System.out.println("SwitchingHandler command call");
// TODO Auto-generated method stub
// HandlerUtil.getActiveWorkbenchWindow
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
IWorkbenchPage page = window.getActivePage();
IEditorReference[] editorRefs = page.getEditorReferences();
// get the editor instance by given id (pEditorId)
if (page.getActiveEditor() == null || page.getActiveEditor().equals("")) {
// Default Editor Open via command
UserEditorInput input = new UserEditorInput();
try {
page.openEditor(input, UserEditor.ID);
} catch (PartInitException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
} else {
// First check Temp ID;
String tempID = checkActiveEditorID(page);
if (tempID.equals(UserEditor.BID)) {
System.out.println("You are in UserEditor.ID");
page.closeAllEditors(true);
EmployeeEditorInput einput = new EmployeeEditorInput();
try {
page.closeAllEditors(true);
page.openEditor(einput, EmployeeEditor.ID);
tempID = null;
} catch (PartInitException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (tempID.equals(EmployeeEditor.BID)) {
System.out.println("You are in EmployeeEditor.ID");
StaffdetailsEditorInput sinput = new StaffdetailsEditorInput();
try {
page.closeAllEditors(true);
page.openEditor(sinput, StaffdetailsEditor.ID);
tempID = null;
} catch (PartInitException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (tempID.equals(StaffdetailsEditor.BID)) {
System.out.println("You are in StaffdetailsEditor.ID");
FoodDetailsEditorInput finput = new FoodDetailsEditorInput();
try {
page.closeAllEditors(true);
page.openEditor(finput, FoodDetailsEditor.ID);
tempID = null;
} catch (PartInitException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (tempID.equals(FoodDetailsEditor.BID)) {
System.out.println("You are in FoodDetailsEditor.ID");
EnquiryEditorInput eeinput = new EnquiryEditorInput();
try {
page.closeAllEditors(true);
page.openEditor(eeinput, EnquiryEditor.ID);
tempID = null;
} catch (PartInitException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (tempID.equals(EnquiryEditor.BID)) {
System.out.println("You are in EnquiryEditor.ID");
UserEditorInput uinput = new UserEditorInput();
try {
page.closeAllEditors(true);
page.openEditor(uinput, UserEditor.ID);
tempID = null;
} catch (PartInitException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
private String checkActiveEditorID(IWorkbenchPage page) {
tempEditorID = page.getActiveEditor().getTitle();
return tempEditorID;
// TODO Auto-generated method stub
}
}
Backward Editor code:
package handler;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.handlers.HandlerUtil;
import rcp_demo.Editor.EmployeeEditor;
import rcp_demo.Editor.EmployeeEditorInput;
import rcp_demo.Editor.EnquiryEditor;
import rcp_demo.Editor.EnquiryEditorInput;
import rcp_demo.Editor.FoodDetailsEditor;
import rcp_demo.Editor.FoodDetailsEditorInput;
import rcp_demo.Editor.StaffdetailsEditor;
import rcp_demo.Editor.StaffdetailsEditorInput;
import rcp_demo.Editor.UserEditor;
import rcp_demo.Editor.UserEditorInput;
public class BackEditorHandler extends AbstractHandler {
/*
* (non-Javadoc)
*
* #see
* org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.
* ExecutionEvent)
*/
String tempBackEditorID = null;
#Override
public Object execute(ExecutionEvent event) throws ExecutionException {
System.out.println("BackEditorHandler call");
// TODO Auto-generated method stub
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
IWorkbenchPage page = window.getActivePage();
IEditorReference[] editorRefs = page.getEditorReferences();
// get the editor instance by given id (pEditorId)
if (page.getActiveEditor() == null || page.getActiveEditor().equals("")) {
// Default Editor Open via command
UserEditorInput input = new UserEditorInput();
try {
page.openEditor(input, UserEditor.ID);
} catch (PartInitException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
} else {
// First check Temp ID;
String tempBackID = checkActiveEditorID(page);
System.out.println("tempID:--" + tempBackID);
if (tempBackID.equals(UserEditor.BID)) {
System.out.println("You are in UserEditor.ID");
page.closeAllEditors(true);
EnquiryEditorInput eeinput = new EnquiryEditorInput();
try {
page.closeAllEditors(true);
page.openEditor(eeinput, EnquiryEditor.ID);
tempBackID = null;
} catch (PartInitException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (tempBackID.equals(EmployeeEditor.BID)) {
System.out.println("You are in EmployeeEditor.ID");
UserEditorInput uinput = new UserEditorInput();
try {
page.closeAllEditors(true);
page.openEditor(uinput, UserEditor.ID);
tempBackID = null;
} catch (PartInitException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (tempBackID.equals(StaffdetailsEditor.BID)) {
System.out.println("You are in StaffdetailsEditor.ID");
EmployeeEditorInput einput = new EmployeeEditorInput();
try {
page.closeAllEditors(true);
page.openEditor(einput, EmployeeEditor.ID);
tempBackID = null;
} catch (PartInitException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (tempBackID.equals(FoodDetailsEditor.BID)) {
System.out.println("You are in FoodDetailsEditor.ID");
StaffdetailsEditorInput sinput = new StaffdetailsEditorInput();
try {
page.closeAllEditors(true);
page.openEditor(sinput, StaffdetailsEditor.ID);
tempBackID = null;
} catch (PartInitException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (tempBackID.equals(EnquiryEditor.BID)) {
System.out.println("You are in EnquiryEditor.ID");
FoodDetailsEditorInput finput = new FoodDetailsEditorInput();
try {
page.closeAllEditors(true);
page.openEditor(finput, FoodDetailsEditor.ID);
tempBackID = null;
} catch (PartInitException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
private String checkActiveEditorID(IWorkbenchPage page) {
tempBackEditorID = page.getActiveEditor().getTitle();
return tempBackEditorID;
// TODO Auto-generated method stub
}
}

Related

Caused by: org.eclipse.swt.SWTException: Invalid thread access

I get "Invalid thread access" in below code. I am not sure where I have written wrong code. My main intention to write the code is to just display subtask (what is happening behind the scene) so I have added subtask before method called.
#Override
public void handleEvent(Event event)
{
if((event.keyCode == SWT.CR || event.keyCode == 13 || event.type == SWT.Selection) && btnAdd.isEnabled())
{
final PreferencesMO permo = new PreferencesMO();
permo.updatePreferences();
permo.updateDocumentNumber();
final ProjectMO pmo = new ProjectMO();
final CoverSheetMO csmo = new CoverSheetMO();
final CommonError cmerror = new CommonError();
final ParameterConfigurationMO pamo = new ParameterConfigurationMO();
final SnippetNew s = new SnippetNew();
final String projName = txtpname.getText();
Display.getDefault().asyncExec(new Runnable()
{
public void run()
{
try
{
new ProgressMonitorDialog(shell).run(true, true, new IRunnableWithProgress() {
#Override
public void run(final IProgressMonitor monitor) throws InvocationTargetException,
InterruptedException
{
monitor.beginTask("Import Data", IProgressMonitor.UNKNOWN);
monitor.subTask("Connecting to databse...");
for(int i=0;i<=100;i++)
{
s.method1(i);
}
//monitor.worked(1);
try { Thread.sleep(2000); } catch (Exception e) { }
monitor.subTask("Analysing Data...");
try { Thread.sleep(2000); } catch (Exception e) { }
if(!projName.equals(""))
{
monitor.subTask("Updating coversheet ...");
try { Thread.sleep(2000); } catch (Exception e) { }
cmerror.updateCoverSheetStatusforNewProject();
monitor.subTask("Inserting Project ...");
try { Thread.sleep(2000); } catch (Exception e) { }
pmo.addProjectManager(projName,"T");
monitor.subTask("Searching Project ID ...");
try { Thread.sleep(2000); } catch (Exception e) { }
String p_id = pmo.searchprojectID(projName);
permo.insertDocumentNumber(p_id);
monitor.subTask("Inserting data into coversheet ...");
try { Thread.sleep(2000); } catch (Exception e) { }
csmo.insertCoversheet(p_id);
pamo.insertParameterConfiguration(p_id);
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell().setText("Demo Tool - "+projName);
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
AuditLogs view = (AuditLogs) page.findView(AuditLogs.ID);
IEditorPart editorPart = page.getActiveEditor();
StackedLambdaChartInput input = new StackedLambdaChartInput();
AnalysisResult_MetricsChartInput metricsinput = new AnalysisResult_MetricsChartInput();
StackedLambdaChart_HorizantalInput stackedhorizantalinput = new StackedLambdaChart_HorizantalInput();
AnalysisResult_Metrics_HorizantalChartInput metricshorizantalinput = new AnalysisResult_Metrics_HorizantalChartInput();
BarChartInput inpuit = new BarChartInput();
BarChart_HorizantalInput barchart_horizantalinput = new BarChart_HorizantalInput();
AuditLogMO auditlog = new AuditLogMO();
monitor.subTask("Fetching audit logs to display ...");
try { Thread.sleep(2000); } catch (Exception e) { }
java.util.List<java.util.List<String>> auditlogs = auditlog.searchAuditLog(null,null);
view.table(auditlogs);
try
{
handlerService.executeCommand(AuditLogView.ID, new Event());
handlerService.executeCommand(ErrorLogView.ID, new Event());
handlerService.executeCommand(DesignHierarchyHandler.ID, new Event());
if(myeditor != null)
{
if(myeditor instanceof CoverSheet)
{
handlerService.executeCommand(CoverSheetHandler.ID, new Event());
}
else if(myeditor instanceof ParameterConfigurations)
{
handlerService.executeCommand(ParameterConfigurationHandler.ID, new Event());
}
}
}
catch (ExecutionException | NotDefinedException | NotEnabledException | PartInitException| NotHandledException e1)
{
e1.printStackTrace();
}
Constant con = new Constant();
con.createNewProject();
}
//shell.close();
monitor.done();
}
});
}
catch (InvocationTargetException | InterruptedException e)
{
e.printStackTrace();
}
}
});
}
}
Put your progress monitor as below :
Display.getDefault().asyncExec( new Runnable()
{
IWorkbenchWindow win = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
new ProgressMonitorDialog(shell).run(true, true, new IRunnableWithProgress() {
#Override
public void run(final IProgressMonitor monitor) throws InvocationTargetException,
InterruptedException
{
monitor.beginTask("Import Data", IProgressMonitor.UNKNOWN);
monitor.subTask("Connecting to databse...");
for(int i=0;i<=100;i++)
}
If you want the workbench page, that also has to be called inside a UI thread like above.
You can't access UI code in the background thread used for the IRunnableWithProgress code.
So you must get the values of controls in the UI thread before you run the progress dialog.
You also can't access things like IWorkbenchPage in the background thread. If you want to update UI objects from a non-UI thread, you need to use Display.asyncExec or Display.syncExec to run the updating code in the UI thread.

DB connection getting closed while inserting record by MDB

I have created MDB to pick the message from MQ and inserting in to DB2.
I have created data sourse to get the DB connection in WAS. Its inserting message. But due to the speed of the MessageListener some messages not inserted because the connection got closed..
Please help me to handle the conction here..
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import javax.naming.NamingException;
#MessageDriven(
activationConfig = { #ActivationConfigProperty(
propertyName = "destinationType", propertyValue = "javax.jms.Queue"), #ActivationConfigProperty(
propertyName = "destination", propertyValue = "jms/MDBQueue")
},
mappedName = "jms/MDBQueue")
public class AsyncMessageConsumerBean implements MessageListener {
// TODO Auto-generated constructor stub
private javax.naming.InitialContext ctx = null;
private javax.sql.DataSource serviceDataSource = null;
private String environment = null;
/**
* #see MessageListener#onMessage(Message)
*/
public void onMessage(Message message) {
// TODO Auto-generated method stub
System.out.println("On Message Started.....");
try{
if (message instanceof javax.jms.BytesMessage)
{
javax.jms.BytesMessage bytesMessage = (javax.jms.BytesMessage) message;
byte[] bytes = new byte[(int) bytesMessage.getBodyLength()];
bytesMessage.readBytes(bytes);
System.out.println("Reply Message");
String replyMessage = new String(bytes, "UTF-8");
System.out.println(" The message received from MQ :-----" + replyMessage);
insertMQMessage(replyMessage);
}else {
javax.jms.TextMessage TextMessage = (javax.jms.TextMessage) message;
System.out.println("----------- The text message received from UM Queue"+TextMessage.getText());
insertMQMessage(TextMessage.getText());
}
}catch (JMSException ex) {
throw new RuntimeException(ex);
}catch(Exception ex){
ex.printStackTrace();
}
}
public void insertMQMessage(String mqMessage) throws Exception
{
Statement stmtsql = null;
Connection connection = null;
try
{
connection = getDBConnection();
System.out.println("Connection Object :"+connection);
String mqMsgTrackerInsertQry = "";
System.out.println("MQ Tracker insert Query:" + mqMsgTrackerInsertQry);
stmtsql = connection.createStatement();
boolean status = stmtsql.execute(mqMsgTrackerInsertQry);
}
catch(Exception e)
{
e.printStackTrace();
throw e;
}
finally
{
if (stmtsql != null)
try {
stmtsql.close();
} catch (SQLException ignore) {
}
if (connection != null)
try {
connection.close();
} catch (SQLException ignore) {
}
}
}
private Connection getDBConnection() throws SQLException {
try {
ctx = new javax.naming.InitialContext();
serviceDataSource = (javax.sql.DataSource) ctx.lookup("jdbc/DB_DS_XA");
System.out.println("Datasource initiallised"+serviceDataSource);
} catch (NamingException e) {
System.out.println("peformanceappraisalstatus: COULDN'T CREATE CONNECTION!");
e.printStackTrace();
}
Connection connection = null;
try {
connection = serviceDataSource.getConnection();
//connection.setAutoCommit(false);
} catch (SQLException e) {
throw e;
}
return connection;
}
}

How to make a program use a file whose name you specify on the command line

How can I get this program to read in the "lab13.txt" in the command line? I've been trying to figure this out for over an hour and nothing seemed to work.
The prompt is "Write a program that determines and displays the number of lines in the file whose name you specify on the command line. Test your program with lab13.txt."
import java.util.Scanner;
import java.io.*;
class homework
{
public static void main(String[] args) throws IOException
{
Scanner inFile= new Scanner(new File("lab13.txt"));
int count=0;
String s;
while (inFile.hasNextLine())
{
s = inFile.nextLine();
count++;
}
System.out.println(count + " Lines in lab13.txt");
inFile.close();
}
}
If you want the user to be able to input the filename from command line or console in eclipse try using this
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter filename : ");
String filename = null;
try {
filename = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
You can then plug the filename into your Scanner object
http://docs.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html
The stuff you add to the command-line after the program name go in the args array, so:
Scanner inFile= new Scanner(new File(args[0]));
Try this
In your code you need to replace new File("lab13.txt") with new File(args[0])
For command line
public static void main(String[] args) {
File inFile =null;
if (0 < args.length) {
File inFile = new File(args[0]);
}
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(inFile));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
For a particular location
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderExample {
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\lab13.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}

How to display only the contents of the workspace in a TreeViewer?

How to display only the contents of the workspace in my TreeViewer?
This is my main view class:
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.part.ViewPart;
public class MainView extends ViewPart {
public static final String ID = "com.MainView";
public MainView() {
// TODO Auto-generated constructor stub
}
#Override
public void createPartControl(Composite parent) {
TreeViewer tv = new TreeViewer(parent);
tv.getTree().setLayoutData(new GridData(GridData.FILL_BOTH));
tv.setContentProvider(new FileTreeContentProvider());
tv.setLabelProvider(new FileTreeLabelProvider());
tv.setInput(ResourcesPlugin.getWorkspace());
}
#Override
public void setFocus() {
// TODO Auto-generated method stub
}
}
This is my content provider class:
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.Viewer;
public class FileTreeContentProvider implements ITreeContentProvider {
public void dispose() {
}
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
public Object[] getElements(Object inputElement) {
return null;
}
public Object[] getChildren(Object parentElement) {
if (parentElement instanceof IProject) {
IProject projects = (IProject) parentElement;
try {
return projects.members();
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (parentElement instanceof IFolder) {
IFolder ifolder = (IFolder) parentElement;
try {
return ifolder.members();
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
public Object getParent(Object element) {
if (element instanceof IProject) {
IProject projects = (IProject) element;
return projects.getParent();
}
if (element instanceof IFolder) {
IFolder folder = (IFolder) element;
return folder.getParent();
}
if (element instanceof IFile) {
IFile file = (IFile) element;
return file.getParent();
}
return null;
}
public boolean hasChildren(Object element) {
if (element instanceof IProject) {
IProject projects = (IProject) element;
try {
return projects.members().length > 0;
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (element instanceof IFolder) {
IFolder folder = (IFolder) element;
try {
return folder.members().length > 0;
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return false;
}
}
This is my label provider class:
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.swt.graphics.Image;
public class FileTreeLabelProvider implements ILabelProvider {
public void addListener(ILabelProviderListener listener) {
}
public void dispose() {
}
public boolean isLabelProperty(Object element, String property) {
return false;
}
public void removeListener(ILabelProviderListener listener) {
}
public Image getImage(Object element) {
return null;
}
public String getText(Object element) {
if (element instanceof IProject) {
String text = ((IProject) element).getName();
return text;
}
if (element instanceof IFolder) {
String text = ((IFolder) element).getName();
return text;
}
if (element instanceof IFile) {
String text = ((IFile) element).getName();
return text;
}
return null;
}
}
public Object[] getElements(Object inputElement) {
return ResourcesPlugin.getWorkspace().getRoot().getProjects();
}
I am able to get projects now.my code is working
A content provider and a label provider for the workspace objects are already present in the Eclipse framework:
org.eclipse.ui.model.WorkbenchLabelProvider
org.eclipse.ui.model.WorkbenchContentProvider
Using them, your code will look like this:
TreeViewer treeViewer = new TreeViewer(parent);
treeViewer.getTree().setLayoutData(new GridData(GridData.FILL_BOTH));
treeViewer.setContentProvider(new WorkbenchContentProvider());
treeViewer.setLabelProvider(new WorkbenchLabelProvider());
treeViewer.setInput(ResourcesPlugin.getWorkspace().getRoot());

Regarding HttpConnection Error

I created a J2me program for HttpConenction to http://www.google.com
But when I run I get an error
error 10054 during TCP read
In this I have just created a HttpConnection and reads a string from inputstream
In this an object of Httpconnection is made then the Inputstream is called which read from url ie http://www.google.com
Below is the code
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import javax.microedition.io.ConnectionNotFoundException;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.OutputConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class NetworkFile extends MIDlet implements CommandListener {
Form form;
Display display;
Command start,exit;
public NetworkFile() {
// TODO Auto-generated constructor stub
form=new Form(null);
exit=new Command("Exit",Command.EXIT, 0);
start=new Command("Start",Command.OK, 1);
form.addCommand(exit);
form.addCommand(start);
form.setCommandListener(this);
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
// TODO Auto-generated method stub
}
protected void pauseApp() {
// TODO Auto-generated method stub
}
protected void startApp() throws MIDletStateChangeException {
// TODO Auto-generated method stub
display=Display.getDisplay(this);
display.setCurrent(form);
}
public void commandAction(Command c, Displayable d) {
// TODO Auto-generated method stub
if (c==start) {
Abc t=new Abc(this);
t.start();
} else if(c==exit){
notifyDestroyed();
}
}
}
class Abc extends Thread
{
NetworkFile net1;
HttpConnection hs=null;
DataOutputStream requestOutputStream;
InputStream is=null;
StringBuffer sb=null;
Abc(NetworkFile net1)
{
this.net1=net1;
}
public void run()
{
try {
/*OutputConnection connection=(OutputConnection)Connector.open("file:///D:/lamp.txt;append=true",Connector.WRITE);
OutputStream out=connection.openOutputStream();
PrintStream output=new PrintStream(out);
output.println("Hi , This is a J2ME project ");
out.close();
connection.close();
Alert alert=new Alert("Alert", "Data Written", null, AlertType.INFO);
alert.setTimeout(Alert.FOREVER);
net1.display.setCurrent(alert);*/
System.out.println("Line 1");
hs = (HttpConnection)Connector.open("http://www.google.com",Connector.READ_WRITE, true);
System.out.println("Line 2");
hs.setRequestMethod(HttpConnection.POST);
System.out.println("Line 3");
is=hs.openInputStream();
System.out.println("Line 4");
int ch=0;
sb = new StringBuffer();
for (int i = 0; i < 150; i++) {
System.out.println("Line 5");
ch=is.read();
System.out.println("Line 6");
if(ch==-1)
{
break;
}
System.out.println("ch "+ch);
sb.append((char)ch);
}
} catch (ConnectionNotFoundException e) {
// TODO Auto-generated catch block
System.out.println(e.toString());
Alert alert=new Alert("Alert", " Connection ERROR !!! "+e.toString(), null, AlertType.INFO);
alert.setTimeout(Alert.FOREVER);
net1.display.setCurrent(alert);
} catch (IOException e) {
System.out.println(e.toString());
// TODO Auto-generated catch block
Alert alert=new Alert("Alert", " IO ERROR !!! "+e.toString(), null, AlertType.INFO);
alert.setTimeout(Alert.FOREVER);
net1.display.setCurrent(alert);
}catch (Exception e) {
// TODO Auto-generated catch block
System.out.println(e.toString());
Alert alert=new Alert("Alert", " Exception ERROR !!! "+e.toString(), null, AlertType.INFO);
alert.setTimeout(Alert.FOREVER);
net1.display.setCurrent(alert);
}
System.out.println(sb.toString());
}
}