Example usage for java.sql ResultSet getTime

List of usage examples for java.sql ResultSet getTime

Introduction

In this page you can find the example usage for java.sql ResultSet getTime.

Prototype

java.sql.Time getTime(String columnLabel) throws SQLException;

Source Link

Document

Retrieves the value of the designated column in the current row of this ResultSet object as a java.sql.Time object in the Java programming language.

Usage

From source file:info.naiv.lab.java.tool.sqlite.exporter.component.ValueHandlerImpl.java

/**
 *
 * @param field/*  ww w  . ja  v a2s .c o m*/
 * @param rowSet
 * @return
 * @throws SQLException
 */
@Override
public Object handleValue(Field field, ResultSet rowSet) throws SQLException {
    String name = field.getOriginalName();
    switch (field.getTypeInfo()) {
    case CHAR:
    case NCHAR:
        return StringUtils.trimTrailingWhitespace(rowSet.getString(name));
    case DATE:
        return Objects.toString(rowSet.getDate(name), null);
    case TIME:
        return Objects.toString(rowSet.getTime(name), null);
    case TIMESTAMP:
        return Objects.toString(rowSet.getTimestamp(name), null);
    default:
        return rowSet.getObject(name);
    }
}

From source file:dao.DatasetWithUserRowMapper.java

@Override
public Dataset mapRow(ResultSet rs, int rowNum) throws SQLException {
    int id = rs.getInt(DATASET_ID_COLUMN);
    String name = rs.getString(DATASET_NAME_COLUMN);
    String urn = rs.getString(DATASET_URN_COLUMN);
    String source = rs.getString(DATASET_SOURCE_COLUMN);
    String schema = rs.getString(DATASET_SCHEMA_COLUMN);
    Time created = rs.getTime(DATASET_CREATED_TIME_COLUMN);
    Time modified = rs.getTime(DATASET_MODIFIED_TIME_COLUMN);
    Integer favoriteId = rs.getInt(FAVORITE_DATASET_ID_COLUMN);
    Integer schemaHistoryId = rs.getInt(SCHEMA_HISTORY_ID_COLUMN);
    Long watchId = rs.getLong(DATASET_WATCH_ID_COLUMN);
    Long sourceModifiedTime = rs.getLong(DATASET_SOURCE_MODIFIED_TIME_COLUMN);
    String strOwner = rs.getString(DATASET_OWNER_ID_COLUMN);
    String strOwnerName = rs.getString(DATASET_OWNER_NAME_COLUMN);
    Dataset dataset = new Dataset();
    dataset.id = id;/*from  w  w  w.  j  a v a2 s  .c  om*/
    dataset.name = name;
    dataset.urn = urn;
    dataset.schema = schema;
    String[] owners = null;
    if (StringUtils.isNotBlank(strOwner)) {
        owners = strOwner.split(",");
    }
    String[] ownerNames = null;
    if (StringUtils.isNotBlank(strOwnerName)) {
        ownerNames = strOwnerName.split(",");
    }
    dataset.owners = new ArrayList<User>();
    if (owners != null && ownerNames != null) {
        if (owners.length == ownerNames.length) {
            for (int i = 0; i < owners.length; i++) {
                User user = new User();
                user.userName = owners[i];
                if (StringUtils.isBlank(ownerNames[i]) || ownerNames[i].equalsIgnoreCase("*")) {
                    user.name = owners[i];
                } else {
                    user.name = ownerNames[i];
                    dataset.owners.add(user);
                }
            }
        } else {
            Logger.error("DatasetWithUserRowMapper get wrong owner and names. Dataset ID: "
                    + Long.toString(dataset.id) + " Owner: " + owners + " Owner names: " + ownerNames);
        }
    }
    if (StringUtils.isNotBlank(dataset.urn)) {
        if (dataset.urn.substring(0, 4).equalsIgnoreCase(HDFS_PREFIX)) {
            dataset.hdfsBrowserLink = Play.application().configuration()
                    .getString(DatasetsDAO.HDFS_BROWSER_URL_KEY)
                    + dataset.urn.substring(DatasetRowMapper.HDFS_URN_PREFIX_LEN);
        }
    }
    dataset.source = source;
    if (modified != null && sourceModifiedTime != null && sourceModifiedTime > 0) {
        dataset.modified = new java.util.Date(modified.getTime());
        dataset.formatedModified = dataset.modified.toString();
    }
    if (created != null) {
        dataset.created = new java.util.Date(created.getTime());
    } else if (modified != null) {
        dataset.created = new java.util.Date(modified.getTime());
    }
    if (favoriteId != null && favoriteId > 0) {
        dataset.isFavorite = true;
    } else {
        dataset.isFavorite = false;
    }
    if (watchId != null && watchId > 0) {
        dataset.watchId = watchId;
        dataset.isWatched = true;
    } else {
        dataset.watchId = 0L;
        dataset.isWatched = false;
    }

    if (schemaHistoryId != null && schemaHistoryId > 0) {
        dataset.hasSchemaHistory = true;
    } else {
        dataset.hasSchemaHistory = false;
    }

    return dataset;
}

