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:org.springframework.jdbc.support.JdbcUtils.java

/**
 * Retrieve a JDBC column value from a ResultSet, using the specified value type.
 * <p>Uses the specifically typed ResultSet accessor methods, falling back to
 * {@link #getResultSetValue(java.sql.ResultSet, int)} for unknown types.
 * <p>Note that the returned value may not be assignable to the specified
 * required type, in case of an unknown type. Calling code needs to deal
 * with this case appropriately, e.g. throwing a corresponding exception.
 * @param rs is the ResultSet holding the data
 * @param index is the column index//ww  w  .  j av  a  2s.  c o  m
 * @param requiredType the required value type (may be {@code null})
 * @return the value object (possibly not of the specified required type,
 * with further conversion steps necessary)
 * @throws SQLException if thrown by the JDBC API
 * @see #getResultSetValue(ResultSet, int)
 */
@Nullable
public static Object getResultSetValue(ResultSet rs, int index, @Nullable Class<?> requiredType)
        throws SQLException {
    if (requiredType == null) {
        return getResultSetValue(rs, index);
    }

    Object value;

    // Explicitly extract typed value, as far as possible.
    if (String.class == requiredType) {
        return rs.getString(index);
    } else if (boolean.class == requiredType || Boolean.class == requiredType) {
        value = rs.getBoolean(index);
    } else if (byte.class == requiredType || Byte.class == requiredType) {
        value = rs.getByte(index);
    } else if (short.class == requiredType || Short.class == requiredType) {
        value = rs.getShort(index);
    } else if (int.class == requiredType || Integer.class == requiredType) {
        value = rs.getInt(index);
    } else if (long.class == requiredType || Long.class == requiredType) {
        value = rs.getLong(index);
    } else if (float.class == requiredType || Float.class == requiredType) {
        value = rs.getFloat(index);
    } else if (double.class == requiredType || Double.class == requiredType || Number.class == requiredType) {
        value = rs.getDouble(index);
    } else if (BigDecimal.class == requiredType) {
        return rs.getBigDecimal(index);
    } else if (java.sql.Date.class == requiredType) {
        return rs.getDate(index);
    } else if (java.sql.Time.class == requiredType) {
        return rs.getTime(index);
    } else if (java.sql.Timestamp.class == requiredType || java.util.Date.class == requiredType) {
        return rs.getTimestamp(index);
    } else if (byte[].class == requiredType) {
        return rs.getBytes(index);
    } else if (Blob.class == requiredType) {
        return rs.getBlob(index);
    } else if (Clob.class == requiredType) {
        return rs.getClob(index);
    } else if (requiredType.isEnum()) {
        // Enums can either be represented through a String or an enum index value:
        // leave enum type conversion up to the caller (e.g. a ConversionService)
        // but make sure that we return nothing other than a String or an Integer.
        Object obj = rs.getObject(index);
        if (obj instanceof String) {
            return obj;
        } else if (obj instanceof Number) {
            // Defensively convert any Number to an Integer (as needed by our
            // ConversionService's IntegerToEnumConverterFactory) for use as index
            return NumberUtils.convertNumberToTargetClass((Number) obj, Integer.class);
        } else {
            // e.g. on Postgres: getObject returns a PGObject but we need a String
            return rs.getString(index);
        }
    }

    else {
        // Some unknown type desired -> rely on getObject.
        try {
            return rs.getObject(index, requiredType);
        } catch (AbstractMethodError err) {
            logger.debug("JDBC driver does not implement JDBC 4.1 'getObject(int, Class)' method", err);
        } catch (SQLFeatureNotSupportedException ex) {
            logger.debug("JDBC driver does not support JDBC 4.1 'getObject(int, Class)' method", ex);
        } catch (SQLException ex) {
            logger.debug("JDBC driver has limited support for JDBC 4.1 'getObject(int, Class)' method", ex);
        }

        // Corresponding SQL types for JSR-310 / Joda-Time types, left up
        // to the caller to convert them (e.g. through a ConversionService).
        String typeName = requiredType.getSimpleName();
        if ("LocalDate".equals(typeName)) {
            return rs.getDate(index);
        } else if ("LocalTime".equals(typeName)) {
            return rs.getTime(index);
        } else if ("LocalDateTime".equals(typeName)) {
            return rs.getTimestamp(index);
        }

        // Fall back to getObject without type specification, again
        // left up to the caller to convert the value if necessary.
        return getResultSetValue(rs, index);
    }

    // Perform was-null check if necessary (for results that the JDBC driver returns as primitives).
    return (rs.wasNull() ? null : value);
}

