I have a problem regarding java.lang.NoSuchMethodError. This program is about Compiler API (JSR 199). When I create a prototype for this it run work, but when I try to make it to become library it throw NoSuchMethodError Exception.
Here is the First Prototype:
public class DynaCompTest {
public static void main(String[] args) {
String fullName = "HelloWorld";
StringBuilder sourceCode = new StringBuilder();
sourceCode.append("public class HelloWorld {\n")
.append("\tpublic static void main(String[] args) {\n")
.append("\t\tSystem.out.println(\"Hello World\")\n")
.append("\t}\n")
.append("}");
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
JavaFileManager fileManager = new ClassFileManager(compiler.getStandardFileManager(null, null, null));
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
List<JavaFileObject> jFiles = new ArrayList<>();
jFiles.add(new CharSequenceJavaFileObject(fullName, sourceCode));
compiler.getTask(null, fileManager, diagnostics, null, null, jFiles).call();
for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
System.out.format("Error on line %d in %s\n", diagnostic.getLineNumber(), diagnostic);
}
}
}
public class CharSequenceJavaFileObject extends SimpleJavaFileObject {
private CharSequence content;
public CharSequenceJavaFileObject(String className, CharSequence content) {
super(URI.create("string:///" + className.replace('.', '/') + Kind.SOURCE.extension), Kind.SOURCE);
this.content = content;
}
#Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return content;
}
}
public class ClassFileManager extends ForwardingJavaFileManager {
private JavaClassObject jClassObject;
public ClassFileManager(StandardJavaFileManager standardManager) {
super(standardManager);
}
#Override
public ClassLoader getClassLoader(Location location) {
return new SecureClassLoader() {
#Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
byte[] b = jClassObject.getBytes();
return super.defineClass(name, jClassObject.getBytes(), 0, b.length);
}
};
}
#Override
public JavaFileObject getJavaFileForOutput(Location location, String className, Kind kind, FileObject sibling) throws IOException {
jClassObject = new JavaClassObject(className, kind);
return jClassObject;
}
}
public class JavaClassObject extends SimpleJavaFileObject {
protected final ByteArrayOutputStream bos = new ByteArrayOutputStream();
public JavaClassObject(String name, Kind kind) {
super(URI.create("string:///" + name.replace('.', '/') + kind.extension), kind);
}
public byte[] getBytes() {
return bos.toByteArray();
}
#Override
public OutputStream openOutputStream() {
return bos;
}
}
I changed the DynaCompTest become DynamicCompiler for the library:
public class DynamicCompiler {
private JavaCompiler compiler;
private JavaFileManager fileManager;
private List<JavaFileObject> jFiles;
private DiagnosticCollector<JavaFileObject> diagnostics;
public DiagnosticCollector<JavaFileObject> getDiagnostics() {
return diagnostics;
}
public DynamicCompiler(String className, StringBuilder sourceCode) {
compiler = ToolProvider.getSystemJavaCompiler();
fileManager = new ClassFileManager(compiler.getStandardFileManager(null, null, null));
diagnostics = new DiagnosticCollector<>();
jFiles = new ArrayList<>();
jFiles.add(new CharSequenceJavaFileObject(className, sourceCode));
}
public boolean doCompilation() {
return compiler.getTask(null, fileManager, diagnostics, null, null, jFiles).call();
}
}
And I created Second Prototype to test the library:
public class Compiler {
private static StringBuilder sourceCode = new StringBuilder();
public static void main(String[] args) {
boolean status;
sourceCode.append("public class HelloWorld {\n")
.append("\tpublic static void main(String[] args) {\n")
.append("\t\tSystem.out.println(\"Hello World\");\n")
.append("\t}\n")
.append("}");
DynamicCompiler compiler = new DynamicCompiler("HelloWorld", sourceCode);
status = compiler.doCompilation();
StringBuilder messages = new StringBuilder();
if (!status) {
for (Diagnostic diagnostic : compiler.getDiagnostics().getDiagnostics()) {
messages.append("Error on line ")
.append(diagnostic.getLineNumber())
.append(" in ")
.append(diagnostic)
.append("\n");
}
} else {
messages.append("BUILD SUCCESSFUL ");
}
System.out.println(messages.toString());
}
}
When I test with code above it run well and print BUILD SUCCESSFUL but when I tried to make it error for example I deleted the semicolon ; like the first prototype, it throw the NoSuchMethodError Exception when access the compiler.getDiagnostics().getDiagnostics() inside the looping.
The question is, why in the First Prototype it run well when try to make an error but when I tried with my own library it become Exception?
Edit
Here is the stacktrace:
/HelloWorld.java:3: error: ';' expected
System.out.println("Hello World")
^
1 error
Exception in thread "main" java.lang.NoSuchMethodError: org.ert.lib.DynamicCompiler.getDiagnostics()Ljavax/tools/DiagnosticCollector;
at org.ert.exp.Compiler.main(Compiler.java:28)
Java Result: 1
It should be like this:
Error on line 3 in /HelloWorld.java:3: error: ';' expected
System.out.println("Hello World")
^
When trying to debug it, it shown an error:
public DiagnosticCollector<JavaFileObject> getDiagnostics() {
return diagnostics; // Set Breakpoint here
}
Here is the error message:
Not able to submit breakpoint LineBreakpoint DynamicCompiler.java : 25, reason: No executable location available at line 25 in class org.ert.lib.DynamicCompiler.
Invalid LineBreakpoint DynamicCompiler.java : 25
Update
Got the problem, this problem will occur if we add the whole project instead build the jar of the library. So when I build the library jar it works. But anyone can explain why this thing happen when I try add the whole project instead the jar file?
Note
I'm using:
JDK 1.7 from Oracle
Netbeans 7.1.1
It seems that you have similar class exists in two different libraries(jars).
e.g.
com.test.Example.class in a.jar
com.test.Example.class in b.jar
Now class loader will load the first first Example.class and it seems that you need class which is there in b.jar. Then it will not throw exception such as NoMethodFound but throw an Exception that NoSuchMethodFound because class still exists in memory but can not find required method.
Such problems can be resolved by changing library order. You need to make required library's order higher. You can do this from the eclipse
Project Setting -> Java Build Path -> Order and Export.
Hope this is helpful.
After I tried with Eclipse Indigo, I found that it works when add the Project or add the jar file. While in Netbeans 7.1.1 will get an error if add the Project, but works if add the jar file.
Maybe it one of the bugs of Netbeans...
Thank you for your attention...
Related
I have a class with a function as follows
`
private static Path compileNamedModuleTest() throws IOException {
Path base = Paths.get(".", "named");
Path src = base.resolve("src");
Path classes = base.resolve("classes");
ModuleInfoMaker maker = new ModuleInfoMaker(src);
maker.writeJavaFiles("test",
"module test {}",
"package test; public sealed interface Base permits test.a.ImplA1, test.a.ImplA2, test.b.ImplB, test.c.ImplC {}",
"package test.a; public final class ImplA1 implements test.Base {}",
"package test.a; public final class ImplA2 implements test.Base {}",
"package test.b; public final class ImplB implements test.Base {}",
"package test.c; public final class ImplC implements test.Base {}"
);
System.out.println("Default Charset: "
+ Charset.defaultCharset());
if (!CompilerUtils.compile(src, classes.resolve("test"), "--enable-preview", "-source", System.getProperty("java.specification.version"))) {
throw new AssertionError("Compilation didn't succeed!");
}
Files.delete(classes.resolve("test").resolve("test").resolve("c").resolve("ImplC.class"));
return classes;
}
`
and WriteJavaFiles function as
/**
* Create java source files of the given module
*/
public void writeJavaFiles(String module, String moduleInfoJava, String... contents)
throws IOException
{
Path msrc = dir.resolve(module);
new JavaSource(moduleInfoJava).write(msrc);
for (String c : contents) {
new JavaSource(c).write(msrc);
}
}
I am getting error as Error:
Java files created during execution have encoding issues due to which
compilation fails.
./named/src/test/test/a/ImplA1.java:1: error: illegal character: '\u009b'
/named/src/test/test/a/ImplA2.java:1: error: illegal character: '\u0080'
Which I believe is an encoding issue and need to add charset.defaultCharset() somewhere. But I am unsure where to put it?
JavaSource class
static class JavaSource {
final String source;
JavaSource(String source) {
this.source = source;
}
/**
* Writes the source code to a file in a specified directory.
* #param dir the directory
* #throws IOException if there is a problem writing the file
*/
public void write(Path dir) throws IOException {
Path file = dir.resolve(getJavaFileNameFromSource(source));
Files.createDirectories(file.getParent());
try (BufferedWriter out = Files.newBufferedWriter(file)) {
out.write(source.replace("\n", System.lineSeparator()));
}
}
I tried adding Charset as argument in WriteJavaFiles but did not help.
I am attempting to test a method that returns a File object using JUnit and JMockit. I am a beginner with both of these.
The problem I am having is that I can't figure out how to properly/successfully mock the implementation method returning a file, since in reality, the user has to actually select a file for the method to return. The error I keep running into is:
java.lang.IllegalStateException: Missing invocation to mocked type at this point; please make sure such invocations appear only after the declaration of a suitable mock field or parameter
Any suggestions?
Here is a recreation of my implementation:
public final class MyClass {
public static File OpenFile(Stage stage, String title, String fileTypeText, ArrayList<String> fileType) throws Exception {
File file = null;
try {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle(title);
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionsFilter(fileTypeText + fileType, fileType);
fileChooser.getExtensionsFilters().add(extFilter);
file = fileChooser.showOpenDialog(stage);
return file;
}
catc (Exception e) {
if(fileType==null) {
...
}
return file;
}
}
}
Here is a recreation of my attempted JUnit test:
#Test
public void TestOpenFile(#Mocked Stage stage) throws Exception {
final ArrayList<String> extensions = new ArrayList<String>();
extensions.add(".txt");
final File file = null;
new Expectations() {{
MyClass.OpenFile(stage, anyString, anyString, extensions); returns(file);
}};
assertEquals(file, MyClass.OpenFile(stage, "some title", "some type", extensions));
}
Your solution is correct, but I would use expectations instead:
public void TestOpenFile(#Mocked FileChooser chooser) throws Exception{
new Expectations() {
{
chooser.showOpenDialog(stage); result = expectedFile;
}};
final File actualFile = MyClass.OpenFile(...);
assertEquals(expectedFile, actualFile);}
I find this easier to understand and write (my personal preference)
I realized that I was approaching the problem incorrectly at first. What I did to resolve this was:
Mock the FileChooser.showOpenDialog method to return a file instead of trying to mock my own method to return a file, which would have defeated the purpose of testing.
final File expectedFile = new File("abc");
new MockUp<FileChooser>() {
#Mock
File showOpenDialog(final Window overWindow) {
return expectedFile;
}
};
final File actualFile = MyClass.OpenFile(...);
assertEquals(expectedFile, actualFile);
Hi I am working on a project and using PrintWriter class for opening and writing in the file. But when I am writing the test case for same it gives following error at Line 153
Wanted but not invoked:
mockPrintWriter.println("ID url1
");
-> at x.y.z.verify(ProcessImageDataTest.java:153)
Actually, there were zero interactions with this mock.
Code: (Uses Lombok Library)
ProcessImageData.java
#Setter
#RequiredArgsConstructor
public class ProcessImageData implements T {
private final File newImageDataTextFile;
#Override
public void execute() {
LineIterator inputFileIterator = null;
try {
File filteredImageDataTextFile = new File(filteredImageDataTextFilepath);
PrintWriter writer = new PrintWriter(newImageDataTextFile);
inputFileIterator = FileUtils.lineIterator(filteredImageDataTextFile, StandardCharsets.UTF_8.displayName());
while (inputFileIterator.hasNext()) {
if(someCondition)
**Line51** writer.println(imageDataFileLine);
//FileUtils.writeStringToFile(newImageDataTextFile, imageDataFileLine + NEWLINE, true);
}
}
} catch (Exception e) {
} finally {
LineIterator.closeQuietly(inputFileIterator);
**LINE63** writer.close();
}
}
ProcessImageDataTest.java
#RunWith(PowerMockRunner.class)
#PrepareForTest({ ProcessImageData.class, FileUtils.class, Printwriter.class })
public class ProcessImageDataTest {
private ProcessImageData processImageData;
private static final String FILTERED_IMAGE_DATA_TEXT_FILE_PATH = "filteredFilepath";
private File FILTEREDFILE = new File(FILTERED_PATH);
private static final File IMAGE__FILE = new File("imageFilePath");
private LineIterator lineIterator;
#Mock
private PrintWriter mockPrintWriter;
#Before
public void init() throws Exception {
MockitoAnnotations.initMocks(this);
processImageData = new ProcessImageData(Palettes_file, FILTERED_PATH, IMAGE_FILE);
PowerMockito.mockStatic(FileUtils.class);
PowerMockito.whenNew(PrintWriter.class).withArguments(IMAGE_FILE).thenReturn(mockPrintWriter);
PowerMockito.when(FileUtils.lineIterator(FILTERED_FILE, StandardCharsets.UTF_8.displayName())).thenReturn(lineIterator);
PowerMockito.when(lineIterator.hasNext()).thenReturn(true, true, false);
}
#Test
public void testTaskWhenIDInDBAndStale() throws IOException {
PowerMockito.when(lineIterator.nextLine()).thenReturn(ID2 + SPACE + URL1, ID1 + SPACE + URL2);
processImageData.execute();
List<String> exepctedFileContentOutput = Arrays.asList(ID2 + SPACE + URL1 + NEWLINE);
verify(exepctedFileContentOutput, 1, 1);
}
#Test
public void testTaskWhenIDNotInDB() throws IOException {
PowerMockito.when(lineIterator.nextLine()).thenReturn(ID2 + SPACE + URL1, ID3 + SPACE + URL2);
processImageData.execute();
List<String> exepctedFileContentOutput = Arrays.asList(ID3 + SPACE + URL2 + NEWLINE);
verify(exepctedFileContentOutput, 1, 1);
}
private void verify(List<String> exepctedFileContentOutput, int fileWriteTimes, int fileReadTimes) throws IOException {
for (String line : exepctedFileContentOutput){
**Line153** Mockito.verify(mockPrintWriter, Mockito.times(fileWriteTimes)).print(line);
}
PowerMockito.verifyStatic(Mockito.times(fileReadTimes));
FileUtils.lineIterator(FILTERED_IMAGE_DATA_TEXT_FILE, StandardCharsets.UTF_8.displayName());
}
}
I am mocking a new operator for PrintWriter also, injecting using beans. What is the mistake I am doing?? I am stuck on it from long time and not getting the error?
Any help is appreciated.
Updated :
I did changes suggested below and updated the code, but now I get the error:
Wanted but not invoked: mockPrintWriter.print("ASIN2 url1 "); ->
at softlines.ctl.ruleExecutor.tasks.ProcessImageDataTest.verify(ProcessImageDataTest.java:153)
However, there were other interactions with this mock: -> at softlines.ctl.ruleExecutor.tasks.ProcessImageData.execute(ProcessImageData.java:51) ->
at softlines.ctl.ruleExecutor.tasks.ProcessImageData.execute(ProcessImageData.java:51) ->
at softlines.ctl.ruleExecutor.tasks.ProcessImageData.execute(ProcessImageData.java:58) –
I see 3 issues in your test:
You don't try to mock the correct constructor, indeed in the method execute, you create your PrintWriter with only one argument of type File while you try to mock the constructor with 2 arguments one of type File and the other one of type String.
So the code should rather be:
PowerMockito.whenNew(PrintWriter.class)
.withArguments(IMAGE_FILE)
.thenReturn(mockPrintWriter);
To be able to mock a constructor you need to prepare the class creating the instance which is ProcessImageData in this case, so you need to add ProcessImageData.class in the annotation #PrepareForTest. (I'm not sure ProcessImageDataTest.class is needed there)
The field lineIterator should be annotated with #Mock.
Instead of verifying print with a new line, you should verify directly println without new line it is much less error prone.
I simplified your code to show the idea.
Assuming that ProcessImageData is:
public class ProcessImageData {
private final File newImageDataTextFile;
public ProcessImageData(final File newImageDataTextFile) {
this.newImageDataTextFile = newImageDataTextFile;
}
public void execute() throws Exception{
try (PrintWriter writer = new PrintWriter(newImageDataTextFile)) {
LineIterator inputFileIterator = FileUtils.lineIterator(
newImageDataTextFile, StandardCharsets.UTF_8.displayName()
);
while (inputFileIterator.hasNext()) {
writer.println(inputFileIterator.nextLine());
}
}
}
}
My unit test would then be:
#RunWith(PowerMockRunner.class)
#PrepareForTest({ProcessImageData.class, FileUtils.class})
public class ProcessImageDataTest {
private File file = new File("imageFilePath");
private ProcessImageData processImageData;
#Mock
private PrintWriter mockPrintWriter;
#Mock
private LineIterator lineIterator;
#Before
public void init() throws Exception {
MockitoAnnotations.initMocks(this);
processImageData = new ProcessImageData(file);
PowerMockito.whenNew(PrintWriter.class)
.withArguments(file)
.thenReturn(mockPrintWriter);
PowerMockito.mockStatic(FileUtils.class);
PowerMockito.when(
FileUtils.lineIterator(file, StandardCharsets.UTF_8.displayName())
).thenReturn(lineIterator);
PowerMockito.when(lineIterator.hasNext()).thenReturn(true, true, false);
}
#Test
public void testExecute() throws Exception {
PowerMockito.when(lineIterator.nextLine()).thenReturn("Foo", "Bar");
processImageData.execute();
Mockito.verify(mockPrintWriter, Mockito.times(1)).println("Foo");
Mockito.verify(mockPrintWriter, Mockito.times(1)).println("Bar");
}
}
For more details please refer to How to mock construction of new objects.
how can I add verification in unit test for writer.close?
One way could be to simply check that close() at be called once by adding the next line to your unit test:
Mockito.verify(mockPrintWriter, Mockito.times(1)).close();
Your construction of the PrintWriter doesn't match the mock. You told PowerMockito to return your mock like this:
PowerMockito.whenNew(PrintWriter.class).withArguments(IMAGE_FILE , StandardCharsets.UTF_8.name()).thenReturn(mockPrintWriter);
So you would have to say:
new PrintWriter(IMAGE_FILE, "UTF-8"); // 2 arguments
But instead in your execute method in the code that is being tested, you do:
PrintWriter writer = new PrintWriter(newImageDataTextFile); // only 1 argument
So you either need to change the PowerMockito withArguments clause, or you need to add "UTF-8" to the constructor invocation in the execute method.
I am getting the following error when running nachos in eclipse:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
at nachos.machine.Lib.assertTrue(Lib.java:75)
at nachos.machine.Machine.main(Machine.java:24)
The above two methods are as follows:
nachos.machine.Lib.assertTrue:
public static void assertTrue(boolean expression) {
if (!expression)
throw new AssertionFailureError();
}
nachos.machine.Machine.main:
public static void main(final String[] args) {
System.out.println("nachos 5.0j initializing...");
Lib.assertTrue(Machine.args == null);//This is the call after which error is thrown
Machine.args = args;
processArgs();
Config.load(configFileName);
// get the current directory (.)
baseDirectory = new File(new File("").getAbsolutePath());
// get the nachos directory (./nachos)
nachosDirectory = new File(baseDirectory, "nachos");
String testDirectoryName =
Config.getString("FileSystem.testDirectory");
// get the test directory
if (testDirectoryName != null) {
testDirectory = new File(testDirectoryName);
}
else {
// use ../test
testDirectory = new File(baseDirectory.getParentFile(), "test");
}
securityManager = new NachosSecurityManager(testDirectory);
privilege = securityManager.getPrivilege();
privilege.machine = new MachinePrivilege();
TCB.givePrivilege(privilege);
privilege.stats = stats;
securityManager.enable();
createDevices();
checkUserClasses();
autoGrader = (AutoGrader) Lib.constructObject(autoGraderClassName);
new TCB().start(new Runnable() {
public void run() { autoGrader.start(privilege); }
});
}
I had this same error come up for me when I was trying to run nachos through eclipse. What I did was to look at Lib.java and scroll down to the function with an eclipse error on it. For me it was checkDerivation. There should be an eclipse error on the parameters <?>, if you look at the auto fix eclipse gives you and pick the project wide fix nachos should run after that.
I built a servlet that compiles java code and returns compilation errors (if any).
I'm calling it from an html form where I type the code. The thing is, whenever I use the "+" operator for arithmetic addition or to concatenate strings, it just doesn't like it.
This is my servlet class:
#WebServlet("/compiler")
public class Compiler extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
StringBuffer sb = new StringBuffer();
String code = request.getParameter("codeToCompile").toString();
String results = this.compile(code);
sb.append(results);
out.println(sb);
}
private String compile(String codeToCompile){
String compilationResults = null;
String toCompile = "class test {" + codeToCompile + "}";
/*Creating dynamic java source code file object*/
SimpleJavaFileObject fileObject = new JavaObjectFromString ("ejercicio", toCompile);
JavaFileObject javaFileObjects[] = new JavaFileObject[]{fileObject} ;
/*Instantiating the java compiler*/
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
/*Create a diagnostic controller, which holds the compilation problems*/
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
/*get a standard file manager from compiler, this file manager helps us to customize how a compiler reads and writes to files*/
StandardJavaFileManager stdFileManager = compiler.getStandardFileManager(diagnostics, null, null);
/* Prepare a list of compilation units (java source code file objects) to input to compilation task*/
Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(javaFileObjects);
/*Prepare any compilation options to be used during compilation
//In this example, we are asking the compiler to place the output files under bin folder.*/
String[] compileOptions = new String[]{"-d", "c:"} ;
Iterable<String> compilationOptions = Arrays.asList(compileOptions);
/*Create a compilation task from compiler by passing in the required input objects prepared above*/
CompilationTask compilerTask = compiler.getTask(null, stdFileManager, diagnostics, compilationOptions, null, compilationUnits) ;
/*Perform the compilation by calling the call method on compilerTask object.*/
boolean status = compilerTask.call();
/*On compilation failure, we can use the diagnostic collector to read the error messages and log them in specific format.*/
if (!status){//If compilation error occurs
/*Iterate through each compilation problem and print it*/
for (#SuppressWarnings("rawtypes") Diagnostic diagnostic : diagnostics.getDiagnostics()){
compilationResults = "ERROR IN LINE "+ diagnostic.getLineNumber() + ": " + diagnostic.getMessage(new Locale(null));
}
}
else
{
compilationResults = "SUCCESS";
}
/*Finally close the fileManager instance to flush out anything that is there in the buffer.*/
try {
stdFileManager.close() ;//Close the file manager
} catch (IOException e) {
e.printStackTrace();
}
return compilationResults;
}
}
It instantiates a class called "JavaObjectFromString" which looks like this:
public class JavaObjectFromString extends SimpleJavaFileObject{
private String contents;
private String name;
public JavaObjectFromString(String className, String contents){
super(URI.create(className.replace('.', '/') + Kind.SOURCE.extension), Kind.SOURCE);
this.contents = contents;
this.name = className;
}
public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
return this.contents;
}
}
Everything works fine until I attempt to use the + operator either with Strings or with numbers.
I've been testing different scenarios. For example, some code like this:
String someText = "test" + "test";
trows Error on line 1: ';' expected. Also happens when I use the operator inside a method:
public String testMethod(){
return "test" + "test";
}
If I then try:
public String testMethod(String one, String two){
return one + two;
}
it throws Error on line 2: not a statement
If I do:
public int someNumber = 12 + 345;
I also get Error on line 1: ';' expected
Where in my servlet code am I breaking the + operator??
SOLVED. The problem was not in how the servlet handles the code but in how it was sent using ajax to post the form contents. All I needed was to encode the text before sending it:
ajaxObject.send('codigo='+encodeURIComponent(codigo));