Example usage for com.google.gson JsonObject toString

List of usage examples for com.google.gson JsonObject toString

Introduction

In this page you can find the example usage for com.google.gson JsonObject toString.

Prototype

@Override
public String toString() 

Source Link

Document

Returns a String representation of this element.

Usage

From source file:co.cask.cdap.internal.AppFabricClient.java

License:Apache License

public void setServiceInstances(String namespaceId, String applicationId, String serviceName, int instances)
        throws Exception {
    MockResponder responder = new MockResponder();
    String uri = String.format("%s/apps/%s/services/%s/instances", getNamespacePath(namespaceId), applicationId,
            serviceName);/*from   w w w.  j av a2  s  . com*/
    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PUT, uri);
    JsonObject json = new JsonObject();
    json.addProperty("instances", instances);
    request.setContent(ChannelBuffers.wrappedBuffer(json.toString().getBytes()));
    programLifecycleHttpHandler.setServiceInstances(request, responder, namespaceId, applicationId,
            serviceName);
    verifyResponse(HttpResponseStatus.OK, responder.getStatus(), "Set service instances failed");
}

From source file:co.cask.cdap.internal.AppFabricClient.java

License:Apache License

public void setFlowletInstances(String namespaceId, String applicationId, String flowId, String flowletName,
        int instances) throws Exception {
    MockResponder responder = new MockResponder();
    String uri = String.format("%s/apps/%s/flows/%s/flowlets/%s/instances/%s", getNamespacePath(namespaceId),
            applicationId, flowId, flowletName, instances);
    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PUT, uri);
    JsonObject json = new JsonObject();
    json.addProperty("instances", instances);
    request.setContent(ChannelBuffers.wrappedBuffer(json.toString().getBytes()));
    programLifecycleHttpHandler.setFlowletInstances(request, responder, namespaceId, applicationId, flowId,
            flowletName);/*from   w w w . j ava2s.c  o m*/
    verifyResponse(HttpResponseStatus.OK, responder.getStatus(), "Set flowlet instances failed");
}

From source file:co.cask.cdap.security.server.GrantAccessToken.java

License:Apache License

private void grantToken(HttpServletRequest request, HttpServletResponse response, long tokenValidity)
        throws IOException, ServletException {

    String username = request.getUserPrincipal().getName();
    List<String> userGroups = Collections.emptyList();

    long issueTime = System.currentTimeMillis();
    long expireTime = issueTime + tokenValidity;
    // Create and sign a new AccessTokenIdentifier to generate the AccessToken.
    AccessTokenIdentifier tokenIdentifier = new AccessTokenIdentifier(username, userGroups, issueTime,
            expireTime);/*  w w  w  .j  a  v  a 2  s  .  c  o  m*/
    AccessToken token = tokenManager.signIdentifier(tokenIdentifier);
    LOG.debug("Issued token for user {}", username);

    // Set response headers
    response.setContentType("application/json;charset=UTF-8");
    response.addHeader(HttpHeaders.Names.CACHE_CONTROL, "no-store");
    response.addHeader(HttpHeaders.Names.PRAGMA, "no-cache");

    // Set response body
    JsonObject json = new JsonObject();
    byte[] encodedIdentifier = Base64.encodeBase64(tokenCodec.encode(token));
    json.addProperty(ExternalAuthenticationServer.ResponseFields.ACCESS_TOKEN,
            new String(encodedIdentifier, Charsets.UTF_8));
    json.addProperty(ExternalAuthenticationServer.ResponseFields.TOKEN_TYPE,
            ExternalAuthenticationServer.ResponseFields.TOKEN_TYPE_BODY);
    json.addProperty(ExternalAuthenticationServer.ResponseFields.EXPIRES_IN,
            TimeUnit.SECONDS.convert(tokenValidity, TimeUnit.MILLISECONDS));

    response.getOutputStream().print(json.toString());
    response.setStatus(HttpServletResponse.SC_OK);
}

From source file:co.cask.cdap.test.internal.AppFabricClient.java

License:Apache License