From source file:org.ojbc.adapters.analyticaldatastore.dao.IncidentRowMapper.java

@Override
public Incident mapRow(ResultSet rs, int rowNum) throws SQLException {
    Incident incident = new Incident();

    incident.setIncidentCaseNumber(rs.getString("IncidentCaseNumber"));
    incident.setIncidentDate(rs.getDate("IncidentDate"));
    incident.setIncidentID(rs.getInt("IncidentID"));
    incident.setIncidentLocationStreetAddress(rs.getString("IncidentLocationStreetAddress"));
    incident.setIncidentLocationTown(rs.getString("IncidentLocationTown"));
    incident.setIncidentTime(rs.getTime("IncidentTime"));
    incident.setReportingAgencyID(rs.getInt("ReportingAgencyID"));
    incident.setIncidentLocationLatitude(rs.getBigDecimal("IncidentLocationLatitude"));
    incident.setIncidentLocationLongitude(rs.getBigDecimal("IncidentLocationLongitude"));
    incident.setReportingSystem(rs.getString("ReportingSystem"));

    String recordType = rs.getString("RecordType");

    if (StringUtils.isNotBlank(recordType)) {
        incident.setRecordType(recordType.charAt(0));
    }/*from   ww  w. j a  va 2  s.com*/

    return incident;
}

From source file:org.castor.cpa.test.test203.TestTimezone.java

public void testTime() throws Exception {
    Database db = getJDOManager(DBNAME, MAPPING).getDatabase();

    LOG.debug("user.timezone = " + System.getProperty("user.timezone"));

    AbstractProperties properties = CPAProperties.newInstance();
    String testTimezone = properties.getString(CPAProperties.DEFAULT_TIMEZONE, "CET");
    LOG.debug(CPAProperties.DEFAULT_TIMEZONE + " = " + testTimezone);

    /*/*w  w w .  ja va  2s . c o m*/
     * Create a date object
     */
    String dateString = "1968-09-22 00:00:00 " + testTimezone;
    Date date = null;
    try {
        date = DF.parse(dateString);
    } catch (ParseException e) {
        LOG.error("ParseException thrown", e);
        fail("Unable to parse " + dateString);
    }
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    cal.set(1970, 0, 1);
    date = cal.getTime();
    LOG.debug("Original = " + DF.format(date) + "[" + date.getTime() + "]");

    /*
     * Remove old entities from the database
     */
    LOG.debug("Remove old entities");
    db.begin();
    String sqldel = "DELETE FROM " + TABLE_NAME;
    Connection connectiondel = db.getJdbcConnection();
    Statement statementdel = connectiondel.createStatement();
    statementdel.execute(sqldel);
    db.commit();

    /*
     * Insert new entity into the database
     */
    LOG.debug("Insert new entity");
    db.begin();
    TimezoneEntity insertEntity = new TimezoneEntity();
    insertEntity.setId(new Integer(100));
    insertEntity.setName("entity 100");
    insertEntity.setStartDate(null);
    insertEntity.setStartTime(date);
    insertEntity.setStartTimestamp(null);
    db.create(insertEntity);
    db.commit();

    Integer id = insertEntity.getId();

    /*
     * Clear the cache to ensure we aren't reading cached data
     */
    LOG.debug("Clearing Castor's cache");
    db.begin();
    db.getCacheManager().expireCache();
    db.commit();

    /*
     * Fetch the object again
     */
    LOG.debug("Fetch entity with id = " + id + " with Castor");
    db.begin();
    Object fetchEntity = db.load(TimezoneEntity.class, id);
    Date castorDate = ((TimezoneEntity) fetchEntity).getStartTime();
    LOG.debug("Castor = " + DF.format(castorDate) + "[" + castorDate.getTime() + "]");
    db.commit();

    assertEquals("Castor date differs from original one!", date, castorDate);

    /*
     * Fetch using straight SQL and compare the result with our original date
     */
    LOG.debug("Fetch entity with id = " + id + " with straight SQL");
    Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone(testTimezone));
    String sql = "SELECT start_time FROM " + TABLE_NAME + " WHERE id = " + id;
    try {
        db.begin();
        Connection connection = db.getJdbcConnection();
        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery(sql);
        resultSet.next();
        Date localDate = resultSet.getTime(1);
        LOG.debug("SQL without Calendar " + DF.format(localDate) + " [" + localDate.getTime() + "]");
        Date utcDate = resultSet.getTime(1, calendar);
        LOG.debug("SQL with " + testTimezone + " Calendar " + DF.format(utcDate) + " [" + utcDate.getTime()
                + "]");
        db.commit();

        assertEquals("SQL date differs from original one!", date, utcDate);
    } catch (PersistenceException e) {
        LOG.error("PersistenceException thrown", e);
        fail();
    } catch (SQLException e) {
        LOG.error("SQLException thrown", e);
        fail();
    }

    db.close();
}

