Webservice with different datatype? - web-services

I'm writing one of my very first web-service, as far as now it was more than ok, but when I'm trying to create sperate class:
public class Workers {
private String name;
private String surname;
private boolean type;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public boolean isType() {
return type;
}
public void setType(boolean type) {
this.type = type;
}
public Workers(String name, String surname, boolean type) {
this.name = name;
this.surname = surname;
this.type = type;
}
}
and than to use it in webservice like this:
#WebMethod(operationName = "SelectWorker")
public Pracownicy SelectWorker(#WebParam(name = "username") String username, #WebParam(name = "password") String password) {
ResultSet rs = null;
String name = null;
String surname = null;
boolean type = false;
PreparedStatement st = null;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("db_address", "login", "password");
System.out.println("connection status: " +con);
st = con.prepareStatement("select name, surname from clients where login = ? and passwd= ?");
st.setString(1, username);
st.setString(2, password);
rs = st.executeQuery();
if (rs.next()) {
name = rs.getString(2);
surname=rs.getString(3);
type = rs.getBoolean(5);
Workers pr = new Workers(name, surname, type);
return pr;
}
} catch (Exception e) {
System.out.println("error: " + e.toString());
}
return null;
}
the body of method can be empty or filled with code, it doesn't matter - I'm getting the same error:
Error occurred during deployment: Exception while loading the app
:java.lang.IllegalStateException: ContainerBase.addChild: start:
org.apache.catalina.LifecycleException: java.lang.RuntimeException: Servlet web
service endpoint '' failure.
Are the int, string, boolean etc only allowed as return type?