From source file:au.com.ish.derbydump.derbydump.metadata.Column.java

/**
 * Get a string value for the value in this column in the datarow
 * //from  ww  w. j a  v  a  2  s  .c  om
 * @param dataRow The row which we are exporting
 * @return an SQL statement compliant string version of the value
 */
public String toString(ResultSet dataRow) throws SQLException {

    switch (getColumnDataType()) {
    case Types.BINARY:
    case Types.VARBINARY:
    case Types.BLOB: {
        Blob obj = dataRow.getBlob(columnName);
        return (obj == null) ? "NULL" : processBinaryData(obj);
    }

    case Types.CLOB: {
        Clob obj = dataRow.getClob(columnName);
        return (obj == null) ? "NULL" : processClobData(obj);
    }

    case Types.CHAR:
    case Types.LONGNVARCHAR:
    case Types.VARCHAR: {
        String obj = dataRow.getString(columnName);
        return (obj == null) ? "NULL" : processStringData(obj);
    }

    case Types.TIME: {
        Time obj = dataRow.getTime(columnName);
        return (obj == null) ? "NULL" : processStringData(obj.toString());
    }

    case Types.DATE: {
        Date obj = dataRow.getDate(columnName);
        return (obj == null) ? "NULL" : processStringData(obj.toString());
    }

    case Types.TIMESTAMP: {
        Timestamp obj = dataRow.getTimestamp(columnName);
        return (obj == null) ? "NULL" : processStringData(obj.toString());
    }

    case Types.SMALLINT: {
        Object obj = dataRow.getObject(columnName);
        return (obj == null) ? "NULL" : obj.toString();
    }

    case Types.BIGINT: {
        Object obj = dataRow.getObject(columnName);
        return (obj == null) ? "NULL" : obj.toString();
    }

    case Types.INTEGER: {
        Object obj = dataRow.getObject(columnName);
        return (obj == null) ? "NULL" : obj.toString();
    }

    case Types.NUMERIC:
    case Types.DECIMAL: {
        BigDecimal obj = dataRow.getBigDecimal(columnName);
        return (obj == null) ? "NULL" : String.valueOf(obj);
    }

    case Types.REAL:
    case Types.FLOAT: {
        Float obj = dataRow.getFloat(columnName);
        // dataRow.getFloat() always returns a value. only way to check the null is wasNull() method
        return (dataRow.wasNull()) ? "NULL" : String.valueOf(obj);
    }

    case Types.DOUBLE: {
        Double obj = dataRow.getDouble(columnName);
        return (dataRow.wasNull()) ? "NULL" : String.valueOf(obj);
    }

    default: {
        Object obj = dataRow.getObject(columnName);
        return (obj == null) ? "NULL" : obj.toString();
    }
    }
}

From source file:CSVWriter.java