public void setRunnableInstances(String applicationId, String serviceName, String runnableName, int instances) {
    MockResponder responder = new MockResponder();
    String uri = String.format("/v2/apps/%s/services/%s/runnables/%s/instances", applicationId, serviceName,
            runnableName);/*from  w  w w.  ja  va 2 s . com*/
    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PUT, uri);
    JsonObject json = new JsonObject();
    json.addProperty("instances", instances);
    request.setContent(ChannelBuffers.wrappedBuffer(json.toString().getBytes()));
    serviceHttpHandler.setInstances(request, responder, applicationId, serviceName, runnableName);
    Preconditions.checkArgument(responder.getStatus().getCode() == 200, "set runnable instances failed");
}

From source file:co.cask.cdap.test.internal.AppFabricClient.java

License:Apache License

public void setFlowletInstances(String applicationId, String flowId, String flowletName, int instances) {

    MockResponder responder = new MockResponder();
    String uri = String.format("/v2/apps/%s/flows/%s/flowlets/%s/instances/%s", applicationId, flowId,
            flowletName, instances);//from  w ww  . j av a2 s . c o m
    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PUT, uri);
    JsonObject json = new JsonObject();
    json.addProperty("instances", instances);
    request.setContent(ChannelBuffers.wrappedBuffer(json.toString().getBytes()));
    httpHandler.setFlowletInstances(request, responder, applicationId, flowId, flowletName);
    Preconditions.checkArgument(responder.getStatus().getCode() == 200, "set flowlet instances failed");
}

From source file:co.cask.common.security.server.GrantAccessToken.java

License:Apache License

private void grantToken(HttpServletRequest request, HttpServletResponse response, long tokenValidity)
        throws IOException, ServletException {

    String username = request.getUserPrincipal().getName();
    List<String> userGroups = Collections.emptyList();

    long issueTime = System.currentTimeMillis();
    long expireTime = issueTime + tokenValidity;
    // Create and sign a new AccessTokenIdentifier to generate the AccessToken.
    AccessTokenIdentifier tokenIdentifier = new AccessTokenIdentifier(username, userGroups, issueTime,
            expireTime);//  w  w w  .  j  av a  2 s.  c om
    AccessToken token = tokenManager.signIdentifier(tokenIdentifier);
    LOG.debug("Issued token for user {}", username);

    // Set response headers
    response.setContentType("application/json;charset=UTF-8");
    response.addHeader("Cache-Control", "no-store");
    response.addHeader("Pragma", "no-cache");

    // Set response body
    JsonObject json = new JsonObject();
    byte[] encodedIdentifier = Base64.encodeBase64(tokenCodec.encode(token));
    json.addProperty(ExternalAuthenticationServer.ResponseFields.ACCESS_TOKEN,
            new String(encodedIdentifier, Charsets.UTF_8));
    json.addProperty(ExternalAuthenticationServer.ResponseFields.TOKEN_TYPE,
            ExternalAuthenticationServer.ResponseFields.TOKEN_TYPE_BODY);
    json.addProperty(ExternalAuthenticationServer.ResponseFields.EXPIRES_IN,
            TimeUnit.SECONDS.convert(tokenValidity, TimeUnit.MILLISECONDS));

    response.getOutputStream().print(json.toString());
    response.setStatus(HttpServletResponse.SC_OK);
}

From source file:co.com.konrad.interbolsa.ws.CompraAccionesFacadeREST.java

@POST
@Override/*from  ww  w .  j av  a2 s.co m*/
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public String create(CompraAcciones entity) throws Exception {
    //VAriable json
    JsonObject res = new JsonObject();
    try {
        //retorno
        res.addProperty("codigo", 200);
        res.addProperty("mensaje", "operacion exitosa");
        super.create(entity);
    } catch (Throwable ex) {
        java.util.logging.Logger.getLogger(AbstractFacade.class.getName()).log(Level.SEVERE,
                "Erro guardando entidad", ex);
        res.addProperty("codigo", 400);
        res.addProperty("mensaje", "operacion fallida");
    }
    return res.toString();
}

From source file:co.com.konrad.interbolsa.ws.EmpresaFacadeREST.java

