0

I have a problem in jersey restfull. When I execute my update operation, the console of eclipse and console of browser show an error.

for console of eclipse, the error is:

    GRAVE: Servlet.service() for servlet [JerseyWebApplication] in context with path [/APIRest] threw exception [java.lang.IllegalArgumentException: argument type mismatch] with root cause
java.lang.IllegalArgumentException: argument type mismatch
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.eclipse.yasson.internal.model.SetWithSetter.internalSetValue(SetWithSetter.java:27)

for console of browser, the error is:

POST http://localhost:8081/APIRest/resources/langue/update 500 (Erreur Interne de Servlet)
localhost/:1 Failed to load http://localhost:8081/APIRest/resources/langue/update: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 500.
update-langue.component.ts:31 Error saving langue!
(anonymous) @ update-langue.component.ts:31

It's my DAO code

@Override
    public void update(Langue object) {
        // TODO Auto-generated method stub
        EntityManager em = emf.createEntityManager();
        try {
            em.getTransaction().begin();
            em.merge(object);
            em.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("Erreur lors de la mise a jour d'une Langue");
        } finally {
            if (em.getTransaction().isActive())
                em.getTransaction().rollback();
            em.close();
        }

    }

It's my rest code

@Path("/update")
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public void update(Langue langue) {
        langueDao.update(langue);
    }

It's my angular code service

    import {Injectable} from '@angular/core';
    import {Http, Response, RequestOptions, Headers, ResponseContentType} from '@angular/http';
    import {AppSettingsService} from "./config.service";
    import { Langue } from "./langue";
    import {Observable} from 'rxjs/Observable';

    @Injectable()
    export class LangueService {

      private baseUrl: string = '';
      private settings: any;

      constructor(private http: Http, private appSettingsService: AppSettingsService) {
        this.appSettingsService.getSettings()
          .subscribe(settings => {
            this.settings = settings;
            this.baseUrl = this.settings.pathAPI + "/langue";
          });

      }
      // lister toutes les Langues
      getAll(): Observable<any[]> {
        let langue$ = this.http
          .get(`http://localhost:8081/APIRest/resources/langue/getall`, this.appSettingsService.setHeaders())
          .map((response: Response) => response.json())
        return langue$;
      }
//create langue
      create(langue: Langue): Observable<Response> {
        return this.http.post(`http://localhost:8081/APIRest/resources/langue/add`, JSON.stringify(langue), this.appSettingsService.setHeaders());
      }
      //delete a langue
      delete(langue: any): Observable<Response> {
        return this.http.post(`http://localhost:8081/APIRest/resources/langue/delete`, JSON.stringify(langue), this.appSettingsService.setHeaders());
      }
      // modifier une langue
      update(langue:Langue) {
        return this.http.post('http://localhost:8081/APIRest/resources/langue/update', JSON.stringify(langue), this.appSettingsService.setHeaders());
      }
    }

It's my update-langue.component.ts

import { Langue } from "../langue";
import { LangueService } from "../langue.service";
import { LangueComponent } from "../langue/langue.component";
import { Component, OnInit, Input } from '@angular/core';
import { Observable } from "rxjs";

@Component({
  selector: 'app-update-langue',
  templateUrl: './update-langue.component.html',
  styleUrls: ['./update-langue.component.css']
})
export class UpdateLangueComponent implements OnInit {
  @Input() langue: Langue = new Langue; 


  constructor(private langueService: LangueService, private langueComponent: LangueComponent) { }

  ngOnInit() {
    this.langueService.getAll();
  }

  updateLangue() {
    this.langueService.update(this.langue).subscribe(
      data => {
                // refresh the list
                this.langueComponent.getAll()
                alert('Modification avec succes');
                return true;
              },
      error => {
                console.error("Error saving langue!");
                return Observable.throw(error);
               }
    );
  }

}

It's my langue.component.ts

import { Langue } from "../langue";
import { LangueService } from '../langue.service';
import { Component, OnInit } from '@angular/core';
import { Observable } from "rxjs";

@Component({
  selector: 'app-langue',
  templateUrl: './langue.component.html',
  styleUrls: ['./langue.component.css']
})
export class LangueComponent implements OnInit {
  public langues;
  langue: Langue;
  constructor(private langueService: LangueService) { }

  ngOnInit() {
    this.getAll();
  }

  selectedLangue: Langue;
  modifedLangue: Langue
  getAll() {
    this.langueService.getAll().subscribe(
      data => { this.langues = data }, err => console.error(err), () => console.log('done loading langues'));
  }

  detail(langue: Langue){
    this.selectedLangue = langue;
  }

  modification(langue: Langue){
    this.modifedLangue = langue;
  }

  delete(langue) {

    if (confirm("Are you sure you want to delete " + this.langue.Id + "" + this.langue.cod + "?")) {
        this.langueService.delete(this.langue).subscribe(
          data => {
             // refresh the list
             this.getAll();
             return true;
          },
          error => {
           console.error("Error deleting langue!");
           return Observable.throw(error);
         }
      );
    }
  }
}

