List of usage examples for java.sql ResultSet isBeforeFirst
boolean isBeforeFirst() throws SQLException;
ResultSet
object. From source file:com.github.woonsan.jdbc.jcr.impl.JcrJdbcResultSetTest.java
@Test public void testExecuteSQLQuery() throws Exception { Statement statement = getConnection().createStatement(); ResultSet rs = statement.executeQuery(SQL_EMPS); assertSame(statement, rs.getStatement()); assertEquals(ResultSet.TYPE_FORWARD_ONLY, rs.getType()); assertEquals(ResultSet.CONCUR_READ_ONLY, rs.getConcurrency()); assertEquals(ResultSet.HOLD_CURSORS_OVER_COMMIT, rs.getHoldability()); assertFalse(rs.isClosed());/*from ww w . jav a 2s .co m*/ assertTrue(rs.isBeforeFirst()); assertFalse(rs.isAfterLast()); assertEquals(1, rs.findColumn("empno")); assertEquals(2, rs.findColumn("ename")); assertEquals(3, rs.findColumn("salary")); assertEquals(4, rs.findColumn("hiredate")); int count = printResultSet(rs); assertEquals(getEmpRowCount(), count); assertFalse(rs.isBeforeFirst()); assertTrue(rs.isAfterLast()); rs.close(); assertTrue(rs.isClosed()); statement.close(); assertTrue(statement.isClosed()); }
From source file:com.github.woonsan.jdbc.jcr.impl.JcrJdbcResultSetTest.java
@SuppressWarnings("deprecation") @Test//from w w w. j a va 2s .c om public void testResultSetWhenClosed() throws Exception { Statement statement = getConnection().createStatement(); ResultSet rs = statement.executeQuery(SQL_EMPS); rs.close(); try { rs.isBeforeFirst(); fail(); } catch (SQLException ignore) { } try { rs.isAfterLast(); fail(); } catch (SQLException ignore) { } try { rs.isFirst(); fail(); } catch (SQLException ignore) { } try { rs.isLast(); fail(); } catch (SQLException ignore) { } try { rs.beforeFirst(); fail(); } catch (SQLException ignore) { } try { rs.afterLast(); fail(); } catch (SQLException ignore) { } try { rs.first(); fail(); } catch (SQLException ignore) { } try { rs.last(); fail(); } catch (SQLException ignore) { } try { rs.next(); fail(); } catch (SQLException ignore) { } try { rs.getRow(); fail(); } catch (SQLException ignore) { } try { rs.getType(); fail(); } catch (SQLException ignore) { } try { rs.getConcurrency(); fail(); } catch (SQLException ignore) { } try { rs.rowUpdated(); fail(); } catch (SQLException ignore) { } try { rs.rowDeleted(); fail(); } catch (SQLException ignore) { } try { rs.rowInserted(); fail(); } catch (SQLException ignore) { } try { rs.getStatement(); fail(); } catch (SQLException ignore) { } try { rs.wasNull(); fail(); } catch (SQLException ignore) { } try { rs.getString(1); fail(); } catch (SQLException ignore) { } try { rs.getString("col1"); fail(); } catch (SQLException ignore) { } try { rs.getBoolean(1); fail(); } catch (SQLException ignore) { } try { rs.getBoolean("col1"); fail(); } catch (SQLException ignore) { } try { rs.getByte(1); fail(); } catch (SQLException ignore) { } try { rs.getByte("col1"); fail(); } catch (SQLException ignore) { } try { rs.getShort(1); fail(); } catch (SQLException ignore) { } try { rs.getShort("col1"); fail(); } catch (SQLException ignore) { } try { rs.getInt(1); fail(); } catch (SQLException ignore) { } try { rs.getInt("col1"); fail(); } catch (SQLException ignore) { } try { rs.getLong(1); fail(); } catch (SQLException ignore) { } try { rs.getLong("col1"); fail(); } catch (SQLException ignore) { } try { rs.getFloat(1); fail(); } catch (SQLException ignore) { } try { rs.getFloat("col1"); fail(); } catch (SQLException ignore) { } try { rs.getDouble(1); fail(); } catch (SQLException ignore) { } try { rs.getDouble("col1"); fail(); } catch (SQLException ignore) { } try { rs.getBigDecimal(1); fail(); } catch (SQLException ignore) { } try { rs.getBigDecimal("col1"); fail(); } catch (SQLException ignore) { } try { rs.getBytes(1); fail(); } catch (SQLException ignore) { } try { rs.getBytes("col1"); fail(); } catch (SQLException ignore) { } try { rs.getDate(1); fail(); } catch (SQLException ignore) { } try { rs.getDate(1, null); fail(); } catch (SQLException ignore) { } try { rs.getDate("col1"); fail(); } catch (SQLException ignore) { } try { rs.getDate("col1", null); fail(); } catch (SQLException ignore) { } try { rs.getTime(1); fail(); } catch (SQLException ignore) { } try { rs.getTime(1, null); fail(); } catch (SQLException ignore) { } try { rs.getTime("col1"); fail(); } catch (SQLException ignore) { } try { rs.getTime("col1", null); fail(); } catch (SQLException ignore) { } try { rs.getTimestamp(1); fail(); } catch (SQLException ignore) { } try { rs.getTimestamp(1, null); fail(); } catch (SQLException ignore) { } try { rs.getTimestamp("col1"); fail(); } catch (SQLException ignore) { } try { rs.getTimestamp("col1", null); fail(); } catch (SQLException ignore) { } try { rs.getAsciiStream(1); fail(); } catch (SQLException ignore) { } try { rs.getAsciiStream("col1"); fail(); } catch (SQLException ignore) { } try { rs.getUnicodeStream(1); fail(); } catch (SQLException ignore) { } try { rs.getUnicodeStream("col1"); fail(); } catch (SQLException ignore) { } try { rs.getBinaryStream(1); fail(); } catch (SQLException ignore) { } try { rs.getBinaryStream("col1"); fail(); } catch (SQLException ignore) { } try { rs.getCharacterStream(1); fail(); } catch (SQLException ignore) { } try { rs.getCharacterStream("col1"); fail(); } catch (SQLException ignore) { } try { rs.getMetaData(); fail(); } catch (SQLException ignore) { } try { rs.setFetchDirection(1); fail(); } catch (SQLException ignore) { } try { rs.getFetchDirection(); fail(); } catch (SQLException ignore) { } try { rs.setFetchSize(100); fail(); } catch (SQLException ignore) { } try { rs.getFetchSize(); fail(); } catch (SQLException ignore) { } try { rs.getHoldability(); fail(); } catch (SQLException ignore) { } statement.close(); }
From source file:com.emr.utilities.CSVLoader.java
/** * Parse CSV file using OpenCSV library and load in * given database table. /*from w w w . j a v a2s .c o m*/ * @param csvFile {@link String} Input CSV file * @param tableName {@link String} Database table name to import data * @param truncateBeforeLoad {@link boolean} Truncate the table before inserting * new records. * @param destinationColumns {@link String[]} Array containing the destination columns */ public void loadCSV(String csvFile, String tableName, boolean truncateBeforeLoad, String[] destinationColumns, List columnsToBeMapped) throws Exception { CSVReader csvReader = null; if (null == this.connection) { throw new Exception("Not a valid connection."); } try { csvReader = new CSVReader(new FileReader(csvFile), this.seprator); } catch (Exception e) { String stacktrace = org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace(e); JOptionPane.showMessageDialog(null, "Error occured while executing file. Error Details: " + stacktrace, "File Error", JOptionPane.ERROR_MESSAGE); throw new Exception("Error occured while executing file. " + stacktrace); } String[] headerRow = csvReader.readNext(); if (null == headerRow) { throw new FileNotFoundException( "No columns defined in given CSV file." + "Please check the CSV file format."); } //Get indices of columns to be mapped List mapColumnsIndices = new ArrayList(); for (Object o : columnsToBeMapped) { String column = (String) o; column = column.substring(column.lastIndexOf(".") + 1, column.length()); int i; for (i = 0; i < headerRow.length; i++) { if (headerRow[i].equals(column)) { mapColumnsIndices.add(i); } } } String questionmarks = StringUtils.repeat("?,", headerRow.length); questionmarks = (String) questionmarks.subSequence(0, questionmarks.length() - 1); String query = SQL_INSERT.replaceFirst(TABLE_REGEX, tableName); query = query.replaceFirst(KEYS_REGEX, StringUtils.join(destinationColumns, ",")); query = query.replaceFirst(VALUES_REGEX, questionmarks); String log_query = query.substring(0, query.indexOf("VALUES(")); String[] nextLine; Connection con = null; PreparedStatement ps = null; PreparedStatement ps2 = null; PreparedStatement reader = null; ResultSet rs = null; try { con = this.connection; con.setAutoCommit(false); ps = con.prepareStatement(query); File file = new File("sqlite/db"); if (!file.exists()) { file.createNewFile(); } db = new SQLiteConnection(file); db.open(true); //if destination table==person, also add an entry in the table person_identifier //get column indices for the person_id and uuid columns int person_id_column_index = -1; int uuid_column_index = -1; int maxLength = 100; int firstname_index = -1; int middlename_index = -1; int lastname_index = -1; int clanname_index = -1; int othername_index = -1; if (tableName.equals("person")) { int i; ps2 = con.prepareStatement( "insert ignore into person_identifier(person_id,identifier_type_id,identifier) values(?,?,?)"); for (i = 0; i < headerRow.length; i++) { if (headerRow[i].equals("person_id")) { person_id_column_index = i; } if (headerRow[i].equals("uuid")) { uuid_column_index = i; } /*if(headerRow[i].equals("first_name")){ System.out.println("Found firstname index: " + i); firstname_index=i; } if(headerRow[i].equals("middle_name")){ System.out.println("Found firstname index: " + i); middlename_index=i; } if(headerRow[i].equals("last_name")){ System.out.println("Found firstname index: " + i); lastname_index=i; } if(headerRow[i].equals("clan_name")){ System.out.println("Found firstname index: " + i); clanname_index=i; } if(headerRow[i].equals("other_name")){ System.out.println("Found firstname index: " + i); othername_index=i; }*/ } } if (truncateBeforeLoad) { //delete data from table before loading csv try (Statement stmnt = con.createStatement()) { stmnt.execute("DELETE FROM " + tableName); stmnt.close(); } } if (tableName.equals("person")) { try (Statement stmt2 = con.createStatement()) { stmt2.execute( "ALTER TABLE person CHANGE COLUMN first_name first_name VARCHAR(50) NULL DEFAULT NULL AFTER person_guid,CHANGE COLUMN middle_name middle_name VARCHAR(50) NULL DEFAULT NULL AFTER first_name,CHANGE COLUMN last_name last_name VARCHAR(50) NULL DEFAULT NULL AFTER middle_name;"); stmt2.close(); } } final int batchSize = 1000; int count = 0; Date date = null; while ((nextLine = csvReader.readNext()) != null) { if (null != nextLine) { int index = 1; int person_id = -1; String uuid = ""; int identifier_type_id = 3; if (tableName.equals("person")) { reader = con.prepareStatement( "select identifier_type_id from identifier_type where identifier_type_name='UUID'"); rs = reader.executeQuery(); if (!rs.isBeforeFirst()) { //no uuid row //insert it Integer numero = 0; Statement stmt = con.createStatement(); numero = stmt.executeUpdate( "insert into identifier_type(identifier_type_id,identifier_type_name) values(50,'UUID')", Statement.RETURN_GENERATED_KEYS); ResultSet rs2 = stmt.getGeneratedKeys(); if (rs2.next()) { identifier_type_id = rs2.getInt(1); } rs2.close(); stmt.close(); } else { while (rs.next()) { identifier_type_id = rs.getInt("identifier_type_id"); } } } int counter = 1; String temp_log = log_query + "VALUES("; //string to be logged for (String string : nextLine) { //if current index is in the list of columns to be mapped, we apply that mapping for (Object o : mapColumnsIndices) { int i = (int) o; if (index == (i + 1)) { //apply mapping to this column string = applyDataMapping(string); } } if (tableName.equals("person")) { //get person_id and uuid if (index == (person_id_column_index + 1)) { person_id = Integer.parseInt(string); } if (index == (uuid_column_index + 1)) { uuid = string; } } //check if string is a date if (string.matches("\\d{2}-[a-zA-Z]{3}-\\d{4} \\d{2}:\\d{2}:\\d{2}") || string.matches("\\d{2}-[a-zA-Z]{3}-\\d{4}")) { java.sql.Date dt = formatDate(string); temp_log = temp_log + "'" + dt.toString() + "'"; ps.setDate(index++, dt); } else { if ("".equals(string)) { temp_log = temp_log + "''"; ps.setNull(index++, Types.NULL); } else { temp_log = temp_log + "'" + string + "'"; ps.setString(index++, string); } } if (counter < headerRow.length) { temp_log = temp_log + ","; } else { temp_log = temp_log + ");"; System.out.println(temp_log); } counter++; } if (tableName.equals("person")) { if (!"".equals(uuid) && person_id != -1) { ps2.setInt(1, person_id); ps2.setInt(2, identifier_type_id); ps2.setString(3, uuid); ps2.addBatch(); } } ps.addBatch(); } if (++count % batchSize == 0) { ps.executeBatch(); if (tableName.equals("person")) { ps2.executeBatch(); } } } ps.executeBatch(); // insert remaining records if (tableName.equals("person")) { ps2.executeBatch(); } con.commit(); } catch (Exception e) { if (con != null) con.rollback(); if (db != null) db.dispose(); String stacktrace = org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace(e); JOptionPane.showMessageDialog(null, "Error occured while executing file. Error Details: " + stacktrace, "File Error", JOptionPane.ERROR_MESSAGE); throw new Exception("Error occured while executing file. " + stacktrace); } finally { if (null != reader) reader.close(); if (null != ps) ps.close(); if (null != ps2) ps2.close(); if (null != con) con.close(); csvReader.close(); } }
From source file:i5.las2peer.services.mobsos.SurveyService.java
/** * Retrieves identifier of questionnaire for given survey or -1 if no questionnaire was defined, yet. *//*ww w . j av a 2 s .c o m*/ private int getQuestionnaireIdForSurvey(int sid) throws SQLException { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = dataSource.getConnection(); stmt = conn.prepareStatement("select qid from " + jdbcSchema + ".survey where id = ?"); stmt.setInt(1, sid); rs = stmt.executeQuery(); if (!rs.isBeforeFirst()) { return -1; } else { rs.next(); return rs.getInt("qid"); } } catch (SQLException | UnsupportedOperationException e) { throw e; } finally { try { if (rs != null) rs.close(); } catch (Exception e) { throw e; } try { if (stmt != null) stmt.close(); } catch (Exception e) { throw e; } try { if (conn != null) conn.close(); } catch (Exception e) { throw e; } } }
From source file:i5.las2peer.services.mobsos.SurveyService.java
/** * Given a survey identifier, checks if the respective survey already defines a database view for survey responses. * @param sid/*ww w . ja v a 2s .c om*/ * @return * @throws SQLException */ private boolean existsResponseView(int sid) throws SQLException { try { Connection c = null; PreparedStatement s = null; ResultSet rs = null; // +++ dsi try { c = dataSource.getConnection(); s = c.prepareStatement("show tables in " + jdbcSchema + " like ?"); s.setString(1, "responses_survey_" + sid); rs = s.executeQuery(); // view does not exist if (!rs.isBeforeFirst()) { return false; } else { return true; } } catch (Exception e) { throw e; } finally { try { if (rs != null) rs.close(); } catch (Exception e) { throw e; } try { if (s != null) s.close(); } catch (Exception e) { throw e; } try { if (c != null) c.close(); } catch (Exception e) { throw e; } } // --- dsi } catch (Exception e) { throw e; } }
From source file:i5.las2peer.services.mobsos.SurveyService.java
/** * TODO: write documentation//from w w w . j ava 2 s . c o m * Retrieves information for a given questionnaire. * * @param id * @return */ @GET @Produces(MediaType.APPLICATION_JSON) @Path("questionnaires/{id}") @Summary("retrieve given questionnaire.") @Notes("Use parent resource to retrieve list of existing questionnaires. ") @ApiResponses(value = { @ApiResponse(code = 200, message = "Questionnaire data (TODO: introduce Swagger models)"), @ApiResponse(code = 404, message = "Questionnaire does not exist.") }) public HttpResponse getQuestionnaire(@PathParam("id") int id) { String onAction = "retrieving questionnaire " + id; try { Connection conn = null; PreparedStatement stmt = null; ResultSet rset = null; try { conn = dataSource.getConnection(); stmt = conn.prepareStatement("select id, owner, name, description, organization, logo, lang from " + jdbcSchema + ".questionnaire where id = ?"); stmt.setInt(1, id); rset = stmt.executeQuery(); if (!rset.isBeforeFirst()) { HttpResponse result = new HttpResponse("Questionnaire " + id + " does not exist!"); result.setStatus(404); return result; } rset.next(); JSONObject r = readQuestionnaireFromResultSet(rset); HttpResponse result = new HttpResponse(r.toJSONString()); result.setStatus(200); return result; } catch (SQLException | UnsupportedOperationException e) { return internalError(onAction); } finally { try { if (rset != null) rset.close(); } catch (Exception e) { e.printStackTrace(); return internalError(onAction); } try { if (stmt != null) stmt.close(); } catch (Exception e) { e.printStackTrace(); return internalError(onAction); } try { if (conn != null) conn.close(); } catch (Exception e) { e.printStackTrace(); return internalError(onAction); } } } catch (Exception e) { e.printStackTrace(); return internalError(onAction); } }
From source file:i5.las2peer.services.mobsos.SurveyService.java
/** * TODO: write documentation//from ww w .j av a 2 s . c o m * @param id * @return */ @GET @Produces(MediaType.TEXT_HTML) @Path("surveys/{id}/questionnaire") @Summary("Download questionnaire form for given survey. Enables response submission.") @Notes("Can be used with or without authentication, including response submission.") @ApiResponses(value = { @ApiResponse(code = 200, message = "Survey questionnaire HTML representation."), @ApiResponse(code = 400, message = "Survey questionnaire form invalid. Cause: ..."), @ApiResponse(code = 404, message = "Questionnaire does not exist. <b>-or-</b> Survey questionnaire not set. <b>-or-</b> Survey questionnaire does not define form.") }) public HttpResponse getSurveyQuestionnaireFormHTML( @HeaderParam(name = "accept-language", defaultValue = "") String lang, @PathParam("id") int id) { String onAction = "downloading questionnaire form for survey " + id; try { // if survey does not exist, return 404. if (checkExistenceOwnership(id, 0) == -1) { HttpResponse result = new HttpResponse("Survey does not exist!"); result.setStatus(404); return result; } } catch (Exception e1) { return internalError(onAction); } Connection conn = null; PreparedStatement stmt = null; ResultSet rset = null; String formXml; // ----------------- try { // retrieve survey data; if survey does not exist, return 404. HttpResponse r = getSurvey(id); if (200 != r.getStatus()) { System.err.println(r.getResult()); return r; } JSONObject survey = (JSONObject) JSONValue.parse(r.getResult()); // check if survey has the questionnaire id field qid set. If not, return not found. if (null == survey.get("qid")) { HttpResponse result = new HttpResponse("Questionnaire not set for survey " + id + "."); result.setStatus(404); return result; } // if questionnaire was found, download questionnaire form long qid = (Long) survey.get("qid"); try { conn = dataSource.getConnection(); stmt = conn.prepareStatement("select form from " + jdbcSchema + ".questionnaire where id = ?"); stmt.setLong(1, qid); ResultSet rs = stmt.executeQuery(); // if no form was uploaded for questionnaire, respond to user with not found if (!rs.isBeforeFirst()) { HttpResponse result = new HttpResponse("Form for questionnaire " + qid + " does not exist!"); result.setStatus(404); return result; } rs.next(); formXml = rs.getString(1); } catch (SQLException | UnsupportedOperationException e) { return internalError(onAction); } finally { try { if (rset != null) rset.close(); } catch (Exception e) { e.printStackTrace(); return internalError(onAction); } try { if (stmt != null) stmt.close(); } catch (Exception e) { e.printStackTrace(); return internalError(onAction); } try { if (conn != null) conn.close(); } catch (Exception e) { e.printStackTrace(); return internalError(onAction); } } // adapt form template to concrete survey and user String adaptedFormXml = adaptForm(formXml, survey, (UserAgent) this.getActiveAgent(), null); //String adaptedFormXml = formXml; Document form; // before returning form, make sure it's still valid (may be obsolete step...) try { form = validateQuestionnaireData(adaptedFormXml); } catch (IOException e) { e.printStackTrace(); return internalError(onAction); } catch (SAXException e) { e.printStackTrace(); HttpResponse result = new HttpResponse("Questionnaire form is invalid! Cause: " + e.getMessage()); result.setStatus(400); return result; } // now start to transform XML into ready-to-use HTML // start off with template String html = new Scanner(new File("./etc/html/survey-form-template.html")).useDelimiter("\\A").next(); // fill in placeholders html = fillPlaceHolder(html, "EP_URL", epUrl); html = fillPlaceHolder(html, "SC_URL", staticContentUrl); html = fillPlaceHolder(html, "OIDC_PROV_NAME", oidcProviderName); html = fillPlaceHolder(html, "OIDC_PROV_LOGO", oidcProviderLogo); html = fillPlaceHolder(html, "OIDC_PROV_URL", oidcProviderUrl); html = fillPlaceHolder(html, "OIDC_CLNT_ID", oidcClientId); // do all adaptation to user and survey String adaptHtml = adaptForm(html, survey, (UserAgent) this.getActiveAgent(), null); adaptHtml = i18n(adaptHtml, lang); //String adaptText = text; // add HTML elements for all questionnaire items accordingly Vector<String> qpages = new Vector<String>(); Vector<String> navpills = new Vector<String>(); NodeList nodeList = form.getElementsByTagNameNS(MOBSOS_QUESTIONNAIRE_NS, "Page"); // then iterate over all question pages for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element e = (Element) node; // set first page and navpill item to active String active = ""; if (i == 0) { active = " class='active'"; } // differentiate between possible item types and add HTML accordingly if (e.getAttribute("xsi:type").endsWith("InformationPageType")) { // first add navpill item String navpill = "\t\t\t\t\t<li" + active + "><a href=\"#step-" + i + "\"><span class=\"list-group-item-heading\">" + i + "</span></a></li>\n"; navpills.add(navpill); // then add information page String qpage = "\t\t<div class=\"row setup-content\" id=\"step-" + i + "\"><div class=\"col-xs-12\"><div class=\"col-md-12 well text-center\">\n"; String name = e.getAttribute("name"); qpage += "\t\t\t<h4><b>" + name + "</b></h4>\n"; String instr = escapeHtml4(e.getElementsByTagNameNS(MOBSOS_QUESTIONNAIRE_NS, "Instructions") .item(0).getTextContent().trim()); qpage += "\t\t\t<p>\n\t\t\t\t" + instr + "\n" + "\t\t\t</p>\n"; qpage += "\t\t</div></div></div>\n"; qpages.add(qpage); } else if (e.getAttribute("xsi:type").endsWith("QuestionPageType")) { // first add nav pill item String navpill = "\t\t\t\t\t<li" + active + "><a href=\"#step-" + i + "\"><span class=\"list-group-item-heading\">" + i + "</span></a></li>\n"; navpills.add(navpill); // then add question page String qpage = "\t\t<div class=\"row setup-content\" id=\"step-" + i + "\"><div class=\"col-xs-12\"><div class=\"col-md-12 text-center\">\n"; String name = e.getAttribute("name"); String quid = e.getAttribute("qid"); qpage += "\t\t\t<h4><b>" + name + " (" + quid + ")</b></h4>\n"; String instr = escapeHtml4(e.getElementsByTagNameNS(MOBSOS_QUESTIONNAIRE_NS, "Instructions") .item(0).getTextContent().trim()); String cssClass = "question"; if (e.getAttribute("required") != null && e.getAttribute("required").equals("true")) { cssClass += " required"; instr += " (<i>" + i18n("${required}", lang) + "</i>)"; } qpage += "\t\t\t<div class=\"" + cssClass + "\" style='text-align: justify;'>" + instr + "</div><p/>\n"; String qtype = e.getAttribute("xsi:type"); if ("qu:OrdinalScaleQuestionPageType".equals(qtype)) { // TODO: do something with default value, if set. //int defval = Integer.parseInt(e.getAttribute("defval")); String minlabel = escapeHtml4(e.getAttribute("minlabel")); String maxlabel = escapeHtml4(e.getAttribute("maxlabel")); int minval = Integer.parseInt(e.getAttribute("minval")); int maxval = Integer.parseInt(e.getAttribute("maxval")); // do UI in a button style (not really nice in terms of responsive design) /* qpage += "\t\t\t<div class=\"btn-group\" data-toggle=\"buttons\">\n"; qpage += "\t\t\t\t<span class=\"btn\">" + minlabel + "</span>\n"; for(int k=minval;k<=maxval;k++){ qpage += "\t\t\t\t<label class=\"btn btn-primary\">\n"; qpage += "\t\t\t\t\t<input name=\""+ quid + "\" type=\"radio\" value=\""+k + "\">" + k + "\n"; qpage += "\t\t\t\t</label>\n"; } qpage += "\t\t\t\t<span class=\"btn\">" + maxlabel + "</span>\n"; qpage += "\t\t\t</div>\n"; */ // --- end UI button style // do UI in range slider style (better responsive design) /* <div class="row well"> <input class="col-md-12 col-xs-12 scale" name="SQ.N.1" type="range" min="1" max="7" step="1" list="SQ.N.1-scale"/><br> <datalist id="SQ.N.1-scale"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> <option>6</option> <option>7</option> </datalist> <span class="col-md-4 col-xs-4">Totally disagree</span><span name="SQ.N.1" class="col-md-4 col-xs-4 text-center h4 response scale-response alert" data-toggle="tooltip" data-placement="left" title="Click to reset to n/a.">n/a</span> <span class="col-md-4 col-xs-4 pull-right text-right">Totally agree</span> </div>*/ qpage += "\t\t\t<div class='row well'>\n"; qpage += "\t\t\t\t<input class='col-md-12 col-xs-12 scale' name='" + quid + "' type='range' min='" + minval + "' max='" + maxval + "' step='1' list='" + quid.replace(".", "-") + "-scale'/><br>\n"; qpage += "\t\t\t\t<datalist id='" + quid.replace(".", "-") + "-scale'>\n"; for (int k = minval; k <= maxval; k++) { qpage += "\t\t\t\t\t<option>" + k + "</option>\n"; } qpage += "\t\t\t\t</datalist>"; qpage += "<span class='col-md-4 col-xs-5 text-left'>" + minlabel + "</span><span name='" + quid + "' class='col-md-4 col-xs-2 text-center h2 response scale-response' data-toggle='tooltip' data-placement='left' title='Click to reset to n/a.'>n/a</span> <span class='col-md-4 col-xs-5 pull-right text-right'>" + maxlabel + "</span>"; qpage += "\t\t\t</div>\n"; // --- end UI range slider style } else if ("qu:FreeTextQuestionPageType".equals(qtype)) { qpage += "\t\t\t<textarea name=\"" + quid + "\" class=\"form-control response freetext-response\" rows=\"3\"></textarea>\n"; } qpage += "\t\t</div></div></div>\n"; qpages.add(qpage); } } } // now that all questions are extracted and transformed to HTML, append nav pill items and question pages to final HTML. // first serialize nav pill items String navpillItems = ""; for (int j = 0; j < navpills.size(); j++) { navpillItems += navpills.get(j); } // then serialize question page divs String questionDivs = ""; for (int j = 0; j < qpages.size(); j++) { questionDivs += qpages.get(j); } // then generate answer link URL answerUrl = new URL(epUrl + "surveys/" + id + "/answers"); String answerLink = "<a href=\"" + answerUrl + "\" id=\"return-url\" class=\"hidden\" ></a>"; // finally insert all generated parts into the resulting adapted HTML adaptHtml = adaptHtml.replaceAll("<!-- NAVPILLS -->", navpillItems); adaptHtml = adaptHtml.replaceAll("<!-- QUESTIONPAGES -->", questionDivs); adaptHtml = adaptHtml.replaceAll("<!-- ANSWERLINK -->", answerLink); // return adapted HTML HttpResponse result = new HttpResponse(adaptHtml); result.setStatus(200); return result; } catch (Exception e) { e.printStackTrace(); return internalError(onAction); } }
From source file:i5.las2peer.services.mobsos.SurveyService.java
@GET @Produces(MediaType.APPLICATION_JSON)/*from w w w. j ava 2 s . c om*/ @Path("oidc/clients/{id}") public HttpResponse getClientMetadata(@PathParam(value = "id") String id) { String onAction = "retrieving metadata for client " + id; try { Connection conn = null; PreparedStatement stmt = null; ResultSet rset = null; try { conn = dataSource.getConnection(); stmt = conn.prepareStatement( "select client_id, client_name, client_description, client_uri, logo_uri from " + oidcSchema + ".client_details where client_id = ?"); stmt.setString(1, id); rset = stmt.executeQuery(); if (!rset.isBeforeFirst()) { HttpResponse result = new HttpResponse("No metadata found for client " + id + "!"); result.setStatus(404); return result; } rset.next(); JSONObject meta = new JSONObject(); meta.put("id", rset.getString("client_id")); meta.put("name", rset.getString("client_name")); meta.put("description", rset.getString("client_description")); meta.put("uri", rset.getString("client_uri")); meta.put("logo", rset.getString("logo_uri")); HttpResponse result = new HttpResponse(meta.toJSONString()); result.setStatus(200); return result; } catch (SQLException | UnsupportedOperationException e) { return internalError(onAction); } finally { try { if (rset != null) rset.close(); } catch (Exception e) { e.printStackTrace(); return internalError(onAction); } try { if (stmt != null) stmt.close(); } catch (Exception e) { e.printStackTrace(); return internalError(onAction); } try { if (conn != null) conn.close(); } catch (Exception e) { e.printStackTrace(); return internalError(onAction); } } } catch (Exception e) { e.printStackTrace(); return internalError(onAction); } }
From source file:i5.las2peer.services.mobsos.SurveyService.java
/** * Checks if survey or questionnaire exists and active agent is owner. * /*from w ww .j a v a 2 s . c o m*/ * @param id int survey or questionnaire id * @param type int 0 for survey, 1 for questionnaire * @return int -1 if questionnaire/survey does not exist, 0 if active agent is not owner, 1 if active agent is owner * @throws Exception */ private int checkExistenceOwnership(int id, int type) throws Exception { try { Connection c = null; PreparedStatement s = null; ResultSet rs = null; // +++ dsi try { c = dataSource.getConnection(); if (type == 0) { s = c.prepareStatement("select owner from " + jdbcSchema + ".survey where id = ?"); } else { s = c.prepareStatement("select owner from " + jdbcSchema + ".questionnaire where id = ?"); } s.setInt(1, id); rs = s.executeQuery(); // survey/questionnaire does not exist if (!rs.isBeforeFirst()) { return -1; } rs.next(); String owner = rs.getString(1); // active agent is not owner. String sub = (String) getActiveUserInfo().get("sub"); if (!owner.equals(sub)) { return 0; } // active agent is owner. else { return 1; } } catch (Exception e) { throw e; } finally { try { if (rs != null) rs.close(); } catch (Exception e) { throw e; } try { if (s != null) s.close(); } catch (Exception e) { throw e; } try { if (c != null) c.close(); } catch (Exception e) { throw e; } } // --- dsi } catch (Exception e) { throw e; } }
From source file:i5.las2peer.services.mobsos.SurveyService.java
/** * TODO: write documentation/* w w w . j ava 2s .co m*/ * Retrieves information for a given survey * * @param id * @return */ @GET @Produces(MediaType.APPLICATION_JSON) @Path("surveys/{id}") @Summary("retrieve given survey.") @Notes("Use <b>/surveys</b> to retrieve list of existing surveys. ") @ApiResponses(value = { @ApiResponse(code = 200, message = "Survey data (TODO: introduce Swagger models)"), @ApiResponse(code = 404, message = "Survey does not exist.") }) public HttpResponse getSurvey(@PathParam("id") int id) { String onAction = "retrieving survey " + id; try { JSONObject r = new JSONObject(); //result to return in HTTP response Connection c = null; PreparedStatement s = null; ResultSet rs = null; // +++ dsi try { // query for given survey c = dataSource.getConnection(); // TODO: restore, as soon as resource information comes from an external source s = c.prepareStatement("select * from " + jdbcSchema + ".survey where id = ?"); // TODO: replace by external source for retrieving resource information //s = c.prepareStatement("select s.*, r.name as rname, r.description as rdesc from " + jdbcSchema + ".survey s left join " + jdbcSchema + ".resource r on (s.resource = r.uri) where id = ?"); s.setInt(1, id); rs = s.executeQuery(); // if survey does not exist, respond to user with not found if (!rs.isBeforeFirst()) { HttpResponse result = new HttpResponse("Survey " + id + " does not exist!"); result.setStatus(404); return result; } // if survey was found, respond to user with JSON result rs.next(); r = readSurveyFromResultSet(rs); // TODO: replace by external resource information //String resource_name = rs.getString("rname"); //String resource_description = rs.getString("rdesc"); //String resource_uri = (String) r.get("resource"); //JSONObject res = new JSONObject(); //res.put("uri",resource_uri); //res.put("name", resource_name); //res.put("description", resource_description); //r.put("resource", res); // before, try to retrieve information on resource HttpResponse result = new HttpResponse(r.toJSONString()); result.setStatus(200); return result; } catch (Exception e) { e.printStackTrace(); return internalError(onAction); } finally { try { if (rs != null) rs.close(); } catch (Exception e) { e.printStackTrace(); return internalError(onAction); } try { if (s != null) s.close(); } catch (Exception e) { e.printStackTrace(); return internalError(onAction); } try { if (c != null) c.close(); } catch (Exception e) { e.printStackTrace(); return internalError(onAction); } } // --- dsi } catch (Exception e) { e.printStackTrace(); return internalError(onAction); } }