From source file:dao.DatasetRowMapper.java

@Override
public Dataset mapRow(ResultSet rs, int rowNum) throws SQLException {
    int id = rs.getInt(DATASET_ID_COLUMN);
    String name = rs.getString(DATASET_NAME_COLUMN);
    String urn = rs.getString(DATASET_URN_COLUMN);
    String source = rs.getString(DATASET_SOURCE_COLUMN);
    String strOwner = rs.getString(DATASET_OWNER_ID_COLUMN);
    String strOwnerName = rs.getString(DATASET_OWNER_NAME_COLUMN);
    String schema = rs.getString(DATASET_SCHEMA_COLUMN);
    Time created = rs.getTime(DATASET_CREATED_TIME_COLUMN);
    Time modified = rs.getTime(DATASET_MODIFIED_TIME_COLUMN);
    Integer schemaHistoryId = rs.getInt(SCHEMA_HISTORY_ID_COLUMN);
    Long sourceModifiedTime = rs.getLong(DATASET_SOURCE_MODIFIED_TIME_COLUMN);
    Dataset dataset = new Dataset();
    dataset.id = id;/*from   ww  w  .  j av a 2  s.  c o  m*/
    dataset.name = name;
    dataset.urn = urn;
    dataset.schema = schema;
    String[] owners = null;
    if (StringUtils.isNotBlank(strOwner)) {
        owners = strOwner.split(",");
    }
    String[] ownerNames = null;
    if (StringUtils.isNotBlank(strOwnerName)) {
        ownerNames = strOwnerName.split(",");
    }
    dataset.owners = new ArrayList<User>();
    if (owners != null && ownerNames != null) {
        if (owners.length == ownerNames.length) {
            for (int i = 0; i < owners.length; i++) {
                User user = new User();
                user.userName = owners[i];
                if (StringUtils.isBlank(ownerNames[i]) || ownerNames[i].equalsIgnoreCase("*")) {
                    user.name = owners[i];
                } else {
                    user.name = ownerNames[i];
                    dataset.owners.add(user);
                }
            }
        } else {
            Logger.error("DatasetWithUserRowMapper get wrong owner and names. Dataset ID: "
                    + Long.toString(dataset.id) + " Owner: " + owners + " Owner names: " + ownerNames);
        }
    }

    if (StringUtils.isNotBlank(dataset.urn)) {
        if (dataset.urn.substring(0, 4).equalsIgnoreCase(HDFS_PREFIX)) {
            dataset.hdfsBrowserLink = Play.application().configuration()
                    .getString(DatasetsDAO.HDFS_BROWSER_URL_KEY) + dataset.urn.substring(HDFS_URN_PREFIX_LEN);
        }
    }
    dataset.source = source;
    if (modified != null && sourceModifiedTime != null && sourceModifiedTime > 0) {
        dataset.modified = new java.util.Date(modified.getTime());
        dataset.formatedModified = dataset.modified.toString();
    }
    if (created != null) {
        dataset.created = new java.util.Date(created.getTime());
    } else if (modified != null) {
        dataset.created = new java.util.Date(modified.getTime());
    }

    if (schemaHistoryId != null && schemaHistoryId > 0) {
        dataset.hasSchemaHistory = true;
    } else {
        dataset.hasSchemaHistory = false;
    }

    return dataset;
}

