Example usage for java.sql SQLException printStackTrace

List of usage examples for java.sql SQLException printStackTrace

Introduction

In this page you can find the example usage for java.sql SQLException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:jobimtext.thesaurus.distributional.DatabaseThesaurusDatastructure.java

public Long getKeyCount(String key) {
    Long count = 0L;//from w  ww .ja va  2  s . c o m
    String sql = "SELECT count FROM " + tableKey + " WHERE word = ?";
    PreparedStatement ps;
    try {
        ps = getDatabaseConnection().getConnection().prepareStatement(sql);

        ps.setString(1, key);
        ResultSet set = ps.executeQuery();

        if (set.next()) {
            count = set.getLong("count");
        }
        ps.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return count;
}

From source file:ch.zhaw.init.walj.projectmanagement.util.chart.LineChart.java

/**
  * creates a line chart with all booked and planned PMs
 *//*  w  ww. j  ava2 s  . c  o  m*/
public void createChart() {

    // get dataset
    XYSeriesCollection dataset = null;
    try {
        dataset = (XYSeriesCollection) createDataset();
    } catch (SQLException e) {
        e.printStackTrace();
    }

    // create line chart
    JFreeChart xylineChart = ChartFactory.createXYLineChart("", "Month", "PM", dataset,
            PlotOrientation.VERTICAL, true, true, false);

    // set color of chart
    XYPlot plot = xylineChart.getXYPlot();
    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
    renderer.setSeriesPaint(0, new Color(0, 101, 166));
    renderer.setSeriesPaint(1, new Color(0, 62, 102));
    plot.setRenderer(renderer);

    // set size of the chart and save it as small JPEG for project overview
    int width = 600;
    int height = 400;
    File lineChart = new File(path + "EffortProject" + project.getID() + ".jpg");
    try {
        ChartUtilities.saveChartAsJPEG(lineChart, xylineChart, width, height);
    } catch (IOException e) {
        e.printStackTrace();
    }

    // set size of the chart and save it as large JPEG for effort detail page
    width = 1200;
    height = 600;
    lineChart = new File(path + "/Charts/EffortProject" + project.getID() + "_large.jpg");
    try {
        ChartUtilities.saveChartAsJPEG(lineChart, xylineChart, width, height);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.its.web.services.LicensesService.java

public List<License> findByCpuMacProductName(String cpu, String mac, Long parentId) {

    Map<String, Object> fieldValues = new HashMap<String, Object>();
    fieldValues.put("cpu", cpu);
    fieldValues.put("mac", mac);
    fieldValues.put("parent_id", parentId);

    try {/*  w  w w  . ja  v  a  2 s  . co m*/
        return database.getLicenseDao().queryForFieldValues(fieldValues);
    } catch (SQLException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.jjtree.servelet.Fans.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request/*w w  w  .  j a  v a2 s  .com*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);

    int accountID = Integer.parseInt(request.getParameter("accountID"));
    int pageSize = Integer.parseInt(request.getParameter("pageSize"));
    int pageIndex = Integer.parseInt(request.getParameter("pageIndex"));

    try {
        Class.forName(JConstant.JDBC_DRIVER);
        conn = DriverManager.getConnection(JConstant.DB_URL, JConstant.USER, JConstant.PASSWORD);
        stmt = conn.createStatement();

        String sql = "SELECT DISTINCT subjectID FROM JUserBehaviors WHERE objectID = " + accountID
                + " AND predicate = 'watch' OFFSET " + pageSize * pageIndex + " ROWS FETCH NEXT " + pageSize
                + " ROWS ONLY";
        ;

        ResultSet rs = stmt.executeQuery(sql);

        JSONArray fans = new JSONArray();
        while (rs.next()) {
            int _accountID = rs.getInt("subjectID");

            String accountUrl = "/accounts/" + _accountID;
            JSONObject accountObject = JServeletManager.fetchFrom(request, accountUrl);

            fans.put(accountObject);
        }

        JSONObject fansObject = new JSONObject();
        fansObject.put("fans", fans);

        JResponse.sendJson(response, fansObject);

        // Clean-up environment
        rs.close();
        ;
        stmt.close();
        conn.close();
    } catch (SQLException se) {
        //Handle errors for JDBC
        se.printStackTrace();
    } catch (Exception e) {
        //Handle errors for Class.forName
        e.printStackTrace();
    } finally {
        //finally block used to close resources
        try {
            if (stmt != null) {
                stmt.close();
            }
        } catch (SQLException se2) {
        } // nothing we can do
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException se) {
            se.printStackTrace();
        } //end finally try
    } //end try
}

From source file:gsn.vsensor.TestStreamExporterVirtualSensor.java

public void testLogStatementIntoMySQLDB() {
    StreamExporterVirtualSensor vs = new StreamExporterVirtualSensor();
    // configure parameters
    ArrayList<KeyValue> params = new ArrayList<KeyValue>();
    params.add(new KeyValueImp(StreamExporterVirtualSensor.PARAM_URL, url));
    params.add(new KeyValueImp(StreamExporterVirtualSensor.PARAM_USER, user));
    params.add(new KeyValueImp(StreamExporterVirtualSensor.PARAM_PASSWD, passwd));
    config.setMainClassInitialParams(params);
    vs.setVirtualSensorConfiguration(config);
    vs.initialize();//www  .j ava  2 s.  c o  m

    // configure datastream
    Vector<DataField> fieldTypes = new Vector<DataField>();
    Object[] data = null;

    for (String type : DataTypes.TYPE_NAMES)
        fieldTypes.add(new DataField(type, type, type));
    int i = 0;
    for (Object value : DataTypes.TYPE_SAMPLE_VALUES)
        data[i++] = value;

    long timeStamp = new Date().getTime();
    StreamElement streamElement = new StreamElement(fieldTypes.toArray(new DataField[] {}),
            (Serializable[]) data, timeStamp);

    // give datastream to vs
    vs.dataAvailable(streamName, streamElement);

    // clean up and control
    boolean result = true;
    try {
        DriverManager.registerDriver(new com.mysql.jdbc.Driver());
        Connection connection = DriverManager.getConnection(url, user, passwd);
        Statement statement = connection.createStatement();
        statement.execute("SELECT * FROM " + streamName);
        System.out.println("result" + result);
        result = statement.getResultSet().last();
        System.out.println("result" + result);
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        result = false;
    }
    assertTrue(result);
}

From source file:com.its.web.services.LicensesService.java

public boolean saveOrUpdate(License license) {

    try {//from  ww  w. j  a v a  2 s  . c  om

        if (license.getId() == null) {
            database.getLicenseDao().create(license);
        } else {
            database.getLicenseDao().update(license);
        }
    } catch (SQLException e) {
        e.printStackTrace();
        return false;
    }

    return true;
}

From source file:com.haulmont.cuba.core.DataManagerDistinctResultsTest.java

@After
public void tearDown() throws Exception {
    Transaction tx = cont.persistence().createTransaction();
    try {/*from  w  w  w. j  ava2 s . c o  m*/
        QueryRunner runner = new QueryRunner(cont.persistence().getDataSource());
        try {
            String sql = "delete from SEC_USER_ROLE where ROLE_ID = '" + role1Id.toString() + "'";
            runner.update(sql);

            sql = "delete from SEC_USER_ROLE where ROLE_ID = '" + role2Id.toString() + "'";
            runner.update(sql);

            sql = "delete from SEC_ROLE where ID = '" + role1Id.toString() + "'";
            runner.update(sql);

            sql = "delete from SEC_ROLE where ID = '" + role2Id.toString() + "'";
            runner.update(sql);

            sql = "delete from SEC_USER where GROUP_ID = '" + groupId.toString() + "'";
            runner.update(sql);

            sql = "delete from SEC_GROUP where ID = '" + groupId.toString() + "'";
            runner.update(sql);

        } catch (SQLException e) {
            e.printStackTrace();
        }
        tx.commit();
    } finally {
        tx.end();
    }
}

From source file:org.openmrs.module.pmtct.web.view.chart.InfantPCRPieChartView.java

/**
 * @see org.openmrs.module.pmtct.web.view.chart.AbstractChartView#createChart(java.util.Map,
 *      javax.servlet.http.HttpServletRequest)
 *//*w ww  . j  av a 2  s . c  om*/
@Override
protected JFreeChart createChart(Map<String, Object> model, HttpServletRequest request) {
    UserContext userContext = Context.getUserContext();
    ApplicationContext appContext = ContextProvider.getApplicationContext();
    PMTCTModuleTag tag = new PMTCTModuleTag();

    List<Object> res = new ArrayList<Object>();

    DefaultPieDataset pieDataset = new DefaultPieDataset();
    String title = "", descriptionTitle = "", dateInterval = "";
    Concept concept = null;
    SimpleDateFormat df = Context.getDateFormat();

    //            Date myDate1 = new Date("1/1/" + ((new Date()).getYear() + 1900));
    //            String startDate1 = df.format(myDate1);

    Date today = new Date();
    Date oneYearFromNow = new Date(new Date().getTime() - PMTCTConstants.YEAR_IN_MILLISECONDS);

    String endDate1 = df.format(today);
    String startDate1 = df.format(oneYearFromNow);

    dateInterval = "(" + new SimpleDateFormat("dd-MMM-yyyy").format(oneYearFromNow) + " - "
            + new SimpleDateFormat("dd-MMM-yyyy").format(today) + ")";

    try {

        PmtctService pmtct;
        pmtct = Context.getService(PmtctService.class);
        try {
            res = pmtct.getGeneralStatForInfantTests_Charting_PCR(startDate1, endDate1);
        } catch (SQLException ex) {
            ex.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        List<String> hivTestResultOptions = new ArrayList<String>();

        List<Integer> pcr_hivTestResultValues = new ArrayList<Integer>();

        Collection<ConceptAnswer> answers = Context.getConceptService()
                .getConcept(PMTCTConstants.RESULT_OF_HIV_TEST).getAnswers();
        for (ConceptAnswer str : answers) {
            hivTestResultOptions.add(str.getAnswerConcept().getName().getName());

            pcr_hivTestResultValues.add(0);
        }
        hivTestResultOptions.add("Others");
        pcr_hivTestResultValues.add(0);

        for (Object ob : res) {
            int val = 0;
            String temp = "", pcr_hivTestResult = "";

            temp = "" + ((Object[]) ob)[2];
            val = (temp.compareTo("") == 0) ? 0 : Integer.parseInt(temp);
            if (val > 0)
                pcr_hivTestResult = tag.getConceptNameById(temp);

            int i = 0;
            boolean pcr_found = false;
            for (String s : hivTestResultOptions) {
                if ((s.compareToIgnoreCase(pcr_hivTestResult)) == 0) {
                    pcr_hivTestResultValues.set(i, pcr_hivTestResultValues.get(i) + 1);
                    pcr_found = true;
                }
                i++;
            }

            if (!pcr_found) {
                pcr_hivTestResultValues.set(pcr_hivTestResultValues.size() - 1,
                        pcr_hivTestResultValues.get(pcr_hivTestResultValues.size() - 1) + 1);
            }
        }

        int i = 0;
        for (String s : hivTestResultOptions) {
            if (pcr_hivTestResultValues.get(i) > 0) {
                Float percentage = new Float(100 * pcr_hivTestResultValues.get(i) / res.size());
                pieDataset.setValue(s + " (" + pcr_hivTestResultValues.get(i) + " , " + percentage + "%)",
                        percentage);
            }
            i++;
        }

        title = appContext.getMessage("pmtct.menu.infantTest", null, userContext.getLocale());
        concept = null;
        descriptionTitle = Context.getEncounterService()
                .getEncounterType(PMTCTConfigurationUtils.getPCRTestEncounterTypeId()).getName();
        descriptionTitle += dateInterval;
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    JFreeChart chart = ChartFactory.createPieChart(title + " : "
            + ((null != concept) ? concept.getPreferredName(userContext.getLocale()) : descriptionTitle),
            pieDataset, true, true, false);

    return chart;
}

From source file:dk.dbc.rawrepo.oai.OAIIdentifierCollectionIT.java

private void loadRecordsFrom(String... jsons) throws SQLException, IOException {
    Connection connection = pg.getConnection();
    connection.prepareStatement("SET TIMEZONE TO 'UTC'").execute();
    try (PreparedStatement rec = connection
            .prepareStatement("INSERT INTO oairecords (pid, changed, deleted) VALUES(?, ?::timestamp, ?)");
            PreparedStatement recSet = connection
                    .prepareStatement("INSERT INTO oairecordsets (pid, setSpec) VALUES(?, ?)")) {

        for (String json : jsons) {
            InputStream is = getClass().getClassLoader().getResourceAsStream(json);
            if (is == null) {
                throw new RuntimeException("Cannot find: " + json);
            }/* w  ww .j a va  2 s  .c  o  m*/
            ObjectMapper objectMapper = new ObjectMapper();
            List<ObjectNode> array = objectMapper.readValue(is, List.class);
            for (Object object : array) {
                Map<String, Object> obj = (Map<String, Object>) object;
                rec.setString(1, (String) obj.get("pid"));
                rec.setString(2, (String) obj.getOrDefault("changed",
                        DateTimeFormatter.ISO_INSTANT.format(Instant.now().atZone(ZoneId.systemDefault()))));
                rec.setBoolean(3, (boolean) obj.getOrDefault("deleted", false));
                rec.executeUpdate();
                recSet.setString(1, (String) obj.get("pid"));
                List<Object> sets = (List<Object>) obj.get("sets");

                for (Object set : sets) {
                    recSet.setString(2, (String) set);
                    recSet.executeUpdate();
                }
            }
        }
    } catch (SQLException ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    }
}

From source file:edu.byu.wso2.apim.extensions.helpers.BYUEntityHelper.java

public BYUEntity getBYUEntityFromNetId(String netid) {
    Connection con = null;// w  w w  . ja  v  a 2 s  .c o  m
    Statement statement = null;
    ResultSet resultSet = null;
    BYUEntity byuEntity = null;
    try {
        con = ds.getConnection();
        if (log.isDebugEnabled())
            log.debug("connection acquired. creating statement and executing query");
        statement = con.createStatement();
        resultSet = statement.executeQuery("select * from pro.person where net_id = '" + netid + "'");
        if (resultSet.next()) {
            String byu_id = resultSet.getString("byu_id");
            String person_id = resultSet.getString("person_id");
            String net_id = resultSet.getString("net_id");
            String surname = resultSet.getString("surname");
            String rest_of_name = resultSet.getString("rest_of_name");
            if (log.isDebugEnabled())
                log.debug("byu_id: " + byu_id + " person_id: " + person_id + " surname: " + surname
                        + " rest_of_name: " + rest_of_name);
            byuEntity = new BYUEntity(net_id, person_id, byu_id, surname, rest_of_name);
        } else {
            if (log.isDebugEnabled()) {
                log.debug("resultset is empty");
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                /* ignored */ }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                /* ignored */ }
        }
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                /* ignored */ }
        }
    }
    return byuEntity;
}