private static String getColumnValue(ResultSet rs, int colType, int colIndex)
    throws SQLException, IOException {

  String value = "";
      /*from  w  ww .  j  a v a 2  s. c  o  m*/
switch (colType)
{
  case Types.BIT:
    Object bit = rs.getObject(colIndex);
    if (bit != null) {
      value = String.valueOf(bit);
    }
  break;
  case Types.BOOLEAN:
    boolean b = rs.getBoolean(colIndex);
    if (!rs.wasNull()) {
      value = Boolean.valueOf(b).toString();
    }
  break;
  case Types.CLOB:
    Clob c = rs.getClob(colIndex);
    if (c != null) {
      value = read(c);
    }
  break;
  case Types.BIGINT:
  case Types.DECIMAL:
  case Types.DOUBLE:
  case Types.FLOAT:
  case Types.REAL:
  case Types.NUMERIC:
    BigDecimal bd = rs.getBigDecimal(colIndex);
    if (bd != null) {
      value = "" + bd.doubleValue();
    }
  break;
  case Types.INTEGER:
  case Types.TINYINT:
  case Types.SMALLINT:
    int intValue = rs.getInt(colIndex);
    if (!rs.wasNull()) {
      value = "" + intValue;
    }
  break;
  case Types.JAVA_OBJECT:
    Object obj = rs.getObject(colIndex);
    if (obj != null) {
      value = String.valueOf(obj);
    }
  break;
  case Types.DATE:
    java.sql.Date date = rs.getDate(colIndex);
    if (date != null) {
      value = DATE_FORMATTER.format(date);;
    }
  break;
  case Types.TIME:
    Time t = rs.getTime(colIndex);
    if (t != null) {
      value = t.toString();
    }
  break;
  case Types.TIMESTAMP:
    Timestamp tstamp = rs.getTimestamp(colIndex);
    if (tstamp != null) {
      value = TIMESTAMP_FORMATTER.format(tstamp);
    }
  break;
  case Types.LONGVARCHAR:
  case Types.VARCHAR:
  case Types.CHAR:
    value = rs.getString(colIndex);
  break;
  default:
    value = "";
}

    
if (value == null)
{
  value = "";
}
    
return value;
      
}

From source file:org.apache.ode.bpel.extvar.jdbc.JdbcExternalVariableModule.java

RowVal execSelect(DbExternalVariable dbev, Locator locator)
        throws SQLException, ExternalVariableModuleException {
    RowKey rowkey = dbev.keyFromLocator(locator);
    if (__log.isDebugEnabled())
        __log.debug("execSelect: " + rowkey);

    if (rowkey.missingDatabaseGeneratedValues()) {
        return null;
    }//from   www .ja va 2  s .  co  m

    if (rowkey.missingValues()) {
        throw new IncompleteKeyException(rowkey.getMissing());
    }

    RowVal ret = dbev.new RowVal();
    Connection conn = dbev.dataSource.getConnection();
    PreparedStatement stmt = null;
    try {
        if (__log.isDebugEnabled())
            __log.debug("Prepare statement: " + dbev.select);
        stmt = conn.prepareStatement(dbev.select);
        int idx = 1;
        for (Object k : rowkey) {
            if (__log.isDebugEnabled())
                __log.debug("Set key parameter " + idx + ": " + k);
            stmt.setObject(idx++, k);
        }

        ResultSet rs = stmt.executeQuery();
        try {
            if (rs.next()) {
                for (Column c : dbev._columns) {
                    Object val;
                    int i = c.idx + 1;
                    if (c.isDate())
                        val = rs.getDate(i);
                    else if (c.isTimeStamp())
                        val = rs.getTimestamp(i);
                    else if (c.isTime())
                        val = rs.getTime(i);
                    else if (c.isInteger())
                        val = new Long(rs.getLong(i));
                    else if (c.isReal())
                        val = new Double(rs.getDouble(i));
                    else if (c.isBoolean())
                        val = new Boolean(rs.getBoolean(i));
                    else
                        val = rs.getObject(i);
                    if (__log.isDebugEnabled())
                        __log.debug("Result column index " + c.idx + ": " + val);
                    ret.set(c.idx, val);
                }
            } else
                return null;
        } finally {
            rs.close();
        }
    } finally {
        if (stmt != null)
            stmt.close();
        try {
            conn.close();
        } catch (SQLException e) {
            // ignore
        }
    }

    return ret;
}

From source file:org.snaker.engine.access.jdbc.JdbcHelper.java

/**
 * ?ResultSet?index?requiredType?/*from  w  w w . ja v a  2 s  .  c o m*/
 * @param rs
 * @param index
 * @param requiredType
 * @return
 * @throws SQLException
 */
