Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- @author Rafamod
- */
- package com.tecnology.ddsolutions;
- //Import JAX-WS Web Services lib.
- import javax.ws.rs.GET;
- import javax.ws.rs.POST;
- import javax.ws.rs.Consumes;
- import javax.ws.rs.Path;
- import javax.ws.rs.Produces;
- import javax.ws.rs.core.Context;
- import javax.ws.rs.core.Response;
- import javax.servlet.http.HttpServletRequest;
- //Import JSON Utilities.
- import com.google.gson.Gson;
- import com.google.gson.GsonBuilder;
- import org.json.JSONObject;
- //Import Other clases.
- import com.tecnology.ddsolutions.Models;
- //Import Java Utils.
- import java.util.ArrayList;
- //Import DB.
- import java.sql.*;
- @Path("/Articulos")
- public class Articulos {
- @GET
- @POST
- @Produces("application/json")
- @Consumes("application/json")
- public Response articulos(@Context HttpServletRequest request, Models.ApiRequest.Articulos model) throws Exception{
- //Create Json Object.
- JSONObject jsonObject = new JSONObject();
- Connection conn = null;
- //If theres an error, catch it on the Exception.
- try{
- //Get the drivers for the connection DB. Then the URL to connect.
- Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
- String url = "jdbc:sqlserver://localhost:1433;"+"databaseName=TGoma;user=sa;password=raddil12";
- conn = DriverManager.getConnection(url);
- Statement stmt = conn.createStatement();
- ResultSet rs;
- //SQL Query. This is where the code is to get into the DB.
- String SQL = "USE TGoma SELECT art_name, art_stock FROM Articulos WHERE art_name LIKE '"+model.search +"'";
- rs = stmt.executeQuery(SQL);
- //Arrays of Items.
- ArrayList<Models.Db.Articulo> articulos = new ArrayList<Models.Db.Articulo>();
- while (rs.next()) {
- Models.Db.Articulo articulo = new Models.Db.Articulo();
- articulo.name = rs.getString("art_name");
- articulo.stock = rs.getString("art_stock");
- articulos.add(articulo);
- }
- Gson gson = new GsonBuilder().create();
- return Response.status(200).entity(gson.toJson(articulos)).build();
- }
- catch (Exception e){
- //Pass the error.
- jsonObject.put("Got an Exception!",e);
- String result = jsonObject +"\n\n";
- return Response.status(422).entity(result).build();
- }
- //Close connection DB.
- finally{
- if(conn!=null)
- conn.close();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement