Application Client using remote interface - java

Please see the code below:
//Main.Java
package clienttest;
import javax.ejb.EJB;
import test.TestEJBRemote;
/**
*
* #author
*/
public class Main {
#EJB
private static TestEJBRemote testEJB;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
System.out.println(testEJB.getName("Ian"));
}
}
//TestEJBRemote.java
package test;
import javax.ejb.Remote;
/**
*
* #author
*/
#Remote
public interface TestEJBRemote {
public String getName (String name);
}
//TestEJB
package test;
import javax.ejb.Stateless;
/**
*
* #author
*/
#Stateless
public class TestEJB implements TestEJBRemote {
#Override
public String getName(String name) {
return "Hello " + name;
}
// Add business logic below. (Right-click in editor and choose
// "Insert Code > Add Business Method")
}
Q1) Does this mean I can deploy Main.java to another PC on the network and run it?
Q2) Once deployed, then how does Main.java know where to look for testEJB?

The details are vendor-specific, but the application client typically has a command-line option to specify the target server host and port.

Related

Integrating Query dsl with Reactive Mongo Repository in spring 5

Spring 5 comes with a reactive implementation for spring data mongo , before the i was able to extend my mongo repository with QuerydslPredicateExecutor
#Repository
public interface AccountRepo extends MongoRepository<Account,String>
,QuerydslPredicateExecutor<Account>
if i try this
#Repository
public interface AccountRepo extends
ReactiveMongoRepository<Account,String>,
QuerydslPredicateExecutor<Account>
my application does not start it because :
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property exists found for type Account!
is there a way around this
here is the account class
package com.devop.models;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document
#Data
public class Account {
#Id
String id;
String accountName;
String accountNumber;
String schemeCode;
String openDate;
String accountCategory;
String accountCurrency = "Naira";
String accountSecondaryCategory;
String receiveSmsAlert;
String recieveEmailAlert;
String cifId;
}
here is the interface AccountRepo
package com.devop.mongoRepo;
import com.devop.models.Account;
import org.springframework.data.mongodb.repository.*;
import org.springframework.data.mongodb.repository.support*;
import org.springframework.data.querydsl.QuerydslPredicateExecutor;
import org.springframework.stereotype.Repository;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
#Repository
public interface AccountRepo extends
ReactiveMongoRepository<Account,String>
,QuerydslPredicateExecutor<Account> {
Flux<Account> findAccountByAccountNameContains(String accountName);
Mono<Account> findAccountByAccountNumberEquals(String accountNumber);
}
You could use ReactiveQuerydslPredicateExecutor. See example for more information https://github.com/spring-projects/spring-data-examples/tree/master/mongodb/querydsl
I found a workaround solution using a Custom ReactiveMongoRepositoryFactoryBean and ReactiveMongoRepositoryFactory, it could help someone else that is struggling with that
First you need to use repositoryFactoryBeanClass in the reactive annotation.
#EnableReactiveMongoRepositories(repositoryFactoryBeanClass = CustomReactiveMongoRepositoryFactoryBean.class)
#Configuration
public class ReactiveMongoDbHack {
}
CustomReactiveMongoRepositoryFactoryBean class
import org.springframework.data.mongodb.core.ReactiveMongoOperations;
import org.springframework.data.mongodb.repository.support.ReactiveMongoRepositoryFactoryBean;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;
public class CustomReactiveMongoRepositoryFactoryBean extends ReactiveMongoRepositoryFactoryBean {
public CustomReactiveMongoRepositoryFactoryBean(Class repositoryInterface) {
super(repositoryInterface);
}
#Override
protected RepositoryFactorySupport getFactoryInstance(ReactiveMongoOperations operations) {
return new CustomReactiveMongoRepositoryFactory(operations);
}
}
CustomReactiveMongoRepositoryFactory class
import static org.springframework.data.querydsl.QuerydslUtils.QUERY_DSL_PRESENT;
public class CustomReactiveMongoRepositoryFactory extends ReactiveMongoRepositoryFactory {
private static MongoOperations operations;
private final MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> mappingContext;
public CustomReactiveMongoRepositoryFactory(ReactiveMongoOperations operations) {
super(operations);
this.mappingContext = operations.getConverter().getMappingContext();
}
//TODO Must set MongoOperations(MongoTemplate)
public static void setOperations(MongoOperations operations) {
CustomReactiveMongoRepositoryFactory.operations = operations;
}
#Override
protected RepositoryComposition.RepositoryFragments getRepositoryFragments(RepositoryMetadata metadata) {
RepositoryComposition.RepositoryFragments fragments = RepositoryComposition.RepositoryFragments.empty();
boolean isQueryDslRepository = QUERY_DSL_PRESENT
&& QuerydslPredicateExecutor.class.isAssignableFrom(metadata.getRepositoryInterface());
if (isQueryDslRepository) {
MongoEntityInformation<?, Serializable> entityInformation = getEntityInformation(metadata.getDomainType(),
metadata);
fragments = fragments.append(RepositoryFragment.implemented(
getTargetRepositoryViaReflection(QuerydslMongoPredicateExecutor.class, entityInformation, operations)));
}
return fragments;
}
private <T, ID> MongoEntityInformation<T, ID> getEntityInformation(Class<T> domainClass,
#Nullable RepositoryMetadata metadata) {
MongoPersistentEntity<?> entity = mappingContext.getRequiredPersistentEntity(domainClass);
return MongoEntityInformationSupport.<T, ID> entityInformationFor(entity,
metadata != null ? metadata.getIdType() : null);
}
}
MongoEntityInformationSupport class copied from spring-data-mongodb
import org.springframework.data.domain.Persistable;
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
import org.springframework.data.mongodb.repository.query.MongoEntityInformation;
import org.springframework.data.mongodb.repository.support.MappingMongoEntityInformation;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
/**
* Support class responsible for creating {#link MongoEntityInformation} instances for a given
* {#link MongoPersistentEntity}.
*
* #author Christoph Strobl
* #author Mark Paluch
* #since 1.10
*/
final class MongoEntityInformationSupport {
private MongoEntityInformationSupport() {}
/**
* Factory method for creating {#link MongoEntityInformation}.
*
* #param entity must not be {#literal null}.
* #param idType can be {#literal null}.
* #return never {#literal null}.
*/
#SuppressWarnings("unchecked")
static <T, ID> MongoEntityInformation<T, ID> entityInformationFor(MongoPersistentEntity<?> entity,
#Nullable Class<?> idType) {
Assert.notNull(entity, "Entity must not be null!");
MappingMongoEntityInformation<T, ID> entityInformation = new MappingMongoEntityInformation<T, ID>(
(MongoPersistentEntity<T>) entity, (Class<ID>) idType);
return ClassUtils.isAssignable(Persistable.class, entity.getType())
? new PersistableMongoEntityInformation<>(entityInformation) : entityInformation;
}
}
PersistableMongoEntityInformation class also copied from spring-data-mongodb
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Persistable;
import org.springframework.data.mongodb.repository.query.MongoEntityInformation;
/**
* {#link MongoEntityInformation} implementation wrapping an existing {#link MongoEntityInformation} considering
* {#link Persistable} types by delegating {#link #isNew(Object)} and {#link #getId(Object)} to the corresponding
* {#link Persistable#isNew()} and {#link Persistable#getId()} implementations.
*
* #author Christoph Strobl
* #author Oliver Gierke
* #since 1.10
*/
#RequiredArgsConstructor
class PersistableMongoEntityInformation<T, ID> implements MongoEntityInformation<T, ID> {
private final #NonNull MongoEntityInformation<T, ID> delegate;
/*
* (non-Javadoc)
* #see org.springframework.data.mongodb.repository.MongoEntityInformation#getCollectionName()
*/
#Override
public String getCollectionName() {
return delegate.getCollectionName();
}
/*
* (non-Javadoc)
* #see org.springframework.data.mongodb.repository.MongoEntityInformation#getIdAttribute()
*/
#Override
public String getIdAttribute() {
return delegate.getIdAttribute();
}
/*
* (non-Javadoc)
* #see org.springframework.data.repository.core.EntityInformation#isNew(java.lang.Object)
*/
#Override
#SuppressWarnings("unchecked")
public boolean isNew(T t) {
if (t instanceof Persistable) {
return ((Persistable<ID>) t).isNew();
}
return delegate.isNew(t);
}
/*
* (non-Javadoc)
* #see org.springframework.data.repository.core.EntityInformation#getId(java.lang.Object)
*/
#Override
#SuppressWarnings("unchecked")
public ID getId(T t) {
if (t instanceof Persistable) {
return ((Persistable<ID>) t).getId();
}
return delegate.getId(t);
}
/*
* (non-Javadoc)
* #see org.springframework.data.repository.core.support.PersistentEntityInformation#getIdType()
*/
#Override
public Class<ID> getIdType() {
return delegate.getIdType();
}
/*
* (non-Javadoc)
* #see org.springframework.data.repository.core.support.EntityMetadata#getJavaType()
*/
#Override
public Class<T> getJavaType() {
return delegate.getJavaType();
}
}
Then your Reactive Repository with Query DSL would work.
public interface AssetRepository extends ReactiveCrudRepository<Asset, String>, QuerydslPredicateExecutor<Asset> {
}
PS: It must need to set MongoOperations at CustomReactiveMongoRepositoryFactory.setOperations, what I did was to use the auto config classes(MongoAutoConfiguration and MongoDataAutoConfiguration) for Mongo then using #PostConstruct in a method to set it.