public static Object getResultSetValue(ResultSet rs, int index, Class<?> requiredType) throws SQLException {
    if (requiredType == null) {
        return getResultSetValue(rs, index);
    }

    Object value = null;
    boolean wasNullCheck = false;

    if (String.class.equals(requiredType)) {
        value = rs.getString(index);
    } else if (boolean.class.equals(requiredType) || Boolean.class.equals(requiredType)) {
        value = rs.getBoolean(index);
        wasNullCheck = true;
    } else if (byte.class.equals(requiredType) || Byte.class.equals(requiredType)) {
        value = rs.getByte(index);
        wasNullCheck = true;
    } else if (short.class.equals(requiredType) || Short.class.equals(requiredType)) {
        value = rs.getShort(index);
        wasNullCheck = true;
    } else if (int.class.equals(requiredType) || Integer.class.equals(requiredType)) {
        value = rs.getInt(index);
        wasNullCheck = true;
    } else if (long.class.equals(requiredType) || Long.class.equals(requiredType)) {
        value = rs.getLong(index);
        wasNullCheck = true;
    } else if (float.class.equals(requiredType) || Float.class.equals(requiredType)) {
        value = rs.getFloat(index);
        wasNullCheck = true;
    } else if (double.class.equals(requiredType) || Double.class.equals(requiredType)
            || Number.class.equals(requiredType)) {
        value = rs.getDouble(index);
        wasNullCheck = true;
    } else if (byte[].class.equals(requiredType)) {
        value = rs.getBytes(index);
    } else if (java.sql.Date.class.equals(requiredType)) {
        value = rs.getDate(index);
    } else if (java.sql.Time.class.equals(requiredType)) {
        value = rs.getTime(index);
    } else if (java.sql.Timestamp.class.equals(requiredType) || java.util.Date.class.equals(requiredType)) {
        value = rs.getTimestamp(index);
    } else if (BigDecimal.class.equals(requiredType)) {
        value = rs.getBigDecimal(index);
    } else if (Blob.class.equals(requiredType)) {
        value = rs.getBlob(index);
    } else if (Clob.class.equals(requiredType)) {
        value = rs.getClob(index);
    } else {
        value = getResultSetValue(rs, index);
    }

    if (wasNullCheck && value != null && rs.wasNull()) {
        value = null;
    }
    return value;
}

From source file:org.apache.phoenix.end2end.CSVCommonsLoaderTest.java

@Test
public void testAllDatatypes() throws Exception {
    CSVParser parser = null;/*w  w  w . ja v  a2 s.  c o m*/
    PhoenixConnection conn = null;
    try {
        // Create table
        String statements = "CREATE TABLE IF NOT EXISTS " + DATATYPE_TABLE
                + " (CKEY VARCHAR NOT NULL PRIMARY KEY,"
                + "  CVARCHAR VARCHAR, CINTEGER INTEGER, CDECIMAL DECIMAL(31,10), CUNSIGNED_INT UNSIGNED_INT, CBOOLEAN BOOLEAN, CBIGINT BIGINT, CUNSIGNED_LONG UNSIGNED_LONG, CTIME TIME, CDATE DATE);";
        conn = DriverManager.getConnection(getUrl()).unwrap(PhoenixConnection.class);
        PhoenixRuntime.executeStatements(conn, new StringReader(statements), null);

        // Upsert CSV file
        CSVCommonsLoader csvUtil = new CSVCommonsLoader(conn, DATATYPE_TABLE, Collections.<String>emptyList(),
                true);
        csvUtil.upsert(new StringReader(DATATYPES_CSV_VALUES));

        // Compare Phoenix ResultSet with CSV file content
        PreparedStatement statement = conn.prepareStatement(
                "SELECT CKEY, CVARCHAR, CINTEGER, CDECIMAL, CUNSIGNED_INT, CBOOLEAN, CBIGINT, CUNSIGNED_LONG, CTIME, CDATE FROM "
                        + DATATYPE_TABLE);
        ResultSet phoenixResultSet = statement.executeQuery();
        parser = new CSVParser(new StringReader(DATATYPES_CSV_VALUES), csvUtil.getFormat());

        for (CSVRecord record : parser) {
            assertTrue(phoenixResultSet.next());
            int i = 0;
            int size = record.size();
            for (String value : record) {
                assertEquals(value, phoenixResultSet.getObject(i + 1).toString().toUpperCase());
                if (i < size - 2)
                    break;
                i++;
            }
            // special case for matching date, time values
            assertEquals(DateUtil.parseTime(record.get(8)), phoenixResultSet.getTime("CTIME"));
            assertEquals(DateUtil.parseDate(record.get(9)), phoenixResultSet.getDate("CDATE"));
        }

        assertFalse(phoenixResultSet.next());
    } finally {
        if (parser != null)
            parser.close();
        if (conn != null)
            conn.close();
    }
}

