Web service Rest using Angular2 and spring with Enum Types - spring

I want to seed an object with format JSON that have an attribute with type enum
when I lanch my request I fet error 403
this is my service in front side
export enum DocumentComponentType {
DIV_12,
DIV_4_4_4,
DIV_4_8,
DIV_8_4,
DIV_6_6,
}
export interface DocumentComponent {
id: number;
type: DocumentComponentType;
// documentContents: DocumentContent[];
}
this.gridService.addDocumentComponent({id: 0, type: DocumentComponentType.DIV_8_4}, 6)
.subscribe(data => {
this.documentComponent = data;
},
error => alert('Erreur ' + error),
() => {
console.log("finished ");
}
);
and in server side
this is my class
public class DocumentComponent {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
DocumentComponentType type;
#OneToMany(mappedBy = "documentComponent")
private List<DocumentContent> documentContents;
#ManyToOne
Document document;
DocumentComponent(){
}
}
and my enum
public enum DocumentComponentType {
DIV_12,
DIV_4_4_4,
DIV_4_8,
DIV_8_4,
DIV_6_6,
}
I get error 500 (Internal Server Error)

I get error 500 (Internal Server Error)
This means that there is an error on the server. The code you have posted is client side code.
Fix
Look at the server side logs (and or) attach a debugger to the server to see what is going on there.
More
https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#5xx_Server_Error The error is a generic error message which essentially means that something unexpected happened.

Related

Why my object instance's variable were not be able to be accessed correctly in cypress/ it block?

In my class object, I have a variable named category, which would be initialed in constructor.
export class Page {
constructor(category) {
this.category = category;
}
categorySession = `[data-cy="${this.category}-form"]`
enterValue(Value){
cy.get(this.categorySession).find('Value').type(`${Value}`).should('have.value',`${Value}`)
}
}
When I run the test,
In cypress, it throws me a error [data-cy="undefined-form"], but never found it.
import {Page} from "./pages/valuePage"
const LiquidityPage = new Page('Liquidity')
console.log(LiquidityPage.category) <--- it show Liquidity
describe('E2E_case', () => {
describe('Portfolio Value', () => {
it('Input Portfolio Value', () => {
cy.visit('http://localhost:30087/')
LiquidityPage.enterValue(123) // this gives me this error - Timed out retrying after 4000ms: Expected to find element: [data-cy="undefined-form"], but never found it.
})
})
Why is that [data-cy="undefined-form"] but not as my expected value [data-cy="Liquidity-form"]
You would also need to set sessionCategory in the constructor.
That way you will avoid the undefined value in the selector string.
export class Page {
constructor(category) {
this.category = category;
this.categorySession = `[data-cy="${this.category}-form"]`
}
...
}
But that seems quite obvious, you must have tried it already?

Spring, How to set error message from custom constraint validator at runtime

I have this constraint for validating dhcp host addresses.
annotation class DHCPAddressConstraint(
val message: String = "Invalid dhcp address.",
val groups: Array<KClass<*>> = [],
val payload: Array<KClass<out Payload>> = [],
val cidrField: String = "",
val addressRangeField: String = ""
)
class DHCPAddressValidator: ConstraintValidator<DHCPAd, Any> {
override fun isValid(obj: Any, context: ConstraintValidatorContext): Boolean {
val cidr = ReflectionUtils.get(obj, cidrField)
val addressRange = ReflectionUtils.get(obj, addressRangeField)
return isValidCIDR(cidr) && isValidAdressRange(cidr, addressRange)
}
}
So if something is invalid it would return just "Invalid dhcp address.". I want to set the error message to be more specific so why is it invalid. For example the dhcp address range may not be in the CIDR range or the user enters reserved IP address and so on. I expect to have error message like this "Invalid dhcp address due to ${reason}". how can I set the constraint error message at runtime?
you could take help of #ControllerAdvice & #ExceptionHandler
Please look at the example code below
#RestControllerAdvice
public class ApiExceptionController {
#ExceptionHandler(value = PageNotFoundApiException.class)
public ResponseEntity<Object> pageNotFoundApiException(PageNotFoundApiException exception){
return new ResponseEntity<>("Page Not Found 404", HttpStatus.NOT_FOUND);
}
}
You can also take a reference over this documentation
I hope, it helps!

Error: Returned error: VM Exception while processing transaction: out of gas

I have a simple smart contract deployed on the local truffle env using migrate. I am using react-components package to work with the smart contract.
So my issue is that simple getters and setters are working, but when I try to run a method with 2-3 arguments I am getting this exception.
My truffleconfig is as follows:
module.exports = {
// See <http://truffleframework.com/docs/advanced/configuration>
// to customize your Truffle configuration!
contracts_build_directory: path.join(__dirname, "app/src/contracts"),
networks: {
develop: { // default with truffle unbox is 7545, but we can use develop to test changes, ex. truffle migrate --network develop
host: "127.0.0.1",
port: 8545,
network_id: "*",
gas: 6921975,
gasPrice: 25000000000
}
},
solc: {
optimizer: {
enabled: true,
runs: 200
}
}
};
And in my react component I am calling like this:
<div className="section">
<h2>Testing Poni</h2>
<p>
This is a initial test to create Poni
</p>
<p>
<strong>Stored Value: </strong>
<ContractData
drizzle={drizzle}
drizzleState={drizzleState}
contract="PoniOwnership"
method="getMyPonies"
/>
</p>
<ContractForm drizzle={drizzle} contract="PoniOwnership" method="createPoni" />
</div>
My solidity functions are like this:
function createPoni(string memory _code, string memory _imgLink) public onlyOwner poniIsUnique(_code){
uint randDna = _generateRandomDna(_code);
//!!pass imgHash here also later
_createPoni(_code, _imgLink, randDna);
}
function _createPoni(string memory _code, string memory _imgLink, uint _dna) private {
uint id = ponies.push(Poni(msg.sender, _code, _imgLink, _dna, 0, true)) - 1;
poniToOwner[id] = msg.sender;
codeToId[_code] = id;
ownerPoniCount[msg.sender] = ownerPoniCount[msg.sender].add(1);
emit NewPoni(id, _code, _imgLink, _dna);
}
struct Poni {
address owner;
string code;
string imgLink;
uint dna;
}
I have tried to additionally send gas from the drizzle react-component as options are given here: https://www.trufflesuite.com/docs/drizzle/react/react-components, but it throws errors saying function is not payable. I am not able to figure out how to deal with this exception.
You want to set a higher gas for the transaction
You want to tweak the sendArgs({gas:}) on the ContractForm component.
https://www.trufflesuite.com/docs/drizzle/react/react-components#contractform

Log Spring webflux types - Mono and Flux

I am new to spring 5.
1) How I can log the method params which are Mono and flux type without blocking them?
2) How to map Models at API layer to Business object at service layer using Map-struct?
Edit 1:
I have this imperative code which I am trying to convert into a reactive code. It has compilation issue at the moment due to introduction of Mono in the argument.
public Mono<UserContactsBO> getUserContacts(Mono<LoginBO> loginBOMono)
{
LOGGER.info("Get contact info for login: {}, and client: {}", loginId, clientId);
if (StringUtils.isAllEmpty(loginId, clientId)) {
LOGGER.error(ErrorCodes.LOGIN_ID_CLIENT_ID_NULL.getDescription());
throw new ServiceValidationException(
ErrorCodes.LOGIN_ID_CLIENT_ID_NULL.getErrorCode(),
ErrorCodes.LOGIN_ID_CLIENT_ID_NULL.getDescription());
}
if (!loginId.equals(clientId)) {
if (authorizationFeignClient.validateManagerClientAccess(new LoginDTO(loginId, clientId))) {
loginId = clientId;
} else {
LOGGER.error(ErrorCodes.LOGIN_ID_VALIDATION_ERROR.getDescription());
throw new AuthorizationException(
ErrorCodes.LOGIN_ID_VALIDATION_ERROR.getErrorCode(),
ErrorCodes.LOGIN_ID_VALIDATION_ERROR.getDescription());
}
}
UserContactDetailEntity userContactDetail = userContactRepository.findByLoginId(loginId);
LOGGER.debug("contact info returned from DB{}", userContactDetail);
//mapstruct to map entity to BO
return contactMapper.userEntityToUserContactBo(userContactDetail);
}
You can try like this.
If you want to add logs you may use .map and add logs there. if filters are not passed it will return empty you can get it with swichifempty
loginBOMono.filter(loginBO -> !StringUtils.isAllEmpty(loginId, clientId))
.filter(loginBOMono1 -> loginBOMono.loginId.equals(clientId))
.filter(loginBOMono1 -> authorizationFeignClient.validateManagerClientAccess(new LoginDTO(loginId, clientId)))
.map(loginBOMono1 -> {
loginBOMono1.loginId = clientId;
return loginBOMono1;
})
.flatMap(o -> {
return userContactRepository.findByLoginId(o.loginId);
})

