I don't know why this web services does not work - java

This is a sample class
public class NewClass {
public String hello1(String txt) {
String a = "Hello " + txt + " !";
return a;
}
}
and this is a sample web service
#WebService(serviceName = "NewWebService2")
public class NewWebService2 {
private NewClass newess;
/**
* This is a sample web service operation
*/
#WebMethod(operationName = "hello")
public String hello(#WebParam(name = "name") String txt) {
return "Hello " + txt + " !";
}
#WebMethod(operationName = "hello11")
public String hello11(#WebParam(name = "name") String txt) {
String ess=newess.hello1(txt);
return ess;
}
}
The first method hello works exactly but the second method hello11 is not working. I don't understand the problem. The server shows this message:
SEVERE: java.lang.NullPointerException
at newpackage.NewWebService2.hello11(NewWebService2.java:31)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.glassfish.webservices.InstanceResolverImpl$1.invoke(InstanceResolverImpl.java:143)
at com.sun.xml.ws.server.InvokerTube$2.invoke(InvokerTube.java:149)
at com.sun.xml.ws.server.sei.SEIInvokerTube.processRequest(SEIInvokerTube.java:94)
at com.sun.xml.ws.api.pipe.Fiber.__doRun(Fiber.java:961)
.
.
.
please I need to understand this problem and how I can resolve it.

Initialize your NewClass newess. You are trying to access newess.hello1() without initializing your newess variable

Try it like this:
this.newess = new NewClass();
This isn't thread safe. The member variable is unnecessary.
Not good code, but I'm sure it's just a bad example.

Related

Java - JUnit how to do?