there is by no means enough information given in your post... How are you creating the web service (I guess with an #WebService), your're telling it does not matter if method SelectWorker (which btw should be called selectWorker by proper naming conventions) is empty or not, but with an empty body your source would not even compile...
what I can tell you: int, String, boolean are not the only allowed return types. You can of course also return instances of your classes from a web service.

For future googlers :
I've had the same error, and checked the server log and got the error :
Two classes have the same XML type name
Which I found wierd but adding this :
#XmlType(namespace="someName")
To my class I was trying to return ( I chose the same name of the class) fixed the problem.

I had this problem, the glassfish was on Linux environment. check your $JAVA_HOME
it should be set in to jdk
export JAVA_HOME=/usr/java/jdk1.7.0_55
/opt/glassfish4/glassfish/bin # echo $JAVA_HOME
/usr/java/jdk1.7.0_55
then problem was solved..

Related

Lambda Error: #DynamoDBIndexHashKey must specify one of HASH GSI name/names

I have the following class:
#DynamoDBTable(tableName = "PodcastReviewService-Episodes")
public class Episode {
private String podcast;
private int episodeNr;
private String name;
private int avgRating;
private String episodeId;
private List<Review> reviews;
public Episode() {}
#DynamoDBIndexHashKey(attributeName = "podcast")
public String getPodcast() {return podcast;}
#DynamoDBRangeKey(attributeName = "episodeNr")
public int getEpisodeNr() {return episodeNr;}
#DynamoDBAttribute(attributeName = "name")
public String getName() {
return name;
}
#DynamoDBIndexHashKey(attributeName = "avgRating", globalSecondaryIndexName = "avgRating")
public int getAvgRating() {
return avgRating;
}
#DynamoDBIndexRangeKey(attributeName = "episodeId", globalSecondaryIndexName = "episodeId")
public String getEpisodeId() {
return episodeId;
}
#DynamoDBAttribute(attributeName = "reviews")
public List<Review> getReviews() {
return reviews;
}
The class that attempts to add an object Episode to my DynamoDB table is :
public class EpisodeDao {
private final DynamoDBMapper dynamoDBMapper;
public EpisodeDao() {
this.dynamoDBMapper = new DynamoDBMapper(AmazonDynamoDBClientBuilder.standard().withCredentials(DefaultAWSCredentialsProviderChain.getInstance()).withRegion(Regions.US_WEST_2).build());
}
public Episode getEpisode(String podcast, int episodeNr) {
Episode episode = this.dynamoDBMapper.load(Episode.class, podcast, episodeNr);
if (episode == null) {
throw new EpisodeNotFoundException("Could not find episode of " + podcast + " nr." + episodeNr);
}
return episode;
}
public Episode saveEpisode(String podcast, String name, int episodeNr) {
Episode episode = new Episode();
//Check if episode already exists, if so return an DuplicateEpisodeException
//We initialize average rating at 0 since no reviews have been submitted
if (getEpisode(podcast, episodeNr) == null) {
episode.setPodcast(podcast);
episode.setName(name);
episode.setEpisodeNr(episodeNr);
episode.setEpisodeId(podcast.charAt(0) + name.charAt(0) + PodcastReviewsUtils.generateRandomID());
episode.setAvgRating(0);
episode.setReviews(new ArrayList<>());
} else throw new DuplicateEpisodeException("The episode that you are trying to add seems to already exist.");
return episode;
}
This is the output I get on Lambda:
"errorMessage": "#DynamoDBIndexHashKey must specify one of HASH GSI name/names",
"errorType": "com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException",
"stackTrace": [
"com.amazonaws.services.dynamodbv2.datamodeling.StandardAnnotationMaps$FieldMap.globalSecondaryIndexNames(StandardAnnotationMaps.java:345)",
"com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperFieldModel$Properties$Immutable.<init>(DynamoDBMapperFieldModel.java:459)",
"com.amazonaws.services.dynamodbv2.datamodeling.StandardBeanProperties$Bean.<init>(StandardBeanProperties.java:92)",
"com.amazonaws.services.dynamodbv2.datamodeling.StandardBeanProperties$Bean.<init>(StandardBeanProperties.java:86)",
"com.amazonaws.services.dynamodbv2.datamodeling.StandardBeanProperties$BeanMap.putOrFlatten(StandardBeanProperties.java:217)",
"com.amazonaws.services.dynamodbv2.datamodeling.StandardBeanProperties$BeanMap.putAll(StandardBeanProperties.java:207)",
"com.amazonaws.services.dynamodbv2.datamodeling.StandardBeanProperties$BeanMap.<init>(StandardBeanProperties.java:198)",
"com.amazonaws.services.dynamodbv2.datamodeling.StandardBeanProperties$CachedBeans.getBeans(StandardBeanProperties.java:55)",
"com.amazonaws.services.dynamodbv2.datamodeling.StandardBeanProperties$CachedBeans.access$100(StandardBeanProperties.java:48)",
"com.amazonaws.services.dynamodbv2.datamodeling.StandardBeanProperties.of(StandardBeanProperties.java:42)",
"com.amazonaws.services.dynamodbv2.datamodeling.StandardModelFactories$TableBuilder.<init>(StandardModelFactories.java:132)",
"com.amazonaws.services.dynamodbv2.datamodeling.StandardModelFactories$TableBuilder.<init>(StandardModelFactories.java:116)",
"com.amazonaws.services.dynamodbv2.datamodeling.StandardModelFactories$StandardTableFactory.getTable(StandardModelFactories.java:107)",
"com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper.getTableModel(DynamoDBMapper.java:409)",
"com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper.load(DynamoDBMapper.java:447)",
"com.amazonaws.services.dynamodbv2.datamodeling.AbstractDynamoDBMapper.load(AbstractDynamoDBMapper.java:85)",
"com.podcast_reviews_service.dynamodb.EpisodeDao.getEpisode(EpisodeDao.java:35)",
"com.podcast_reviews_service.dynamodb.EpisodeDao.saveEpisode(EpisodeDao.java:50)",
"com.podcast_reviews_service.activity.AddEpisodeActivity.handleRequest(AddEpisodeActivity.java:35)",
"java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)",
"java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)",
"java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)",
"java.base/java.lang.reflect.Method.invoke(Unknown Source)"
]
I haven't yet implemented the class that utilizes the GSI. I tried without the secondary index annotation but since my table has them I get the same error.
The error makes me think that I either annotated the Episode class wrong or I'm sending a null value as HASH key for the GSI, which I'm pretty sure I'm not.
You must define the name of your index for the indexhashkey.
#DynamoDBIndexHashKey(attributeName = "podcast",globalSecondaryIndexNames={ "my-index-name"})
public String getPodcast() {return podcast;}

Getting null values in REST web service PUT command

I am writing a PUT request REST web service. I have a POJO User.java having String name. Below is my POJO:
#XmlRootElement(name = "User")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private String Name;
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public User() {
}
public User(String Name) {
this.Name = Name;
}
}
My Web service is as below:
#Path("/user")
public class UserService {
#Path("/xml")
#PUT
#Produces({MediaType.APPLICATION_XML})
#Consumes({MediaType.APPLICATION_XML})
public User putUsers(User user){
System.out.println("***** Received User XML *****");
System.out.println("Name :: "+user.getName());
return user;
}
}
From Postman, i am sending below in Request body:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><User>
<Name>abcd</Name></User>
and PUT URL executed:
http://localhost:8080/rest/users/xml
But i am getting null as output:
***** Received User XML *****
Name :: null
Why am i not getting abcd as output?
Ok.. i found the answer..
1) I just added #XmlElement(name = "Name") above the getter getName().
2) Changed it to small n in the variable declaration Name as 'name'.
This fixed it.