cannot find the datastore during the compiling in Angular2

When I try to run my page in Wakanda studio 1.1.3, I am getting an error during the compiling when converting the TS to JS. It shows me an error stating "cannot find the datastore"; which is present in my wakanda database. Is anyone else getting the same error?
here is the code:
this.wakanda.catalog.then(ds=>{
ds.TestDatabase.testmethod().then(op=>{
console.log(op);
});
});
my wakanda.service.ts is of the following
import {WakandaClient} from 'wakanda-client/browser/no-promise';
export class Wakanda {
private _client: WakandaClient;
private _catalog;
constructor() {
//this._client = new WakandaClient({ host: 'http://127.0.0.1:8081' });
this._client = new WakandaClient({});
this._catalog = null;
}
get catalog() {
if (!this._catalog) {
return this._client.getCatalog().then(c => {
this._catalog = c;
return c;
});
}
return Promise.resolve(this._catalog);
}
get directory() {
return this._client.directory;
}
get wakandaClientVersion() {
return this._client.version();
}
}
where TestDatavase is a table in my datastore and has a method called testmethod.
[default]
/Users/adithyavinayak/Documents/Wakanda/solutions/TestDatabase/TestDatabase/web/src/app/home/home.component.ts:21:8
Property 'TestDatabase' does not exist on type 'Catalog'. [default]
Checking finished with 4 errors
This one happens even if i make a call to any datastore during compile time.
The solution for this problem is by using the return type of the catalog to any
this.wakanda.catalog.then((ds:any)=>{
ds.TestDatabase.testmethod().then(op=>{
console.log(op);
});
});
This one works without any problem during the time of compilation.

Resources