From source file:org.apache.torque.generated.peer.DefaultValuesFromDatabaseTest.java

private Date doSelect(String toSelect, Class<?> classToSelect) throws Exception {
    String sql;/* w w  w .j ava  2s.co  m*/
    if (defaultAdapter instanceof OracleAdapter) {
        sql = "select " + toSelect + " from dual";
    } else if (defaultAdapter instanceof DerbyAdapter) {
        sql = "values(" + toSelect + ")";
    } else if (defaultAdapter instanceof HsqldbAdapter) {
        sql = "call " + toSelect;
    } else if (defaultAdapter instanceof MssqlAdapter) {
        sql = "select convert(datetime," + toSelect + ")";
    } else {
        sql = "select " + toSelect;
    }
    Connection connection = null;
    try {
        connection = Torque.getConnection();
        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery(sql);
        if (!resultSet.next()) {
            fail("Statement " + sql + " returned 0 rows");
        }
        Date result;
        if (Time.class == classToSelect) {
            result = resultSet.getTime(1);
        } else if (java.sql.Date.class == classToSelect) {
            result = resultSet.getDate(1);
        } else if (Timestamp.class == classToSelect) {
            result = resultSet.getTimestamp(1);
        } else {
            throw new IllegalArgumentException("unknown classToSelect " + classToSelect.getName());
        }
        if (resultSet.next()) {
            fail("Statement " + sql + " returned more than 1 row");
        }
        return result;
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception e) {
                // ignore
            }
        }
    }
}

From source file:YourProductModel.YourProductWS.java

/**
 * Web service operation//from   www.j  a v  a2 s .  co  m
 */
@WebMethod(operationName = "getProduct")
public ArrayList<String> getProduct(@WebParam(name = "access_token") String access_token)
        throws IOException, ParseException {
    int status = 0;
    ArrayList<String> answers = new ArrayList<String>();
    answers.add("");
    Connection dbConn = DbConnectionManager.getConnection();
    String targetIS = "ValidateToken";
    String urlParameters = "access_token=" + access_token;
    HttpURLConnection urlConn = UrlConnectionManager.doReqPost(targetIS, urlParameters);
    String resp = UrlConnectionManager.getResponse(urlConn);
    JSONParser parser = new JSONParser();
    JSONObject obj = (JSONObject) parser.parse(resp);
    String statusResp = (String) obj.get("status");
    String username = (String) obj.get("username");
    String user_id = (String) obj.get("user_id");
    switch (statusResp) {
    case "valid":
        if (hasProduct(username)) {
            try {
                String query = "SELECT * FROM catalogue WHERE username='" + username
                        + "' ORDER BY product_id DESC";

                Statement ps = dbConn.createStatement();
                ResultSet rs = ps.executeQuery(query);
                while (rs.next()) {
                    String productname = rs.getString("productname");
                    int product_id = rs.getInt("product_id");
                    int price = rs.getInt("price");
                    String productdesc = rs.getString("productdesc");
                    Date dateAddedF = rs.getDate("dateadded");
                    SimpleDateFormat simpledatafo = new SimpleDateFormat("dd/MM/yyyy");
                    Time timeAddedF = rs.getTime("timeadded");
                    SimpleDateFormat simpletimefo = new SimpleDateFormat("dd/MM/yyyy");
                    String dateadded = rs.getString("dateadded");
                    String timeadded = rs.getString("timeadded");
                    String qLike = "SELECT * from likes WHERE product_id='" + product_id + "'";
                    Statement psLike = dbConn.createStatement();
                    ResultSet rsLike = psLike.executeQuery(qLike);
                    int count = 0;
                    while (rsLike.next()) {
                        count++;
                    }
                    int likes = count;
                    int purchases = rs.getInt("purchases");
                    String imagepath = rs.getString("imagepath");

                    String answer = "<li>" + "<span id='date'>" + "<b>" + dateadded + "</b> " + "<br/>" + "at "
                            + timeadded + "<hr></hr>" + "</span>" + "<div class='item-list-product'>"
                            + "<div style='position:absolute'>" + "<a href='" + imagepath
                            + "'><img class='img-item' src='" + imagepath + "'></img></a>" + "</div>"
                            + "<div id='product-info'>" + "<span><b>" + productname + "</b></span> <br/>"
                            + "<span>IDR " + price + "</span> <br/>"
                            + "<span style='font-size:12px;position:relative'>" + productdesc + "</span>"
                            + "</div>" + "<div id='eddel'>" + "<br/>" + "<span style='font-size:14px'>" + likes
                            + " likes</span> <br/>" + "<span style='font-size:14px'>" + purchases
                            + " purchase</span> <br/>" + "<br/>"
                            + "<span><a id='edit' href='edit_product.jsp?product_id=" + product_id
                            + "'><b> EDIT  </b></a> </span>"
                            + "<span style='margin-left:5px'><a  id='delete' href='del_db?product_id="
                            + product_id + "'><b>DELETE </b></a> </span>" + "</div>" + "</div>" + "</li>"
                            + "<br/><br/>";
                    answers.add(answer);
                }
            } catch (SQLException ex) {
                System.out.println("Inser to database failed: An Exception has occurred! " + ex);
            }
        } else {
            String answer = "<b>You do not have any product.<b>";
            answers.add(answer);
        }
        break;
    case "non-valid":
        String answer = "2";
        answers.add(answer);
        break;
    default:
        answer = "3";
        answers.add(answer);
        break;
    }
    return answers;
}