How to use #UsingDataSet in Arquillian test

I have trouble using #UsingDataSet in my project.
Example in manual https://docs.jboss.org/author/display/ARQ/Persistence
doesn`t helps.
I have simple entity:
#Entity(name = "game")
#Table(name = "game_entity", schema = "graph")
#GenericGenerator(name="uuid2", strategy = "uuid2")
public class Game implements Serializable {
private static final long serialVersionUID = -4832711740307931146L;
private UUID id;
private String name;
#Id
#GeneratedValue(generator="uuid2")
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
#NotNull
#Column(name = "name", length = 256, nullable = false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public boolean equals(Object value) {
if (!(value instanceof Game)) {
return false;
}
if (value == this) {
return true;
}
Game obj = (Game) value;
if (!obj.getId().equals(getId())) {
return false;
}
return true;
}
#Override
public int hashCode() {
int result = 29;
result += 29 * (getId() != null ? getId().hashCode() : 0);
result += 29*(getName() != null ? getName().hashCode() : 0);
return result;
}
}
And .yml file
game_entity:
- id : d5c58afd-7c99-41bb-ab0a-6357bfddfe14
name : Call of Duty
My test:
public class MyTest extends Arquillian {
#PersistenceContext(unitName = "spo")
private EntityManager em;
#Test
#UsingDataSet("datasets/gameDataSet.yml")
public void testAttribute() {
System.out.println("Hello world !");
}
#Deployment
public static WebArchive createArchive() {
WebArchive war = ShrinkWrap
.create(WebArchive.class, "myTest.war")
.addAsLibraries(
// blah-blah-blah
)
.addAsResource("my-persistence.xml", "META-INF/persistence.xml")
//.addAsResource("datasets/gameDataSet.yml", "datasets/gameDataSet.yml") // do I need to add this to archive ??
.addAsWebInfResource("META-INF/beans.xml", "beans.xml")
.setWebXML("web.xml")
;
return war;
}
}
When I run this test I getting 2 "strange" exeptions.
Sometimes:
Caused by: org.dbunit.dataset.NoSuchColumnException: game_entity.ID - (Non-uppercase input column: id) in ColumnNameToIndexes cache map. Note that the map's column names are NOT case sensitive.
But there are 2 columns in database! "id" and "name"
Sometimes, even more strange exception:
Caused by: org.postgresql.util.PSQLException: ERROR: relation "info_resource_attributes" does not exist
This is cross-table for another 2 entities, it exist in archive and myPersistence.xml but I dont use them in this test.
I use Wildfly 10 and Postgres 9.5. Without #UsingDataSet everything fine.
But I dont want programmaticaly hardcode data for tests like that:
Entity newEntityForTest = new Entity();
newEntityForTest.setA(...);
newEntityForTest.setB(...);
newEntityForTest.setC(...);
em.persist(newEntityForTest);
// testing ...
em.remove(newEntityForTest);

can not mapping entity when using AWS DynamoDB

I am begin with dynamoDB. I using annotion mapping enity follow :
#DynamoDBTable(tableName = "ProductCatalogz")
public static class Book {
private int id;+
private String title;+
private String ISBN;+
private Set<String> bookAuthors;+
// private DimensionType dimensionType;
#DynamoDBHashKey(attributeName = "Id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#DynamoDBAttribute(attributeName = "Title")
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#DynamoDBAttribute(attributeName = "ISBN")
public String getISBN() {
return ISBN;
}
public void setISBN(String ISBN) {
this.ISBN = ISBN;
}
}
and
public static void main(String[] args) throws IOException {
AWSCredentials credentials = new PropertiesCredentials(
Tester2.class.getResourceAsStream("/AwsCredentials.properties"));
client = new AmazonDynamoDBClient(credentials);
Region usWest2 = Region.getRegion(Regions.US_EAST_1);
client.setRegion(usWest2);
Book book = new Book();
book.setId(1);
book.setTitle("Book 502");
book.setISBN("5555555555555");
book.setBookAuthors(new HashSet<String>(Arrays.asList("Author1",
"Author2")));
// book.setDimensions(dimType);
DynamoDBMapper mapper = new DynamoDBMapper(client);
mapper.save(book);
}
But when I run this error :
Exception in thread "main" ResourceNotFoundException: Status Code: 400, AWS Service: AmazonDynamoDBv2, AWS Request ID: NSG3K0BQOBCPNQONE8, AWS Error Code: ResourceNotFoundException, AWS Error Message: Requested resource not found
at com.amazonaws.http.AmazonHttpClient.handleErrorResponse(AmazonHttpClient.java:644)
at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:338)
at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:190)
at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.invoke(AmazonDynamoDBClient.java:1245)
at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.updateItem(AmazonDynamoDBClient.java:1026)
at com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper.save(DynamoDBMapper.java:636)
at com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper.save(DynamoDBMapper.java:483)
at test.Tester2.main(Tester2.java:47)
please help me
The message Requested resource not found means that Dynamo DB table is not found. You should create it first through AWS console, API, or CLI.
Ensure that you have set the endpoint on the client
BasicAWSCredentials b = new BasicAWSCredentials("Access Key ID","Secret Access Key");
AmazonDynamoDBClient client = new AmazonDynamoDBClient(b);
client.setEndpoint("dynamodb.ap-northeast-1.amazonaws.com");
Refer http://docs.aws.amazon.com/general/latest/gr/rande.html#ddb_region for the complete list of End Points for DynamoDB

Asmx receiving POST -ed values(params) from Extjs?

How to receive posted values to variable in .asmx that was posted from extjs, so it can be saved using ado.net to database?
SENDING DATA WITH EXT.AJAX
{
text: 'Add',
formBind: true,
disabled: true,
handler: function () {
var form = this.up('form').getForm();
var formValues = form.getValues();
var firstName = formValues.firstName;
var lastName = formValues.lastName;
if (form.isValid()) {
Ext.Ajax.request({
url: 'WebServices/WebService.asmx/AddAgent',
headers: { 'Content-Type': 'application/json' },
method: 'POST',
jsonData: { FirstName: firstName, LastName: lastName }
});
}
}
}
When submited, firebug reports error:
How to properly recieve this values in .asmx so they can be used in [WebMethod] and saved with Ado.Net?
[Serializable]
public class Agents
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
//CREATE
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
public string AddAgent()
{
string connStr = ConfigurationManager.ConnectionStrings["AgentsServices"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connStr))
{
connection.Open();
using (SqlCommand command = new SqlCommand("insert into Agent(id, firstName, lastName) values(#id, #firstName, #lastName)", connection))
{
command.Parameters.AddWithValue("#firstName", FirstName); //here i get message( The name "FirstNAme does not exist in current context")
command.Parameters.AddWithValue("#lastName", LastName); // -||-
command.ExecuteNonQuery();
}
}
}
EDIT:
No. stil 500 Internal Server Error:
Your web method doesn't seem to take any argument. Also your method expects to return a string and yet you do not return anything. So either return something or modify your method signature to void. Also you have set UseHttpGet = true and yet you are sending a POST request. Try like this:
[WebMethod]
[ScriptMethod]
public void AddAgent(Agents agents)
{
string connStr = ConfigurationManager.ConnectionStrings["AgentsServices"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connStr))
{
connection.Open();
using (SqlCommand command = new SqlCommand("insert into Agent(id, firstName, lastName) values(#id, #firstName, #lastName)", connection))
{
command.Parameters.AddWithValue("#firstName", agents.FirstName);
command.Parameters.AddWithValue("#lastName", agents.LastName);
command.ExecuteNonQuery();
}
}
}
Also since you have defined the Id property of your Agents model as a non-nullable integer I would recommend you sending a value for it:
jsonData: { agents: { Id: 0, FirstName: firstName, LastName: lastName } }