I have the following method and how can I do the JUnit testing on it?
Parser is my constructor, which I am also using as my return type of my following method.
As this method is splitting the string in three one, so for that I want to write a unit test case.
I am somehow familiar with JUnit but not that much. Any guidance/ link/ help will be appreciated.
public class Example {
public Parser thirdValueCleanup(String value) {
String thirdValueValue = value.trim();
System.out.println("TestData: "+thirdValueValue);
String firstValueRegex = "[A-z]\\d[A-z]";
String secondValueRegex = "\\d[A-z]\\d";
String thirdValueRegex = "[SK|sk]{2}";
Pattern firstValuePattern = Pattern.compile(".*\\W*("+firstValueRegex+")\\W*.*");
Pattern secondValuePattern = Pattern.compile(".*\\W*("+secondValueRegex+")\\W*.*");
Pattern thirdValuePattern = Pattern.compile(".*\\W*("+thirdValueRegex+")\\W*.*");
String firstValue = "";
String secondValue = "";
String thirdValue = "";
Matcher firstValueMatcher = firstValuePattern.matcher(thirdValueValue);
if(firstValueMatcher.matches()) {
firstValue = firstValueMatcher.group(1);
}
Matcher secondValueMatcher = secondValuePattern.matcher(thirdValueValue);
if(secondValueMatcher.matches()) {
secondValue = secondValueMatcher.group(1);
}
Matcher thirdValueMatcher = thirdValuePattern.matcher(thirdValueValue);
if(thirdValueMatcher.matches()) {
thirdValue = thirdValueMatcher.group(1);
}
String FirstValueName = firstValue + " " + secondValue;
String thirdValueName = thirdValue;
return new Parser(FirstValueName, thirdValueName);
}
public Parser(String firstValue, String secondValue) {
this.firstValue = firstValue;
this.secondValue = secondValue;
}
public String getFirstValue() {
return firstValue;
}
public String getSecondValue() {
return secondValue;
}
}
I tried in my test:
public final void testThirdValueCleanup() {
System.out.println("retrieve");
String factories = "SK S6V 7L4";
Parser parser = new Parser();
Parser expResult = SK S6V 7L4;
Parser result = parser.thirdValueCleanup(factories);
assertEquals(expResult, result);
}
I got this error:
junit.framework.AssertionFailedError: expected:<SK S6V 7L4> but was:<com.example.Parser#379619aa>
at junit.framework.Assert.fail(Assert.java:57)
at junit.framework.Assert.failNotEquals(Assert.java:329)
at junit.framework.Assert.assertEquals(Assert.java:78)
at junit.framework.Assert.assertEquals(Assert.java:86)
at junit.framework.TestCase.assertEquals(TestCase.java:253)
at com.example.ParserTest.testthirdValueCleanup(ParserTest.java:29)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at junit.framework.TestCase.runTest(TestCase.java:176)
at junit.framework.TestCase.runBare(TestCase.java:141)
at junit.framework.TestResult$1.protect(TestResult.java:122)
at junit.framework.TestResult.runProtected(TestResult.java:142)
at junit.framework.TestResult.run(TestResult.java:125)
at junit.framework.TestCase.run(TestCase.java:129)
at junit.framework.TestSuite.runTest(TestSuite.java:252)
at junit.framework.TestSuite.run(TestSuite.java:247)
at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:86)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
try this
#Test
public final void testThirdValue() {
System.out.println("retrieve");
String factories = " BK M6B 7A4";
Parser parser = new Parser();
Parser province = parser.thirdValue(factories);
assertEquals("M6B 7A4", province.getFirstValue());
assertEquals("BK", province.getSecondValue());
}
Any guidance/ link/ help will be appreciated. thanks
As a simple approach, you might want to try out something within the following lines. As a first step create the test class:
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ExampleTest {
Example example = new Example();
#Test
public void testThirdValueCleanup(){
//pass some inputs to your function
//by exclicitly calling
//example.thirdValueCleanup(input params...);
//a simple test case would be to check if it you get what your expect
Parser expected = new Parser("set this one as it should be");
assertEquals(example.thirdValueCleanup(some inputs...), expected);
}
/*
* Here you can define more test cases
*/
}
Next you can create a class to run your test:
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class TestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(ExampleTest.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
For more information you can consult either this tutorial or getting started by JUnit.

How can I get the translate () method to receive Strings or a given list compatible with the string type?

I have these two classes and I want to make them work. The problem is this line:
TranslationResult translationResult = service.translate(lista.get(0).toString(), Language.PORTUGUESE, Language.ENGLISH).execute();
I want it to receive a list containing a list value something like:
TranslationResult translationResult = service.translate(lista.get(0).toString(), lista.get(1).toString() , lista.get(2).toString()).execute();
I want it to receive a list containing a list value something like:
import com.ibm.watson.developer_cloud.language_translation.v2.model.TranslationResult;
import Teste.Watson;
import java.util.Map;
public class Cognitive implements Serializable {
static public String Translate(ArrayList lista) {
LanguageTranslation service = new LanguageTranslation();
service.setUsernameAndPassword(lista.get(3).toString(), lista.get(4).toString());
TranslationResult translationResult = service.translate(lista.get(0).toString(), Language.PORTUGUESE, Language.ENGLISH).execute();
String translation = translationResult.getFirstTranslation();
return translation;
}
}
Class Test:
public class Watson {
public static void main(String[] args) {
ArrayList<Object> lista = new ArrayList<>();
lista.add("Isse texto vai virar ingles");
lista.add(Language.PORTUGUESE);
lista.add(Language.ITALIAN);
lista.add("adm");
lista.add("password");
String result= Cognitive.Translate(lista);
System.out.println(result);
}
}
I tried that way but gives this error:
static public String Translate(ArrayList lista){
LanguageTranslation service = new LanguageTranslation();
final Language srcLang;
final Language srcDest;
srcLang = (Language) lista.get(1);
srcDest = (Language) lista.get(2);
service.setUsernameAndPassword(lista.get(3).toString(), lista.get(4).toString());
TranslationResult translationResult = service.translate(lista.get(0).toString(), srcLang, srcDest).execute();
String translation = translationResult.getFirstTranslation();
return translation;
}
Error:
jun 30, 2016 10:09:50 AM com.ibm.watson.developer_cloud.service.WatsonService processServiceCall
GRAVE: POST https://gateway.watsonplatform.net/language- translation/api/v2/translate, status: 404, error: cannot find service matching the request data
Exception in thread "main" com.ibm.watson.developer_cloud.service.exception.NotFoundException: cannot find service matching the request data
at com.ibm.watson.developer_cloud.service.WatsonService.processServiceCall(WatsonService.java:381)
at com.ibm.watson.developer_cloud.service.WatsonService$1.execute(WatsonService.java:170)
at ibm.Cognitive.Translate(Cognitive.java:28)
at Teste.Watson.main(Watson.java:21)
Instead of using a List which is a strange and hacky solution, you should instead just have parameters for your method:
public class Cognitive implements Serializable {
public static String translate(final String text, final Language srcLang, final Language destLang, final String username, final String password) {
LanguageTranslation service = new LanguageTranslation();
service.setUsernameAndPassword(username, password);
TranslationResult translationResult = service.translate(text, srcLang, destLang).execute();
return translationResult.getFirstTranslation();
}
}

NullPointerException in Gdx.net.sendHttpRequest

I have tried to write a little code using libGDX to work with network. Here's a code:
public class Test {
public static void main(String[] args) {
String accessToken = "********"; //a set of symbols, not important because it is specific of request target
String userID = "*********"; //also not important
String message = "Hello World";
String uri = "method/wall.post?owner_id=" + userID + "&message=" + message + "&access_token=" + accessToken;
HttpRequestBuilder requestBuilder = new HttpRequestBuilder();
HttpRequest httpRequest = requestBuilder.newRequest().method(HttpMethods.GET).url("https://api.vk.com/").content(uri).build();
Gdx.net.sendHttpRequest(httpRequest, //Here Eclipse shows NullPointerException
null); //But not here
}
If I write this URL in browser, it works right. It means, that the problem on my side. How to fix it?
Summary of values of the object which causes NullPointerException:
You are writing this code in the static main entry point of your program. Your Gdx is not yet loaded,so Gdx is still null at this point.
Create a none static class and put your code in it's constructor and initialize that class within this static entry point.
public class WebTest()
{
public WebTest()
{
String accessToken = "********"; //a set of symbols, not important because it is specific of request target
String userID = "*********"; //also not important
String message = "Hello World";
String uri = "method/wall.post?owner_id=" + userID + "&message=" + message + "&access_token=" + accessToken;
HttpRequestBuilder requestBuilder = new HttpRequestBuilder();
HttpRequest httpRequest = requestBuilder.newRequest().method(HttpMethods.GET).url("https://api.vk.com/").content(uri).build();
Gdx.net.sendHttpRequest(httpRequest, //Here Eclipse shows NullPointerException
null); //But not here
}
}
public class Test {
public static void main(String[] args) {
new WebTest();
}
}

JMockit NullPointerException on Exceptions block?

Having already spent a lot of time on this test and unable to reason my way out of it, i have no other choice than ask for your help :)
Using JMockit to test some of my own JDBC "Wrapper" classes, i came to a dead end.
This is the class im testing:
public class JdbcConnectionProperties {
private Properties properties = new Properties();
private String username;
private String password;
private String connectionString;
public JdbcConnectionProperties(String propertiesFilePath) {
loadProperties(propertiesFilePath);
}
public void setProperties() {
username = properties.getProperty("user");
password = properties.getProperty("password");
String connectionType = properties.getProperty("connection_type");
String serverAddress = properties.getProperty("server_address");
String port = properties.getProperty("port");
String sid = properties.getProperty("sid");
//Create a connection string
connectionString = "jdbc:oracle:" + connectionType + ":#" + serverAddress + ":" + port + ":" + sid;
}
private void loadProperties(String propertiesFilePath) {
String filePath = Thread.currentThread().getContextClassLoader().getResource(propertiesFilePath).getFile();
//Load properties from classpath
try {
properties.load(new FileInputStream(filePath));
} catch (IOException e) {
e.printStackTrace();
}
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public String getConnectionString() {
return connectionString;
}
public Properties getProperties() {
return properties;
}
}
This is the test:
public class JdbcConnectionPropertiesTest {
#Test
public void testSetProperties(
// #Mocked final Properties properties
) throws Exception {
//Mock loadFilePath method so i dont end up mocking a ton of classes
new MockUp<JdbcConnectionProperties>() {
#Mock
void loadProperties(String propertiesFilePath) {
//Doing nothing, simple "stub" method
}
};
JdbcConnectionProperties jdbcConnectionProperties = new JdbcConnectionProperties("bla");
// Deencapsulation.setField(jdbcConnectionProperties, "properties", properties);
// Mockit.stubOutClass(JdbcConnectionProperties.class, "loadProperties");
final String username = "username";
final String password = "password";
final String connectionType = "thin";
final String serverAddress = "localhost";
final String port = "1521";
final String sid = "orcl";
String connectionString = "jdbc:oracle:" + connectionType + ":#" + serverAddress + ":" + port + ":" + sid;
new Expectations() {
#Mocked
Properties properties;
{
properties.get("user");
result = username;
properties.get("password");
result = password;
properties.get("connection_type");
result = connectionType;
properties.get("server_address");
result = serverAddress;
properties.get("port");
result = port;
properties.get("sid");
result = sid;
}
};
jdbcConnectionProperties.setProperties();
Assert.assertEquals("Incorrect user", username, jdbcConnectionProperties.getUsername());
Assert.assertEquals("Incorrect password", password, jdbcConnectionProperties.getPassword());
Assert.assertEquals("Incorrect connection string", connectionString, jdbcConnectionProperties.getConnectionString());
}
}
A couple of notes. I tried forsing the mocked properties into the object with Deencapsulation(i left them commented in the code).
I tried just mocking it with the #Mocked annotation.
I tried stubing it with stubOutClass.
This is not a first test i am writing, but im relativly new to JMockit.
The tests i wrote before never caused me headaches like this one. I think i wrote about 20 - 30 tests with JMockit and never had problems like this.
The error is(in all the mentioned scenarios) :
java.lang.NullPointerException
at java.util.Hashtable.get(Hashtable.java:335)
at jdbc.JdbcConnectionPropertiesTest$2.<init>(JdbcConnectionPropertiesTest.java:49)
at jdbc.JdbcConnectionPropertiesTest.testSetProperties(JdbcConnectionPropertiesTest.java:44)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:71)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:199)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:62)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
The class is very simple. The test should be very simple. But somehow the test crashes on the Expectations block(on the first properties expectation). If I comment the first ones, then it continues to throw it on next one. Tried any, anyString for argument matching.
The way I see it, i mock the JdbcConnectionProperties loadProperties so i can simplify my testing. Then i pass a mocked Properties object into the test.
And then...
...it should work.
BTW, I never saw an exception of this magnitude in a Exceptions block.
Thank you.
Hashtable#get is one of a few methods not mocked by default by JMockit, because it can interfere with the JDK or with JMockit itself when mocked. You can get this particular test to work by explicitly asking for it to be mocked, with #Mocked("get").
It might be simpler to just use an actual ".properties" file in the test, though, with no mocking.
new Expectations() {
#Mocked("getProperty")
Properties properties;
{
properties.getProperty("user");
result = username;
properties.getProperty("password");
result = password;
properties.getProperty("connection_type");
result = connectionType;
properties.getProperty("server_address");
result = serverAddress;
properties.getProperty("port");
result = port;
properties.getProperty("sid");
result = sid;
}
};
Thanks Rogerio. As he pointed out, the reason is the "internal" class mocking. A very small limitation to have in mind.
The other classes that require some attention are(i hope i can write this):