From source file:org.glom.web.server.SqlUtils.java

/**
 * @param dataItem//from  w  ww.j  a v  a 2s.c om
 * @param field
 * @param rsIndex
 * @param rs
 * @param primaryKeyValue
 * @throws SQLException
 */
public static void fillDataItemFromResultSet(final DataItem dataItem, final LayoutItemField field,
        final int rsIndex, final ResultSet rs, final String documentID, final String tableName,
        final TypedDataItem primaryKeyValue) throws SQLException {

    switch (field.getGlomType()) {
    case TYPE_TEXT:
        final String text = rs.getString(rsIndex);
        dataItem.setText(text != null ? text : "");
        break;
    case TYPE_BOOLEAN:
        dataItem.setBoolean(rs.getBoolean(rsIndex));
        break;
    case TYPE_NUMERIC:
        dataItem.setNumber(rs.getDouble(rsIndex));
        break;
    case TYPE_DATE:
        final Date date = rs.getDate(rsIndex);
        if (date != null) {
            // TODO: Pass Date and Time types instead of converting to text here?
            // TODO: Use a 4-digit-year short form, somehow.
            final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.ROOT);
            dataItem.setText(dateFormat.format(date));
        } else {
            dataItem.setText("");
        }
        break;
    case TYPE_TIME:
        final Time time = rs.getTime(rsIndex);
        if (time != null) {
            final DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.ROOT);
            dataItem.setText(timeFormat.format(time));
        } else {
            dataItem.setText("");
        }
        break;
    case TYPE_IMAGE:
        //We don't get the data here.
        //Instead we provide a way for the client to get the image separately.

        //This doesn't seem to work,
        //presumably because the base64 encoding is wrong:
        //final byte[] imageByteArray = rs.getBytes(rsIndex);
        //if (imageByteArray != null) {
        //   String base64 = org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString(imageByteArray);
        //   base64 = "data:image/png;base64," + base64;

        final String url = Utils.buildImageDataUrl(primaryKeyValue, documentID, tableName, field);
        dataItem.setImageDataUrl(url);
        break;
    case TYPE_INVALID:
    default:
        Log.warn(documentID, tableName, "Invalid LayoutItem Field type. Using empty string for value.");
        dataItem.setText("");
        break;
    }
}

From source file:CatalogWSModel.CatalogWS.java

