Making a relationship update using REST, Jax-rs, Jersey and Javascript

Asked

Viewed 165 times

1

Well, I took a basis to make a simple CRUD of just one table using REST and the others that I put in the question, everything worked perfectly, until I put more tables(classes) and relationship between them, after the addition of relationships I can still visualize the information and even delete, but I can’t do an update I tried several things and nothing, in one of my last attempts I tried to do something similar to what I did in java in a class I created to test my DAO’s , I would very much like to know the reasons for such a problem I would be very grateful for the help. Extra information, Service order has customer relationship, service and status already the customer has relationship with user and level.

Java code of the Main test class I created to test DAO Classes (JAVA):

//UPDATE ORDEM DE SERVICO.
        ServicoDAO sdao = new ServicoDAO();
        Servico serv = sdao.porId(2);

        UsuarioDAO udao = new UsuarioDAO();
        Usuario usu = udao.porId(4);

        NivelDAO niDAO = new NivelDAO();
        Nivel niv = niDAO.porId(2);

        ClienteDAO cliDAO = new ClienteDAO();
        Cliente cli = cliDAO.porId(3);
        cli.setNivel(niv);
        cli.setUsuario(usu);

        OrdemDeServicoDAO dao = new OrdemDeServicoDAO();
        OrdemDeServico ordem = new OrdemDeServico(2);
        ordem.setStatus(2);
        ordem.setCodServico(serv);
        ordem.setCodCliente(cli);

        dao.atualizar(ordem);
        System.out.println(" " + ordem.getStatus());

Resource code (Only what I found necessary to show)(JAVA):

@Path("/ordens")

public class OrdemDeServicoResource {
OrdemDeServicoDAO dao = new OrdemDeServicoDAO();

@PUT
@Path("{id}")
@Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
@Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
public OrdemDeServico atualizar(OrdemDeServico ordem)throws Exception{
    System.out.println("Atualização de ordem de servico:" +ordem.getStatus());
    dao.atualizar(ordem);
    return ordem;
}

@DELETE @Path("{id}")
@Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
public void remover(@PathParam("id")int id)throws Exception{
    OrdemDeServico ordem = dao.porId(id);
    dao.delete(ordem);

}

Codigo Javascript Ordemdetalhes:

var rootURL ="http://localhost:8080/TCC02/rest";

var rootcli = "http://localhost:8080/TCC02/rest/clientes/";

var rootser = "http://localhost:8080/TCC02/rest/servicos/";

var rootLogin ="http://localhost:8080/TCC02/rest/usuarios/"

listOrdem();

function listOrdem(){
    var id = getId();
    $("#orId").attr("data-value",id);
    if(id<1){
        alert('id invalido');
        return;
    }
    console.log('getOrdem ' +id);
    $.getJSON(rootURL + '/ordens/' + id, function(data){
        if(!data){
            alert('Ordem de servico não encontrada');
            return
        }
    var ordem = data;
    renderDetails(ordem);
    return ordem;       
    });
}

function porIdSer(id3){
    console.log('Ache o Servico pelo ID: ' +id3);
    $.getJSON(rootser + id3, function(data){
        if(!data){
            alert('Cliente não encontrado por id');
            return
        }
        var ser = data;
        renderDetailsSer(ser);
        return ser;
    });
}

function porIdLogin(id4){
    console.log('Ache o Usuario pelo ID: ' +id4);
    $.getJSON(rootLogin + id4, function(data){
        if(!data){
            alert('Usuario não encontrado pelo id');
            return
        }
        var usu = data;
        renderDetailsUsu(usu);
        return usu;
    });
}

function porIdNivel(id5){
    console.log('Ache o nivel pelo ID: ' + id5);
    $.getJSON(rootURL+ '/niveis/'+ id5,function(data){
        if(!data){
            alert('Id do nivel não compativel');
            return
        }
        var niv = data;
        renderDetailsNiv(niv);
        return niv;
    });
}

function porIdCli(id2){
    console.log('Ache Cliente Pelo iD:' + id2);
    $.getJSON(rootcli + id2, function(data){
        if(!data){
            alert('Cliente não encontrado por id');
            return
        }
        var cli = data;
        renderDetailsCli(cli);
        return cli;
    });
}

    $('#btnAtt').click(function(){
        $("#myModal").modal();
        console.log('Carregar Detalhes');
        var id = getId();
        if(id<1){
            alert ('id invalido');
            return;
        }
        console.log ('getOrdem' + id);
        $.getJSON(rootURL+'/ordens/' + id, function(data){
            if(!data){
                alert('Erro ao selecionar o id');
                return
            }
            var ordem = data;
            renderDetails1(ordem);
        });
    });

    $('#btnSave').click(function(){
        atualizarOrdem();
    });

    function atualizarOrdem(){
        var ident = $("#orId").attr("data-value");
        console.log('Atualizar Ordem de servico:' +ident);
        $.ajax({
            type:'PUT',
            contentType: 'application/json',
            url:rootURL + '/ordens/' + ident,
            dataType:"json",
            data:formToJSON(),
            success:function(data,textStatus,jqXHR){
                alert('Ordem de serviço atualizada com sucesso');   
            },
            error: function(jqXHR, textStatus, errorThrown){
                alert('Erro ao atualizar a ordem de servico ' + errorThrown);           
            }
        });
    }