@POST
@Override//from ww w .j  av  a2 s  .c  om
@Path("create")
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public String create(Empresa entity) throws Exception {
    //VAriable json
    JsonObject res = new JsonObject();
    Gson gson = new Gson();
    try {
        super.create(entity);
        //retorno
        res.addProperty("codigo", 200);
        res.addProperty("mensaje", "operacion exitosa");

        javax.persistence.criteria.CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
        javax.persistence.criteria.CriteriaQuery cq = cb.createQuery();
        javax.persistence.criteria.Root<Empresa> rt = cq.from(Empresa.class);
        cq.where(cb.equal(rt.get(Empresa_.empresaNit), entity.getEmpresaNit()));
        javax.persistence.TypedQuery<Empresa> q = getEntityManager().createQuery(cq);
        Empresa empresa = q.getSingleResult();
        res.add("data", gson.toJsonTree(empresa));

    } catch (Throwable ex) {
        java.util.logging.Logger.getLogger(AbstractFacade.class.getName()).log(Level.SEVERE,
                "Error guardando entidad", ex);
        res.addProperty("codigo", 400);
        res.addProperty("mensaje", "operacion fallida");
    }
    return res.toString();
}

From source file:co.com.konrad.interbolsa.ws.UsuarioFacadeREST.java

@POST
@Override//from   w  ww  .  j  a v  a  2 s  . c o m
@Path("create")
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public String create(Usuario entity) throws Exception {
    JsonObject res = new JsonObject();
    Gson gson = new Gson();
    try {
        super.create(entity);
        //retorno
        res.addProperty("codigo", 200);
        res.addProperty("mensaje", "operacion exitosa");

        javax.persistence.criteria.CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
        javax.persistence.criteria.CriteriaQuery cq = cb.createQuery();
        javax.persistence.criteria.Root<Usuario> rt = cq.from(Usuario.class);
        cq.where(cb.equal(rt.get(Usuario_.usuarioCedula), entity.getUsuarioCedula()));
        javax.persistence.TypedQuery<Usuario> q = getEntityManager().createQuery(cq);
        Usuario usuario = q.getSingleResult();
        res.add("data", gson.toJsonTree(usuario));
    } catch (Throwable ex) {
        java.util.logging.Logger.getLogger(AbstractFacade.class.getName()).log(Level.SEVERE,
                "Erro guardando entidad", ex);
        res.addProperty("codigo", 400);
        res.addProperty("mensaje", "operacion fallida");
    }
    return res.toString();
}

From source file:co.com.konrad.interbolsa.ws.UsuarioFacadeREST.java

@POST
@Path("login")
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public String login(Usuario entity) {
    JsonObject res = new JsonObject();
    Gson gson = new Gson();
    System.out.println("Correo " + entity.getUsuarioCorreo());
    System.out.println("Clave " + entity.getUsuairoClave());
    try {//from w w  w . java 2s.c  o  m
        //retorno
        res.addProperty("codigo", 200);
        res.addProperty("mensaje", "operacion exitosa");
        /*
        javax.persistence.criteria.CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
        javax.persistence.criteria.CriteriaQuery cq = cb.createQuery();
        javax.persistence.criteria.Root<Usuario> rt = cq.from(Usuario.class);
        cq.where(
            cb.equal(rt.get(Usuario_.usuarioCorreo), entity.getUsuarioCorreo()),
            cb.equal(rt.get(Usuario_.usuairoClave), entity.getUsuairoClave())
        );
        javax.persistence.TypedQuery<Usuario> q = getEntityManager().createQuery(cq);
        Usuario usuario = q.getSingleResult();*/
        //res.add("data", gson.toJsonTree(usuario));

        String nativeQuery = " SELECT * FROM usuario INNER JOIN empresa ON empresa_id = empresa_empresa_id WHERE usuario_correo = ? AND usuairo_clave = ?";
        Query query = getEntityManager().createNativeQuery(nativeQuery);
        query.setParameter(1, entity.getUsuarioCorreo());
        query.setParameter(2, entity.getUsuairoClave());
        Object usuario = query.getSingleResult();
        res.add("data", gson.toJsonTree(usuario));
    } catch (Exception ex) {
        java.util.logging.Logger.getLogger(AbstractFacade.class.getName()).log(Level.SEVERE,
                "Erro guardando entidad", ex);
        res.addProperty("codigo", 300);
        res.addProperty("mensaje", "Error de autenticacin");
    }
    return res.toString();
}