From source file:org.apache.cocoon.util.JDBCTypeConversions.java

/**
 * Get the Statement column so that the results are mapped correctly.
 * (this has been copied from AbstractDatabaseAction and modified slightly)
 *//* w  w w. j  av a 2s .  c  om*/
public static Object getColumn(ResultSet set, Configuration column) throws Exception {

    Integer type = (Integer) JDBCTypeConversions.typeConstants.get(column.getAttribute("type"));
    String dbcol = column.getAttribute("name");
    Object value = null;

    switch (type.intValue()) {
    case Types.CLOB:
    case Types.CHAR:
        Clob dbClob = set.getClob(dbcol);
        int length = (int) dbClob.length();
        InputStream asciiStream = new BufferedInputStream(dbClob.getAsciiStream());
        byte[] buffer = new byte[length];
        asciiStream.read(buffer);
        String str = new String(buffer);
        asciiStream.close();
        value = str;
        break;
    case Types.BIGINT:
        value = set.getBigDecimal(dbcol);
        break;
    case Types.TINYINT:
        value = new Byte(set.getByte(dbcol));
        break;
    case Types.VARCHAR:
        value = set.getString(dbcol);
        break;
    case Types.DATE:
        value = set.getDate(dbcol);
        break;
    case Types.DOUBLE:
        value = new Double(set.getDouble(dbcol));
        break;
    case Types.FLOAT:
        value = new Float(set.getFloat(dbcol));
        break;
    case Types.INTEGER:
        value = new Integer(set.getInt(dbcol));
        break;
    case Types.NUMERIC:
        value = new Long(set.getLong(dbcol));
        break;
    case Types.SMALLINT:
        value = new Short(set.getShort(dbcol));
        break;
    case Types.TIME:
        value = set.getTime(dbcol);
        break;
    case Types.TIMESTAMP:
        value = set.getTimestamp(dbcol);
        break;
    case Types.ARRAY:
        value = set.getArray(dbcol); // new Integer(set.getInt(dbcol));
        break;
    case Types.BIT:
        value = BooleanUtils.toBooleanObject(set.getBoolean(dbcol));
        break;
    case Types.STRUCT:
        value = (Struct) set.getObject(dbcol);
        break;
    case Types.OTHER:
        value = set.getObject(dbcol);
        break;

    default:
        // The blob types have to be requested separately, via a Reader.
        value = "";
        break;
    }

    return value;
}

From source file:jeeves.resources.dbms.Dbms.java