    function deletarOrdem(){
        console.log('Deletar ordem de serviço');
        $.ajax({
            type:'DELETE',
            url:rootURL + '/' + $('#orId').val(),
            success: function(data, textStatus,jqXHR){
            alert('Ordem de serviço deletada'); 
            },
            error: function(jqXHR, textStatus, errorThrown){
                alert('Erro ao deletar ordem de serviço')
            }       
        });
    }
function getId(){
    //localiza e pega o id da url
    var id = window.location.hash.substr(1);
    //Confirmar se o ID é um int
    var intRegex = /^\d+$/;
    return intRegex.test(id)? id : -1;
}
// Pega os dados em JSON e arruma eles na minha form.
function renderDetails(ordem){
    $('#orId').val(ordem.id);
    $('#nomecliente').val(ordem.codCliente.nome);
    $('#servico').val(ordem.codServico.nomeservico);
    $('#codserv').val(ordem.codServico.id);
    $('#codcli').val(ordem.codCliente.id);
    $('#status').append('<option>' + ordem.status + '</option>');   
    //Definindo valores para campos codservico e codcliente de acordo com seu relacionamento com OrdemServico.
    var atributo2 = ordem.codServico.id;
    $("#codserv").attr("data-value",atributo2);
    var atributo = ordem.codCliente.nivel.id
    $("#codcli").attr("data-value",atributo);   
    porIdCli(atributo);
    porIdSer(atributo2);
}

function formToJSON(){
    var orId = $('#orId1').val();
    return JSON.stringify({
        "id": orId == "" ? null : orId,
        "status": $('#status1').val(),
        "servico": $('#servico1').data(),
        "nomecliente":$('#nomecliente1').data(),        
    });
}
  • In the code that updates the order, in the line dao.update(order); , instead of having it updated straight, try to locate this order before and then have it updated. I’ve had problems with JPA that I solved like this, first finding the object and having it updated by the found object. Maybe if you do that it will solve. Try it out there.

  • Thanks for the help, what happens is that I do just that on the client side in my job update() in javascript I select the Ordemdeservico specified by its Id, as I commented I can do the update with my main class in java, but I can not do the client-side update that is my problem.

  • So, I’m still stuck at this part and I haven’t found any solution yet, can anyone find any light for this problem?

  • When you run your javascript function updateOrdem() the return shows your Success Alert or the error one? If it is the error, what error appears? If it is the Success, what would you like to see happen more? Java return is in the date variable.

  • Shows the error, but appears only the message without much information as an error code for example 500, in case I saw in the log which URL was being passed and this was being passed when I ran the function: localhost:8080/TCC02/Gerentearea/servico/ordemDetails.html? orId1=2&servico1=%5Bobject+Object%5D&cliente1=%5Bobject+Object%5D&status1=1#2 In this case I just want to update the Status in this case was 1 and I tried to change to 2.

  • If possible, I would like to create something like my java test class but in javascript I tried everything I could think of but nothing worked probably because I need to use these URL’s.

  • In the Jquery ajax documentation the following is written: error - Type: Function( jqXHR jqXHR, String textStatus, String errorThrown ) A Function to be called if the request fails. The Function receives three Arguments: The jqXHR (in jQuery 1.4.x, Xmlhttprequest) Object, a string describing the type of error that occurred and an optional Exception Object, if one occurred. Possible values for the Second argument (Besides null) are "timeout", "error", "abort", and "parsererror". (continue)

  • (continuation) When an HTTP error occurs, errorThrown receives the textual Portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error Setting can Accept an array of functions. Each Function will be called in turn. Note: This Handler is not called for cross-Domain script and cross-Domain JSONP requests. This is an Ajax Event. Source: http://api.jquery.com/jquery.ajax/

  • This for me means that the page being called with Ajax is returning error 500 (Internal Server Error). Try to see if when being processed without being by ajax request(if you can access the page directly, or create a test passing the same data that ajax goes through but not by ajax) if the page tb will give this error and if given, it will be easier to debug without going through ajax. For me your ajax is normal and has to see why Java is giving error. Check if you are passing the parameters via ajax correctly tb later.

  • I understand would be really better to see the mistakes but could give me an example of what I could use instead of ajax? .

  • Another thing, I was seeing here that the URL I sent was kind of wrong fixing I got this URL where it makes more practical sense for the application now when I click update this link that appears; localhost:8080/TCC02/Gerentearea/servico/ordemDetails.html? servico=%5Bobject+Object%5D&codserv=2&nomecliente=%5Bobject+Object%5D&status=2 , I don’t know if it helps but when I directly execute an error message regarding the ID error in the INVALID ID case, I was searching here for what could be a problem regarding the lack of use of sub-Sources?

  • Does that make sense? In this case I want to update the status of the service order, so I need to select the service related to the order, then select the client that requested the service, the client has access user so I need to point to the reference id and the client has access level. In my head would be something like this: PUT localhost:8080/TCC02/Rest/orders/{Order ID}/service/{Service ID}/client/{Client ID}/status =2; Does that make any sense? If you do how I could apply this, remembering that I can make updates in classes without relationship for example the service class

Show 7 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.