It's my lang.component.html

<app-new-langue></app-new-langue>
<kendo-grid [data]="langues" [height]="410">
            <kendo-grid-column field="Id" title="ID" width="40">
            </kendo-grid-column>
            <kendo-grid-column field="cod" title="Code" width="40">
            </kendo-grid-column>
            <kendo-grid-column field="des" title="Description" width="60">
            </kendo-grid-column>
            <kendo-grid-column field="cod1" title="code 1" width="80">
            </kendo-grid-column>
            <kendo-grid-column field="cod2" title="code 2" width="80">
            </kendo-grid-column>
            <kendo-grid-column field="dat1" title="date 1" width="80">
            </kendo-grid-column>
            <kendo-grid-column field="dat1" title="date 2" width="80">
            </kendo-grid-column>
            <kendo-grid-column title="Opération" width="120">
                <ng-template kendoGridCellTemplate column="column" let-dataItem let-columnIndex="columnIndex" >
                    <button (click)="modification(dataItem)">Modifier</button>
                    <button (click)="delete(dataItem)">Supprimer</button>
                    <button (click)="detailLangue(dataItem)">Consulter</button>
                </ng-template>
            </kendo-grid-column>
 </kendo-grid>
 <app-langue-details [langue]="selectedLangue"></app-langue-details>
 <app-update-langue [langue]="modifedLangue"></app-update-langue>

It's my It's my update-lang.component.html

<h2>Modification de la langue</h2>
<div *ngIf="langue">
<form>
<table>
  <!-- <tr>
      <td>Id</td><td><input name="id" [(ngModel)]="langue.langueId"/></td>
  </tr> -->
  <tr>
      <td>Code</td><td><input name="code" [(ngModel)]="langue.codlan"/></td>
  </tr>
  <tr>  
      <td>des</td><td><input name="des" [(ngModel)]="langue.deslan"/></td>
  </tr>
  <tr>    
      <td>Code1</td><td><input name="code1" [(ngModel)]="langue.codopercrehoro"/></td>
  </tr>
  <tr>    
      <td>Code2</td><td><input name="code2" [(ngModel)]="langue.codopermajhoro"/></td>
  </tr>
  <!--<tr>  
      <td>T1</td><td><input type="datetime-local" name="date1"  [(ngModel)]="langue.dattimcrehoro"/></td>
  </tr>
  <tr>
      <td>T2 </td><td><input type="datetime-local" name="date2" [(ngModel)]="langue.dattimmajhoro"/></td>
  </tr>-->
  <tr>
        <td></td><td><button (click)="updateLangue()">Enregistrer</button></td>
  </tr>
</table>
</form> 

</div>

It's my file configuration config.service.ts

import {Injectable} from '@angular/core';
import {Http, Headers, Response, RequestOptions} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

/**
 *  Service permettant de mettre en commun des fonctions utilisées dans toute l'application
 */

@Injectable()
export class AppSettingsService {
  settings: Observable<any>;
  currentUser: any;
  toasterTradMessage: string;

  constructor(
    private http: Http,
  ) {
    this.settings = this.http.get("../../assets/appsettings.json")
      .map(this.extractData)
      .catch(this.handleErrors);
  }

  /**
  * Fonction de recuperation du lien vers l'API contenu dans le json assets/appsettings.json
  * Retour : json avec lien vers API (settings.pathAPI)
  *
  */
  getSettings(): Observable<any> {
    return this.settings;
  }

  private extractData(res: Response) {
    let body = res.json();
    return body || {};
  }

  private handleErrors(error: any): Observable<any> {
    console.error(error);
    return Observable.throw(error.message || error);
  }
}

It's my entity lange.ts

export class Langue {
  Id: number;
  cod: string;
  des: string;
  cod1: string;
  cod2: string;
  dat1: null;
  dat2: null;
}

Please, Can you help me because it's important, it's the first time I'm having these problems, that's why I'm in trouble.

  • Refer this post https://stackoverflow.com/questions/46788969/angular2-spring-boot-allow-cross-origin-on-put/46789290#46789290 – hrdkisback Jun 03 '18 at 08:40

1 Answers1

0

Your request to a different domain(localhost in your case) then your page is on. So the browser is blocking it as it usually allows a request in the same origin for security reasons.

http://localhost:8081/APIRest/resources/langue/update: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 500.

If you closely look at the URL you will find that the port numbers for the same hosts are varying.

Update: Refer to the following link:

Why does my JavaScript get a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error when Postman does not?

Yati Sawhney
  • 1,372
  • 1
  • 12
  • 19
  • thank you very much for your answer. So I want to know, what solutions can I resolve this problem. what code lignes can I add in my program or can I proceed to configuration in or over project (as browser configuration or/and systeme security) – papaletunde Jun 05 '18 at 12:29
  • @papaletunde I have update my answer. Accept it if you find it usefull https://stackoverflow.com/help/someone-answers – Yati Sawhney Jun 05 '18 at 13:32