@WebMethod(operationName = "searchProduct")
public ArrayList searchProduct(@WebParam(name = "keyword") String keyword,
        @WebParam(name = "filter") String filter, @WebParam(name = "user_id") String user_id) {
    ArrayList<String> answers = new ArrayList<String>();
    Connection dbConn = DbConnectionManager.getConnection();
    try {//from   ww  w.j  av a2 s . c o  m
        String query;
        if (filter.equals("product")) {
            query = "SELECT * FROM catalogue WHERE productname like '%" + keyword + "%'";
        } else {
            query = "SELECT * FROM catalogue WHERE username like '%" + keyword + "%'";
        }

        Statement ps = dbConn.createStatement();
        ResultSet rs = ps.executeQuery(query);
        while (rs.next()) {
            String productname = rs.getString("productname");
            int product_id = rs.getInt("product_id");
            int price = rs.getInt("price");
            String seller = rs.getString("username");
            String productdesc = rs.getString("productdesc");
            Date dateAddedF = rs.getDate("dateadded");
            SimpleDateFormat simpledatafo = new SimpleDateFormat("dd/MM/yyyy");
            Time timeAddedF = rs.getTime("timeadded");
            SimpleDateFormat simpletimefo = new SimpleDateFormat("dd/MM/yyyy");
            String dateadded = rs.getString("dateadded");
            String timeadded = rs.getString("timeadded");
            String qLike = "SELECT * from likes WHERE product_id='" + product_id + "'";
            Statement psLike = dbConn.createStatement();
            ResultSet rsLike = psLike.executeQuery(qLike);
            int count = 0;
            while (rsLike.next()) {
                count++;
            }
            int likes = count;
            int purchases = rs.getInt("purchases");
            String imagepath = rs.getString("imagepath");

            String statuslike = "<span><a id=\"like\" href=\"like?product_id=" + product_id
                    + "\"><b>LIKE</b></a></span>";
            String checkLike = "SELECT * from likes WHERE product_id='" + product_id + "' AND user_id='"
                    + user_id + "'";
            Statement psCheckLike = dbConn.createStatement();
            ResultSet rsCheckLike = psLike.executeQuery(checkLike);
            count = 0;
            boolean hasLiked = rsCheckLike.next();
            if (!hasLiked) {
                statuslike = "<span><a id=\"like\" href=\"like?product_id=" + product_id
                        + "\"><b>LIKE</b></a></span>";
            } else {
                statuslike = "<span><a id=\"dislike\" href=\"dislike?product_id=" + product_id
                        + "\"><b>LIKED</b></a></span>";
            }

            String answer = "<li>" + "<span id='date'>" + "<b>" + seller + "</b>" + "</span><br/>"
                    + "<span id='date'>" + dateadded + "<br/>" + "at " + timeadded + "<hr></hr>" + "</span>"
                    + "<div class='item-list-product'>" + "<div style='position:absolute'>" + "<a href='"
                    + imagepath + "'><img class='img-item' src='" + imagepath + "'></img></a>" + "</div>"
                    + "<div id='product-info'>" + "<span><b>" + productname + "</b></span> <br/>" + "<span>IDR "
                    + price + "</span> <br/>" + "<span style='font-size:12px;position:relative'>" + productdesc
                    + "</span>" + "</div>" + "<div id='eddel'>" + "<br/>" + "<span style='font-size:14px'>"
                    + likes + " likes</span> <br/>" + "<span style='font-size:14px'>" + purchases
                    + " purchase</span> <br/>" + "<br/>" + statuslike
                    + "<span style='margin-left:10px'><a id='buy' href='confirm.jsp?product_id=" + product_id
                    + "'><b>    BUY </b></a> </span>" + "</div>" + "</div>" + "</li>" + "<br/><br/>";
            answers.add(answer);

        }
    } catch (SQLException ex) {
        System.out.println("Insert to database failed: An Exception has occurred! " + ex);
    }

    return answers;
}

From source file:CatalogWSModel.CatalogWS.java

/**
 * This is a sample web service operation
 *///  www.j  a  v a  2  s .c o m