private Element buildElement(ResultSet rs, int col, String name, int type, Hashtable<String, String> formats)
        throws SQLException {
    String value = null;//www . j a  v  a  2 s . c  om

    switch (type) {
    case Types.DATE:
        Date date = rs.getDate(col + 1);
        if (date == null)
            value = null;
        else {
            String format = formats.get(name);
            SimpleDateFormat df = (format == null) ? new SimpleDateFormat(DEFAULT_DATE_FORMAT)
                    : new SimpleDateFormat(format);
            value = df.format(date);
        }
        break;

    case Types.TIME:
        Time time = rs.getTime(col + 1);
        if (time == null)
            value = null;
        else {
            String format = formats.get(name);
            SimpleDateFormat df = (format == null) ? new SimpleDateFormat(DEFAULT_TIME_FORMAT)
                    : new SimpleDateFormat(format);
            value = df.format(time);
        }
        break;

    case Types.TIMESTAMP:
        Timestamp timestamp = rs.getTimestamp(col + 1);
        if (timestamp == null)
            value = null;
        else {
            String format = formats.get(name);
            SimpleDateFormat df = (format == null) ? new SimpleDateFormat(DEFAULT_TIMESTAMP_FORMAT)
                    : new SimpleDateFormat(format);
            value = df.format(timestamp);
        }
        break;

    case Types.TINYINT:
    case Types.SMALLINT:
    case Types.INTEGER:
    case Types.BIGINT:
        long l = rs.getLong(col + 1);
        if (rs.wasNull())
            value = null;
        else {
            String format = formats.get(name);
            if (format == null)
                value = l + "";
            else {
                DecimalFormat df = new DecimalFormat(format);
                value = df.format(l);
            }
        }
        break;

    case Types.DECIMAL:
    case Types.FLOAT:
    case Types.DOUBLE:
    case Types.REAL:
    case Types.NUMERIC:
        double n = rs.getDouble(col + 1);

        if (rs.wasNull())
            value = null;
        else {
            String format = formats.get(name);

            if (format == null) {
                value = n + "";

                // --- this fix is mandatory for oracle
                // --- that shit returns integers like xxx.0

                if (value.endsWith(".0"))
                    value = value.substring(0, value.length() - 2);
            } else {
                DecimalFormat df = new DecimalFormat(format);
                value = df.format(n);
            }
        }
        break;

    default:
        value = rs.getString(col + 1);
        if (value != null) {
            value = stripIllegalChars(value);
        }

        break;
    }
    return new Element(name).setText(value);
}

From source file:cn.clickvalue.cv2.model.rowmapper.BeanPropertyRowMapper.java

/**
 * Retrieve a JDBC column value from a ResultSet, using the specified value type.
 * <p>Uses the specifically typed ResultSet accessor methods, falling back to
 * {@link #getResultSetValue(java.sql.ResultSet, int)} for unknown types.
 * <p>Note that the returned value may not be assignable to the specified
 * required type, in case of an unknown type. Calling code needs to deal
 * with this case appropriately, e.g. throwing a corresponding exception.
 * @param rs is the ResultSet holding the data
 * @param index is the column index//from  w  w  w  .  j a  v  a 2  s  .  c o m
 * @param requiredType the required value type (may be <code>null</code>)
 * @return the value object
 * @throws SQLException if thrown by the JDBC API
 */
public static Object getResultSetValue(ResultSet rs, int index, Class requiredType) throws SQLException {
    if (requiredType == null) {
        return getResultSetValue(rs, index);
    }

    Object value = null;
    boolean wasNullCheck = false;

    // Explicitly extract typed value, as far as possible.
    if (String.class.equals(requiredType)) {
        value = rs.getString(index);
    } else if (boolean.class.equals(requiredType) || Boolean.class.equals(requiredType)) {
        value = Boolean.valueOf(rs.getBoolean(index));
        wasNullCheck = true;
    } else if (byte.class.equals(requiredType) || Byte.class.equals(requiredType)) {
        value = Byte.valueOf(rs.getByte(index));
        wasNullCheck = true;
    } else if (short.class.equals(requiredType) || Short.class.equals(requiredType)) {
        value = Short.valueOf(rs.getShort(index));
        wasNullCheck = true;
    } else if (int.class.equals(requiredType) || Integer.class.equals(requiredType)) {
        value = Integer.valueOf(rs.getInt(index));
        wasNullCheck = true;
    } else if (long.class.equals(requiredType) || Long.class.equals(requiredType)) {
        value = Long.valueOf(rs.getLong(index));
        wasNullCheck = true;
    } else if (float.class.equals(requiredType) || Float.class.equals(requiredType)) {
        value = Float.valueOf(rs.getFloat(index));
        wasNullCheck = true;
    } else if (double.class.equals(requiredType) || Double.class.equals(requiredType)
            || Number.class.equals(requiredType)) {
        value = Double.valueOf(rs.getDouble(index));
        wasNullCheck = true;
    } else if (byte[].class.equals(requiredType)) {
        value = rs.getBytes(index);
    } else if (java.sql.Date.class.equals(requiredType)) {
        value = rs.getDate(index);
    } else if (java.sql.Time.class.equals(requiredType)) {
        value = rs.getTime(index);
    } else if (java.sql.Timestamp.class.equals(requiredType) || java.util.Date.class.equals(requiredType)) {
        value = rs.getTimestamp(index);
    } else if (BigDecimal.class.equals(requiredType)) {
        value = rs.getBigDecimal(index);
    } else if (Blob.class.equals(requiredType)) {
        value = rs.getBlob(index);
    } else if (Clob.class.equals(requiredType)) {
        value = rs.getClob(index);
    } else {
        // Some unknown type desired -> rely on getObject.
        value = getResultSetValue(rs, index);
    }

    // Perform was-null check if demanded (for results that the
    // JDBC driver returns as primitives).
    if (wasNullCheck && value != null && rs.wasNull()) {
        value = null;
    }
    return value;
}

