ASM ByteCode Instrumentation , Which Method is Executed - java-bytecode-asm

I am using ASM Bytecode Library to instrument Java Classes using pre-main.
How do we get the name of the method executed?
Thanks in advance...

In short, there is a name parameter on corresponding visit*() method call. You'll have to produce a more specific example to get more detailed answer.

Attached my Code for your reference
package com.eg.agent;
import java.lang.instrument.Instrumentation;
public class Agent {
private Agent(Instrumentation instrumentation){
}
public static void premain(String agentArgs, Instrumentation inst)
{
EgClassFileTransformer egClassFileTransformer =
new EgClassFileTransformer (agentArgs , inst);
}
}
package com.eg.agent;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation;
import java.security.ProtectionDomain;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import org.objectweb.asm.ClassReader;
public class EgClassFileTransformer implements ClassFileTransformer {
protected String agentArgString = "";
protected Instrumentation instrumentation;
public EgClassFileTransformer(String agentArgs, Instrumentation inst){
agentArgString = agentArgs;
instrumentation = inst;
instrumentation.addTransformer(this);
}
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException
{
//System.out.println("ClassName :"+className);
InputStream in = loader.getResourceAsStream(className.replace('.', '/') + ".class");
try{
ClassReader classReader=new ClassReader(in);
String superClassName = classReader.getSuperName();
String[] interfaces = classReader.getInterfaces();
if(interfaces!=null && interfaces.length > 0){
for(int k=0;k<interfaces.length;k++){
String inface = interfaces[k];
System.out.println(" \t interface :"+inface);
}
}
//System.out.println("superClassName :"+superClassName);
ArrayList thisList = new ArrayList();
thisList.add(superClassName);
ArrayList superList = printSuperClassNames(superClassName , thisList);
System.out.println("className :"+className +" ==>"+ " superList :"+superList);
} catch (IOException e) {
//e.printStackTrace();
System.out.println("[EXECEPTION] ..."+className);
}
return null;
}
public static ArrayList printSuperClassNames(String className, ArrayList list)
{
ClassReader cr=null;
try {
cr = new ClassReader(className);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String superName = cr.getSuperName();
//System.out.println("[superName]"+superName);
if(superName!=null && !superName.equals("java/lang/Object"))
{
list.add(superName);
String superClass = superName.replace('.', '/');
printSuperClassNames(superClass, list);
}
return list;
}
}

Related

How to generate extent report for cucumber + testng framework

How to generate extent report for cucumber + testng framework in such a way that on each scenario failure I can get the screen shot captured, without repeating the code with every scenario in step definition file
I have setup the Testing framework using Cucumber+Testng. However, I need extent reporting but not sure how to achieve it through testNG runner class without actually repeating the code with every scenario of step definition. So the idea is to write code in one place just like using cucumber hooks which will run for each and every scenario.
I Have already tried the approach with TestNG listener with Extent report but with this the drawback is I have to write the code every time for each and every scenario. LIke below I have ITestListnerImpl.java, ExtentReportListner and YouTubeChannelValidationStepDef where for each scenario I have to repeat the loginfo and screencapture methods
Code: ItestListerner.java
package com.testuatomation.Listeners;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
import com.aventstack.extentreports.ExtentReports;
public class ITestListenerImpl extends ExtentReportListener implements ITestListener {
private static ExtentReports extent;
#Override
public void onFinish(ITestContext arg0) {
// TODO Auto-generated method stub
extent.flush();
System.out.println("Execution completed on UAT env ......");
}
#Override
public void onStart(ITestContext arg0) {
// TODO Auto-generated method stub
extent = setUp();
System.out.println("Execution started on UAT env ......");
}
#Override
public void onTestFailedButWithinSuccessPercentage(ITestResult arg0){
// TODO Auto-generated method stub
}
#Override
public void onTestFailure(ITestResult arg0) {
// TODO Auto-generated method stub
System.out.println("FAILURE");
}
#Override
public void onTestSkipped(ITestResult arg0) {
System.out.println("SKIP");
}
#Override
public void onTestStart(ITestResult arg0) {
System.out.println("STARTED");
}
#Override
public void onTestSuccess(ITestResult arg0) {
// TODO Auto-generated method stub
System.out.println("PASS-----");
}
}
ExtentReportListener. java
package com.testuatomation.Listeners;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.markuputils.ExtentColor;
import com.aventstack.extentreports.markuputils.MarkupHelper;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
import com.aventstack.extentreports.reporter.configuration.Theme;
public class ExtentReportListener {
public static ExtentHtmlReporter report = null;
public static ExtentReports extent = null;
public static ExtentTest test = null;
public static ExtentReports setUp() {
String reportLocation = "./Reports/Extent_Report.html";
report = new ExtentHtmlReporter(reportLocation);
report.config().setDocumentTitle("Automation Test Report");
report.config().setReportName("Automation Test Report");
report.config().setTheme(Theme.STANDARD);
System.out.println("Extent Report location initialized . . .");
report.start();
extent = new ExtentReports();
extent.attachReporter(report);
extent.setSystemInfo("Application", "Youtube");
extent.setSystemInfo("Operating System", System.getProperty("os.name"));
extent.setSystemInfo("User Name", System.getProperty("user.name"));
System.out.println("System Info. set in Extent Report");
return extent;
}
public static void testStepHandle(String teststatus,WebDriver driver,ExtentTest extenttest,Throwable throwable) {
switch (teststatus) {
case "FAIL":
extenttest.fail(MarkupHelper.createLabel("Test Case is Failed : ", ExtentColor.RED));
extenttest.error(throwable.fillInStackTrace());
try {
extenttest.addScreenCaptureFromPath(captureScreenShot(driver));
} catch (IOException e) {
e.printStackTrace();
}
if (driver != null) {
driver.quit();
}
break;
case "PASS":
extenttest.pass(MarkupHelper.createLabel("Test Case is Passed : ", ExtentColor.GREEN));
break;
default:
break;
}
}
public static String captureScreenShot(WebDriver driver) throws IOException {
TakesScreenshot screen = (TakesScreenshot) driver;
File src = screen.getScreenshotAs(OutputType.FILE);
String dest = "C:\\Users\\Prateek.Nehra\\workspace\\SeleniumCucumberBDDFramework\\screenshots\\" + getcurrentdateandtime() + ".png";
File target = new File(dest);
FileUtils.copyFile(src, target);
return dest;
}
private static String getcurrentdateandtime() {
String str = null;
try {
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss:SSS");
Date date = new Date();
str = dateFormat.format(date);
str = str.replace(" ", "").replaceAll("/", "").replaceAll(":", "");
} catch (Exception e) {
}
return str;
}
}
YoutubeChannelValidationsStepDef.java
package com.testautomation.StepDef;
import java.util.Properties;
import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.GherkinKeyword;
import com.aventstack.extentreports.gherkin.model.Feature;
import com.aventstack.extentreports.gherkin.model.Scenario;
import com.testuatomation.Listeners.ExtentReportListener;
import com.testautomation.PageObjects.YoutubeChannelPage;
import com.testautomation.PageObjects.YoutubeResultPage;
import com.testautomation.PageObjects.YoutubeSearchPage;
import com.testautomation.Utility.BrowserUtility;
import com.testautomation.Utility.PropertiesFileReader;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class YoutubeChannelValidationsStepDef extends ExtentReportListener
{
PropertiesFileReader obj= new PropertiesFileReader();
private WebDriver driver;
#Given("^Open Chrome browser with URL$")
public void open_Chrome_browser_with_URL() throws Throwable
{
ExtentTest logInfo=null;
try {
test = extent.createTest(Feature.class, "Youtube channel name validation");
test=test.createNode(Scenario.class, "Youtube channel name validations");
logInfo=test.createNode(new GherkinKeyword("Given"), "open_Chrome_browser_with_URL");
Properties properties=obj.getProperty();
driver=BrowserUtility.OpenBrowser(driver, properties.getProperty("browser.name"), properties.getProperty("browser.baseURL"));
logInfo.pass("Opened chrome browser and entered url");
logInfo.addScreenCaptureFromPath(captureScreenShot(driver));
} catch (AssertionError | Exception e) {
testStepHandle("FAIL",driver,logInfo,e);
}
}
#When("^Search selenium tutorial$")
public void search_selenium_tutorial() throws Throwable
{
ExtentTest logInfo=null;
try {
logInfo=test.createNode(new GherkinKeyword("When"), "search_selenium_tutorial");
new YoutubeSearchPage(driver).NavigateToResultPage("selenium by bakkappa n");
logInfo.pass("Searching selenium tutorial");
logInfo.addScreenCaptureFromPath(captureScreenShot(driver));
} catch (AssertionError | Exception e) {
testStepHandle("FAIL",driver,logInfo,e);
}
}
#When("^Search selenium tutorial \"([^\"]*)\"$")
public void search_selenium_tutorial(String searchString) throws Throwable
{
new YoutubeSearchPage(driver).NavigateToResultPage(searchString);
}
#When("^Click on channel name$")
public void click_on_channel_name() throws Throwable
{
ExtentTest logInfo=null;
try {
logInfo=test.createNode(new GherkinKeyword("When"), "click_on_channel_name");
new YoutubeResultPage(driver).NavigateToChannel();
logInfo.pass("Clicked on the channel name");
logInfo.addScreenCaptureFromPath(captureScreenShot(driver));
} catch (AssertionError | Exception e) {
testStepHandle("FAIL",driver,logInfo,e);
}
}
#Then("^Validate channel name$")
public void validate_channel_name() throws Throwable
{
ExtentTest logInfo=null;
try {
logInfo=test.createNode(new GherkinKeyword("Then"), "validate_channel_name");
String expectedChannelName="1Selenium Java TestNG Tutorials - Bakkappa N - YouTube";
String actualChannelName=new YoutubeChannelPage(driver).getTitle();
Assert.assertEquals(actualChannelName, expectedChannelName,"Channel names are not matching"); //
logInfo.pass("Validated channel title");
logInfo.addScreenCaptureFromPath(captureScreenShot(driver));
System.out.println("closing browser");
driver.quit();
} catch (AssertionError | Exception e) {
testStepHandle("FAIL",driver,logInfo,e);
}
}
}
Your lofInfo is null, should be something like this
#Then("Open Chrome browser with URL")
public void open_Chrome_browser_with_URL() {
try {
logInfo = test.createNode(new GherkinKeyword("Then"), "open_Chrome_browser_with_URL");
//YOUR CODE HERE
logInfo.pass("Chrome opens URL");
}
catch (AssertionError | Exception e) {testStepHandle("FAIL", d, logInfo, e);
}
}

Xpages and EL: Syntax for retrieving HashMap Values

I have a cacheBean written in Java. I am successfully pulling out Vectors using EL, but I have a HashMap and when I try to access a value I throw an error.
My cacheBean is:
package com.scoular.cache;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Vector;
import org.openntf.domino.utils.Factory;
import org.openntf.domino.Database;
import org.openntf.domino.Session;
import org.openntf.domino.View;
import org.openntf.domino.ViewEntry;
import org.openntf.domino.ViewNavigator;
public class PCConfig implements Serializable {
private static final long serialVersionUID = 1L;
private Database thisDB;
private Database compDirDB;
public Database PCDataDB;
public HashMap<Integer, String> status = new HashMap<Integer, String>();
public static Vector<Object> geoLocations = new Vector<Object>();
public static Vector<Object> models = new Vector<Object>();
// #SuppressWarnings("unchecked")
private void initConfigData() {
try {
getStatus();
getGeoLocations();
getModels();
} catch (Exception e) {
e.printStackTrace();
}
}
public PCConfig() {
// initialize application config
System.out.println("Starting CacheBean");
initConfigData();
System.out.println("Ending CacheBean");
}
public static void setModels(Vector<Object> models) {
PCConfig.models = models;
}
public void getStatus() {
status.put(1, "In Inventory");
status.put(2, "Being Built");
status.put(3, "In Production");
status.put(4, "Aquiring PC");
status.put(5, "Decommissioning");
}
public Vector<Object> getGeoLocations() {
if (PCConfig.geoLocations == null || PCConfig.geoLocations.isEmpty()) {
try {
Session session = Factory.getSession();
thisDB = session.getCurrentDatabase();
compDirDB = session.getDatabase(thisDB.getServer(), "compdir.nsf", false);
View geoView = compDirDB.getView("xpGeoLocationsByName");
for (ViewEntry ce : geoView.getAllEntries()) {
Vector<Object> rowVal = ce.getColumnValues();
geoLocations.addElement(rowVal.elementAt(0));
}
} catch (Exception e) {
e.printStackTrace();
}
}
return geoLocations;
}
public Vector<Object> getModels() {
if (PCConfig.models == null || PCConfig.models.isEmpty()) {
try {
Session session = Factory.getSession();
thisDB = session.getCurrentDatabase();
PCDataDB = session.getDatabase(thisDB.getServer(), "scoApps\\PC\\PCData.nsf", false);
ViewNavigator vn = PCDataDB.getView("dbLookupModels").createViewNav();
ViewEntry entry = vn.getFirstDocument();
while (entry != null) {
Vector<Object> thisCat = entry.getColumnValues();
if (entry.isCategory()) {
String thisCatString = thisCat.elementAt(0).toString();
models.addElement(thisCatString);
}
entry = vn.getNext(entry);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return models;
}
}
and the code to grab the a value is:
<xp:text escape="true" id="computedField2">
<xp:this.value><![CDATA[#{PCConfig.status[0]}]]></xp:this.value></xp:text>
Your method getStatus() has to return the HashMap.
public HashMap<Integer, String> getStatus() {
...
return status;
}
In addition, #{PCConfig.status[0]} tries to read the value for key 0. There is no key 0 in your HashMap status though...
As far I know you should do as follow
#{javascript:PCConfig.status.get(1)}

How to get JSONArray which has no JSONArray keyword in Android Studio

I am new to this JSON, I am trying to get the JSON values, it is actually as JSONArray with No name. I have gone through some tutorials where they accessed through JSONArray Keyword. But in my JSON File there is no such ArrayName. Kindly help me to solve this. This is my JSON Value:
[
{"id":"4","name":"Trichy"},
{"id":"5","name":"Pondy"},
{"id":"6","name":"Kovai"},
{"id":"7","name":"Madurai"},
{"id":"8","name":"Chennai"},
{"id":"9","name":"Hyderabad"}
]
I need to get "name" from this. Here comes my MainActivity file.
try {
// Locate the NodeList name
JSONArray json=new JSONArray(???); //I dont know what to give here
for (int i = 0; i < json.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
Cites worldpop = new Cites();
worldpop.setCity(jsonobject.optString("name"));
cit.add(worldpop);
// Populate spinner with country names
worldlist.add(jsonobject.optString("name"));
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
This is my City.java file.
package com.example.user.spinnercontrol;
public class Cites {
private String city;
public String getCity()
{
return city;
}
public void setCity(String city)
{
this.city=city;
}
}
This is my JSON.java file (for reference)
package com.example.user.spinnercontrol;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONCity {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
MainActivity class should be like this ::
public class MainActivity extends Activity {
JSONObject jsonobject;
ArrayList<String> worldlist = new ArrayList<>();
ArrayList<Cites> cit = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
JSONArray arr = JSONCity.getJSONfromURL("http://www.prateektechnosoft.com/justcall/cities/getall");
for (int i = 0; i < arr.length(); i++) {
try {
jsonobject = arr.getJSONObject(i);
Cites worldpop = new Cites();
worldpop.setCity(jsonobject.optString("name"));
cit.add(worldpop);
// Populate spinner with country names
worldlist.add(jsonobject.optString("name"));
} catch (JSONException e) {
e.printStackTrace();
}
}
Spinner mySpinner = (Spinner) findViewById(R.id.my_spinner);
// Spinner adapter
mySpinner
.setAdapter(new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_dropdown_item,
worldlist));
// Spinner on item click listener
mySpinner
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}

Read text file and display it in Jtable?

i need to read the contents of text file, line by line and display it on the Jtable, the table should be editable by users as needed, Any help Appreciated. I am new to Java. Thank You.
My Text File: File Name(people.txt)
COLUMN_NAME COLUMN_TYPE IS_NULLABLE COLUMN_KEY COLUMN_DEFAULT EXTRA
Names VARCHAR(500) NO
Address VARCHAR(500) NO
My Code So Far:
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Vector;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class readtext {
static public void main(String[] arg){
JScrollPane scroll;
JTable table;
DefaultTableModel model;
String fname="people";
try
{
FileInputStream fstream = new FileInputStream("D:/joy/text/"+fname+".txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine,str = null;
//Read File Line By Line
String text = "";
Vector myVector = new Vector();
while ((strLine = br.readLine()) != null) //loop through each line
{
myVector.add(strLine );
// Print the content on the console
text +=(strLine+"\n"); // Store the text file in the string
}
in.close();//Close the input stream
int i=0;
String fline=myVector.elementAt(0).toString();
String[] sp=fline.split("\\s+");
for(String spt:sp){
System.out.println(spt);
//model = new DefaultTableModel(spt, ); // I dont know how to put the strings
into Jtable here
table = new JTable(){
public boolean isCellEditable(int row, int column){
return false;
}
};
int a=0;// for text box name
for(i=1;i<myVector.size();i++){
str=myVector.elementAt(i).toString();
String[] res =str.split("\\s+");
int k=0;
for(String st:res)
System.out.println(st);
k++;a++; }
} }
catch(Exception e)
{
e.printStackTrace();
}
}
}
Thank You.
File Content: (Each attribute is separated by a semicolon and each line is a record.)
Hello1;123
World1;234
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
public class FileToJTable {
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
new FileToJTable().createUI();
}
};
EventQueue.invokeLater(r);
}
private void createUI() {
try {
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
JTable table = new JTable();
String readLine = null;
StudentTableModel tableModel = new StudentTableModel();
File file = new File(""/*Give your File Path here*/);
FileReader reader = new FileReader(file);
BufferedReader bufReader = new BufferedReader(reader);
List<Student> studentList = new ArrayList<Student>();
while((readLine = bufReader.readLine()) != null) {
String[] splitData = readLine.split(";");
Student student = new Student();
student.setName(splitData[0]);
student.setNumber(splitData[1]);
studentList.add(student);
}
tableModel.setList(studentList);
table.setModel(tableModel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JScrollPane(table));
frame.setTitle("File to JTable");
frame.pack();
frame.setVisible(true);
} catch(IOException ex) {}
}
class Student {
private String name;
private String number;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}
class StudentTableModel extends AbstractTableModel {
private List<Student> list = new ArrayList<Student>();
private String[] columnNames = {"Name", "Number"};
public void setList(List<Student> list) {
this.list = list;
fireTableDataChanged();
}
#Override
public String getColumnName(int column) {
return columnNames[column];
}
public int getRowCount() {
return list.size();
}
public int getColumnCount() {
return columnNames.length;
}
public Object getValueAt(int rowIndex, int columnIndex) {
switch (columnIndex) {
case 0:
return list.get(rowIndex).getName();
case 1:
return list.get(rowIndex).getNumber();
default:
return null;
}
}
}
}
Well i didnt read ur code...however i'm telling u one of the simplest way of doing this...hope this helps
Define a DefaultTableModel:
String columns[] = { //Column Names// };
JTable contactTable = new JTable();
DefaultTableModel tableModel;
// specify number of columns
tableModel = new DefaultTableModel(0,2);
tableModel.setColumnIdentifiers(columns);
contactTable.setModel(tableModel);
Reading from text file:
String line;
BufferedReader reader;
try{
reader = new BufferedReader(new FileReader(file));
while((line = reader.readLine()) != null)
{
tableModel.addRow(line.split(", "));
}
reader.close();
}
catch(IOException e){
JOptionPane.showMessageDialog(null, "Error");
e.printStackTrace();
}
Also, if you want to allow users to edit the data, then you need to set a TableCellEditor on the cells that you want people to edit. You probably also want to start using a TableModel instead of hard coding the data in the JTable itself.
See http://docs.oracle.com/javase/tutorial/uiswing/components/table.html

Why I am getting the bad length exception when I am running this application?

I want to communicate to a server from J2me app using UDP.However, when I am running the app, I am getting a bad length exception.My codes and output are given below.
client code
import javax.microedition.midlet.MIDlet;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.TextBox;
import javax.microedition.lcdui.TextField;
import javax.microedition.io.Connector;
import javax.microedition.io.Datagram;
import javax.microedition.io.DatagramConnection;
import java.io.IOException;
public class DatagramTest extends MIDlet
implements CommandListener, Runnable
{
private static final int BUF_SIZE = 1024;
private static Command exit = new Command("Exit", Command.EXIT, 1);
private static DatagramTest instance;
private Display display;
private TextBox dgramText;
private DatagramConnection conn;
private Datagram dgram;
private String address = "datagram://myip:9876";
public DatagramTest()
{
super();
instance = this;
}
public DatagramTest(String service)
{
this();
address = service;
}
/**
Returns the single instance of this class. Calling
this method before constructing an object will return
a null pointer.
#return an instance of this class.
*/
public static DatagramTest getInstance()
{
return instance;
}
public void startApp()
{
display = Display.getDisplay(this);
dgramText = new TextBox("Datagram contents",
null,
2048,
TextField.ANY);
dgramText.setCommandListener(this);
display.setCurrent(dgramText);
System.out.println("Starting run....");
run();
System.out.println("Stopping run....");
}
public void run()
{
System.out.println("In run....");
try
{
int maxLength;
conn = (DatagramConnection)Connector.open(address);
maxLength = conn.getMaximumLength();
dgram = conn.newDatagram(1024);
dgram.reset();
conn.send(dgram);
conn.receive(dgram);
byte[] data = dgram.getData();
// Extract the response string.
String str = new String(data);
System.out.println(str);
dgram.reset();
System.out.println("Exit run....");
}
catch (IOException ioe)
{
System.out.println(ioe.getMessage());
ioe.printStackTrace();
quit();
}
return;
}
public void pauseApp()
{
}
void quit()
{
destroyApp(true);
notifyDestroyed();
}
public void destroyApp(boolean destroy)
{
try
{
conn.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
public void display()
{
Display.getDisplay(this).setCurrent(dgramText);
}
public void commandAction(Command c, Displayable d)
{
if (c == exit)
{
quit();
}
}
}
Server code
import java.io.*;
import java.net.*;
class UDPServer
{
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true)
{
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData());
System.out.println("RECEIVED: " + sentence);
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
}
}
Output at clientside
Starting run.... In run.... Bad
datagram length java.io.IOException:
Bad datagram length
at com.sun.midp.io.j2me.datagram.Protocol.receive(Protocol.java:367)
at hello.DatagramTest.run(DatagramTest.java:89)
at hello.DatagramTest.startApp(DatagramTest.java:69)
at javax.microedition.midlet.MIDletProxy.startApp(MIDletProxy.java:43)
at com.sun.midp.midlet.Scheduler.schedule(Scheduler.java:374)
at com.sun.midp.main.Main.runLocalClass(Main.java:466)
at com.sun.midp.main.Main.main(Main.java:120)
Stopping run....
Why I am getting this bad length exception and how do I sort it out?
One thing you need to try is to send and receive datagrams in a separate thread.
The documentation for DatagramConnection.receive() says: "This method blocks until a datagram is received"
You are calling it from inside MIDlet.startApp().
Blocking the application management system thread that calls startApp() is bad practice.

Resources