@WebMethod(operationName = "viewCatalog")
public ArrayList<String> viewCatalog(@WebParam(name = "access_token") String access_token)
        throws IOException, ParseException {
    int status = 0;
    ArrayList<String> answers = new ArrayList<String>();
    Connection dbConn = DbConnectionManager.getConnection();
    String targetIS = "ValidateToken";
    String urlParameters = "access_token=" + access_token;
    HttpURLConnection urlConn = UrlConnectionManager.doReqPost(targetIS, urlParameters);
    String resp = UrlConnectionManager.getResponse(urlConn);
    JSONParser parser = new JSONParser();
    JSONObject obj = (JSONObject) parser.parse(resp);
    String statusResp = (String) obj.get("status");
    String username = (String) obj.get("username");
    System.out.println("obj= " + obj.get("user_id"));
    String user_id = (String) obj.get("user_id");
    System.out.println("String id = " + user_id);
    switch (statusResp) {
    case "valid":
        try {
            String query = "SELECT * FROM catalogue Order by product_id DESC";

            Statement ps = dbConn.createStatement();
            ResultSet rs = ps.executeQuery(query);
            while (rs.next()) {
                String productname = rs.getString("productname");
                String seller = rs.getString("username");
                int product_id = rs.getInt("product_id");
                int price = rs.getInt("price");
                String productdesc = rs.getString("productdesc");
                Date dateAddedF = rs.getDate("dateadded");
                SimpleDateFormat simpledatafo = new SimpleDateFormat("dd/MM/yyyy");
                Time timeAddedF = rs.getTime("timeadded");
                SimpleDateFormat simpletimefo = new SimpleDateFormat("dd/MM/yyyy");
                String dateadded = rs.getString("dateadded");
                String timeadded = rs.getString("timeadded");
                String qLike = "SELECT * from likes WHERE product_id='" + product_id + "'";
                Statement psLike = dbConn.createStatement();
                ResultSet rsLike = psLike.executeQuery(qLike);
                int count = 0;
                while (rsLike.next()) {
                    count++;
                }
                int likes = count;
                int purchases = rs.getInt("purchases");
                String imagepath = rs.getString("imagepath");

                String statuslike = "<span><a id=\"like\" href=\"like?product_id=" + product_id
                        + "\"><b>ASD</b></a></span>";
                String checkLike = "SELECT * from likes WHERE product_id='" + product_id + "' AND user_id='"
                        + user_id + "'";
                boolean hasLiked;
                Statement psCheckLike = dbConn.createStatement();
                ResultSet rsCheckLike = psLike.executeQuery(checkLike);
                hasLiked = rsCheckLike.next();

                if (!hasLiked) {
                    statuslike = "<span><a id=\"like\" href=\"like?product_id=" + product_id
                            + "\"><b>LIKE</b></a></span>";
                } else {
                    statuslike = "<span><a id=\"dislike\" href=\"dislike?product_id=" + product_id
                            + "\"><b>LIKED</b></a></span>";
                }
                String answer = "<li>" + "<span id='date'>" + "<b>" + seller + "</b>" + "</span>" + "<br/>"
                        + "<span id='date'>" + dateadded + "<br/>" + "at " + timeadded + "<hr></hr>" + "</span>"
                        + "<div class='item-list-product'>" + "<div style='position:absolute'>" + "<a href='"
                        + imagepath + "'><img class='img-item' src='" + imagepath + "'></img></a>" + "</div>"
                        + "<div id='product-info'>" + "<span><b>" + productname + "</b></span> <br/>"
                        + "<span>IDR " + price + "</span> <br/>"
                        + "<span style='font-size:12px;position:relative'>" + productdesc + "</span>" + "</div>"
                        + "<div id='eddel'>" + "<br/>" + "<span style='font-size:14px'>" + likes
                        + " likes</span> <br/>" + "<span style='font-size:14px'>" + purchases
                        + " purchase</span> <br/>" + "<br/>" + statuslike
                        + "<span style='margin-left:10px'><a id='buy' href='confirm.jsp?product_id="
                        + product_id + "'><b>    BUY </b></a> </span>" + "</div>" + "</div>" + "</li>"
                        + "<br/><br/>";
                answers.add(answer);
            }
        } catch (SQLException ex) {
            System.out.println("Insert to database failed: An Exception has occurred! " + ex);
        }

        break;
    case "non-valid":
        String answer = "2";
        answers.add(answer);
        break;
    default:
        answer = "3";
        answers.add(answer);
        break;
    }
    System.out.println("Answer = " + answers.get(0));
    return answers;
}