From source file:SalesModel.SalesWS.java

/**
 * Web service operation//from   www .j ava  2  s  .c om
 * @param access_token
 * @param user_id
 */
@WebMethod(operationName = "getSales")
public ArrayList<String> getSales(@WebParam(name = "access_token") String access_token)
        throws IOException, ParseException {
    ArrayList<String> answers = new ArrayList<String>();
    Connection conn = 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");
    switch (statusResp) {
    case "valid":
        if (hasSales(username)) {
            try {
                String query = "SELECT * FROM purchase WHERE purchase.seller = '" + username
                        + "' ORDER BY purchase.purchase_id DESC ";
                Statement stmt = conn.createStatement();
                ResultSet rslt = stmt.executeQuery(query);
                while (rslt.next()) {
                    int product_id = rslt.getInt("purchase_id");
                    String product_name = rslt.getString("product_name");
                    int product_price = rslt.getInt("product_price");
                    String seller = rslt.getString("seller");
                    String buyer = rslt.getString("buyer");
                    String image = rslt.getString("image");
                    int quantity = rslt.getInt("quantity");
                    String consignee = rslt.getString("consignee");
                    String fulladdress = rslt.getString("fulladdress");
                    int postalcode = rslt.getInt("postalcode");
                    String phonenumber = rslt.getString("newphonenumber");
                    String creditcard = rslt.getString("creditcard");
                    String verification = rslt.getString("verification");
                    Date dateBoughtF = rslt.getDate("datebought");
                    SimpleDateFormat simpledatefo = new SimpleDateFormat("dd/MM/yyyy");
                    Time timeBoughtF = rslt.getTime("timebought");
                    SimpleDateFormat simpletimefo = new SimpleDateFormat("dd/MM/yyyy");
                    String datebought = rslt.getString("datebought");
                    String timebought = rslt.getString("timebought");
                    int totalprice = quantity * product_price;

                    String answer = "<li>" + "<span id='date'>" + "<b>" + datebought + "</b>" + "<br/>" + "at "
                            + timebought + "<hr></hr>" + "</span>" + "<div class='item-list-product'>"
                            + "<div style='position:absolute'>" + "<a href='" + image
                            + "'><img class='img-item' src='" + image + "'></img></a>" + "</div>"
                            + "<div id='product-info' style='width:250px'>" + "<span><b>" + product_name
                            + "</b></span><br/>" + "<span>IDR " + totalprice + "</span> <br/>" + "<span>"
                            + quantity + "pcs</span><br/>" + "<span>@IDR " + product_price + "</span>"
                            + "</div>" + "<div id='eddel' style='font-size:12px;left:380px;width:220px'>"
                            + "<span>Delivery to <b>" + consignee + "</b> </span> <br/>" + "<span>"
                            + fulladdress + "</span> <br/>" + "<span>" + postalcode + "</span><br/>" + "<span>"
                            + phonenumber + "</span>" + "</div>" + "</div>"
                            + "<span style=\"margin-left:120px;font-size:12px\">bought by <b>" + buyer
                            + "</b></span>" + "</li>" + "<br>";
                    answers.add(answer);
                }
            } catch (SQLException ex) {
                System.out.println("Insert to database failed: An Exception has occurred! " + ex);
            }
        } else {
            String answer = "<b>You have not sold 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;
}