Spring Data Rest -Disable self links(HAL) in Json

I am newbie to spring-data-rest. In my Application when i make a rest call i am getting json which consist on self-links and links to foreign key tables. But i want json instead on links. I generated my code using telosys tool generator. Here is my JSON what i am gettin when i made a REST call to the "merchandise" table in database.:
{
"id" : 1,
"rate": 300,
"type": "item",
"shortDescription": "test",
"longDescription": "test test",
"_links": {
"self": {
"href": "http://localhost:8080/sportsrest/merchandises/1"
},
"listOfMerchandiseAttribute": {
"href": "http://localhost:8080/sportsrest/merchandises/1/listOfMerchandiseAttribute"
},
}
}
But in instead of getting link of "listOfMerchandiseAttribute" i want to get JSON of listOfMerchandiseAttribute. listOfMerchandiseAttribute is my another table in database
That is i want my json like this:
{
"id": 1,
"rate": 300,
"type": "item",
"shortDescription": "test",
"longDescription": "test test",
"_links": {
"self": {
"href": "http://localhost:8080/sportsrest/merchandises/1"
},
"listOfMerchandiseAttribute": {
"id": 1,
"attributeName": "testname",
"attributeValue": 50
},
}
}
When i search on google i got some results and changed the ApplicationConfig.java file according to that but still i am getting links instead of JSON. Here is My ApplicationConfig file.
ApplicationConfig.java
/*
* Created on 19 Mar 2015 ( Time 14:41:07 )
* Generated by Telosys Tools Generator ( version 2.1.0 )
*/
package co.vitti.sports;
import org.springframework.context.MessageSource;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.data.rest.core.config.RepositoryRestConfiguration;
import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration;
import org.springframework.http.MediaType;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import co.vitti.sports.validator.BinaryValidator;
import co.vitti.sports.validator.CustomerPackageBalValidator;
import co.vitti.sports.validator.MerchandiseItemValidator;
import co.vitti.sports.validator.CustomerPackageValidator;
import co.vitti.sports.validator.InvoiceValidator;
import co.vitti.sports.validator.UserRoleValidator;
import co.vitti.sports.validator.SportValidator;
import co.vitti.sports.validator.MerchandiseTypeValidator;
import co.vitti.sports.validator.BookingValidator;
import co.vitti.sports.validator.TenantValidator;
import co.vitti.sports.validator.PaymentModeValidator;
import co.vitti.sports.validator.CourtValidator;
import co.vitti.sports.validator.MerchandisePackageValidator;
import co.vitti.sports.validator.CartValidator;
import co.vitti.sports.validator.MigrationValidator;
import co.vitti.sports.validator.TenantSportValidator;
import co.vitti.sports.repository.converter.TenantSportKeyConverter;
import co.vitti.sports.validator.TenantPaymentmodeValidator;
import co.vitti.sports.repository.converter.TenantPaymentmodeKeyConverter;
import co.vitti.sports.validator.MerchandiseAttributeValidator;
import co.vitti.sports.repository.converter.MerchandiseAttributeKeyConverter;
import co.vitti.sports.validator.CartItemValidator;
import co.vitti.sports.validator.MerchandiseValidator;
import co.vitti.sports.validator.UserValidator;
import co.vitti.sports.validator.TimeslotValidator;
import co.vitti.sports.validator.RoleValidator;
import org.springframework.core.convert.support.ConfigurableConversionService;
/**
* Application configuration.
* ( messages resources, validators)
* #author Telosys Tools Generator
*
*/
#Configuration
#ComponentScan(basePackageClasses = ApplicationConfig.class)
#EnableWebMvc
public class ApplicationConfig extends RepositoryRestMvcConfiguration {
#Override
protected void configureRepositoryRestConfiguration(RepositoryRestConfiguration config){
config.setDefaultMediaType((MediaType) MediaType.parseMediaTypes("application/x-spring-data-verbose+json"));
}
#Bean
public DataSource dataSource(){
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
return builder.setType(EmbeddedDatabaseType.HSQL).build();
}
/**
* Message Ressource declaration.
* #return MessageRessource
*/
#Bean
public MessageSource messageSource() {
ResourceBundleMessageSource source = new ResourceBundleMessageSource();
source.setBasename("i18n/messages");
source.setUseCodeAsDefaultMessage(true);
return source;
}
/**
* Validator declaration for Binary
* #return the BinaryValidator
*/
#Bean
public BinaryValidator beforeCreateBinaryValidator() {
return new BinaryValidator();
}
/**
* Validator declaration for CustomerPackageBal
* #return the CustomerPackageBalValidator
*/
#Bean
public CustomerPackageBalValidator beforeCreateCustomerPackageBalValidator() {
return new CustomerPackageBalValidator();
}
/**
* Validator declaration for MerchandiseItem
* #return the MerchandiseItemValidator
*/
#Bean
public MerchandiseItemValidator beforeCreateMerchandiseItemValidator() {
return new MerchandiseItemValidator();
}
/**
* Validator declaration for CustomerPackage
* #return the CustomerPackageValidator
*/
#Bean
public CustomerPackageValidator beforeCreateCustomerPackageValidator() {
return new CustomerPackageValidator();
}
/**
* Validator declaration for Invoice
* #return the InvoiceValidator
*/
#Bean
public InvoiceValidator beforeCreateInvoiceValidator() {
return new InvoiceValidator();
}
/**
* Validator declaration for UserRole
* #return the UserRoleValidator
*/
#Bean
public UserRoleValidator beforeCreateUserRoleValidator() {
return new UserRoleValidator();
}
/**
* Validator declaration for Sport
* #return the SportValidator
*/
#Bean
public SportValidator beforeCreateSportValidator() {
return new SportValidator();
}
/**
* Validator declaration for MerchandiseType
* #return the MerchandiseTypeValidator
*/
#Bean
public MerchandiseTypeValidator beforeCreateMerchandiseTypeValidator() {
return new MerchandiseTypeValidator();
}
/**
* Validator declaration for Booking
* #return the BookingValidator
*/
#Bean
public BookingValidator beforeCreateBookingValidator() {
return new BookingValidator();
}
/**
* Validator declaration for Tenant
* #return the TenantValidator
*/
#Bean
public TenantValidator beforeCreateTenantValidator() {
return new TenantValidator();
}
/**
* Validator declaration for PaymentMode
* #return the PaymentModeValidator
*/
#Bean
public PaymentModeValidator beforeCreatePaymentModeValidator() {
return new PaymentModeValidator();
}
/**
* Validator declaration for Court
* #return the CourtValidator
*/
#Bean
public CourtValidator beforeCreateCourtValidator() {
return new CourtValidator();
}
/**
* Validator declaration for MerchandisePackage
* #return the MerchandisePackageValidator
*/
#Bean
public MerchandisePackageValidator beforeCreateMerchandisePackageValidator() {
return new MerchandisePackageValidator();
}
/**
* Validator declaration for Cart
* #return the CartValidator
*/
#Bean
public CartValidator beforeCreateCartValidator() {
return new CartValidator();
}
/**
* Validator declaration for Migration
* #return the MigrationValidator
*/
#Bean
public MigrationValidator beforeCreateMigrationValidator() {
return new MigrationValidator();
}
/**
* Validator declaration for TenantSport
* #return the TenantSportValidator
*/
#Bean
public TenantSportValidator beforeCreateTenantSportValidator() {
return new TenantSportValidator();
}
/**
* Validator declaration for TenantPaymentmode
* #return the TenantPaymentmodeValidator
*/
#Bean
public TenantPaymentmodeValidator beforeCreateTenantPaymentmodeValidator() {
return new TenantPaymentmodeValidator();
}
/**
* Validator declaration for MerchandiseAttribute
* #return the MerchandiseAttributeValidator
*/
#Bean
public MerchandiseAttributeValidator beforeCreateMerchandiseAttributeValidator() {
return new MerchandiseAttributeValidator();
}
/**
* Validator declaration for CartItem
* #return the CartItemValidator
*/
#Bean
public CartItemValidator beforeCreateCartItemValidator() {
return new CartItemValidator();
}
/**
* Validator declaration for Merchandise
* #return the MerchandiseValidator
*/
#Bean
public MerchandiseValidator beforeCreateMerchandiseValidator() {
return new MerchandiseValidator();
}
/**
* Validator declaration for User
* #return the UserValidator
*/
#Bean
public UserValidator beforeCreateUserValidator() {
return new UserValidator();
}
/**
* Validator declaration for Timeslot
* #return the TimeslotValidator
*/
#Bean
public TimeslotValidator beforeCreateTimeslotValidator() {
return new TimeslotValidator();
}
/**
* Validator declaration for Role
* #return the RoleValidator
*/
#Bean
public RoleValidator beforeCreateRoleValidator() {
return new RoleValidator();
}
/**
* Add all converters for composite keys
*/
#Override
protected void configureConversionService(ConfigurableConversionService conversionService) {
super.configureConversionService(conversionService);
conversionService.addConverter(this.tenantsportKeyConverter());
conversionService.addConverter(this.tenantpaymentmodeKeyConverter());
conversionService.addConverter(this.merchandiseattributeKeyConverter());
}
/**
* Converter for the composite key in the TenantSport entity
* #return the converter
*/
#Bean
public TenantSportKeyConverter tenantsportKeyConverter() {
return new TenantSportKeyConverter();
}
/**
* Converter for the composite key in the TenantPaymentmode entity
* #return the converter
*/
#Bean
public TenantPaymentmodeKeyConverter tenantpaymentmodeKeyConverter() {
return new TenantPaymentmodeKeyConverter();
}
/**
* Converter for the composite key in the MerchandiseAttribute entity
* #return the converter
*/
#Bean
public MerchandiseAttributeKeyConverter merchandiseattributeKeyConverter() {
return new MerchandiseAttributeKeyConverter();
}
// equivalents for <mvc:resources/> tags
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/app/**").addResourceLocations("/app/")
.setCachePeriod(31556926);
}
// equivalent for <mvc:default-servlet-handler/> tag
#Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
Can anyone please help me to solve my issue and get the JSON instead on links.
Thanks in Advance.
You should make sure that listOfMerchandiseAttribute is a member of your domain class. Then default converting to JSON should have it there.
And Spring Data REST will use what-ever you current representation is and add Hypermedia.
See also Disable Hypertext Application Language (HAL) in JSON?
You could use Excerpts (especially made for this scenario). Because the Spring example is so eloquent and it's silly to just copy it here I'll just point it: https://docs.spring.io/spring-data/rest/docs/3.1.x/reference/html/#projections-excerpts.excerpting-commonly-accessed-data.
But just for the record and your convenience I'll paste the main parts of the spring example:
#Projection(name = "inlineAddress", types = { Person.class })
interface InlineAddress {
String getFirstName();
String getLastName();
Address getAddress();
}
see at Projection javadoc that types means The type the projection type is bound to.
The excerpt could be used this way:
#RepositoryRestResource(excerptProjection = InlineAddress.class)
interface PersonRepository extends CrudRepository<Person, Long> {}
in order to get this:
{
"firstName" : "Frodo",
"lastName" : "Baggins",
"address" : {
"street": "Bag End",
"state": "The Shire",
"country": "Middle Earth"
},
"_links": ...
}
For you merchandise is the equivalent of Person and the listOfMerchandiseAttribute is the equivalent of address.
How to get rid of _links
Check my answer at Disable Hypertext Application Language (HAL) in JSON?.
Final notes
Spring is evolving so be aware that this works with at least:
spring-data-rest-webmvc 3.1.3.RELEASE
or, if you prefeer spring boot version:
spring-boot-starter-parent 2.1.1.RELEASE
A cleaner way to do it would be to set the following property to false in application.properties along with creating Projections
spring.hateoas.use-hal-as-default-json-media-type=false

Java - Avoid create empty sub Class & Interface or generate Java source code template

I am developing a java web project using Spring and Mybatis.
In the dao level, I defined a super class and a super interface which implemented all common methods.
Thus when create sub class or interface for a specific model in dao level, I only need to implement the super dao class & interface, and left the class body and interface body empty.
Over half of the sub dao level class & interface is empty through all the time.
(Example of the empty dao class & interface:)
RoleDao.java
package core.dao;
import core.dao.base.BaseDao;
import core.model.Role;
public interface RoleDao extends BaseDao<Role> {
}
RoleDaoImpl.java
package core.dao.impl;
import org.springframework.stereotype.Repository;
import core.dao.RoleDao;
import core.dao.base.BaseDaoImpl;
import core.model.Role;
#Repository
public class RoleDaoImpl extends BaseDaoImpl<Role> implements RoleDao {
}
My question is:
Is there a good way to avoid writing these empty class & interface, while still could use them?
I am thinking of using Code generator to generate these class file, or use Java reflection to create such class & interface at runtime as need, but didn't get into detail yet.
#Update
It seems not flexible to achieve the target without creating source code, so I decided to write some simple java source code generator for java web project.
And a tool called codemodel is very suitable to do that, it is developed by Sun, and now owned by Oracle I guess.
And, I gave an answer by myself with code that I wrote to generate java source code.
The Repository classes for the classes in our projects that use QueryDSL and JPA only have an interface, but not an implementation. However, it does not answer the question whether it is possible to directly generate these repositories based on the entity classes, although it would be similar to what the Apt Maven Plugin does to create the QEntity classes for use with QueryDSL.
#NoRepositoryBean
public interface BaseRepository<T, ID extends Serializable> extends JpaRepository<T, ID>, QueryDslPredicateExecutor<T> {
}
#Repository
public interface DummyDataRepository extends BaseRepository<DummyData, Long> {
}
About a month ago I was asking myself the same thing :)
So, seems that we have a kind of solution, since you are using Spring library. As I read on docs:
Rather than code data access objects (DAOs) manually using
SqlSessionDaoSupport or SqlSessionTemplate, Mybatis-Spring provides a
proxy factory: MapperFactoryBean. This class lets you inject data
mapper interfaces directly into your service beans. When using mappers
you simply call them as you have always called your DAOs, but you
won't need to code any DAO implementation because MyBatis-Spring will
create a proxy for you.
There's an example on GitHub and also on this MyBatis' page.
I hope that it gives you some insights, because maybe it isn't feasible refactoring your whole system to be benefited of such nice feature.
I just wrote a simple code generator for my project.
It's just a single class, and could generate model/dao/service/action level code template for 1 or more models in a single execution.
Dependence:
It use codemodel and apache commons-io lib, and it's a spring + springMVC project.
How to use it:
It import some base class/interface in my project, from which the generated class extends/implements from, so you might can't run it directly. But you can create them as empty class/interface, or remove them from the genSourceXxx() function.
CodeGenerator.java:
package my.project.util;
import my.project.dao.base.BaseDao;
import my.project.dao.base.BaseDaoImpl;
import my.project.model.base.BaseIdModel;
import my.project.service.base.BaseService;
import my.project.service.base.BaseServiceImpl;
import my.project.web.action.base.BaseAction;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.Map;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.FileFileFilter;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import com.sun.codemodel.ClassType;
import com.sun.codemodel.JClass;
import com.sun.codemodel.JClassAlreadyExistsException;
import com.sun.codemodel.JCodeModel;
import com.sun.codemodel.JDefinedClass;
import com.sun.codemodel.JFieldVar;
import com.sun.codemodel.JMethod;
import com.sun.codemodel.JMod;
/**
* code generator
*
* #author eric
* #date Apr 10, 2015 3:32:57 PM
*/
public class CodeGenerator {
// location of source folder
public static final String tmpSourceFolderBaseLocation = "/tmp/java_code/"; // tmp location for generated code,
public static final String actualSourceFolderBaseLocation = "/mnt/star/workplace/eclipse_j2ee_workplace/project-name/source/java/"; // actual source folder,
// package
public static final String packageSeparator = ".";
public static final String basePackage = "my.project";
public static final String modelPackage = "model";
public static final String daoPackage = "dao";
public static final String daoImplPackage = "dao.impl";
public static final String servicePackage = "service";
public static final String serviceImplPackage = "service.impl";
public static final String actionPackage = "web.action";
// source file path
public static final String pkgPathSeparator = File.separator;
public static final String sourceSuffix = ".java";
public static final String basePkgPath = "my/project";
public static final String modelPkgPath = "model";
public static final String daoPkgPath = "dao";
public static final String daoImplPkgPath = "dao" + pkgPathSeparator + "impl";
public static final String servicePkgPath = "service";
public static final String serviceImplPkgPath = "service" + pkgPathSeparator + "impl";
public static final String actionPkgPath = "web" + pkgPathSeparator + "action";
// naming
public static final String daoSuffix = "Dao";
public static final String daoImplSuffix = "DaoImpl";
public static final String serviceSuffix = "Service";
public static final String serviceImplSuffix = "ServiceImpl";
public static final String actionSuffix = "Action";
// compiler for generated source code,
public static final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
// classloader for compiled class,
public static final ClassLoader cl = genCl(tmpSourceFolderBaseLocation);
/**
* compile a source file,
*
* #param sourcePath
* #throws MalformedURLException
*/
public static void compileSource(String sourcePath) throws MalformedURLException {
// set this so that won't get compile error,
System.setProperty("java.class.path", System.getProperty("java.class.path") + File.pathSeparator + tmpSourceFolderBaseLocation);
compiler.run(null, null, null, sourcePath);
}
/**
* generate a classloader,
*
* #param path
* #return
* #throws MalformedURLException
*/
public static ClassLoader genCl(String path) {
ClassLoader cl = null;
try {
cl = new URLClassLoader(new URL[] { new File(path).toURI().toURL() });
} catch (MalformedURLException e) {
e.printStackTrace();
}
return cl;
}
/**
* <p>
* Generate source for model.
* </p>
*
* #param modelName
* #throws IOException
* #throws JClassAlreadyExistsException
*/
public static void genSourceModel(String modelName) throws IOException, JClassAlreadyExistsException {
String modelFullName = genFullName(modelPackage, modelName);
JCodeModel cm = new JCodeModel();
// define type,
JDefinedClass dc = cm._class(modelFullName, ClassType.CLASS);
// extends
dc._extends(BaseIdModel.class);
// id
JFieldVar idField = dc.field(JMod.PRIVATE, Integer.class, "id"); // field
// id - getter method
JMethod getIdMethod = dc.method(JMod.PUBLIC, Integer.class, "getId");
getIdMethod.body()._return(idField);
getIdMethod.annotate(cm.ref(Override.class)); // annotation - override
// generate source code,
cm.build(new File(tmpSourceFolderBaseLocation));
// compile
compileSource(genFullPath(modelPkgPath, modelName));
}
public static void genSourceDao(String modelName) throws JClassAlreadyExistsException, ClassNotFoundException, IOException {
String daoFullName = genFullName(daoPackage, modelName, daoSuffix);
String modelFullName = genFullName(modelPackage, modelName);
JCodeModel cm = new JCodeModel();
// define type,
JDefinedClass dc = cm._class(daoFullName, ClassType.INTERFACE);
// extends
JClass superClazz = cm.ref(BaseDao.class).narrow(cl.loadClass(modelFullName));
dc._extends(superClazz);
// generate source code,
cm.build(new File(tmpSourceFolderBaseLocation));
// compile
compileSource(genFullPath(daoPkgPath, modelName, daoSuffix));
}
public static void genSourceDaoImpl(String modelName) throws JClassAlreadyExistsException, ClassNotFoundException, IOException {
String daoImplFullName = genFullName(daoImplPackage, modelName, daoImplSuffix);
String daoFullName = genFullName(daoPackage, modelName, daoSuffix);
String modelFullName = genFullName(modelPackage, modelName);
JCodeModel cm = new JCodeModel();
// define type,
JDefinedClass dc = cm._class(daoImplFullName, ClassType.CLASS);
dc.annotate(Repository.class);
// extends
JClass superClazz = cm.ref(BaseDaoImpl.class).narrow(cl.loadClass(modelFullName));
dc._extends(superClazz);
// implements
dc._implements(cl.loadClass(daoFullName));
// generate source code,
cm.build(new File(tmpSourceFolderBaseLocation));
// compile
compileSource(genFullPath(daoImplPkgPath, modelName, daoImplSuffix));
}
public static void genSourceService(String modelName) throws JClassAlreadyExistsException, ClassNotFoundException, IOException {
String serviceFullName = genFullName(servicePackage, modelName, serviceSuffix);
JCodeModel cm = new JCodeModel();
// define type,
JDefinedClass dc = cm._class(serviceFullName, ClassType.INTERFACE);
// extends
dc._extends(BaseService.class);
// generate source code,
cm.build(new File(tmpSourceFolderBaseLocation));
// compile
compileSource(genFullPath(servicePkgPath, modelName, serviceSuffix));
}
public static void genSourceServiceImpl(String modelName, boolean serviceTransaction) throws JClassAlreadyExistsException, ClassNotFoundException,
IOException {
String serviceImplFullName = genFullName(serviceImplPackage, modelName, serviceImplSuffix);
String serviceFullName = genFullName(servicePackage, modelName, serviceSuffix);
JCodeModel cm = new JCodeModel();
// define type,
JDefinedClass dc = cm._class(serviceImplFullName, ClassType.CLASS);
// annotation
dc.annotate(Service.class);
if (serviceTransaction) {
dc.annotate(Transactional.class);
}
// extends
dc._extends(BaseServiceImpl.class);
// implements
dc._implements(cl.loadClass(serviceFullName));
// generate source code,
cm.build(new File(tmpSourceFolderBaseLocation));
// compile
compileSource(genFullPath(serviceImplPkgPath, modelName, serviceImplSuffix));
}
public static void genSourceAction(String modelName) throws JClassAlreadyExistsException, ClassNotFoundException, IOException {
genSourceAction(modelName, null);
}
/**
* generate action,
*
* #param modelName
* #param rootMappingPath
* root mapping path, if null or empty then don't have this annotation,
* #throws JClassAlreadyExistsException
* #throws ClassNotFoundException
* #throws IOException
*/
public static void genSourceAction(String modelName, String rootMappingPath) throws JClassAlreadyExistsException, ClassNotFoundException, IOException {
String actionFullName = genFullName(actionPackage, modelName, actionSuffix);
JCodeModel cm = new JCodeModel();
// define type,
JDefinedClass dc = cm._class(actionFullName, ClassType.CLASS);
// annotation
dc.annotate(Controller.class);
if (StringUtils.isNotBlank(rootMappingPath)) {
dc.annotate(cm.ref(RequestMapping.class)).param("value", rootMappingPath);
}
// extends
dc._extends(BaseAction.class);
// generate source code,
cm.build(new File(tmpSourceFolderBaseLocation));
// compile
compileSource(genFullPath(actionPkgPath, modelName, actionSuffix));
}
/**
* <p>
* generate a serial java source code base on a single model, don't include service level,
* </p>
* <p>
* Warning: this will override existing code, so, be careful!
* </p>
*
* #param modelName
*/
public static void genStack(String modelName) {
genStack(modelName, false, false, null);
}
/**
* <p>
* generate a serial java source code base on a single model.
* </p>
* <p>
* Warning: this will override existing code, so, be careful!
* </p>
*
* #param modelName
* #param includeService
* specify whether include service level,
* #param serviceTransaction
* whether add transaction annotation to service impl class,
* #param actionRootMappingPath
* root mapping path, if null or empty then don't have this annotation,
*/
public static void genStack(String modelName, boolean includeService, boolean serviceTransaction, String actionRootMappingPath) {
try {
initTmp(); // clean or create folder,
// generate code - start
genSourceModel(modelName);
genSourceDao(modelName);
genSourceDaoImpl(modelName);
if (includeService) {
genSourceService(modelName);
genSourceServiceImpl(modelName, serviceTransaction);
}
genSourceAction(modelName, actionRootMappingPath);
// generate code - end
merge(); // copy,
initTmp(); // clean, so that won't have duplicated class,
} catch (IOException | JClassAlreadyExistsException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* <p>
* batch generate.
* </p>
* <p>
* Warning: this will override existing code, so, be careful!
* </p>
*
* #param models
* map of "modelName : actionRootMappingPath"
* #param includeService
* specify whether include service level,
* #param serviceTransaction
* whether add transaction annotation to service impl class,
*/
public static void genStackBatch(Map<String, String> models, boolean includeService, boolean serviceTransaction) {
for (String modelName : models.keySet()) {
genStack(modelName, includeService, serviceTransaction, models.get(modelName));
}
}
/**
* generate class fullname,
*
* #param subPackage
* #param modelName
* #return
*/
public static String genFullName(String subPackage, String modelName) {
return genFullName(subPackage, modelName, "");
}
/**
* generate class fullname,
*
* #param subPackage
* #param modelName
* #param suffix
* #return
*/
public static String genFullName(String subPackage, String modelName, String suffix) {
return new StringBuilder().append(basePackage).append(packageSeparator).append(subPackage).append(packageSeparator).append(modelName).append(suffix)
.toString();
}
/**
* generate source file path,
*
* #param subPkgPath
* #param modelName
* #return
*/
public static String genFullPath(String subPkgPath, String modelName) {
return genFullPath(subPkgPath, modelName, "");
}
/**
* generate source file path,
*
* #param subPkgPath
* #param modelName
* #param suffix
* #return
*/
public static String genFullPath(String subPkgPath, String modelName, String suffix) {
return new StringBuilder().append(tmpSourceFolderBaseLocation).append(basePkgPath).append(pkgPathSeparator).append(subPkgPath).append(pkgPathSeparator)
.append(modelName).append(suffix).append(sourceSuffix).toString();
}
/**
* clean tmp location,
*
* #throws IOException
*/
public static void initTmp() throws IOException {
File tmp = new File(tmpSourceFolderBaseLocation);
if (!tmp.exists()) { // create if not exists,
tmp.mkdirs();
} else { // clean if exists,
FileUtils.cleanDirectory(tmp);
}
}
/**
* <p>
* move generated code into source folder,
* </p>
* <p>
* Warning: this will override existing code, so, be careful!
* </p>
*/
public static void merge() {
File originalFile = new File(tmpSourceFolderBaseLocation + basePkgPath);
File targetFile = new File(actualSourceFolderBaseLocation + basePkgPath);
try {
// filter - java file,
IOFileFilter javaSuffixFilter = FileFilterUtils.suffixFileFilter(".java");
IOFileFilter javaFiles = FileFilterUtils.and(FileFileFilter.FILE, javaSuffixFilter);
// filter - dir or java file,
FileFilter filter = FileFilterUtils.or(DirectoryFileFilter.DIRECTORY, javaFiles);
FileUtils.copyDirectory(originalFile, targetFile, filter);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
// String modelName = "LoginHistory";
// String actionRootMappingPath = "/loginHistory";
// genStack(modelName, true, false, actionRootMappingPath);
Map<String, String> models = new HashMap<String, String>();
models.put("AdminAccount", "/adminAccount");
models.put("CustomerAccount", "/customerAccount");
models.put("Role", "/role");
genStackBatch(models, true, true);
}
}

create array of agents in jade

good morning, i would like to create an array that contain a multiple instances of an agent (many agents that have a same behaviour), so i used netbeans to create firstly an agent management who create the others agents and draw a circle that represent every agent in a frame. this the code for the main agent:
package jade;
/**
*
* #author walid
*/
import jade.core.Agent;
import jade.core.Runtime;
import jade.core.ProfileImpl;
import jade.wrapper.*;
import javax.swing.JFrame;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.util.logging.Level;
import java.util.logging.Logger;
import jade.Agent1;
public class AgentEnvironement extends Agent{
private JFrame jFrame = null;
private Agent1 []tab;
#Override
protected void setup() {
try {
getJFrame().setVisible(true);
} catch (StaleProxyException ex) {
Logger.getLogger(AgentEnvironement.class.getName()).log(Level.SEVERE, null, ex);
}
}
public JFrame getJFrame() throws StaleProxyException {
if (jFrame == null) {
jFrame = new JFrame();
jFrame.setSize(new java.awt.Dimension(500,350));
Dimension tailleEcran =Toolkit.getDefaultToolkit().getScreenSize();
int largeurEcran = tailleEcran.width;
int hauteurEcran = tailleEcran.height;
jFrame.setLocation((largeurEcran-500)/2,(hauteurEcran-350)/2);
jFrame.setTitle("Environement des agents rumeurs.");
jFrame.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
//jFrame.setContentPane(getJContentPane());
Runtime rt = Runtime.instance();
// Création du profil par défault
ProfileImpl p = new ProfileImpl(false);
AgentContainer container =rt.createMainContainer(p);
// Agent controleur pour permettre la création des agents
AgentController Agent=null;
Agent = container.createNewAgent("Agent1", "jade.Agent1", null);
Agent.start();
}
return jFrame;
}
}
and this the code for the agent class that i would like to create many instance of him
package jade;
import jade.core.AID;
import jade.core.Agent;
import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;
/**
*
* #author walid
*/
public class Agent1 extends Agent {
/**
*/
#Override
public void setup() {
addBehaviour(new comportement());
}
class comportement extends CyclicBehaviour {
public void action() {
System.out.println ("ready");
}
}
public static void main(String[] args) {
}
}
honestly i'm not good in java programming and if someone can help me i will be very pleasure.
Create an array of agents???? I'm not sure what that means but if you want to create multiple agents use a for loop and a counter to increment the name.
for (agentcounter=1;agentcounter++;agentcounter<agentmax)
{
Agent = container.createNewAgent("Agent"+agentcounter, "jade.Agent1", null);
}
this should create multiple agents of type jade.Agent1
eg for agentmax=10
Agent1 (Type jade.Agent1)
Agent2 (Type jade.Agent1)
Agent3 (Type jade.Agent1)
....
Agent10 (Type jade.Agent1)
Notice that in
Agent = container.createNewAgent("Agent"+agentcounter, "jade.AgentClass", null);
The first field is the name of the instance of the agent
The second field is the agent class
You cannot call your agent 'Agent', because is the name of another class, the root class your agents are inheriting from.
AgentController anotherName=null;
anotherName = container.createNewAgent("Agent1", "jade.Agent1", null);
anotherName.start();
That should work fine.
Another comment; Agents don't need and don't have a 'main()' method, because they are created in another fashion, as you have just seen.

Unable to execute Java code after compile

I want to create and publish simple WebService using Java.
Everything compiles.
When I run
>java -cp . ts.TimeServerPublisher
I am getting error
Error: Could not find or load main class ts.TimeServerPublisher
Any idea why it is a problem?
My code looks like following
TimeServerPublisher
package ts;
import javax.xml.ws.Endpoint;
public class TimeServerPublisher {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Endpoint.publish("http://127.0.0.1:9876/ts", new TimeServerImpl());
}
}
TimeServerImpl.java
package ts;
import java.util.Date;
import javax.jws.WebService;
#WebService(endpointInterface = "ts.TimeServer")
public class TimeServerImpl implements TimeServer {
public String getTimeAsString() { return new Date().toString(); }
public long getTimeAsElapsed() { return new Date().getTime(); }
}
TimeServer.java
package ts;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
#WebService
#SOAPBinding(style = Style.RPC)
public interface TimeServer {
#WebMethod String getTimeAsString();
#WebMethod long getTimeAsElapsed();
}
The class you are tryin to run is in the package ts.
So if you have this file tree:
/bin/ts/TimeServerPublisher
You have to run the following command
java -cp /bin ts/TimeServerPublisher

Categories