Where did I go wrong in this code?

A few of my classes aren't passing automated tests. Unfortunately, said tests do not provide any useful information about why they failed. Here is my code for a couple of the classes. I'd really appreciate it if you could tell me where I went wrong. The comments should explain what each method is supposed to do.
public class CellPhone {
protected String ownerName;
public CellPhone(String owner) {
ownerName = owner;
}
public String receiveCall(CellPhone sender) {
// returns a String of the form:
// owner's name " is receiving a call from " sender's name
String receivingCall = ownerName + " is receiving a call from " + sender;
return receivingCall;
}
public String call(CellPhone receiver) {
// returns a String by using the receiver to invoke receiveCall
// while passing in the current phone
String invokingReceiveCall = receiver.receiveCall(receiver);
return invokingReceiveCall;
}
}
public class TextMessagingPhone extends CellPhone {
private int availMessages;
public TextMessagingPhone(String owner, int messageLimit) {
// invokes the superclass constructor
super(owner);
// sets the new instance variable
availMessages = messageLimit;
}
public TextMessagingPhone(String owner) {
// invokes the other constructor of this class with 15 as the message limit
this(owner, 15);
}
public String receiveText(TextMessagingPhone sender, String message) {
// decreases the number of messages available to send
availMessages--;
// returns a String of the form:
// owner's name " has received TEXT from " sender's name ":" message
String receivedText = ownerName + " has received TEXT from " + sender + ":" + message;
return receivedText;
}
public String sendText(TextMessagingPhone receiver, String message) {
// decreases the number of messages available to send
availMessages--;
// returns a String by using the receiver to invoke receiveText
// while passing in the current phone and the message
String invokingReceiveText = receiver.receiveText(receiver, message);
return invokingReceiveText;
}
}
When a phone makes a call, it passes the receiver as a parameter, so the receiver thinks it is receiving from itself. Also it never gets the name from the passed sender. Try:
public String receiveCall(CellPhone sender) {
// returns a String of the form:
// owner's name " is receiving a call from " sender's name
String receivingCall = ownerName + " is receiving a call from " + sender.getName();
return receivingCall;
}
public String call(CellPhone receiver) {
// returns a String by using the receiver to invoke receiveCall
// while passing in the current phone
String invokingReceiveCall = receiver.receiveCall(this);
return invokingReceiveCall;
}
public String getName() {
return ownerName;
}
public CellPhone(String owner) {
}
You don't assign anything to ownerName...
public CellPhone(String owner) {
ownerName = owner;
}
Check this
String receivingCall = ownerName + " is receiving a call from " + sender;
You are using "sender" which is an object in the string expression. Using sender.ownerName after making it public or defining getOwnerName and using it should work. This same mistake is repeated couple more times!

Categories