rem
stringlengths 0
477k
| add
stringlengths 0
313k
| context
stringlengths 6
599k
|
---|---|---|
ArrayList<String> answers = (ArrayList<String>) session.getAttribute("answers"); | Object obj = session.getAttribute("answers"); ArrayList<String> answers = null; if(obj instanceof PersistentList){ Iterator iter = ((PersistentList) obj).iterator(); answers = new ArrayList<String>(); while(iter.hasNext()){ answers.add((String) iter.next()); } } else answers = (ArrayList<String>) session.getAttribute("answers"); | public void addStringListQuestionToSection(HttpServletRequest request){ HttpSession session = request.getSession(); Section section = (Section) session.getAttribute("currentSection"); String name = request.getParameter("name"); String image = request.getParameter("image"); String questionText = request.getParameter("questionTxt"); ArrayList<String> answers = (ArrayList<String>) session.getAttribute("answers"); // now parse different params depending on the type StringListQuestion question = new StringListQuestion(); question.setDescription(questionText); question.setSection(section); question.setTitle(name); question.setItems(answers); question.setImage(image); List<Question> quests = section.getQuestions(); quests.add(question); section.setQuestions(quests); session.setAttribute("currentSection", section); session.removeAttribute("answers"); } |
ArrayList<String> answers = (ArrayList<String>) session.getAttribute("answers"); | Collection answers = (Collection) session.getAttribute("answers"); | public void removeAnswerFromSession(HttpServletRequest request){ HttpSession session = request.getSession(); int rowId = Integer.parseInt(request.getParameter("row")); rowId--; ArrayList<String> answers = (ArrayList<String>) session.getAttribute("answers"); answers.remove(rowId); session.setAttribute("answers", answers); } |
ArrayList<String> columns = (ArrayList<String>) session.getAttribute("columns"); | ArrayList<String> columns = null; Object obj = session.getAttribute("columns"); if(obj instanceof PersistentList){ Iterator iter = ((PersistentList) obj).iterator(); columns = new ArrayList<String>(); while(iter.hasNext()){ columns.add((String)iter.next()); } } else columns = (ArrayList<String>) session.getAttribute("columns"); | public void removeColumnFromSession(HttpServletRequest request){ HttpSession session = request.getSession(); int rowId = Integer.parseInt(request.getParameter("row")); rowId--; ArrayList<String> columns = (ArrayList<String>) session.getAttribute("columns"); columns.remove(rowId); session.setAttribute("columns", columns); } |
ArrayList<String> answers = (ArrayList<String>) session.getAttribute("answers"); | ArrayList<String> answers = null; Object obj = session.getAttribute("answers"); if(obj instanceof PersistentList){ Iterator iter = ((PersistentList) obj).iterator(); answers = new ArrayList<String>(); while(iter.hasNext()){ answers.add((String)iter.next()); } } else answers = (ArrayList<String>) session.getAttribute("answers"); | public void updateAnswerInSession(HttpServletRequest request){ HttpSession session = request.getSession(); int rowId = Integer.parseInt(request.getParameter("row")); String answer = request.getParameter("answer"); rowId--; ArrayList<String> answers = (ArrayList<String>) session.getAttribute("answers"); answers.set(rowId, answer); session.setAttribute("answers", answers); } |
ArrayList<String> answers = (ArrayList<String>) session.getAttribute("answers"); | Object obj = session.getAttribute("answers"); ArrayList<String> answers = null; if(obj instanceof PersistentList){ Iterator iter = ((PersistentList) obj).iterator(); answers = new ArrayList<String>(); while(iter.hasNext()){ answers.add((String) iter.next()); } } else answers = (ArrayList<String>) session.getAttribute("answers"); | public void updateCheckBoxQuestionInSection(HttpServletRequest request){ HttpSession session = request.getSession(); Section section = (Section) session.getAttribute("currentSection"); String name = request.getParameter("name"); String image = request.getParameter("image"); String questionText = request.getParameter("questionTxt"); int rowId = Integer.parseInt(request.getParameter("row")); rowId--; ArrayList<String> answers = (ArrayList<String>) session.getAttribute("answers"); // now parse different params depending on the type CheckBoxListQuestion question = new CheckBoxListQuestion(); question.setDescription(questionText); question.setSection(section); question.setTitle(name); question.setItems(answers); question.setImage(image); List<Question> quests = section.getQuestions(); quests.set(rowId, question); section.setQuestions(quests); session.setAttribute("currentSection", section); session.removeAttribute("answers"); } |
ArrayList<String> columns = (ArrayList<String>) session.getAttribute("columns"); | ArrayList<String> columns = null; Object obj = session.getAttribute("columns"); if(obj instanceof PersistentList){ Iterator iter = ((PersistentList) obj).iterator(); columns = new ArrayList<String>(); while(iter.hasNext()){ columns.add((String)iter.next()); } } else columns = (ArrayList<String>) session.getAttribute("columns"); | public void updateColumnInSession(HttpServletRequest request){ HttpSession session = request.getSession(); int rowId = Integer.parseInt(request.getParameter("row")); String column = request.getParameter("column"); rowId--; ArrayList<String> columns = (ArrayList<String>) session.getAttribute("columns"); columns.set(rowId, column); session.setAttribute("columns", columns); } |
ArrayList<String> answers = (ArrayList<String>) session.getAttribute("answers"); ArrayList<String> columns = (ArrayList<String>) session.getAttribute("columns"); | Object obj = session.getAttribute("answers"); ArrayList<String> answers = null; if(obj instanceof PersistentList){ Iterator iter = ((PersistentList) obj).iterator(); answers = new ArrayList<String>(); while(iter.hasNext()){ answers.add((String) iter.next()); } } else answers = (ArrayList<String>) session.getAttribute("answers"); obj = session.getAttribute("columns"); ArrayList<String> columns = null; if(obj instanceof PersistentList){ Iterator iter = ((PersistentList) obj).iterator(); columns = new ArrayList<String>(); while(iter.hasNext()){ columns.add((String) iter.next()); } } else columns = (ArrayList<String>) session.getAttribute("columns"); | public void updateMatrixQuestionInSection(HttpServletRequest request){ HttpSession session = request.getSession(); Section section = (Section) session.getAttribute("currentSection"); String name = request.getParameter("name"); String image = request.getParameter("image"); String questionText = request.getParameter("questionTxt"); int rowId = Integer.parseInt(request.getParameter("row")); rowId--; ArrayList<String> answers = (ArrayList<String>) session.getAttribute("answers"); ArrayList<String> columns = (ArrayList<String>) session.getAttribute("columns"); // now parse different params depending on the type RadioMatrixQuestion question = new RadioMatrixQuestion(columns.size(), answers.size()); question.setDescription(questionText); question.setSection(section); question.setTitle(name); question.setItems(answers); question.setColumnsTitles(columns); question.setImage(image); List<Question> quests = section.getQuestions(); quests.set(rowId, question); section.setQuestions(quests); session.setAttribute("currentSection", section); session.removeAttribute("answers"); session.removeAttribute("columns"); } |
ArrayList<String> answers = (ArrayList<String>) session.getAttribute("answers"); | Object obj = session.getAttribute("answers"); ArrayList<String> answers = null; if(obj instanceof PersistentList){ Iterator iter = ((PersistentList) obj).iterator(); answers = new ArrayList<String>(); while(iter.hasNext()){ answers.add((String) iter.next()); } } else answers = (ArrayList<String>) session.getAttribute("answers"); | public void updateNumericQuestionInSection(HttpServletRequest request){ HttpSession session = request.getSession(); Section section = (Section) session.getAttribute("currentSection"); String name = request.getParameter("name"); String image = request.getParameter("image"); String validationType = request.getParameter("validationType"); String min = request.getParameter("min"); String max = request.getParameter("max"); String total = request.getParameter("total"); String questionText = request.getParameter("questionTxt"); int rowId = Integer.parseInt(request.getParameter("row")); rowId--; ArrayList<String> answers = (ArrayList<String>) session.getAttribute("answers"); // now parse different params depending on the type NumberListQuestion question = new NumberListQuestion(answers.size()); question.setDescription(questionText); question.setSection(section); question.setTitle(name); question.setItems(answers); if(validationType.equals("individual")){ question.setMin(Integer.parseInt(min)); question.setMax(Integer.parseInt(max)); } else if (validationType.equals("total")){ question.setTotal(Integer.parseInt(total)); } question.setImage(image); List<Question> quests = section.getQuestions(); quests.set(rowId, question); section.setQuestions(quests); session.setAttribute("currentSection", section); session.removeAttribute("answers"); } |
question.setValidationType(validationType); | public void updateNumericQuestionInSection(HttpServletRequest request){ HttpSession session = request.getSession(); Section section = (Section) session.getAttribute("currentSection"); String name = request.getParameter("name"); String image = request.getParameter("image"); String validationType = request.getParameter("validationType"); String min = request.getParameter("min"); String max = request.getParameter("max"); String total = request.getParameter("total"); String questionText = request.getParameter("questionTxt"); int rowId = Integer.parseInt(request.getParameter("row")); rowId--; ArrayList<String> answers = (ArrayList<String>) session.getAttribute("answers"); // now parse different params depending on the type NumberListQuestion question = new NumberListQuestion(answers.size()); question.setDescription(questionText); question.setSection(section); question.setTitle(name); question.setItems(answers); if(validationType.equals("individual")){ question.setMin(Integer.parseInt(min)); question.setMax(Integer.parseInt(max)); } else if (validationType.equals("total")){ question.setTotal(Integer.parseInt(total)); } question.setImage(image); List<Question> quests = section.getQuestions(); quests.set(rowId, question); section.setQuestions(quests); session.setAttribute("currentSection", section); session.removeAttribute("answers"); } |
|
if(sform.getFlowScript()!=null && sform.getFlowScript().length()>0){ | if(sform.getMethod().equals("addSection")){ | public void updateSessionSurvey(HttpServletRequest request, SurveyForm sform){ Survey survey = null; HttpSession session = request.getSession(); if(sform.getFlowScript()!=null && sform.getFlowScript().length()>0){ // add a new section survey = addSectionToSurvey(request, sform); } else { // set survey's values survey = updateSessionSurveyValues(request, sform); } session.setAttribute("currentSurvey", survey); Section section = new Section(); session.setAttribute("currentSection", section); } |
ArrayList<String> answers = (ArrayList<String>) session.getAttribute("answers"); | ArrayList<String> answers; Object obj = session.getAttribute("answers"); PersistentList persist = null; if(obj instanceof PersistentList){ persist = (PersistentList) obj; answers = new ArrayList<String>(); Iterator iter = persist.iterator(); while(iter.hasNext()){ answers.add((String) iter.next()); } } else answers = (ArrayList<String>) obj; | public void updateStringListQuestionInSection(HttpServletRequest request){ HttpSession session = request.getSession(); Section section = (Section) session.getAttribute("currentSection"); String name = request.getParameter("name"); String image = request.getParameter("image"); String questionText = request.getParameter("questionTxt"); int rowId = Integer.parseInt(request.getParameter("row")); rowId--; ArrayList<String> answers = (ArrayList<String>) session.getAttribute("answers"); // now parse different params depending on the type StringListQuestion question = new StringListQuestion(); question.setDescription(questionText); question.setSection(section); question.setTitle(name); question.setItems(answers); question.setImage(image); List<Question> quests = section.getQuestions(); quests.set(rowId, question); section.setQuestions(quests); session.setAttribute("currentSection", section); session.removeAttribute("answers"); } |
buffer = new byte[4096]; | buffer = new byte[BUFSIZE]; | ReaderToUTF8Stream(LimitReader reader) { this.reader = reader; buffer = new byte[4096]; blen = -1; } |
private static void testAutoCommitFailure(Connection con) throws SQLException { DatabaseMetaData dmd = con.getMetaData(); boolean shouldBeClosed = dmd.autoCommitFailureClosesAllResultSets(); | public void testAutoCommitFailure() throws SQLException { Connection con = getConnection(); | private static void testAutoCommitFailure(Connection con) throws SQLException { DatabaseMetaData dmd = con.getMetaData(); boolean shouldBeClosed = dmd.autoCommitFailureClosesAllResultSets(); con.setAutoCommit(true); Statement s1 = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT); ResultSet resultSet = s1.executeQuery("VALUES (1, 2), (3, 4)"); Statement s2 = con.createStatement(); try { String query = "SELECT dummy, nonexistent, phony FROM imaginarytable34521"; s2.execute(query); System.out.println("\"" + query + "\" is expected to fail, " + "but it didn't."); } catch (SQLException e) { // should fail, but we don't care how } boolean isClosed = resultSet.isClosed(); if (isClosed != shouldBeClosed) { System.out.println("autoCommitFailureClosesAllResultSets() " + "returned " + shouldBeClosed + ", but ResultSet is " + (isClosed ? "closed." : "not closed.")); } resultSet.close(); s1.close(); s2.close(); } |
System.out.println("\"" + query + "\" is expected to fail, " + "but it didn't."); | fail("Query didn't fail."); | private static void testAutoCommitFailure(Connection con) throws SQLException { DatabaseMetaData dmd = con.getMetaData(); boolean shouldBeClosed = dmd.autoCommitFailureClosesAllResultSets(); con.setAutoCommit(true); Statement s1 = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT); ResultSet resultSet = s1.executeQuery("VALUES (1, 2), (3, 4)"); Statement s2 = con.createStatement(); try { String query = "SELECT dummy, nonexistent, phony FROM imaginarytable34521"; s2.execute(query); System.out.println("\"" + query + "\" is expected to fail, " + "but it didn't."); } catch (SQLException e) { // should fail, but we don't care how } boolean isClosed = resultSet.isClosed(); if (isClosed != shouldBeClosed) { System.out.println("autoCommitFailureClosesAllResultSets() " + "returned " + shouldBeClosed + ", but ResultSet is " + (isClosed ? "closed." : "not closed.")); } resultSet.close(); s1.close(); s2.close(); } |
boolean isClosed = resultSet.isClosed(); if (isClosed != shouldBeClosed) { System.out.println("autoCommitFailureClosesAllResultSets() " + "returned " + shouldBeClosed + ", but ResultSet is " + (isClosed ? "closed." : "not closed.")); } | assertEquals("autoCommitFailureClosesAllResultSets() returned value " + "which doesn't match actual behaviour.", resultSet.isClosed(), meta.autoCommitFailureClosesAllResultSets()); | private static void testAutoCommitFailure(Connection con) throws SQLException { DatabaseMetaData dmd = con.getMetaData(); boolean shouldBeClosed = dmd.autoCommitFailureClosesAllResultSets(); con.setAutoCommit(true); Statement s1 = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT); ResultSet resultSet = s1.executeQuery("VALUES (1, 2), (3, 4)"); Statement s2 = con.createStatement(); try { String query = "SELECT dummy, nonexistent, phony FROM imaginarytable34521"; s2.execute(query); System.out.println("\"" + query + "\" is expected to fail, " + "but it didn't."); } catch (SQLException e) { // should fail, but we don't care how } boolean isClosed = resultSet.isClosed(); if (isClosed != shouldBeClosed) { System.out.println("autoCommitFailureClosesAllResultSets() " + "returned " + shouldBeClosed + ", but ResultSet is " + (isClosed ? "closed." : "not closed.")); } resultSet.close(); s1.close(); s2.close(); } |
private static void testStoredProcEscapeSyntax(Connection con) throws SQLException { con.setAutoCommit(false); | public void testStoredProcEscapeSyntax() throws SQLException { getConnection().setAutoCommit(false); | private static void testStoredProcEscapeSyntax(Connection con) throws SQLException { con.setAutoCommit(false); String call = "{CALL SYSCS_UTIL.SYSCS_SET_RUNTIMESTATISTICS(0)}"; Statement stmt = con.createStatement(); boolean success; try { stmt.execute(call); success = true; } catch (SQLException e) { success = false; } DatabaseMetaData dmd = con.getMetaData(); boolean supported = dmd.supportsStoredFunctionsUsingCallSyntax(); if (success != supported) { System.out.println("supportsStoredFunctionsUsingCallSyntax() " + "returned " + supported + ", but executing " + call + (success ? " succeeded." : " failed.")); } stmt.close(); con.rollback(); } |
Statement stmt = con.createStatement(); | Statement stmt = createStatement(); | private static void testStoredProcEscapeSyntax(Connection con) throws SQLException { con.setAutoCommit(false); String call = "{CALL SYSCS_UTIL.SYSCS_SET_RUNTIMESTATISTICS(0)}"; Statement stmt = con.createStatement(); boolean success; try { stmt.execute(call); success = true; } catch (SQLException e) { success = false; } DatabaseMetaData dmd = con.getMetaData(); boolean supported = dmd.supportsStoredFunctionsUsingCallSyntax(); if (success != supported) { System.out.println("supportsStoredFunctionsUsingCallSyntax() " + "returned " + supported + ", but executing " + call + (success ? " succeeded." : " failed.")); } stmt.close(); con.rollback(); } |
DatabaseMetaData dmd = con.getMetaData(); boolean supported = dmd.supportsStoredFunctionsUsingCallSyntax(); if (success != supported) { System.out.println("supportsStoredFunctionsUsingCallSyntax() " + "returned " + supported + ", but executing " + call + (success ? " succeeded." : " failed.")); } | assertEquals("supportsStoredFunctionsUsingCallSyntax() returned " + "value which doesn't match actual behaviour.", success, meta.supportsStoredFunctionsUsingCallSyntax()); | private static void testStoredProcEscapeSyntax(Connection con) throws SQLException { con.setAutoCommit(false); String call = "{CALL SYSCS_UTIL.SYSCS_SET_RUNTIMESTATISTICS(0)}"; Statement stmt = con.createStatement(); boolean success; try { stmt.execute(call); success = true; } catch (SQLException e) { success = false; } DatabaseMetaData dmd = con.getMetaData(); boolean supported = dmd.supportsStoredFunctionsUsingCallSyntax(); if (success != supported) { System.out.println("supportsStoredFunctionsUsingCallSyntax() " + "returned " + supported + ", but executing " + call + (success ? " succeeded." : " failed.")); } stmt.close(); con.rollback(); } |
con.rollback(); | private static void testStoredProcEscapeSyntax(Connection con) throws SQLException { con.setAutoCommit(false); String call = "{CALL SYSCS_UTIL.SYSCS_SET_RUNTIMESTATISTICS(0)}"; Statement stmt = con.createStatement(); boolean success; try { stmt.execute(call); success = true; } catch (SQLException e) { success = false; } DatabaseMetaData dmd = con.getMetaData(); boolean supported = dmd.supportsStoredFunctionsUsingCallSyntax(); if (success != supported) { System.out.println("supportsStoredFunctionsUsingCallSyntax() " + "returned " + supported + ", but executing " + call + (success ? " succeeded." : " failed.")); } stmt.close(); con.rollback(); } |
|
mb.callMethod(VMOpcode.INVOKEVIRTUAL, (String) null, "getParameter", | mb.callMethod(VMOpcode.INVOKEVIRTUAL, ClassName.BaseActivation, "getParameter", | public void generateExpression(ExpressionClassBuilder acb, MethodBuilder mb) throws StandardException { DataTypeDescriptor dtd = getTypeServices(); if ((dtd != null) && dtd.getTypeId().isXMLTypeId()) { // We're a parameter that corresponds to an XML column/target, // which we don't allow. We throw the error here instead of // in "bindExpression" because at the time of bindExpression, // we don't know yet what the type is going to be (only when // the node that points to this parameter calls // "setType" do we figure out the type). throw StandardException.newException( SQLState.LANG_ATTEMPT_TO_BIND_XML); } // PUSHCOMPILE /* Reuse code if possible */ //if (genRetval != null) // return genRetval; /* Generate the return value */ mb.pushThis(); mb.push(parameterNumber); // arg mb.callMethod(VMOpcode.INVOKEVIRTUAL, (String) null, "getParameter", ClassName.DataValueDescriptor, 1); // For some types perform host variable checking // to match DB2/JCC where if a host variable is too // big it is not accepted, regardless of any trailing padding. switch (dtd.getJDBCTypeId()) { case Types.BINARY: case Types.VARBINARY: case Types.LONGVARBINARY: case Types.BLOB: mb.dup(); mb.push(dtd.getMaximumWidth()); mb.callMethod(VMOpcode.INVOKEINTERFACE, (String) null, "checkHostVariable", "void", 1); break; default: break; } /* Cast the result to its specific interface */ mb.cast(getTypeCompiler().interfaceName()); } // End of generateExpression |
Vector paramDrdaTypes = new Vector(); Vector paramLens = new Vector(); ArrayList paramExtPositions = null; | stmt.clearDrdaParams(); | private void parseSQLDTA_work(DRDAStatement stmt) throws DRDAProtocolException,SQLException { String strVal; PreparedStatement ps = stmt.getPreparedStatement(); int codePoint; EngineParameterMetaData pmeta = null; Vector paramDrdaTypes = new Vector(); Vector paramLens = new Vector(); ArrayList paramExtPositions = null; int numVars = 0; boolean rtnParam = false; reader.markCollection(); codePoint = reader.getCodePoint(); while (codePoint != -1) { switch (codePoint) { // required case CodePoint.FDODSC: while (reader.getDdmLength() > 6) //we get parameter info til last 6 byte { int dtaGrpLen = reader.readUnsignedByte(); int numVarsInGrp = (dtaGrpLen - 3) / 3; if (SanityManager.DEBUG) trace("num of vars in this group is: "+numVarsInGrp); reader.readByte(); // tripletType reader.readByte(); // id for (int j = 0; j < numVarsInGrp; j++) { paramDrdaTypes.addElement(new Byte(reader.readByte())); if (SanityManager.DEBUG) trace("drdaType is: "+ "0x" + Integer.toHexString(((Byte ) paramDrdaTypes.lastElement()).byteValue())); int drdaLength = reader.readNetworkShort(); if (SanityManager.DEBUG) trace("drdaLength is: "+drdaLength); paramLens.addElement(new Integer(drdaLength)); } } numVars = paramDrdaTypes.size(); if (SanityManager.DEBUG) trace("numVars = " + numVars); if (ps == null) // it is a CallableStatement under construction { String marks = "(?"; // construct parameter marks for (int i = 1; i < numVars; i++) marks += ", ?"; String prepareString = "call " + stmt.procName + marks + ")"; if (SanityManager.DEBUG) trace ("$$ prepareCall is: "+prepareString); CallableStatement cs = null; try { cs = (CallableStatement) stmt.prepare(prepareString); stmt.registerAllOutParams(); } catch (SQLException se) { if (! stmt.outputExpected || (!se.getSQLState().equals(SQLState.LANG_NO_METHOD_FOUND))) throw se; if (SanityManager.DEBUG) trace("****** second try with return parameter..."); // Save first SQLException most likely suspect if (numVars == 1) prepareString = "? = call " + stmt.procName +"()"; else prepareString = "? = call " + stmt.procName +"("+marks.substring(3) + ")"; if (SanityManager.DEBUG) trace ("$$ prepareCall is: "+prepareString); try { cs = (CallableStatement) stmt.prepare(prepareString); } catch (SQLException se2) { // The first exception is the most likely suspect throw se; } rtnParam = true; } ps = cs; stmt.ps = ps; } pmeta = stmt.getParameterMetaData(); reader.readBytes(6); // descriptor footer break; // optional case CodePoint.FDODTA: reader.readByte(); // row indicator for (int i = 0; i < numVars; i++) { if ((((Byte)paramDrdaTypes.elementAt(i)).byteValue() & 0x1) == 0x1) // nullable { int nullData = reader.readUnsignedByte(); if ((nullData & 0xFF) == FdocaConstants.NULL_DATA) { if (SanityManager.DEBUG) trace("******param null"); if (pmeta.getParameterMode(i + 1) != JDBC30Translation.PARAMETER_MODE_OUT ) ps.setNull(i+1, pmeta.getParameterType(i+1)); if (stmt.isOutputParam(i+1)) stmt.registerOutParam(i+1); continue; } } // not null, read and set it paramExtPositions = readAndSetParams(i, stmt, ((Byte)paramDrdaTypes.elementAt(i)).byteValue(), pmeta, paramExtPositions, ((Integer)(paramLens.elementAt(i))).intValue()); } stmt.cliParamExtPositions = paramExtPositions; stmt.cliParamDrdaTypes = paramDrdaTypes; stmt.cliParamLens = paramLens; break; case CodePoint.EXTDTA: readAndSetAllExtParams(stmt, false); break; default: invalidCodePoint(codePoint); } codePoint = reader.getCodePoint(); } } |
paramDrdaTypes.addElement(new Byte(reader.readByte())); | final byte t = reader.readByte(); | private void parseSQLDTA_work(DRDAStatement stmt) throws DRDAProtocolException,SQLException { String strVal; PreparedStatement ps = stmt.getPreparedStatement(); int codePoint; EngineParameterMetaData pmeta = null; Vector paramDrdaTypes = new Vector(); Vector paramLens = new Vector(); ArrayList paramExtPositions = null; int numVars = 0; boolean rtnParam = false; reader.markCollection(); codePoint = reader.getCodePoint(); while (codePoint != -1) { switch (codePoint) { // required case CodePoint.FDODSC: while (reader.getDdmLength() > 6) //we get parameter info til last 6 byte { int dtaGrpLen = reader.readUnsignedByte(); int numVarsInGrp = (dtaGrpLen - 3) / 3; if (SanityManager.DEBUG) trace("num of vars in this group is: "+numVarsInGrp); reader.readByte(); // tripletType reader.readByte(); // id for (int j = 0; j < numVarsInGrp; j++) { paramDrdaTypes.addElement(new Byte(reader.readByte())); if (SanityManager.DEBUG) trace("drdaType is: "+ "0x" + Integer.toHexString(((Byte ) paramDrdaTypes.lastElement()).byteValue())); int drdaLength = reader.readNetworkShort(); if (SanityManager.DEBUG) trace("drdaLength is: "+drdaLength); paramLens.addElement(new Integer(drdaLength)); } } numVars = paramDrdaTypes.size(); if (SanityManager.DEBUG) trace("numVars = " + numVars); if (ps == null) // it is a CallableStatement under construction { String marks = "(?"; // construct parameter marks for (int i = 1; i < numVars; i++) marks += ", ?"; String prepareString = "call " + stmt.procName + marks + ")"; if (SanityManager.DEBUG) trace ("$$ prepareCall is: "+prepareString); CallableStatement cs = null; try { cs = (CallableStatement) stmt.prepare(prepareString); stmt.registerAllOutParams(); } catch (SQLException se) { if (! stmt.outputExpected || (!se.getSQLState().equals(SQLState.LANG_NO_METHOD_FOUND))) throw se; if (SanityManager.DEBUG) trace("****** second try with return parameter..."); // Save first SQLException most likely suspect if (numVars == 1) prepareString = "? = call " + stmt.procName +"()"; else prepareString = "? = call " + stmt.procName +"("+marks.substring(3) + ")"; if (SanityManager.DEBUG) trace ("$$ prepareCall is: "+prepareString); try { cs = (CallableStatement) stmt.prepare(prepareString); } catch (SQLException se2) { // The first exception is the most likely suspect throw se; } rtnParam = true; } ps = cs; stmt.ps = ps; } pmeta = stmt.getParameterMetaData(); reader.readBytes(6); // descriptor footer break; // optional case CodePoint.FDODTA: reader.readByte(); // row indicator for (int i = 0; i < numVars; i++) { if ((((Byte)paramDrdaTypes.elementAt(i)).byteValue() & 0x1) == 0x1) // nullable { int nullData = reader.readUnsignedByte(); if ((nullData & 0xFF) == FdocaConstants.NULL_DATA) { if (SanityManager.DEBUG) trace("******param null"); if (pmeta.getParameterMode(i + 1) != JDBC30Translation.PARAMETER_MODE_OUT ) ps.setNull(i+1, pmeta.getParameterType(i+1)); if (stmt.isOutputParam(i+1)) stmt.registerOutParam(i+1); continue; } } // not null, read and set it paramExtPositions = readAndSetParams(i, stmt, ((Byte)paramDrdaTypes.elementAt(i)).byteValue(), pmeta, paramExtPositions, ((Integer)(paramLens.elementAt(i))).intValue()); } stmt.cliParamExtPositions = paramExtPositions; stmt.cliParamDrdaTypes = paramDrdaTypes; stmt.cliParamLens = paramLens; break; case CodePoint.EXTDTA: readAndSetAllExtParams(stmt, false); break; default: invalidCodePoint(codePoint); } codePoint = reader.getCodePoint(); } } |
Integer.toHexString(((Byte ) paramDrdaTypes.lastElement()).byteValue())); | Integer.toHexString(t)); | private void parseSQLDTA_work(DRDAStatement stmt) throws DRDAProtocolException,SQLException { String strVal; PreparedStatement ps = stmt.getPreparedStatement(); int codePoint; EngineParameterMetaData pmeta = null; Vector paramDrdaTypes = new Vector(); Vector paramLens = new Vector(); ArrayList paramExtPositions = null; int numVars = 0; boolean rtnParam = false; reader.markCollection(); codePoint = reader.getCodePoint(); while (codePoint != -1) { switch (codePoint) { // required case CodePoint.FDODSC: while (reader.getDdmLength() > 6) //we get parameter info til last 6 byte { int dtaGrpLen = reader.readUnsignedByte(); int numVarsInGrp = (dtaGrpLen - 3) / 3; if (SanityManager.DEBUG) trace("num of vars in this group is: "+numVarsInGrp); reader.readByte(); // tripletType reader.readByte(); // id for (int j = 0; j < numVarsInGrp; j++) { paramDrdaTypes.addElement(new Byte(reader.readByte())); if (SanityManager.DEBUG) trace("drdaType is: "+ "0x" + Integer.toHexString(((Byte ) paramDrdaTypes.lastElement()).byteValue())); int drdaLength = reader.readNetworkShort(); if (SanityManager.DEBUG) trace("drdaLength is: "+drdaLength); paramLens.addElement(new Integer(drdaLength)); } } numVars = paramDrdaTypes.size(); if (SanityManager.DEBUG) trace("numVars = " + numVars); if (ps == null) // it is a CallableStatement under construction { String marks = "(?"; // construct parameter marks for (int i = 1; i < numVars; i++) marks += ", ?"; String prepareString = "call " + stmt.procName + marks + ")"; if (SanityManager.DEBUG) trace ("$$ prepareCall is: "+prepareString); CallableStatement cs = null; try { cs = (CallableStatement) stmt.prepare(prepareString); stmt.registerAllOutParams(); } catch (SQLException se) { if (! stmt.outputExpected || (!se.getSQLState().equals(SQLState.LANG_NO_METHOD_FOUND))) throw se; if (SanityManager.DEBUG) trace("****** second try with return parameter..."); // Save first SQLException most likely suspect if (numVars == 1) prepareString = "? = call " + stmt.procName +"()"; else prepareString = "? = call " + stmt.procName +"("+marks.substring(3) + ")"; if (SanityManager.DEBUG) trace ("$$ prepareCall is: "+prepareString); try { cs = (CallableStatement) stmt.prepare(prepareString); } catch (SQLException se2) { // The first exception is the most likely suspect throw se; } rtnParam = true; } ps = cs; stmt.ps = ps; } pmeta = stmt.getParameterMetaData(); reader.readBytes(6); // descriptor footer break; // optional case CodePoint.FDODTA: reader.readByte(); // row indicator for (int i = 0; i < numVars; i++) { if ((((Byte)paramDrdaTypes.elementAt(i)).byteValue() & 0x1) == 0x1) // nullable { int nullData = reader.readUnsignedByte(); if ((nullData & 0xFF) == FdocaConstants.NULL_DATA) { if (SanityManager.DEBUG) trace("******param null"); if (pmeta.getParameterMode(i + 1) != JDBC30Translation.PARAMETER_MODE_OUT ) ps.setNull(i+1, pmeta.getParameterType(i+1)); if (stmt.isOutputParam(i+1)) stmt.registerOutParam(i+1); continue; } } // not null, read and set it paramExtPositions = readAndSetParams(i, stmt, ((Byte)paramDrdaTypes.elementAt(i)).byteValue(), pmeta, paramExtPositions, ((Integer)(paramLens.elementAt(i))).intValue()); } stmt.cliParamExtPositions = paramExtPositions; stmt.cliParamDrdaTypes = paramDrdaTypes; stmt.cliParamLens = paramLens; break; case CodePoint.EXTDTA: readAndSetAllExtParams(stmt, false); break; default: invalidCodePoint(codePoint); } codePoint = reader.getCodePoint(); } } |
paramLens.addElement(new Integer(drdaLength)); | stmt.addDrdaParam(t, drdaLength); | private void parseSQLDTA_work(DRDAStatement stmt) throws DRDAProtocolException,SQLException { String strVal; PreparedStatement ps = stmt.getPreparedStatement(); int codePoint; EngineParameterMetaData pmeta = null; Vector paramDrdaTypes = new Vector(); Vector paramLens = new Vector(); ArrayList paramExtPositions = null; int numVars = 0; boolean rtnParam = false; reader.markCollection(); codePoint = reader.getCodePoint(); while (codePoint != -1) { switch (codePoint) { // required case CodePoint.FDODSC: while (reader.getDdmLength() > 6) //we get parameter info til last 6 byte { int dtaGrpLen = reader.readUnsignedByte(); int numVarsInGrp = (dtaGrpLen - 3) / 3; if (SanityManager.DEBUG) trace("num of vars in this group is: "+numVarsInGrp); reader.readByte(); // tripletType reader.readByte(); // id for (int j = 0; j < numVarsInGrp; j++) { paramDrdaTypes.addElement(new Byte(reader.readByte())); if (SanityManager.DEBUG) trace("drdaType is: "+ "0x" + Integer.toHexString(((Byte ) paramDrdaTypes.lastElement()).byteValue())); int drdaLength = reader.readNetworkShort(); if (SanityManager.DEBUG) trace("drdaLength is: "+drdaLength); paramLens.addElement(new Integer(drdaLength)); } } numVars = paramDrdaTypes.size(); if (SanityManager.DEBUG) trace("numVars = " + numVars); if (ps == null) // it is a CallableStatement under construction { String marks = "(?"; // construct parameter marks for (int i = 1; i < numVars; i++) marks += ", ?"; String prepareString = "call " + stmt.procName + marks + ")"; if (SanityManager.DEBUG) trace ("$$ prepareCall is: "+prepareString); CallableStatement cs = null; try { cs = (CallableStatement) stmt.prepare(prepareString); stmt.registerAllOutParams(); } catch (SQLException se) { if (! stmt.outputExpected || (!se.getSQLState().equals(SQLState.LANG_NO_METHOD_FOUND))) throw se; if (SanityManager.DEBUG) trace("****** second try with return parameter..."); // Save first SQLException most likely suspect if (numVars == 1) prepareString = "? = call " + stmt.procName +"()"; else prepareString = "? = call " + stmt.procName +"("+marks.substring(3) + ")"; if (SanityManager.DEBUG) trace ("$$ prepareCall is: "+prepareString); try { cs = (CallableStatement) stmt.prepare(prepareString); } catch (SQLException se2) { // The first exception is the most likely suspect throw se; } rtnParam = true; } ps = cs; stmt.ps = ps; } pmeta = stmt.getParameterMetaData(); reader.readBytes(6); // descriptor footer break; // optional case CodePoint.FDODTA: reader.readByte(); // row indicator for (int i = 0; i < numVars; i++) { if ((((Byte)paramDrdaTypes.elementAt(i)).byteValue() & 0x1) == 0x1) // nullable { int nullData = reader.readUnsignedByte(); if ((nullData & 0xFF) == FdocaConstants.NULL_DATA) { if (SanityManager.DEBUG) trace("******param null"); if (pmeta.getParameterMode(i + 1) != JDBC30Translation.PARAMETER_MODE_OUT ) ps.setNull(i+1, pmeta.getParameterType(i+1)); if (stmt.isOutputParam(i+1)) stmt.registerOutParam(i+1); continue; } } // not null, read and set it paramExtPositions = readAndSetParams(i, stmt, ((Byte)paramDrdaTypes.elementAt(i)).byteValue(), pmeta, paramExtPositions, ((Integer)(paramLens.elementAt(i))).intValue()); } stmt.cliParamExtPositions = paramExtPositions; stmt.cliParamDrdaTypes = paramDrdaTypes; stmt.cliParamLens = paramLens; break; case CodePoint.EXTDTA: readAndSetAllExtParams(stmt, false); break; default: invalidCodePoint(codePoint); } codePoint = reader.getCodePoint(); } } |
numVars = paramDrdaTypes.size(); | numVars = stmt.getDrdaParamCount(); | private void parseSQLDTA_work(DRDAStatement stmt) throws DRDAProtocolException,SQLException { String strVal; PreparedStatement ps = stmt.getPreparedStatement(); int codePoint; EngineParameterMetaData pmeta = null; Vector paramDrdaTypes = new Vector(); Vector paramLens = new Vector(); ArrayList paramExtPositions = null; int numVars = 0; boolean rtnParam = false; reader.markCollection(); codePoint = reader.getCodePoint(); while (codePoint != -1) { switch (codePoint) { // required case CodePoint.FDODSC: while (reader.getDdmLength() > 6) //we get parameter info til last 6 byte { int dtaGrpLen = reader.readUnsignedByte(); int numVarsInGrp = (dtaGrpLen - 3) / 3; if (SanityManager.DEBUG) trace("num of vars in this group is: "+numVarsInGrp); reader.readByte(); // tripletType reader.readByte(); // id for (int j = 0; j < numVarsInGrp; j++) { paramDrdaTypes.addElement(new Byte(reader.readByte())); if (SanityManager.DEBUG) trace("drdaType is: "+ "0x" + Integer.toHexString(((Byte ) paramDrdaTypes.lastElement()).byteValue())); int drdaLength = reader.readNetworkShort(); if (SanityManager.DEBUG) trace("drdaLength is: "+drdaLength); paramLens.addElement(new Integer(drdaLength)); } } numVars = paramDrdaTypes.size(); if (SanityManager.DEBUG) trace("numVars = " + numVars); if (ps == null) // it is a CallableStatement under construction { String marks = "(?"; // construct parameter marks for (int i = 1; i < numVars; i++) marks += ", ?"; String prepareString = "call " + stmt.procName + marks + ")"; if (SanityManager.DEBUG) trace ("$$ prepareCall is: "+prepareString); CallableStatement cs = null; try { cs = (CallableStatement) stmt.prepare(prepareString); stmt.registerAllOutParams(); } catch (SQLException se) { if (! stmt.outputExpected || (!se.getSQLState().equals(SQLState.LANG_NO_METHOD_FOUND))) throw se; if (SanityManager.DEBUG) trace("****** second try with return parameter..."); // Save first SQLException most likely suspect if (numVars == 1) prepareString = "? = call " + stmt.procName +"()"; else prepareString = "? = call " + stmt.procName +"("+marks.substring(3) + ")"; if (SanityManager.DEBUG) trace ("$$ prepareCall is: "+prepareString); try { cs = (CallableStatement) stmt.prepare(prepareString); } catch (SQLException se2) { // The first exception is the most likely suspect throw se; } rtnParam = true; } ps = cs; stmt.ps = ps; } pmeta = stmt.getParameterMetaData(); reader.readBytes(6); // descriptor footer break; // optional case CodePoint.FDODTA: reader.readByte(); // row indicator for (int i = 0; i < numVars; i++) { if ((((Byte)paramDrdaTypes.elementAt(i)).byteValue() & 0x1) == 0x1) // nullable { int nullData = reader.readUnsignedByte(); if ((nullData & 0xFF) == FdocaConstants.NULL_DATA) { if (SanityManager.DEBUG) trace("******param null"); if (pmeta.getParameterMode(i + 1) != JDBC30Translation.PARAMETER_MODE_OUT ) ps.setNull(i+1, pmeta.getParameterType(i+1)); if (stmt.isOutputParam(i+1)) stmt.registerOutParam(i+1); continue; } } // not null, read and set it paramExtPositions = readAndSetParams(i, stmt, ((Byte)paramDrdaTypes.elementAt(i)).byteValue(), pmeta, paramExtPositions, ((Integer)(paramLens.elementAt(i))).intValue()); } stmt.cliParamExtPositions = paramExtPositions; stmt.cliParamDrdaTypes = paramDrdaTypes; stmt.cliParamLens = paramLens; break; case CodePoint.EXTDTA: readAndSetAllExtParams(stmt, false); break; default: invalidCodePoint(codePoint); } codePoint = reader.getCodePoint(); } } |
if ((((Byte)paramDrdaTypes.elementAt(i)).byteValue() & 0x1) == 0x1) | if ((stmt.getParamDRDAType(i+1) & 0x1) == 0x1) | private void parseSQLDTA_work(DRDAStatement stmt) throws DRDAProtocolException,SQLException { String strVal; PreparedStatement ps = stmt.getPreparedStatement(); int codePoint; EngineParameterMetaData pmeta = null; Vector paramDrdaTypes = new Vector(); Vector paramLens = new Vector(); ArrayList paramExtPositions = null; int numVars = 0; boolean rtnParam = false; reader.markCollection(); codePoint = reader.getCodePoint(); while (codePoint != -1) { switch (codePoint) { // required case CodePoint.FDODSC: while (reader.getDdmLength() > 6) //we get parameter info til last 6 byte { int dtaGrpLen = reader.readUnsignedByte(); int numVarsInGrp = (dtaGrpLen - 3) / 3; if (SanityManager.DEBUG) trace("num of vars in this group is: "+numVarsInGrp); reader.readByte(); // tripletType reader.readByte(); // id for (int j = 0; j < numVarsInGrp; j++) { paramDrdaTypes.addElement(new Byte(reader.readByte())); if (SanityManager.DEBUG) trace("drdaType is: "+ "0x" + Integer.toHexString(((Byte ) paramDrdaTypes.lastElement()).byteValue())); int drdaLength = reader.readNetworkShort(); if (SanityManager.DEBUG) trace("drdaLength is: "+drdaLength); paramLens.addElement(new Integer(drdaLength)); } } numVars = paramDrdaTypes.size(); if (SanityManager.DEBUG) trace("numVars = " + numVars); if (ps == null) // it is a CallableStatement under construction { String marks = "(?"; // construct parameter marks for (int i = 1; i < numVars; i++) marks += ", ?"; String prepareString = "call " + stmt.procName + marks + ")"; if (SanityManager.DEBUG) trace ("$$ prepareCall is: "+prepareString); CallableStatement cs = null; try { cs = (CallableStatement) stmt.prepare(prepareString); stmt.registerAllOutParams(); } catch (SQLException se) { if (! stmt.outputExpected || (!se.getSQLState().equals(SQLState.LANG_NO_METHOD_FOUND))) throw se; if (SanityManager.DEBUG) trace("****** second try with return parameter..."); // Save first SQLException most likely suspect if (numVars == 1) prepareString = "? = call " + stmt.procName +"()"; else prepareString = "? = call " + stmt.procName +"("+marks.substring(3) + ")"; if (SanityManager.DEBUG) trace ("$$ prepareCall is: "+prepareString); try { cs = (CallableStatement) stmt.prepare(prepareString); } catch (SQLException se2) { // The first exception is the most likely suspect throw se; } rtnParam = true; } ps = cs; stmt.ps = ps; } pmeta = stmt.getParameterMetaData(); reader.readBytes(6); // descriptor footer break; // optional case CodePoint.FDODTA: reader.readByte(); // row indicator for (int i = 0; i < numVars; i++) { if ((((Byte)paramDrdaTypes.elementAt(i)).byteValue() & 0x1) == 0x1) // nullable { int nullData = reader.readUnsignedByte(); if ((nullData & 0xFF) == FdocaConstants.NULL_DATA) { if (SanityManager.DEBUG) trace("******param null"); if (pmeta.getParameterMode(i + 1) != JDBC30Translation.PARAMETER_MODE_OUT ) ps.setNull(i+1, pmeta.getParameterType(i+1)); if (stmt.isOutputParam(i+1)) stmt.registerOutParam(i+1); continue; } } // not null, read and set it paramExtPositions = readAndSetParams(i, stmt, ((Byte)paramDrdaTypes.elementAt(i)).byteValue(), pmeta, paramExtPositions, ((Integer)(paramLens.elementAt(i))).intValue()); } stmt.cliParamExtPositions = paramExtPositions; stmt.cliParamDrdaTypes = paramDrdaTypes; stmt.cliParamLens = paramLens; break; case CodePoint.EXTDTA: readAndSetAllExtParams(stmt, false); break; default: invalidCodePoint(codePoint); } codePoint = reader.getCodePoint(); } } |
paramExtPositions = readAndSetParams(i, stmt, ((Byte)paramDrdaTypes.elementAt(i)).byteValue(), pmeta, paramExtPositions, ((Integer)(paramLens.elementAt(i))).intValue()); | readAndSetParams(i, stmt, pmeta); | private void parseSQLDTA_work(DRDAStatement stmt) throws DRDAProtocolException,SQLException { String strVal; PreparedStatement ps = stmt.getPreparedStatement(); int codePoint; EngineParameterMetaData pmeta = null; Vector paramDrdaTypes = new Vector(); Vector paramLens = new Vector(); ArrayList paramExtPositions = null; int numVars = 0; boolean rtnParam = false; reader.markCollection(); codePoint = reader.getCodePoint(); while (codePoint != -1) { switch (codePoint) { // required case CodePoint.FDODSC: while (reader.getDdmLength() > 6) //we get parameter info til last 6 byte { int dtaGrpLen = reader.readUnsignedByte(); int numVarsInGrp = (dtaGrpLen - 3) / 3; if (SanityManager.DEBUG) trace("num of vars in this group is: "+numVarsInGrp); reader.readByte(); // tripletType reader.readByte(); // id for (int j = 0; j < numVarsInGrp; j++) { paramDrdaTypes.addElement(new Byte(reader.readByte())); if (SanityManager.DEBUG) trace("drdaType is: "+ "0x" + Integer.toHexString(((Byte ) paramDrdaTypes.lastElement()).byteValue())); int drdaLength = reader.readNetworkShort(); if (SanityManager.DEBUG) trace("drdaLength is: "+drdaLength); paramLens.addElement(new Integer(drdaLength)); } } numVars = paramDrdaTypes.size(); if (SanityManager.DEBUG) trace("numVars = " + numVars); if (ps == null) // it is a CallableStatement under construction { String marks = "(?"; // construct parameter marks for (int i = 1; i < numVars; i++) marks += ", ?"; String prepareString = "call " + stmt.procName + marks + ")"; if (SanityManager.DEBUG) trace ("$$ prepareCall is: "+prepareString); CallableStatement cs = null; try { cs = (CallableStatement) stmt.prepare(prepareString); stmt.registerAllOutParams(); } catch (SQLException se) { if (! stmt.outputExpected || (!se.getSQLState().equals(SQLState.LANG_NO_METHOD_FOUND))) throw se; if (SanityManager.DEBUG) trace("****** second try with return parameter..."); // Save first SQLException most likely suspect if (numVars == 1) prepareString = "? = call " + stmt.procName +"()"; else prepareString = "? = call " + stmt.procName +"("+marks.substring(3) + ")"; if (SanityManager.DEBUG) trace ("$$ prepareCall is: "+prepareString); try { cs = (CallableStatement) stmt.prepare(prepareString); } catch (SQLException se2) { // The first exception is the most likely suspect throw se; } rtnParam = true; } ps = cs; stmt.ps = ps; } pmeta = stmt.getParameterMetaData(); reader.readBytes(6); // descriptor footer break; // optional case CodePoint.FDODTA: reader.readByte(); // row indicator for (int i = 0; i < numVars; i++) { if ((((Byte)paramDrdaTypes.elementAt(i)).byteValue() & 0x1) == 0x1) // nullable { int nullData = reader.readUnsignedByte(); if ((nullData & 0xFF) == FdocaConstants.NULL_DATA) { if (SanityManager.DEBUG) trace("******param null"); if (pmeta.getParameterMode(i + 1) != JDBC30Translation.PARAMETER_MODE_OUT ) ps.setNull(i+1, pmeta.getParameterType(i+1)); if (stmt.isOutputParam(i+1)) stmt.registerOutParam(i+1); continue; } } // not null, read and set it paramExtPositions = readAndSetParams(i, stmt, ((Byte)paramDrdaTypes.elementAt(i)).byteValue(), pmeta, paramExtPositions, ((Integer)(paramLens.elementAt(i))).intValue()); } stmt.cliParamExtPositions = paramExtPositions; stmt.cliParamDrdaTypes = paramDrdaTypes; stmt.cliParamLens = paramLens; break; case CodePoint.EXTDTA: readAndSetAllExtParams(stmt, false); break; default: invalidCodePoint(codePoint); } codePoint = reader.getCodePoint(); } } |
stmt.cliParamExtPositions = paramExtPositions; stmt.cliParamDrdaTypes = paramDrdaTypes; stmt.cliParamLens = paramLens; | private void parseSQLDTA_work(DRDAStatement stmt) throws DRDAProtocolException,SQLException { String strVal; PreparedStatement ps = stmt.getPreparedStatement(); int codePoint; EngineParameterMetaData pmeta = null; Vector paramDrdaTypes = new Vector(); Vector paramLens = new Vector(); ArrayList paramExtPositions = null; int numVars = 0; boolean rtnParam = false; reader.markCollection(); codePoint = reader.getCodePoint(); while (codePoint != -1) { switch (codePoint) { // required case CodePoint.FDODSC: while (reader.getDdmLength() > 6) //we get parameter info til last 6 byte { int dtaGrpLen = reader.readUnsignedByte(); int numVarsInGrp = (dtaGrpLen - 3) / 3; if (SanityManager.DEBUG) trace("num of vars in this group is: "+numVarsInGrp); reader.readByte(); // tripletType reader.readByte(); // id for (int j = 0; j < numVarsInGrp; j++) { paramDrdaTypes.addElement(new Byte(reader.readByte())); if (SanityManager.DEBUG) trace("drdaType is: "+ "0x" + Integer.toHexString(((Byte ) paramDrdaTypes.lastElement()).byteValue())); int drdaLength = reader.readNetworkShort(); if (SanityManager.DEBUG) trace("drdaLength is: "+drdaLength); paramLens.addElement(new Integer(drdaLength)); } } numVars = paramDrdaTypes.size(); if (SanityManager.DEBUG) trace("numVars = " + numVars); if (ps == null) // it is a CallableStatement under construction { String marks = "(?"; // construct parameter marks for (int i = 1; i < numVars; i++) marks += ", ?"; String prepareString = "call " + stmt.procName + marks + ")"; if (SanityManager.DEBUG) trace ("$$ prepareCall is: "+prepareString); CallableStatement cs = null; try { cs = (CallableStatement) stmt.prepare(prepareString); stmt.registerAllOutParams(); } catch (SQLException se) { if (! stmt.outputExpected || (!se.getSQLState().equals(SQLState.LANG_NO_METHOD_FOUND))) throw se; if (SanityManager.DEBUG) trace("****** second try with return parameter..."); // Save first SQLException most likely suspect if (numVars == 1) prepareString = "? = call " + stmt.procName +"()"; else prepareString = "? = call " + stmt.procName +"("+marks.substring(3) + ")"; if (SanityManager.DEBUG) trace ("$$ prepareCall is: "+prepareString); try { cs = (CallableStatement) stmt.prepare(prepareString); } catch (SQLException se2) { // The first exception is the most likely suspect throw se; } rtnParam = true; } ps = cs; stmt.ps = ps; } pmeta = stmt.getParameterMetaData(); reader.readBytes(6); // descriptor footer break; // optional case CodePoint.FDODTA: reader.readByte(); // row indicator for (int i = 0; i < numVars; i++) { if ((((Byte)paramDrdaTypes.elementAt(i)).byteValue() & 0x1) == 0x1) // nullable { int nullData = reader.readUnsignedByte(); if ((nullData & 0xFF) == FdocaConstants.NULL_DATA) { if (SanityManager.DEBUG) trace("******param null"); if (pmeta.getParameterMode(i + 1) != JDBC30Translation.PARAMETER_MODE_OUT ) ps.setNull(i+1, pmeta.getParameterType(i+1)); if (stmt.isOutputParam(i+1)) stmt.registerOutParam(i+1); continue; } } // not null, read and set it paramExtPositions = readAndSetParams(i, stmt, ((Byte)paramDrdaTypes.elementAt(i)).byteValue(), pmeta, paramExtPositions, ((Integer)(paramLens.elementAt(i))).intValue()); } stmt.cliParamExtPositions = paramExtPositions; stmt.cliParamDrdaTypes = paramDrdaTypes; stmt.cliParamLens = paramLens; break; case CodePoint.EXTDTA: readAndSetAllExtParams(stmt, false); break; default: invalidCodePoint(codePoint); } codePoint = reader.getCodePoint(); } } |
|
int numExt = stmt.cliParamExtPositions.size(); for (int i = 0; i < stmt.cliParamExtPositions.size(); i++) | final int numExt = stmt.getExtPositionCount(); for (int i = 0; i < numExt; i++) | private void readAndSetAllExtParams(final DRDAStatement stmt, final boolean streamLOB) throws SQLException, DRDAProtocolException { int numExt = stmt.cliParamExtPositions.size(); for (int i = 0; i < stmt.cliParamExtPositions.size(); i++) { int paramPos = ((Integer) (stmt.cliParamExtPositions).get(i)).intValue(); final boolean doStreamLOB = (streamLOB && i == numExt -1); readAndSetExtParam(paramPos, stmt, ((Byte)stmt.cliParamDrdaTypes.elementAt(paramPos)).intValue(), ((Integer)(stmt.cliParamLens.elementAt(paramPos))).intValue(), doStreamLOB); // Each extdta in it's own dss if (i < numExt -1) { correlationID = reader.readDssHeader(); int codePoint = reader.readLengthAndCodePoint(); } } } |
int paramPos = ((Integer) (stmt.cliParamExtPositions).get(i)).intValue(); | int paramPos = stmt.getExtPosition(i); | private void readAndSetAllExtParams(final DRDAStatement stmt, final boolean streamLOB) throws SQLException, DRDAProtocolException { int numExt = stmt.cliParamExtPositions.size(); for (int i = 0; i < stmt.cliParamExtPositions.size(); i++) { int paramPos = ((Integer) (stmt.cliParamExtPositions).get(i)).intValue(); final boolean doStreamLOB = (streamLOB && i == numExt -1); readAndSetExtParam(paramPos, stmt, ((Byte)stmt.cliParamDrdaTypes.elementAt(paramPos)).intValue(), ((Integer)(stmt.cliParamLens.elementAt(paramPos))).intValue(), doStreamLOB); // Each extdta in it's own dss if (i < numExt -1) { correlationID = reader.readDssHeader(); int codePoint = reader.readLengthAndCodePoint(); } } } |
((Byte)stmt.cliParamDrdaTypes.elementAt(paramPos)).intValue(), ((Integer)(stmt.cliParamLens.elementAt(paramPos))).intValue(), | stmt.getParamDRDAType(paramPos+1), stmt.getParamLen(paramPos+1), | private void readAndSetAllExtParams(final DRDAStatement stmt, final boolean streamLOB) throws SQLException, DRDAProtocolException { int numExt = stmt.cliParamExtPositions.size(); for (int i = 0; i < stmt.cliParamExtPositions.size(); i++) { int paramPos = ((Integer) (stmt.cliParamExtPositions).get(i)).intValue(); final boolean doStreamLOB = (streamLOB && i == numExt -1); readAndSetExtParam(paramPos, stmt, ((Byte)stmt.cliParamDrdaTypes.elementAt(paramPos)).intValue(), ((Integer)(stmt.cliParamLens.elementAt(paramPos))).intValue(), doStreamLOB); // Each extdta in it's own dss if (i < numExt -1) { correlationID = reader.readDssHeader(); int codePoint = reader.readLengthAndCodePoint(); } } } |
private ArrayList readAndSetParams(int i, DRDAStatement stmt, int drdaType, EngineParameterMetaData pmeta, ArrayList paramExtPositions, int paramLenNumBytes) | private void readAndSetParams(int i, DRDAStatement stmt, EngineParameterMetaData pmeta) | private ArrayList readAndSetParams(int i, DRDAStatement stmt, int drdaType, EngineParameterMetaData pmeta, ArrayList paramExtPositions, int paramLenNumBytes) throws DRDAProtocolException, SQLException { PreparedStatement ps = stmt.getPreparedStatement(); // mask out null indicator drdaType = ((drdaType | 0x01) & 0x000000ff); if (ps instanceof CallableStatement) { if (stmt.isOutputParam(i+1)) { CallableStatement cs = (CallableStatement) ps; cs.registerOutParameter(i+1, stmt.getOutputParamType(i+1)); } } switch (drdaType) { case DRDAConstants.DRDA_TYPE_NSMALL: { short paramVal = (short) reader.readShort(getByteOrder()); if (SanityManager.DEBUG) trace("short parameter value is: "+paramVal); // DB2 does not have a BOOLEAN java.sql.bit type, it's sent as small if (pmeta.getParameterType(i+1) == JDBC30Translation.BOOLEAN) ps.setBoolean(i+1, (paramVal == 1)); else ps.setShort(i+1, paramVal); break; } case DRDAConstants.DRDA_TYPE_NINTEGER: { int paramVal = reader.readInt(getByteOrder()); if (SanityManager.DEBUG) trace("integer parameter value is: "+paramVal); ps.setInt(i+1, paramVal); break; } case DRDAConstants.DRDA_TYPE_NINTEGER8: { long paramVal = reader.readLong(getByteOrder()); if (SanityManager.DEBUG) trace("parameter value is: "+paramVal); ps.setLong(i+1, paramVal); break; } case DRDAConstants.DRDA_TYPE_NFLOAT4: { float paramVal = reader.readFloat(getByteOrder()); if (SanityManager.DEBUG) trace("parameter value is: "+paramVal); ps.setFloat(i+1, paramVal); break; } case DRDAConstants.DRDA_TYPE_NFLOAT8: { double paramVal = reader.readDouble(getByteOrder()); if (SanityManager.DEBUG) trace("nfloat8 parameter value is: "+paramVal); ps.setDouble(i+1, paramVal); break; } case DRDAConstants.DRDA_TYPE_NDECIMAL: { int precision = (paramLenNumBytes >> 8) & 0xff; int scale = paramLenNumBytes & 0xff; BigDecimal paramVal = reader.readBigDecimal(precision, scale); if (SanityManager.DEBUG) trace("ndecimal parameter value is: "+paramVal); ps.setBigDecimal(i+1, paramVal); break; } case DRDAConstants.DRDA_TYPE_NDATE: { String paramVal = reader.readStringData(10).trim(); //parameter may be char value if (SanityManager.DEBUG) trace("ndate parameter value is: \""+paramVal+"\""); try { ps.setDate(i+1, java.sql.Date.valueOf(paramVal)); } catch (java.lang.IllegalArgumentException e) { // Just use SQLSTATE as message since, if user wants to // retrieve it, the message will be looked up by the // sqlcamessage() proc, which will get the localized // message based on SQLSTATE, and will ignore the // the message we use here... throw new SQLException(SQLState.LANG_DATE_SYNTAX_EXCEPTION, SQLState.LANG_DATE_SYNTAX_EXCEPTION.substring(0,5)); } break; } case DRDAConstants.DRDA_TYPE_NTIME: { String paramVal = reader.readStringData(8).trim(); //parameter may be char value if (SanityManager.DEBUG) trace("ntime parameter value is: "+paramVal); try { ps.setTime(i+1, java.sql.Time.valueOf(paramVal)); } catch (java.lang.IllegalArgumentException e) { throw new SQLException(SQLState.LANG_DATE_SYNTAX_EXCEPTION, SQLState.LANG_DATE_SYNTAX_EXCEPTION.substring(0,5)); } break; } case DRDAConstants.DRDA_TYPE_NTIMESTAMP: { // JCC represents ts in a slightly different format than Java standard, so // we do the conversion to Java standard here. String paramVal = reader.readStringData(26).trim(); //parameter may be char value if (SanityManager.DEBUG) trace("ntimestamp parameter value is: "+paramVal); try { String tsString = paramVal.substring(0,10) + " " + paramVal.substring(11,19).replace('.', ':') + paramVal.substring(19); if (SanityManager.DEBUG) trace("tsString is: "+tsString); ps.setTimestamp(i+1, java.sql.Timestamp.valueOf(tsString)); } catch (java.lang.IllegalArgumentException e1) { // thrown by Timestamp.valueOf(...) for bad syntax... throw new SQLException(SQLState.LANG_DATE_SYNTAX_EXCEPTION, SQLState.LANG_DATE_SYNTAX_EXCEPTION.substring(0,5)); } catch (java.lang.StringIndexOutOfBoundsException e2) { // can be thrown by substring(...) if syntax is invalid... throw new SQLException(SQLState.LANG_DATE_SYNTAX_EXCEPTION, SQLState.LANG_DATE_SYNTAX_EXCEPTION.substring(0,5)); } break; } case DRDAConstants.DRDA_TYPE_NCHAR: case DRDAConstants.DRDA_TYPE_NVARCHAR: case DRDAConstants.DRDA_TYPE_NLONG: case DRDAConstants.DRDA_TYPE_NVARMIX: case DRDAConstants.DRDA_TYPE_NLONGMIX: { String paramVal = reader.readLDStringData(stmt.ccsidMBCEncoding); if (SanityManager.DEBUG) trace("char/varchar parameter value is: "+paramVal); ps.setString(i+1, paramVal); break; } case DRDAConstants.DRDA_TYPE_NFIXBYTE: { byte[] paramVal = reader.readBytes(); if (SanityManager.DEBUG) trace("fix bytes parameter value is: "+ convertToHexString(paramVal)); ps.setBytes(i+1, paramVal); break; } case DRDAConstants.DRDA_TYPE_NVARBYTE: case DRDAConstants.DRDA_TYPE_NLONGVARBYTE: { int length = reader.readNetworkShort(); //protocol control data always follows big endian if (SanityManager.DEBUG) trace("===== binary param length is: " + length); byte[] paramVal = reader.readBytes(length); ps.setBytes(i+1, paramVal); break; } case DRDAConstants.DRDA_TYPE_NLOBBYTES: case DRDAConstants.DRDA_TYPE_NLOBCMIXED: case DRDAConstants.DRDA_TYPE_NLOBCSBCS: case DRDAConstants.DRDA_TYPE_NLOBCDBCS: { long length = readLobLength(paramLenNumBytes); if (length != 0) //can be -1 for CLI if "data at exec" mode, see clifp/exec test { if (paramExtPositions == null) paramExtPositions = new ArrayList(); paramExtPositions.add(new Integer(i)); } else /* empty */ { if (drdaType == DRDAConstants.DRDA_TYPE_NLOBBYTES) ps.setBytes(i+1, new byte[0]); else ps.setString(i+1, ""); } break; } default: { String paramVal = reader.readLDStringData(stmt.ccsidMBCEncoding); if (SanityManager.DEBUG) trace("default type parameter value is: "+paramVal); ps.setObject(i+1, paramVal); } } return paramExtPositions; } |
drdaType = ((drdaType | 0x01) & 0x000000ff); | final int drdaType = ((stmt.getParamDRDAType(i+1) | 0x01) & 0xff); final int paramLenNumBytes = stmt.getParamLen(i+1); | private ArrayList readAndSetParams(int i, DRDAStatement stmt, int drdaType, EngineParameterMetaData pmeta, ArrayList paramExtPositions, int paramLenNumBytes) throws DRDAProtocolException, SQLException { PreparedStatement ps = stmt.getPreparedStatement(); // mask out null indicator drdaType = ((drdaType | 0x01) & 0x000000ff); if (ps instanceof CallableStatement) { if (stmt.isOutputParam(i+1)) { CallableStatement cs = (CallableStatement) ps; cs.registerOutParameter(i+1, stmt.getOutputParamType(i+1)); } } switch (drdaType) { case DRDAConstants.DRDA_TYPE_NSMALL: { short paramVal = (short) reader.readShort(getByteOrder()); if (SanityManager.DEBUG) trace("short parameter value is: "+paramVal); // DB2 does not have a BOOLEAN java.sql.bit type, it's sent as small if (pmeta.getParameterType(i+1) == JDBC30Translation.BOOLEAN) ps.setBoolean(i+1, (paramVal == 1)); else ps.setShort(i+1, paramVal); break; } case DRDAConstants.DRDA_TYPE_NINTEGER: { int paramVal = reader.readInt(getByteOrder()); if (SanityManager.DEBUG) trace("integer parameter value is: "+paramVal); ps.setInt(i+1, paramVal); break; } case DRDAConstants.DRDA_TYPE_NINTEGER8: { long paramVal = reader.readLong(getByteOrder()); if (SanityManager.DEBUG) trace("parameter value is: "+paramVal); ps.setLong(i+1, paramVal); break; } case DRDAConstants.DRDA_TYPE_NFLOAT4: { float paramVal = reader.readFloat(getByteOrder()); if (SanityManager.DEBUG) trace("parameter value is: "+paramVal); ps.setFloat(i+1, paramVal); break; } case DRDAConstants.DRDA_TYPE_NFLOAT8: { double paramVal = reader.readDouble(getByteOrder()); if (SanityManager.DEBUG) trace("nfloat8 parameter value is: "+paramVal); ps.setDouble(i+1, paramVal); break; } case DRDAConstants.DRDA_TYPE_NDECIMAL: { int precision = (paramLenNumBytes >> 8) & 0xff; int scale = paramLenNumBytes & 0xff; BigDecimal paramVal = reader.readBigDecimal(precision, scale); if (SanityManager.DEBUG) trace("ndecimal parameter value is: "+paramVal); ps.setBigDecimal(i+1, paramVal); break; } case DRDAConstants.DRDA_TYPE_NDATE: { String paramVal = reader.readStringData(10).trim(); //parameter may be char value if (SanityManager.DEBUG) trace("ndate parameter value is: \""+paramVal+"\""); try { ps.setDate(i+1, java.sql.Date.valueOf(paramVal)); } catch (java.lang.IllegalArgumentException e) { // Just use SQLSTATE as message since, if user wants to // retrieve it, the message will be looked up by the // sqlcamessage() proc, which will get the localized // message based on SQLSTATE, and will ignore the // the message we use here... throw new SQLException(SQLState.LANG_DATE_SYNTAX_EXCEPTION, SQLState.LANG_DATE_SYNTAX_EXCEPTION.substring(0,5)); } break; } case DRDAConstants.DRDA_TYPE_NTIME: { String paramVal = reader.readStringData(8).trim(); //parameter may be char value if (SanityManager.DEBUG) trace("ntime parameter value is: "+paramVal); try { ps.setTime(i+1, java.sql.Time.valueOf(paramVal)); } catch (java.lang.IllegalArgumentException e) { throw new SQLException(SQLState.LANG_DATE_SYNTAX_EXCEPTION, SQLState.LANG_DATE_SYNTAX_EXCEPTION.substring(0,5)); } break; } case DRDAConstants.DRDA_TYPE_NTIMESTAMP: { // JCC represents ts in a slightly different format than Java standard, so // we do the conversion to Java standard here. String paramVal = reader.readStringData(26).trim(); //parameter may be char value if (SanityManager.DEBUG) trace("ntimestamp parameter value is: "+paramVal); try { String tsString = paramVal.substring(0,10) + " " + paramVal.substring(11,19).replace('.', ':') + paramVal.substring(19); if (SanityManager.DEBUG) trace("tsString is: "+tsString); ps.setTimestamp(i+1, java.sql.Timestamp.valueOf(tsString)); } catch (java.lang.IllegalArgumentException e1) { // thrown by Timestamp.valueOf(...) for bad syntax... throw new SQLException(SQLState.LANG_DATE_SYNTAX_EXCEPTION, SQLState.LANG_DATE_SYNTAX_EXCEPTION.substring(0,5)); } catch (java.lang.StringIndexOutOfBoundsException e2) { // can be thrown by substring(...) if syntax is invalid... throw new SQLException(SQLState.LANG_DATE_SYNTAX_EXCEPTION, SQLState.LANG_DATE_SYNTAX_EXCEPTION.substring(0,5)); } break; } case DRDAConstants.DRDA_TYPE_NCHAR: case DRDAConstants.DRDA_TYPE_NVARCHAR: case DRDAConstants.DRDA_TYPE_NLONG: case DRDAConstants.DRDA_TYPE_NVARMIX: case DRDAConstants.DRDA_TYPE_NLONGMIX: { String paramVal = reader.readLDStringData(stmt.ccsidMBCEncoding); if (SanityManager.DEBUG) trace("char/varchar parameter value is: "+paramVal); ps.setString(i+1, paramVal); break; } case DRDAConstants.DRDA_TYPE_NFIXBYTE: { byte[] paramVal = reader.readBytes(); if (SanityManager.DEBUG) trace("fix bytes parameter value is: "+ convertToHexString(paramVal)); ps.setBytes(i+1, paramVal); break; } case DRDAConstants.DRDA_TYPE_NVARBYTE: case DRDAConstants.DRDA_TYPE_NLONGVARBYTE: { int length = reader.readNetworkShort(); //protocol control data always follows big endian if (SanityManager.DEBUG) trace("===== binary param length is: " + length); byte[] paramVal = reader.readBytes(length); ps.setBytes(i+1, paramVal); break; } case DRDAConstants.DRDA_TYPE_NLOBBYTES: case DRDAConstants.DRDA_TYPE_NLOBCMIXED: case DRDAConstants.DRDA_TYPE_NLOBCSBCS: case DRDAConstants.DRDA_TYPE_NLOBCDBCS: { long length = readLobLength(paramLenNumBytes); if (length != 0) //can be -1 for CLI if "data at exec" mode, see clifp/exec test { if (paramExtPositions == null) paramExtPositions = new ArrayList(); paramExtPositions.add(new Integer(i)); } else /* empty */ { if (drdaType == DRDAConstants.DRDA_TYPE_NLOBBYTES) ps.setBytes(i+1, new byte[0]); else ps.setString(i+1, ""); } break; } default: { String paramVal = reader.readLDStringData(stmt.ccsidMBCEncoding); if (SanityManager.DEBUG) trace("default type parameter value is: "+paramVal); ps.setObject(i+1, paramVal); } } return paramExtPositions; } |
if (paramExtPositions == null) paramExtPositions = new ArrayList(); paramExtPositions.add(new Integer(i)); | stmt.addExtPosition(i); | private ArrayList readAndSetParams(int i, DRDAStatement stmt, int drdaType, EngineParameterMetaData pmeta, ArrayList paramExtPositions, int paramLenNumBytes) throws DRDAProtocolException, SQLException { PreparedStatement ps = stmt.getPreparedStatement(); // mask out null indicator drdaType = ((drdaType | 0x01) & 0x000000ff); if (ps instanceof CallableStatement) { if (stmt.isOutputParam(i+1)) { CallableStatement cs = (CallableStatement) ps; cs.registerOutParameter(i+1, stmt.getOutputParamType(i+1)); } } switch (drdaType) { case DRDAConstants.DRDA_TYPE_NSMALL: { short paramVal = (short) reader.readShort(getByteOrder()); if (SanityManager.DEBUG) trace("short parameter value is: "+paramVal); // DB2 does not have a BOOLEAN java.sql.bit type, it's sent as small if (pmeta.getParameterType(i+1) == JDBC30Translation.BOOLEAN) ps.setBoolean(i+1, (paramVal == 1)); else ps.setShort(i+1, paramVal); break; } case DRDAConstants.DRDA_TYPE_NINTEGER: { int paramVal = reader.readInt(getByteOrder()); if (SanityManager.DEBUG) trace("integer parameter value is: "+paramVal); ps.setInt(i+1, paramVal); break; } case DRDAConstants.DRDA_TYPE_NINTEGER8: { long paramVal = reader.readLong(getByteOrder()); if (SanityManager.DEBUG) trace("parameter value is: "+paramVal); ps.setLong(i+1, paramVal); break; } case DRDAConstants.DRDA_TYPE_NFLOAT4: { float paramVal = reader.readFloat(getByteOrder()); if (SanityManager.DEBUG) trace("parameter value is: "+paramVal); ps.setFloat(i+1, paramVal); break; } case DRDAConstants.DRDA_TYPE_NFLOAT8: { double paramVal = reader.readDouble(getByteOrder()); if (SanityManager.DEBUG) trace("nfloat8 parameter value is: "+paramVal); ps.setDouble(i+1, paramVal); break; } case DRDAConstants.DRDA_TYPE_NDECIMAL: { int precision = (paramLenNumBytes >> 8) & 0xff; int scale = paramLenNumBytes & 0xff; BigDecimal paramVal = reader.readBigDecimal(precision, scale); if (SanityManager.DEBUG) trace("ndecimal parameter value is: "+paramVal); ps.setBigDecimal(i+1, paramVal); break; } case DRDAConstants.DRDA_TYPE_NDATE: { String paramVal = reader.readStringData(10).trim(); //parameter may be char value if (SanityManager.DEBUG) trace("ndate parameter value is: \""+paramVal+"\""); try { ps.setDate(i+1, java.sql.Date.valueOf(paramVal)); } catch (java.lang.IllegalArgumentException e) { // Just use SQLSTATE as message since, if user wants to // retrieve it, the message will be looked up by the // sqlcamessage() proc, which will get the localized // message based on SQLSTATE, and will ignore the // the message we use here... throw new SQLException(SQLState.LANG_DATE_SYNTAX_EXCEPTION, SQLState.LANG_DATE_SYNTAX_EXCEPTION.substring(0,5)); } break; } case DRDAConstants.DRDA_TYPE_NTIME: { String paramVal = reader.readStringData(8).trim(); //parameter may be char value if (SanityManager.DEBUG) trace("ntime parameter value is: "+paramVal); try { ps.setTime(i+1, java.sql.Time.valueOf(paramVal)); } catch (java.lang.IllegalArgumentException e) { throw new SQLException(SQLState.LANG_DATE_SYNTAX_EXCEPTION, SQLState.LANG_DATE_SYNTAX_EXCEPTION.substring(0,5)); } break; } case DRDAConstants.DRDA_TYPE_NTIMESTAMP: { // JCC represents ts in a slightly different format than Java standard, so // we do the conversion to Java standard here. String paramVal = reader.readStringData(26).trim(); //parameter may be char value if (SanityManager.DEBUG) trace("ntimestamp parameter value is: "+paramVal); try { String tsString = paramVal.substring(0,10) + " " + paramVal.substring(11,19).replace('.', ':') + paramVal.substring(19); if (SanityManager.DEBUG) trace("tsString is: "+tsString); ps.setTimestamp(i+1, java.sql.Timestamp.valueOf(tsString)); } catch (java.lang.IllegalArgumentException e1) { // thrown by Timestamp.valueOf(...) for bad syntax... throw new SQLException(SQLState.LANG_DATE_SYNTAX_EXCEPTION, SQLState.LANG_DATE_SYNTAX_EXCEPTION.substring(0,5)); } catch (java.lang.StringIndexOutOfBoundsException e2) { // can be thrown by substring(...) if syntax is invalid... throw new SQLException(SQLState.LANG_DATE_SYNTAX_EXCEPTION, SQLState.LANG_DATE_SYNTAX_EXCEPTION.substring(0,5)); } break; } case DRDAConstants.DRDA_TYPE_NCHAR: case DRDAConstants.DRDA_TYPE_NVARCHAR: case DRDAConstants.DRDA_TYPE_NLONG: case DRDAConstants.DRDA_TYPE_NVARMIX: case DRDAConstants.DRDA_TYPE_NLONGMIX: { String paramVal = reader.readLDStringData(stmt.ccsidMBCEncoding); if (SanityManager.DEBUG) trace("char/varchar parameter value is: "+paramVal); ps.setString(i+1, paramVal); break; } case DRDAConstants.DRDA_TYPE_NFIXBYTE: { byte[] paramVal = reader.readBytes(); if (SanityManager.DEBUG) trace("fix bytes parameter value is: "+ convertToHexString(paramVal)); ps.setBytes(i+1, paramVal); break; } case DRDAConstants.DRDA_TYPE_NVARBYTE: case DRDAConstants.DRDA_TYPE_NLONGVARBYTE: { int length = reader.readNetworkShort(); //protocol control data always follows big endian if (SanityManager.DEBUG) trace("===== binary param length is: " + length); byte[] paramVal = reader.readBytes(length); ps.setBytes(i+1, paramVal); break; } case DRDAConstants.DRDA_TYPE_NLOBBYTES: case DRDAConstants.DRDA_TYPE_NLOBCMIXED: case DRDAConstants.DRDA_TYPE_NLOBCSBCS: case DRDAConstants.DRDA_TYPE_NLOBCDBCS: { long length = readLobLength(paramLenNumBytes); if (length != 0) //can be -1 for CLI if "data at exec" mode, see clifp/exec test { if (paramExtPositions == null) paramExtPositions = new ArrayList(); paramExtPositions.add(new Integer(i)); } else /* empty */ { if (drdaType == DRDAConstants.DRDA_TYPE_NLOBBYTES) ps.setBytes(i+1, new byte[0]); else ps.setString(i+1, ""); } break; } default: { String paramVal = reader.readLDStringData(stmt.ccsidMBCEncoding); if (SanityManager.DEBUG) trace("default type parameter value is: "+paramVal); ps.setObject(i+1, paramVal); } } return paramExtPositions; } |
return paramExtPositions; | private ArrayList readAndSetParams(int i, DRDAStatement stmt, int drdaType, EngineParameterMetaData pmeta, ArrayList paramExtPositions, int paramLenNumBytes) throws DRDAProtocolException, SQLException { PreparedStatement ps = stmt.getPreparedStatement(); // mask out null indicator drdaType = ((drdaType | 0x01) & 0x000000ff); if (ps instanceof CallableStatement) { if (stmt.isOutputParam(i+1)) { CallableStatement cs = (CallableStatement) ps; cs.registerOutParameter(i+1, stmt.getOutputParamType(i+1)); } } switch (drdaType) { case DRDAConstants.DRDA_TYPE_NSMALL: { short paramVal = (short) reader.readShort(getByteOrder()); if (SanityManager.DEBUG) trace("short parameter value is: "+paramVal); // DB2 does not have a BOOLEAN java.sql.bit type, it's sent as small if (pmeta.getParameterType(i+1) == JDBC30Translation.BOOLEAN) ps.setBoolean(i+1, (paramVal == 1)); else ps.setShort(i+1, paramVal); break; } case DRDAConstants.DRDA_TYPE_NINTEGER: { int paramVal = reader.readInt(getByteOrder()); if (SanityManager.DEBUG) trace("integer parameter value is: "+paramVal); ps.setInt(i+1, paramVal); break; } case DRDAConstants.DRDA_TYPE_NINTEGER8: { long paramVal = reader.readLong(getByteOrder()); if (SanityManager.DEBUG) trace("parameter value is: "+paramVal); ps.setLong(i+1, paramVal); break; } case DRDAConstants.DRDA_TYPE_NFLOAT4: { float paramVal = reader.readFloat(getByteOrder()); if (SanityManager.DEBUG) trace("parameter value is: "+paramVal); ps.setFloat(i+1, paramVal); break; } case DRDAConstants.DRDA_TYPE_NFLOAT8: { double paramVal = reader.readDouble(getByteOrder()); if (SanityManager.DEBUG) trace("nfloat8 parameter value is: "+paramVal); ps.setDouble(i+1, paramVal); break; } case DRDAConstants.DRDA_TYPE_NDECIMAL: { int precision = (paramLenNumBytes >> 8) & 0xff; int scale = paramLenNumBytes & 0xff; BigDecimal paramVal = reader.readBigDecimal(precision, scale); if (SanityManager.DEBUG) trace("ndecimal parameter value is: "+paramVal); ps.setBigDecimal(i+1, paramVal); break; } case DRDAConstants.DRDA_TYPE_NDATE: { String paramVal = reader.readStringData(10).trim(); //parameter may be char value if (SanityManager.DEBUG) trace("ndate parameter value is: \""+paramVal+"\""); try { ps.setDate(i+1, java.sql.Date.valueOf(paramVal)); } catch (java.lang.IllegalArgumentException e) { // Just use SQLSTATE as message since, if user wants to // retrieve it, the message will be looked up by the // sqlcamessage() proc, which will get the localized // message based on SQLSTATE, and will ignore the // the message we use here... throw new SQLException(SQLState.LANG_DATE_SYNTAX_EXCEPTION, SQLState.LANG_DATE_SYNTAX_EXCEPTION.substring(0,5)); } break; } case DRDAConstants.DRDA_TYPE_NTIME: { String paramVal = reader.readStringData(8).trim(); //parameter may be char value if (SanityManager.DEBUG) trace("ntime parameter value is: "+paramVal); try { ps.setTime(i+1, java.sql.Time.valueOf(paramVal)); } catch (java.lang.IllegalArgumentException e) { throw new SQLException(SQLState.LANG_DATE_SYNTAX_EXCEPTION, SQLState.LANG_DATE_SYNTAX_EXCEPTION.substring(0,5)); } break; } case DRDAConstants.DRDA_TYPE_NTIMESTAMP: { // JCC represents ts in a slightly different format than Java standard, so // we do the conversion to Java standard here. String paramVal = reader.readStringData(26).trim(); //parameter may be char value if (SanityManager.DEBUG) trace("ntimestamp parameter value is: "+paramVal); try { String tsString = paramVal.substring(0,10) + " " + paramVal.substring(11,19).replace('.', ':') + paramVal.substring(19); if (SanityManager.DEBUG) trace("tsString is: "+tsString); ps.setTimestamp(i+1, java.sql.Timestamp.valueOf(tsString)); } catch (java.lang.IllegalArgumentException e1) { // thrown by Timestamp.valueOf(...) for bad syntax... throw new SQLException(SQLState.LANG_DATE_SYNTAX_EXCEPTION, SQLState.LANG_DATE_SYNTAX_EXCEPTION.substring(0,5)); } catch (java.lang.StringIndexOutOfBoundsException e2) { // can be thrown by substring(...) if syntax is invalid... throw new SQLException(SQLState.LANG_DATE_SYNTAX_EXCEPTION, SQLState.LANG_DATE_SYNTAX_EXCEPTION.substring(0,5)); } break; } case DRDAConstants.DRDA_TYPE_NCHAR: case DRDAConstants.DRDA_TYPE_NVARCHAR: case DRDAConstants.DRDA_TYPE_NLONG: case DRDAConstants.DRDA_TYPE_NVARMIX: case DRDAConstants.DRDA_TYPE_NLONGMIX: { String paramVal = reader.readLDStringData(stmt.ccsidMBCEncoding); if (SanityManager.DEBUG) trace("char/varchar parameter value is: "+paramVal); ps.setString(i+1, paramVal); break; } case DRDAConstants.DRDA_TYPE_NFIXBYTE: { byte[] paramVal = reader.readBytes(); if (SanityManager.DEBUG) trace("fix bytes parameter value is: "+ convertToHexString(paramVal)); ps.setBytes(i+1, paramVal); break; } case DRDAConstants.DRDA_TYPE_NVARBYTE: case DRDAConstants.DRDA_TYPE_NLONGVARBYTE: { int length = reader.readNetworkShort(); //protocol control data always follows big endian if (SanityManager.DEBUG) trace("===== binary param length is: " + length); byte[] paramVal = reader.readBytes(length); ps.setBytes(i+1, paramVal); break; } case DRDAConstants.DRDA_TYPE_NLOBBYTES: case DRDAConstants.DRDA_TYPE_NLOBCMIXED: case DRDAConstants.DRDA_TYPE_NLOBCSBCS: case DRDAConstants.DRDA_TYPE_NLOBCDBCS: { long length = readLobLength(paramLenNumBytes); if (length != 0) //can be -1 for CLI if "data at exec" mode, see clifp/exec test { if (paramExtPositions == null) paramExtPositions = new ArrayList(); paramExtPositions.add(new Integer(i)); } else /* empty */ { if (drdaType == DRDAConstants.DRDA_TYPE_NLOBBYTES) ps.setBytes(i+1, new byte[0]); else ps.setString(i+1, ""); } break; } default: { String paramVal = reader.readLDStringData(stmt.ccsidMBCEncoding); if (SanityManager.DEBUG) trace("default type parameter value is: "+paramVal); ps.setObject(i+1, paramVal); } } return paramExtPositions; } |
|
numCols = stmt.getNumParams(); | numCols = stmt.getDrdaParamCount(); | private boolean writeFDODTA (DRDAStatement stmt) throws DRDAProtocolException, SQLException { boolean hasdata = false; int blksize = stmt.getBlksize() > 0 ? stmt.getBlksize() : CodePoint.QRYBLKSZ_MAX; long rowCount = 0; ResultSet rs =null; boolean moreData = (stmt.getQryprctyp() == CodePoint.LMTBLKPRC); int numCols; if (!stmt.needsToSendParamData) { rs = stmt.getResultSet(); } if (rs != null) { numCols = stmt.getNumRsCols(); if (stmt.isScrollable()) hasdata = positionCursor(stmt, rs); else hasdata = rs.next(); } else // it's for a CallableStatement { hasdata = stmt.hasOutputParams(); numCols = stmt.getNumParams(); } do { if (!hasdata) { doneData(stmt, rs); moreData = false; return moreData; } // Send ResultSet warnings if there are any SQLWarning sqlw = (rs != null)? rs.getWarnings(): null; if (rs != null) { rs.clearWarnings(); } // for updatable, insensitive result sets we signal the // row updated condition to the client via a warning to be // popped by client onto its rowUpdated state, i.e. this // warning should not reach API level. if (rs != null && rs.rowUpdated()) { SQLWarning w = new SQLWarning("", SQLState.ROW_UPDATED, ExceptionSeverity.WARNING_SEVERITY); if (sqlw != null) { sqlw.setNextWarning(w); } else { sqlw = w; } } // Delete holes are manifest as a row consisting of a non-null // SQLCARD and a null data group. The SQLCARD has a warning // SQLSTATE of 02502 if (rs != null && rs.rowDeleted()) { SQLWarning w = new SQLWarning("", SQLState.ROW_DELETED, ExceptionSeverity.WARNING_SEVERITY); if (sqlw != null) { sqlw.setNextWarning(w); } else { sqlw = w; } } if (sqlw == null) writeSQLCAGRP(nullSQLState, 0, -1, -1); else writeSQLCAGRP(sqlw, sqlw.getErrorCode(), 1, -1); // if we were asked not to return data, mark QRYDTA null; do not // return yet, need to make rowCount right // if the row has been deleted return QRYDTA null (delete hole) boolean noRetrieveRS = (rs != null && (!stmt.getQryrtndta() || rs.rowDeleted())); if (noRetrieveRS) writer.writeByte(0xFF); //QRYDTA null indicator: IS NULL else writer.writeByte(0); //QRYDTA null indicator: not null for (int i = 1; i <= numCols; i++) { if (noRetrieveRS) break; int drdaType; int ndrdaType; int precision; int scale; Object val = null; boolean valNull; if (rs != null) { drdaType = stmt.getRsDRDAType(i) & 0xff; precision = stmt.getRsPrecision(i); scale = stmt.getRsScale(i); ndrdaType = drdaType | 1; if (SanityManager.DEBUG) trace("!!drdaType = " + java.lang.Integer.toHexString(drdaType) + "precision = " + precision +" scale = " + scale); switch (ndrdaType) { case DRDAConstants.DRDA_TYPE_NLOBBYTES: case DRDAConstants.DRDA_TYPE_NLOBCMIXED: EXTDTAInputStream extdtaStream= EXTDTAInputStream.getEXTDTAStream(rs, i, drdaType); writeFdocaVal(i,extdtaStream, drdaType, precision,scale,rs.wasNull(),stmt); break; case DRDAConstants.DRDA_TYPE_NINTEGER: int ival = rs.getInt(i); valNull = rs.wasNull(); if (SanityManager.DEBUG) trace("====== writing int: "+ ival + " is null: " + valNull); writeNullability(drdaType,valNull); if (! valNull) writer.writeInt(ival); break; case DRDAConstants.DRDA_TYPE_NSMALL: short sval = rs.getShort(i); valNull = rs.wasNull(); if (SanityManager.DEBUG) trace("====== writing small: "+ sval + " is null: " + valNull); writeNullability(drdaType,valNull); if (! valNull) writer.writeShort(sval); break; case DRDAConstants.DRDA_TYPE_NINTEGER8: long lval = rs.getLong(i); valNull = rs.wasNull(); if (SanityManager.DEBUG) trace("====== writing long: "+ lval + " is null: " + valNull); writeNullability(drdaType,valNull); if (! valNull) writer.writeLong(lval); break; case DRDAConstants.DRDA_TYPE_NFLOAT4: float fval = rs.getFloat(i); valNull = rs.wasNull(); if (SanityManager.DEBUG) trace("====== writing float: "+ fval + " is null: " + valNull); writeNullability(drdaType,valNull); if (! valNull) writer.writeFloat(fval); break; case DRDAConstants.DRDA_TYPE_NFLOAT8: double dval = rs.getDouble(i); valNull = rs.wasNull(); if (SanityManager.DEBUG) trace("====== writing double: "+ dval + " is null: " + valNull); writeNullability(drdaType,valNull); if (! valNull) writer.writeDouble(dval); break; case DRDAConstants.DRDA_TYPE_NCHAR: case DRDAConstants.DRDA_TYPE_NVARCHAR: case DRDAConstants.DRDA_TYPE_NVARMIX: case DRDAConstants.DRDA_TYPE_NLONG: case DRDAConstants.DRDA_TYPE_NLONGMIX: String valStr = rs.getString(i); if (SanityManager.DEBUG) trace("====== writing char/varchar/mix :"+ valStr + ":"); writeFdocaVal(i, valStr, drdaType, precision,scale,rs.wasNull(),stmt); break; default: writeFdocaVal(i, rs.getObject(i),drdaType, precision,scale,rs.wasNull(),stmt); } } else { drdaType = stmt.getParamDRDAType(i) & 0xff; precision = stmt.getParamPrecision(i); scale = stmt.getParamScale(i); ndrdaType = drdaType | 1; if (stmt.isOutputParam(i)) { if (SanityManager.DEBUG) trace("***getting Object "+i); val = ((CallableStatement) stmt.ps).getObject(i); valNull = (val == null); writeFdocaVal(i,val,drdaType,precision, scale, valNull,stmt); } else writeFdocaVal(i,null,drdaType,precision,scale,true,stmt); } } // does all this fit in one QRYDTA if (writer.getDSSLength() > blksize) { splitQRYDTA(stmt, blksize); return false; } if (rs == null) return moreData; //get the next row rowCount++; if (rowCount < stmt.getQryrowset()) { hasdata = rs.next(); } /*(1) scrollable we return at most a row set; OR (2) no retrieve data */ else if (stmt.isScrollable() || noRetrieveRS) moreData=false; } while (hasdata && rowCount < stmt.getQryrowset()); // add rowCount to statement row count // for non scrollable cursors if (!stmt.isScrollable()) stmt.rowCount += rowCount; if (!hasdata) { doneData(stmt, rs); moreData=false; } if (!stmt.isScrollable()) stmt.setHasdata(hasdata); return moreData; } |
System.out.println("Test the metadata calls related to visibility of *own* changes for different resultset types"); System.out.println("ownUpdatesAreVisible(ResultSet.TYPE_FORWARD_ONLY)? " + met.ownUpdatesAreVisible(ResultSet.TYPE_FORWARD_ONLY)); System.out.println("ownDeletesAreVisible(ResultSet.TYPE_FORWARD_ONLY)? " + met.ownDeletesAreVisible(ResultSet.TYPE_FORWARD_ONLY)); System.out.println("ownInsertsAreVisible(ResultSet.TYPE_FORWARD_ONLY)? " + met.ownInsertsAreVisible(ResultSet.TYPE_FORWARD_ONLY)); System.out.println("Scroll insensitive ResultSet see updates and deletes, but not inserts"); System.out.println("ownUpdatesAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE)? " + met.ownUpdatesAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE)); System.out.println("ownDeletesAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE)? " + met.ownDeletesAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE)); System.out.println("ownInsertsAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE)? " + met.ownInsertsAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE)); System.out.println("Derby does not yet implement scroll sensitive resultsets and hence following metadata calls return false"); System.out.println("ownUpdatesAreVisible(ResultSet.TYPE_SCROLL_SENSITIVE)? " + met.ownUpdatesAreVisible(ResultSet.TYPE_SCROLL_SENSITIVE)); System.out.println("ownDeletesAreVisible(ResultSet.TYPE_SCROLL_SENSITIVE)? " + met.ownDeletesAreVisible(ResultSet.TYPE_SCROLL_SENSITIVE)); System.out.println("ownInsertsAreVisible(ResultSet.TYPE_SCROLL_SENSITIVE)? " + met.othersInsertsAreVisible(ResultSet.TYPE_SCROLL_SENSITIVE)); System.out.println("Test the metadata calls related to detectability of visible changes for different resultset types"); System.out.println("Expect true for updates and deletes of TYPE_SCROLL_INSENSITIVE, all others should be false"); System.out.println("updatesAreDetected(ResultSet.TYPE_FORWARD_ONLY)? " + met.updatesAreDetected(ResultSet.TYPE_FORWARD_ONLY)); System.out.println("deletesAreDetected(ResultSet.TYPE_FORWARD_ONLY)? " + met.deletesAreDetected(ResultSet.TYPE_FORWARD_ONLY)); System.out.println("insertsAreDetected(ResultSet.TYPE_FORWARD_ONLY)? " + met.insertsAreDetected(ResultSet.TYPE_FORWARD_ONLY)); System.out.println("updatesAreDetected(ResultSet.TYPE_SCROLL_INSENSITIVE)? " + met.updatesAreDetected(ResultSet.TYPE_SCROLL_INSENSITIVE)); System.out.println("deletesAreDetected(ResultSet.TYPE_SCROLL_INSENSITIVE)? " + met.deletesAreDetected(ResultSet.TYPE_SCROLL_INSENSITIVE)); System.out.println("insertsAreDetected(ResultSet.TYPE_SCROLL_INSENSITIVE)? " + met.insertsAreDetected(ResultSet.TYPE_SCROLL_INSENSITIVE)); System.out.println("updatesAreDetected(ResultSet.TYPE_SCROLL_SENSITIVE)? " + met.updatesAreDetected(ResultSet.TYPE_SCROLL_SENSITIVE)); System.out.println("deletesAreDetected(ResultSet.TYPE_SCROLL_SENSITIVE)? " + met.deletesAreDetected(ResultSet.TYPE_SCROLL_SENSITIVE)); System.out.println("insertsAreDetected(ResultSet.TYPE_SCROLL_SENSITIVE)? " + met.insertsAreDetected(ResultSet.TYPE_SCROLL_SENSITIVE)); | public void runTest() { DatabaseMetaData met; ResultSet rs; ResultSetMetaData rsmet; System.out.println("Test metadata starting"); try { //Cleanup any leftover database objects from previous test run cleanUp(s); // test decimal type and other numeric types precision, scale, // and display width after operations, beetle 3875, 3906 s.execute("create table t (i int, s smallint, r real, "+ "d double precision, dt date, t time, ts timestamp, "+ "c char(10), v varchar(40) not null, dc dec(10,2))"); s.execute("insert into t values(1,2,3.3,4.4,date('1990-05-05'),"+ "time('12:06:06'),timestamp('1990-07-07 07:07:07.07'),"+ "'eight','nine', 11.1)"); // test decimal type and other numeric types precision, scale, // and display width after operations, beetle 3875, 3906 //rs = s.executeQuery("select dc from t where tn = 10 union select dc from t where i = 1"); rs = s.executeQuery("select dc from t where dc = 11.1 union select dc from t where i = 1"); rsmet = rs.getMetaData(); metadata_test.showNumericMetaData("Union Result", rsmet, 1); rs.close(); rs = s.executeQuery("select dc, r, d, r+dc, d-dc, dc-d from t"); rsmet = rs.getMetaData(); metadata_test.showNumericMetaData("dec(10,2)", rsmet, 1); metadata_test.showNumericMetaData("real", rsmet, 2); metadata_test.showNumericMetaData("double", rsmet, 3); metadata_test.showNumericMetaData("real + dec(10,2)", rsmet, 4); metadata_test.showNumericMetaData("double precision - dec(10,2)", rsmet, 5); metadata_test.showNumericMetaData("dec(10,2) - double precision", rsmet, 6); while (rs.next()) System.out.println("result row: " + rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3) + " " + rs.getString(4) + " " + rs.getString(5) + " " + rs.getString(6) ); rs.close(); rsmet = s.executeQuery("VALUES CAST (0.0 AS DECIMAL(10,0))").getMetaData(); metadata_test.showNumericMetaData("DECIMAL(10,0)", rsmet, 1); rsmet = s.executeQuery("VALUES CAST (0.0 AS DECIMAL(10,10))").getMetaData(); metadata_test.showNumericMetaData("DECIMAL(10,10)", rsmet, 1); rsmet = s.executeQuery("VALUES CAST (0.0 AS DECIMAL(10,2))").getMetaData(); metadata_test.showNumericMetaData("DECIMAL(10,2)", rsmet, 1); s.execute("insert into t values(1,2,3.3,4.4,date('1990-05-05'),"+ "time('12:06:06'),timestamp('1990-07-07 07:07:07.07'),"+ "'eight','nine', 11.11)"); // test decimal/integer static column result scale consistent // with result set metadata after division, beetle 3901 rs = s.executeQuery("select dc / 2 from t"); rsmet = rs.getMetaData(); System.out.println("Column result scale after division is: " + rsmet.getScale(1)); while (rs.next()) System.out.println("dc / 2 = " + rs.getString(1)); rs.close(); s.execute("create table louie (i int not null default 10, s smallint not null, " + "c30 char(30) not null, " + "vc10 varchar(10) not null default 'asdf', " + "constraint PRIMKEY primary key(vc10, i), " + "constraint UNIQUEKEY unique(c30, s), " + "ai bigint generated always as identity (start with -10, increment by 2001))"); // Create another unique index on louie s.execute("create unique index u1 on louie(s, i)"); // Create a non-unique index on louie s.execute("create index u2 on louie(s)"); // Create a view on louie s.execute("create view screwie as select * from louie"); // Create a foreign key s.execute("create table reftab (vc10 varchar(10), i int, " + "s smallint, c30 char(30), " + "s2 smallint, c302 char(30), " + "dprim decimal(5,1) not null, dfor decimal(5,1) not null, "+ "constraint PKEY_REFTAB primary key (dprim), " + "constraint FKEYSELF foreign key (dfor) references reftab, "+ "constraint FKEY1 foreign key(vc10, i) references louie, " + "constraint FKEY2 foreign key(c30, s2) references louie (c30, s), "+ "constraint FKEY3 foreign key(c30, s) references louie (c30, s))"); s.execute("create table reftab2 (t2_vc10 varchar(10), t2_i int, " + "constraint T2_FKEY1 foreign key(t2_vc10, t2_i) references louie)"); // Create a table with all types s.execute("create table alltypes ( "+ //"bitcol16_______ bit(16), "+ //"bitvaryingcol32 bit varying(32), "+ //"tinyintcol tinyint, "+ "smallintcol smallint, "+ "intcol int default 20, "+ "bigintcol bigint, "+ "realcol real, "+ "doublepreccol double precision default 10, "+ "floatcol float default 8.8, "+ "decimalcol10p4s decimal(10,4), "+ "numericcol20p2s numeric(20,2), "+ "char8col___ char(8), "+ "char8forbitcol___ char(8) for bit data, "+ "varchar9col varchar(9), "+ "varchar9bitcol varchar(9) for bit data, "+ "longvarcharcol long varchar,"+ "longvarbinarycol long varchar for bit data, "+ //"nchar10col nchar(10)" //+ ", nvarchar8col nvarchar(8)" //+ ", longnvarchar long nvarchar" //+ ", "blobcol blob(3K), "+ "clobcol clob(3K), "+ "datecol date, "+ "timecol time, "+ "tscol timestamp" + ")" ); // test for beetle 4620 s.execute("CREATE TABLE INFLIGHT(FLT_NUM CHAR(20) NOT NULL," + "FLT_ORIGIN CHAR(6), " + "FLT_DEST CHAR(6), " + "FLT_AIRCRAFT CHAR(20), " + "FLT_FLYING_TIME VARCHAR(22), "+ "FLT_DEPT_TIME CHAR(8), "+ "FLT_ARR_TIME CHAR(8), "+ "FLT_NOTES VARCHAR(510), "+ "FLT_DAYS_OF_WK CHAR(14), "+ "FLT_CRAFT_PIC VARCHAR(32672), "+ "PRIMARY KEY(FLT_NUM))"); // Create procedures so we can test // getProcedureColumns() s.execute("create procedure GETPCTEST1 (" + // for creating, the procedure's params do not need to exactly match the method's "out outb VARCHAR(3), a VARCHAR(3), b NUMERIC, c SMALLINT, " + "e SMALLINT, f INTEGER, g BIGINT, h FLOAT, i DOUBLE PRECISION, " + "k DATE, l TIME, T TIMESTAMP )"+ "language java external name " + "'org.apache.derbyTesting.functionTests.tests.jdbcapi.metadata.getpc'" + " parameter style java"); s.execute("create procedure GETPCTEST2 (pa INTEGER, pb BIGINT)"+ "language java external name " + "'org.apache.derbyTesting.functionTests.tests.jdbcapi.metadata.getpc'" + " parameter style java"); s.execute("create procedure GETPCTEST3A (STRING1 VARCHAR(5), out STRING2 VARCHAR(5))"+ "language java external name " + "'org.apache.derbyTesting.functionTests.tests.jdbcapi.metadata.getpc'" + " parameter style java"); s.execute("create procedure GETPCTEST3B (in STRING3 VARCHAR(5), inout STRING4 VARCHAR(5))"+ "language java external name " + "'org.apache.derbyTesting.functionTests.tests.jdbcapi.metadata.getpc'" + " parameter style java"); s.execute("create procedure GETPCTEST4A() "+ "language java external name " + "'org.apache.derbyTesting.functionTests.tests.jdbcapi.metadata.getpc4a'"+ " parameter style java"); s.execute("create procedure GETPCTEST4B() "+ "language java external name " + "'org.apache.derbyTesting.functionTests.tests.jdbcapi.metadata.getpc4b'" + " parameter style java"); s.execute("create procedure GETPCTEST4Bx(out retparam INTEGER) "+ "language java external name " + "'org.apache.derbyTesting.functionTests.tests.jdbcapi.metadata.getpc4b'" + " parameter style java"); met = con.getMetaData(); System.out.println("JDBC Driver '" + met.getDriverName() + "', version " + met.getDriverMajorVersion() + "." + met.getDriverMinorVersion() + " (" + met.getDriverVersion() + ")"); boolean pass = false; try { pass = TestUtil.compareURL(met.getURL()); }catch (NoSuchMethodError msme) { // DatabaseMetaData.getURL not present - correct for JSR169 if(!TestUtil.HAVE_DRIVER_CLASS) pass = true; } catch (Throwable err) { System.out.println("%%getURL() gave the exception: " + err); } if(pass) System.out.println("DatabaseMetaData.getURL test passed"); else System.out.println("FAIL: DatabaseMetaData.getURL test failed"); System.out.println("allTablesAreSelectable(): " + met.allTablesAreSelectable()); System.out.println("maxColumnNameLength(): " + met.getMaxColumnNameLength()); System.out.println(); System.out.println("getSchemas():"); dumpRS(met.getSchemas()); System.out.println(); System.out.println("getCatalogs():"); dumpRS(met.getCatalogs()); System.out.println("getSearchStringEscape(): " + met.getSearchStringEscape()); System.out.println("getSQLKeywords(): " + met.getSQLKeywords()); System.out.println("getDefaultTransactionIsolation(): " + met.getDefaultTransactionIsolation()); System.out.println("getProcedures():"); dumpRS(GET_PROCEDURES, getMetaDataRS(met, GET_PROCEDURES, new String [] {null, "%", "GETPCTEST%"}, null, null, null)); System.out.println("getUDTs() with user-named types null :"); dumpRS(met.getUDTs(null, null, null, null)); System.out.println("getUDTs() with user-named types in ('JAVA_OBJECT') :"); int[] userNamedTypes = new int[1]; userNamedTypes[0] = java.sql.Types.JAVA_OBJECT; dumpRS(met.getUDTs("a", null, null, userNamedTypes)); System.out.println("getUDTs() with user-named types in ('STRUCT') :"); userNamedTypes[0] = java.sql.Types.STRUCT; dumpRS(met.getUDTs("b", null, null, userNamedTypes)); System.out.println("getUDTs() with user-named types in ('DISTINCT') :"); userNamedTypes[0] = java.sql.Types.DISTINCT; dumpRS(met.getUDTs("c", null, null, userNamedTypes)); System.out.println("getUDTs() with user-named types in ('JAVA_OBJECT', 'STRUCT') :"); userNamedTypes = new int[2]; userNamedTypes[0] = java.sql.Types.JAVA_OBJECT; userNamedTypes[1] = java.sql.Types.STRUCT; dumpRS(met.getUDTs("a", null, null, userNamedTypes)); /* * any methods that were not tested above using code written * specifically for it will now be tested in a generic way. */ System.out.println("allProceduresAreCallable(): " + met.allProceduresAreCallable()); System.out.println("getUserName(): " + met.getUserName()); System.out.println("isReadOnly(): " + met.isReadOnly()); System.out.println("nullsAreSortedHigh(): " + met.nullsAreSortedHigh()); System.out.println("nullsAreSortedLow(): " + met.nullsAreSortedLow()); System.out.println("nullsAreSortedAtStart(): " + met.nullsAreSortedAtStart()); System.out.println("nullsAreSortedAtEnd(): " + met.nullsAreSortedAtEnd()); System.out.println("getDatabaseProductName(): " + met.getDatabaseProductName()); String v = met.getDatabaseProductVersion(); int l = v.indexOf('('); if (l<0) l = v.length(); v = v.substring(0,l); System.out.println("getDatabaseProductVersion(): " + v); System.out.println("getDriverVersion(): " + met.getDriverVersion()); System.out.println("usesLocalFiles(): " + met.usesLocalFiles()); System.out.println("usesLocalFilePerTable(): " + met.usesLocalFilePerTable()); System.out.println("supportsMixedCaseIdentifiers(): " + met.supportsMixedCaseIdentifiers()); System.out.println("storesUpperCaseIdentifiers(): " + met.storesUpperCaseIdentifiers()); System.out.println("storesLowerCaseIdentifiers(): " + met.storesLowerCaseIdentifiers()); System.out.println("storesMixedCaseIdentifiers(): " + met.storesMixedCaseIdentifiers()); System.out.println("supportsMixedCaseQuotedIdentifiers(): " + met.supportsMixedCaseQuotedIdentifiers()); System.out.println("storesUpperCaseQuotedIdentifiers(): " + met.storesUpperCaseQuotedIdentifiers()); System.out.println("storesLowerCaseQuotedIdentifiers(): " + met.storesLowerCaseQuotedIdentifiers()); System.out.println("storesMixedCaseQuotedIdentifiers(): " + met.storesMixedCaseQuotedIdentifiers()); System.out.println("getIdentifierQuoteString(): " + met.getIdentifierQuoteString()); System.out.println("getNumericFunctions(): " + met.getNumericFunctions()); System.out.println("getStringFunctions(): " + met.getStringFunctions()); System.out.println("getSystemFunctions(): " + met.getSystemFunctions()); System.out.println("getTimeDateFunctions(): " + met.getTimeDateFunctions()); System.out.println("getExtraNameCharacters(): " + met.getExtraNameCharacters()); System.out.println("supportsAlterTableWithAddColumn(): " + met.supportsAlterTableWithAddColumn()); System.out.println("supportsAlterTableWithDropColumn(): " + met.supportsAlterTableWithDropColumn()); System.out.println("supportsColumnAliasing(): " + met.supportsColumnAliasing()); System.out.println("nullPlusNonNullIsNull(): " + met.nullPlusNonNullIsNull()); System.out.println("supportsConvert(): " + met.supportsConvert()); System.out.println("supportsConvert(Types.INTEGER, Types.SMALLINT): " + met.supportsConvert(Types.INTEGER, Types.SMALLINT)); System.out.println("supportsTableCorrelationNames(): " + met.supportsTableCorrelationNames()); System.out.println("supportsDifferentTableCorrelationNames(): " + met.supportsDifferentTableCorrelationNames()); System.out.println("supportsExpressionsInOrderBy(): " + met.supportsExpressionsInOrderBy()); System.out.println("supportsOrderByUnrelated(): " + met.supportsOrderByUnrelated()); System.out.println("supportsGroupBy(): " + met.supportsGroupBy()); System.out.println("supportsGroupByUnrelated(): " + met.supportsGroupByUnrelated()); System.out.println("supportsGroupByBeyondSelect(): " + met.supportsGroupByBeyondSelect()); System.out.println("supportsLikeEscapeClause(): " + met.supportsLikeEscapeClause()); System.out.println("supportsMultipleResultSets(): " + met.supportsMultipleResultSets()); System.out.println("supportsMultipleTransactions(): " + met.supportsMultipleTransactions()); System.out.println("supportsNonNullableColumns(): " + met.supportsNonNullableColumns()); System.out.println("supportsMinimumSQLGrammar(): " + met.supportsMinimumSQLGrammar()); System.out.println("supportsCoreSQLGrammar(): " + met.supportsCoreSQLGrammar()); System.out.println("supportsExtendedSQLGrammar(): " + met.supportsExtendedSQLGrammar()); System.out.println("supportsANSI92EntryLevelSQL(): " + met.supportsANSI92EntryLevelSQL()); System.out.println("supportsANSI92IntermediateSQL(): " + met.supportsANSI92IntermediateSQL()); System.out.println("supportsANSI92FullSQL(): " + met.supportsANSI92FullSQL()); System.out.println("supportsIntegrityEnhancementFacility(): " + met.supportsIntegrityEnhancementFacility()); System.out.println("supportsOuterJoins(): " + met.supportsOuterJoins()); System.out.println("supportsFullOuterJoins(): " + met.supportsFullOuterJoins()); System.out.println("supportsLimitedOuterJoins(): " + met.supportsLimitedOuterJoins()); System.out.println("getSchemaTerm(): " + met.getSchemaTerm()); System.out.println("getProcedureTerm(): " + met.getProcedureTerm()); System.out.println("getCatalogTerm(): " + met.getCatalogTerm()); System.out.println("isCatalogAtStart(): " + met.isCatalogAtStart()); System.out.println("getCatalogSeparator(): " + met.getCatalogSeparator()); System.out.println("supportsSchemasInDataManipulation(): " + met.supportsSchemasInDataManipulation()); System.out.println("supportsSchemasInProcedureCalls(): " + met.supportsSchemasInProcedureCalls()); System.out.println("supportsSchemasInTableDefinitions(): " + met.supportsSchemasInTableDefinitions()); System.out.println("supportsSchemasInIndexDefinitions(): " + met.supportsSchemasInIndexDefinitions()); System.out.println("supportsSchemasInPrivilegeDefinitions(): " + met.supportsSchemasInPrivilegeDefinitions()); System.out.println("supportsCatalogsInDataManipulation(): " + met.supportsCatalogsInDataManipulation()); System.out.println("supportsCatalogsInProcedureCalls(): " + met.supportsCatalogsInProcedureCalls()); System.out.println("supportsCatalogsInTableDefinitions(): " + met.supportsCatalogsInTableDefinitions()); System.out.println("supportsCatalogsInIndexDefinitions(): " + met.supportsCatalogsInIndexDefinitions()); System.out.println("supportsCatalogsInPrivilegeDefinitions(): " + met.supportsCatalogsInPrivilegeDefinitions()); System.out.println("supportsPositionedDelete(): " + met.supportsPositionedDelete()); System.out.println("supportsPositionedUpdate(): " + met.supportsPositionedUpdate()); System.out.println("supportsSelectForUpdate(): " + met.supportsSelectForUpdate()); System.out.println("supportsStoredProcedures(): " + met.supportsStoredProcedures()); System.out.println("supportsSubqueriesInComparisons(): " + met.supportsSubqueriesInComparisons()); System.out.println("supportsSubqueriesInExists(): " + met.supportsSubqueriesInExists()); System.out.println("supportsSubqueriesInIns(): " + met.supportsSubqueriesInIns()); System.out.println("supportsSubqueriesInQuantifieds(): " + met.supportsSubqueriesInQuantifieds()); System.out.println("supportsCorrelatedSubqueries(): " + met.supportsCorrelatedSubqueries()); System.out.println("supportsUnion(): " + met.supportsUnion()); System.out.println("supportsUnionAll(): " + met.supportsUnionAll()); System.out.println("supportsOpenCursorsAcrossCommit(): " + met.supportsOpenCursorsAcrossCommit()); System.out.println("supportsOpenCursorsAcrossRollback(): " + met.supportsOpenCursorsAcrossRollback()); System.out.println("supportsOpenStatementsAcrossCommit(): " + met.supportsOpenStatementsAcrossCommit()); System.out.println("supportsOpenStatementsAcrossRollback(): " + met.supportsOpenStatementsAcrossRollback()); System.out.println("getMaxBinaryLiteralLength(): " + met.getMaxBinaryLiteralLength()); System.out.println("getMaxCharLiteralLength(): " + met.getMaxCharLiteralLength()); System.out.println("getMaxColumnsInGroupBy(): " + met.getMaxColumnsInGroupBy()); System.out.println("getMaxColumnsInIndex(): " + met.getMaxColumnsInIndex()); System.out.println("getMaxColumnsInOrderBy(): " + met.getMaxColumnsInOrderBy()); System.out.println("getMaxColumnsInSelect(): " + met.getMaxColumnsInSelect()); System.out.println("getMaxColumnsInTable(): " + met.getMaxColumnsInTable()); System.out.println("getMaxConnections(): " + met.getMaxConnections()); System.out.println("getMaxCursorNameLength(): " + met.getMaxCursorNameLength()); System.out.println("getMaxIndexLength(): " + met.getMaxIndexLength()); System.out.println("getMaxSchemaNameLength(): " + met.getMaxSchemaNameLength()); System.out.println("getMaxProcedureNameLength(): " + met.getMaxProcedureNameLength()); System.out.println("getMaxCatalogNameLength(): " + met.getMaxCatalogNameLength()); System.out.println("getMaxRowSize(): " + met.getMaxRowSize()); System.out.println("doesMaxRowSizeIncludeBlobs(): " + met.doesMaxRowSizeIncludeBlobs()); System.out.println("getMaxStatementLength(): " + met.getMaxStatementLength()); System.out.println("getMaxStatements(): " + met.getMaxStatements()); System.out.println("getMaxTableNameLength(): " + met.getMaxTableNameLength()); System.out.println("getMaxTablesInSelect(): " + met.getMaxTablesInSelect()); System.out.println("getMaxUserNameLength(): " + met.getMaxUserNameLength()); System.out.println("supportsTransactions(): " + met.supportsTransactions()); System.out.println("supportsTransactionIsolationLevel(Connection.TRANSACTION_NONE): " + met.supportsTransactionIsolationLevel(Connection.TRANSACTION_NONE)); System.out.println("supportsTransactionIsolationLevel(Connection.TRANSACTION_REPEATABLE_READ): " + met.supportsTransactionIsolationLevel(Connection.TRANSACTION_REPEATABLE_READ)); System.out.println("supportsTransactionIsolationLevel(Connection.TRANSACTION_SERIALIZABLE): " + met.supportsTransactionIsolationLevel(Connection.TRANSACTION_SERIALIZABLE)); System.out.println("supportsDataDefinitionAndDataManipulationTransactions(): " + met.supportsDataDefinitionAndDataManipulationTransactions()); System.out.println("supportsDataManipulationTransactionsOnly(): " + met.supportsDataManipulationTransactionsOnly()); System.out.println("dataDefinitionCausesTransactionCommit(): " + met.dataDefinitionCausesTransactionCommit()); System.out.println("dataDefinitionIgnoredInTransactions(): " + met.dataDefinitionIgnoredInTransactions()); System.out.println("Test the metadata calls related to visibility of changes made by others for different resultset types"); System.out.println("Since Derby materializes a forward only ResultSet incrementally, it is possible to see changes"); System.out.println("made by others and hence following 3 metadata calls will return true for forward only ResultSets."); System.out.println("othersUpdatesAreVisible(ResultSet.TYPE_FORWARD_ONLY)? " + met.othersUpdatesAreVisible(ResultSet.TYPE_FORWARD_ONLY)); System.out.println("othersDeletesAreVisible(ResultSet.TYPE_FORWARD_ONLY)? " + met.othersDeletesAreVisible(ResultSet.TYPE_FORWARD_ONLY)); System.out.println("othersInsertsAreVisible(ResultSet.TYPE_FORWARD_ONLY)? " + met.othersInsertsAreVisible(ResultSet.TYPE_FORWARD_ONLY)); System.out.println("Scroll insensitive ResultSet by their definition do not see changes made by others and hence following metadata calls return false"); System.out.println("othersUpdatesAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE)? " + met.othersUpdatesAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE)); System.out.println("othersDeletesAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE)? " + met.othersDeletesAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE)); System.out.println("othersInsertsAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE)? " + met.othersInsertsAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE)); System.out.println("Derby does not yet implement scroll sensitive resultsets and hence following metadata calls return false"); System.out.println("othersUpdatesAreVisible(ResultSet.TYPE_SCROLL_SENSITIVE)? " + met.othersUpdatesAreVisible(ResultSet.TYPE_SCROLL_SENSITIVE)); System.out.println("othersDeletesAreVisible(ResultSet.TYPE_SCROLL_SENSITIVE)? " + met.othersDeletesAreVisible(ResultSet.TYPE_SCROLL_SENSITIVE)); System.out.println("othersInsertsAreVisible(ResultSet.TYPE_SCROLL_SENSITIVE)? " + met.othersInsertsAreVisible(ResultSet.TYPE_SCROLL_SENSITIVE)); if (!TestUtil.isJCCFramework()) { // gives false on all.. bug int[] types = {ResultSet.TYPE_FORWARD_ONLY, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.TYPE_SCROLL_SENSITIVE}; int[] conc = {ResultSet.CONCUR_READ_ONLY, ResultSet.CONCUR_UPDATABLE}; String[] typesStr = {"TYPE_FORWARD_ONLY", "TYPE_SCROLL_INSENSITIVE", "TYPE_SCROLL_SENSITIVE"}; String[] concStr = {"CONCUR_READ_ONLY", "CONCUR_UPDATABLE"}; for (int i = 0; i < types.length ; i++) { for (int j = 0; j < conc.length; j++) { System.out.println ("SupportsResultSetConcurrency: " + typesStr[i] + "," + concStr[j] + ": " + met.supportsResultSetConcurrency(types[i], conc[j])); } } } System.out.println("getConnection(): "+ ((met.getConnection()==con)?"same connection":"different connection") ); System.out.println("getProcedureColumns():"); dumpRS(GET_PROCEDURE_COLUMNS, getMetaDataRS(met, GET_PROCEDURE_COLUMNS, new String [] {null, "%", "GETPCTEST%", "%"}, null, null, null)); System.out.println("getTables() with TABLE_TYPE in ('SYSTEM TABLE') :"); String[] tabTypes = new String[1]; tabTypes[0] = "SYSTEM TABLE"; dumpRS(GET_TABLES, getMetaDataRS(met, GET_TABLES, new String [] {null, null, null}, tabTypes, null, null)); System.out.println("getTables() with no types:"); dumpRS(GET_TABLES, getMetaDataRS(met, GET_TABLES, new String [] {"", null, "%"}, null, null, null)); System.out.println("getTables() with TABLE_TYPE in ('VIEW','TABLE') :"); tabTypes = new String[2]; tabTypes[0] = "VIEW"; tabTypes[1] = "TABLE"; dumpRS(GET_TABLES, getMetaDataRS(met, GET_TABLES, new String [] {null, null, null}, tabTypes, null, null)); System.out.println("getTableTypes():"); dumpRS(met.getTableTypes()); System.out.println("getColumns():"); dumpRS(GET_COLUMNS, getMetaDataRS(met, GET_COLUMNS, new String [] {"", null, "", ""}, null, null, null)); System.out.println("getColumns('SYSTABLES'):"); dumpRS(GET_COLUMNS, getMetaDataRS(met, GET_COLUMNS, new String [] {"", "SYS", "SYSTABLES", null}, null, null, null)); System.out.println("getColumns('ALLTYPES'):"); dumpRS(GET_COLUMNS, getMetaDataRS(met, GET_COLUMNS, new String [] {"", "APP", "ALLTYPES", null}, null, null, null)); System.out.println("getColumns('LOUIE'):"); dumpRS(GET_COLUMNS, getMetaDataRS(met, GET_COLUMNS, new String [] {"", "APP", "LOUIE", null}, null, null, null)); // test for beetle 4620 System.out.println("getColumns('INFLIGHT'):"); dumpRS(GET_COLUMNS, getMetaDataRS(met, GET_COLUMNS, new String [] {"", "APP", "INFLIGHT", null}, null, null, null)); System.out.println("getColumnPrivileges():"); dumpRS(GET_COLUMN_PRIVILEGES, getMetaDataRS(met, GET_COLUMN_PRIVILEGES, new String [] {"Huey", "Dewey", "Louie", "Frooey"}, null, null, null)); System.out.println("getTablePrivileges():"); dumpRS(GET_TABLE_PRIVILEGES, getMetaDataRS(met, GET_TABLE_PRIVILEGES, new String [] {"Huey", "Dewey", "Louie"}, null, null, null)); System.out.println("getBestRowIdentifier(\"\",null,\"LOUIE\"):"); dumpRS(GET_BEST_ROW_IDENTIFIER, getMetaDataRS(met, GET_BEST_ROW_IDENTIFIER, new String [] {"", null, "LOUIE"}, null, new int [] {DatabaseMetaData.bestRowTransaction}, new boolean [] {true})); System.out.println("getBestRowIdentifier(\"\",\"SYS\",\"SYSTABLES\"):"); dumpRS(GET_BEST_ROW_IDENTIFIER, getMetaDataRS(met, GET_BEST_ROW_IDENTIFIER, new String [] {"", "SYS", "SYSTABLES"}, null, new int [] {DatabaseMetaData.bestRowTransaction}, new boolean [] {true})); System.out.println("getVersionColumns():"); dumpRS(GET_VERSION_COLUMNS, getMetaDataRS(met, GET_VERSION_COLUMNS, new String [] {"Huey", "Dewey", "Louie"}, null, null, null)); System.out.println("getPrimaryKeys():"); dumpRS(GET_PRIMARY_KEYS, getMetaDataRS(met, GET_PRIMARY_KEYS, new String [] {"", "%", "LOUIE"}, null, null, null)); //beetle 4571 System.out.println("getPrimaryKeys(null, null, tablename):"); dumpRS(GET_PRIMARY_KEYS, getMetaDataRS(met, GET_PRIMARY_KEYS, new String [] {null, null, "LOUIE"}, null, null, null)); System.out.println("getImportedKeys():"); dumpRS(GET_IMPORTED_KEYS, getMetaDataRS(met, GET_IMPORTED_KEYS, new String [] {null, null, "%"}, null, null, null)); System.out.println("getExportedKeys():"); dumpRS(GET_EXPORTED_KEYS, getMetaDataRS(met, GET_EXPORTED_KEYS, new String [] {null, null, "%"}, null, null, null)); System.out.println("---------------------------------------"); System.out.println("getCrossReference('',null,'louie','',null,'reftab' ):"); dumpRS(GET_CROSS_REFERENCE, getMetaDataRS(met, GET_CROSS_REFERENCE, new String [] {"", null, "LOUIE", "", null, "REFTAB"}, null, null, null)); System.out.println("\ngetCrossReference('','APP','reftab','',null,'reftab' ):"); dumpRS(GET_CROSS_REFERENCE, getMetaDataRS(met, GET_CROSS_REFERENCE, new String [] {"", "APP", "REFTAB", "", null, "REFTAB"}, null, null, null)); System.out.println("\ngetCrossReference('',null,null,'','APP','reftab' ):"); dumpRS(GET_CROSS_REFERENCE, getMetaDataRS(met, GET_CROSS_REFERENCE, new String [] {"", null, "%", "", "APP", "REFTAB"}, null, null, null)); System.out.println("\ngetImportedKeys('',null,null,'','APP','reftab' ):"); dumpRS(GET_IMPORTED_KEYS, getMetaDataRS(met, GET_IMPORTED_KEYS, new String [] {"", "APP", "REFTAB"}, null, null, null)); System.out.println("\ngetCrossReference('',null,'louie','','APP',null):"); dumpRS(GET_CROSS_REFERENCE, getMetaDataRS(met, GET_CROSS_REFERENCE, new String [] {"", null, "LOUIE", "", "APP", "%"}, null, null, null)); System.out.println("\ngetExportedKeys('',null,'louie,'','APP',null ):"); dumpRS(GET_EXPORTED_KEYS, getMetaDataRS(met, GET_EXPORTED_KEYS, new String [] {"", null, "LOUIE"}, null, null, null)); System.out.println("\ngetCrossReference('','badschema','LOUIE','','APP','REFTAB' ):"); dumpRS(GET_CROSS_REFERENCE, getMetaDataRS(met, GET_CROSS_REFERENCE, new String [] {"", "BADSCHEMA", "LOUIE", "", "APP", "REFTAB"}, null, null, null)); System.out.println("getTypeInfo():"); dumpRS(GET_TYPE_INFO, getMetaDataRS(met, GET_TYPE_INFO, null, null, null, null)); /* NOTE - we call getIndexInfo() only on system tables here * so that there will be no diffs due to generated names. */ // unique indexes on SYSCOLUMNS System.out.println("getIndexInfo():"); dumpRS(GET_INDEX_INFO, getMetaDataRS(met, GET_INDEX_INFO, new String [] {"", "SYS", "SYSCOLUMNS"}, null, null, new boolean [] {true, false})); // all indexes on SYSCOLUMNS System.out.println("getIndexInfo():"); dumpRS(GET_INDEX_INFO, getMetaDataRS(met, GET_INDEX_INFO, new String [] {"", "SYS", "SYSCOLUMNS"}, null, null, new boolean [] {false, false})); System.out.println("getIndexInfo():"); dumpRS(GET_INDEX_INFO, getMetaDataRS(met, GET_INDEX_INFO, new String [] {"", "SYS", "SYSTABLES"}, null, null, new boolean [] {true, false})); rs = s.executeQuery("SELECT * FROM SYS.SYSTABLES"); System.out.println("getColumns('SYSTABLES'):"); dumpRS(GET_COLUMNS, getMetaDataRS(met, GET_COLUMNS, new String [] {"", "SYS", "SYSTABLES", null}, null, null, null)); try { if (!rs.next()) { System.out.println("FAIL -- user result set closed by"+ " intervening getColumns request"); } } catch (SQLException se) { if (this instanceof metadata) { System.out.println("FAIL -- user result set closed by"+ " intervening getColumns request"); } else { System.out.println("OK -- user result set closed by"+ " intervening OBDC getColumns request; this was" + " expected because of the way the test works."); } } rs.close(); System.out.println("Test escaped numeric functions - JDBC 3.0 C.1"); testEscapedFunctions(con, NUMERIC_FUNCTIONS, met.getNumericFunctions()); System.out.println("Test escaped string functions - JDBC 3.0 C.2"); testEscapedFunctions(con, STRING_FUNCTIONS, met.getStringFunctions()); System.out.println("Test escaped date time functions - JDBC 3.0 C.3"); testEscapedFunctions(con, TIMEDATE_FUNCTIONS, met.getTimeDateFunctions()); System.out.println("Test escaped system functions - JDBC 3.0 C.4"); testEscapedFunctions(con, SYSTEM_FUNCTIONS, met.getSystemFunctions()); // // Test referential actions on delete // System.out.println("---------------------------------------"); //create tables to test that we get the delete and update // referential action correct System.out.println("Referential action values"); System.out.println("RESTRICT = "+ DatabaseMetaData.importedKeyRestrict); System.out.println("NO ACTION = "+ DatabaseMetaData.importedKeyNoAction); System.out.println("CASCADE = "+ DatabaseMetaData.importedKeyCascade); System.out.println("SETNULL = "+ DatabaseMetaData.importedKeySetNull); System.out.println("SETDEFAULT = "+ DatabaseMetaData.importedKeySetDefault); s.execute("create table refaction1(a int not null primary key)"); s.execute("create table refactnone(a int references refaction1(a))"); s.execute("create table refactrestrict(a int references refaction1(a) on delete restrict)"); s.execute("create table refactnoaction(a int references refaction1(a) on delete no action)"); s.execute("create table refactcascade(a int references refaction1(a) on delete cascade)"); s.execute("create table refactsetnull(a int references refaction1(a) on delete set null)"); System.out.println("getCrossReference('','APP','REFACTION1','','APP','REFACTIONNONE' ):"); s.execute("create table refactupdrestrict(a int references refaction1(a) on update restrict)"); s.execute("create table refactupdnoaction(a int references refaction1(a) on update no action)"); dumpRS(GET_CROSS_REFERENCE, getMetaDataRS(met, GET_CROSS_REFERENCE, new String [] {"", "APP", "REFACTION1", "", "APP", "REFACTNONE"}, null, null, null)); System.out.println("\ngetCrossReference('','APP','REFACTION1','','APP','REFACTRESTRICT' ):"); dumpRS(GET_CROSS_REFERENCE, getMetaDataRS(met, GET_CROSS_REFERENCE, new String [] {"", "APP", "REFACTION1", "", "APP", "REFACTRESTRICT"}, null, null, null)); System.out.println("\ngetCrossReference('','APP','REFACTION1','','APP','REFACTNOACTION' ):"); dumpRS(GET_CROSS_REFERENCE, getMetaDataRS(met, GET_CROSS_REFERENCE, new String [] {"", "APP", "REFACTION1", "", "APP", "REFACTNOACTION"}, null, null, null)); System.out.println("\ngetCrossReference('','APP','REFACTION1','','APP','REFACTCASCADE' ):"); dumpRS(GET_CROSS_REFERENCE, getMetaDataRS(met, GET_CROSS_REFERENCE, new String [] {"", "APP", "REFACTION1", "", "APP", "REFACTCASCADE"}, null, null, null)); System.out.println("\ngetCrossReference('','APP','REFACTION1','','APP','REFACTSETNULL' ):"); dumpRS(GET_CROSS_REFERENCE, getMetaDataRS(met, GET_CROSS_REFERENCE, new String [] {"", "APP", "REFACTION1", "", "APP", "REFACTSETNULL"}, null, null, null)); System.out.println("\ngetCrossReference('','APP','REFACTION1','','APP','REFACTUPDRESTRICT' ):"); dumpRS(GET_CROSS_REFERENCE, getMetaDataRS(met, GET_CROSS_REFERENCE, new String [] {"", "APP", "REFACTION1", "", "APP", "REFACTUPDRESTRICT"}, null, null, null)); System.out.println("\ngetCrossReference('','APP','REFACTION1','','APP','REFACTUPDNOACTION' ):"); dumpRS(GET_CROSS_REFERENCE, getMetaDataRS(met, GET_CROSS_REFERENCE, new String [] {"", "APP", "REFACTION1", "", "APP", "REFACTUPDNOACTION"}, null, null, null)); ResultSet refrs = getMetaDataRS(met, GET_IMPORTED_KEYS, new String [] {"", "APP", "REFACTNONE"}, null, null, null); if (refrs.next()) { //check update rule if (refrs.getShort(11) != DatabaseMetaData.importedKeyNoAction) System.out.println("\ngetImportedKeys - none update Failed - action = " + refrs.getShort(11) + " required value = " + DatabaseMetaData.importedKeyNoAction); else System.out.println("\ngetImportedKeys - none update Passed"); //check delete rule if (refrs.getShort(11) != DatabaseMetaData.importedKeyNoAction) System.out.println("\ngetImportedKeys - none delete Failed - action = " + refrs.getShort(11) + " required value = " + DatabaseMetaData.importedKeyNoAction); else System.out.println("\ngetImportedKeys - none delete Passed"); } else System.out.println("\ngetImportedKeys - none Failed no rows"); refrs.close(); refrs = getMetaDataRS(met, GET_IMPORTED_KEYS, new String [] {"", "APP", "REFACTRESTRICT"}, null, null, null); if (refrs.next()) { if (refrs.getShort(11) != DatabaseMetaData.importedKeyRestrict) System.out.println("\ngetImportedKeys - delete Restrict Failed - action = " + refrs.getShort(11) + " required value = " + DatabaseMetaData.importedKeyRestrict); else System.out.println("\ngetImportedKeys - delete Restrict Passed"); } else System.out.println("\ngetImportedKeys - delete Restrict Failed no rows"); refrs.close(); refrs = getMetaDataRS(met, GET_IMPORTED_KEYS, new String [] {"", "APP", "REFACTNOACTION"}, null, null, null); if (refrs.next()) { if (refrs.getShort(11) != DatabaseMetaData.importedKeyNoAction) System.out.println("\ngetImportedKeys - delete NO ACTION Failed - action = " + refrs.getShort(11) + " required value = " + DatabaseMetaData.importedKeyNoAction); else System.out.println("\ngetImportedKeys - delete NO ACTION Passed"); } else System.out.println("\ngetImportedKeys - delete NO ACTION Failed no rows"); refrs.close(); refrs = getMetaDataRS(met, GET_IMPORTED_KEYS, new String [] {"", "APP", "REFACTCASCADE"}, null, null, null); if (refrs.next()) { if (refrs.getShort(11) != DatabaseMetaData.importedKeyCascade) System.out.println("\ngetImportedKeys - delete CASCADE Failed - action = " + refrs.getShort(11) + " required value = " + DatabaseMetaData.importedKeyCascade); else System.out.println("\ngetImportedKeys - delete CASCADE Passed"); } else System.out.println("\ngetImportedKeys - delete CASCADE Failed no rows"); refrs.close(); refrs = getMetaDataRS(met, GET_IMPORTED_KEYS, new String [] {"", "APP", "REFACTSETNULL"}, null, null, null); if (refrs.next()) { if (refrs.getShort(11) != DatabaseMetaData.importedKeySetNull) System.out.println("\ngetImportedKeys - delete SET NULL Failed - action = " + refrs.getShort(11) + " required value = " + DatabaseMetaData.importedKeySetNull); else System.out.println("\ngetImportedKeys - delete SET NULL Passed"); } else System.out.println("\ngetImportedKeys - SET NULL Failed no rows"); refrs.close(); refrs = getMetaDataRS(met, GET_IMPORTED_KEYS, new String [] {"", "APP", "REFACTRESTRICT"}, null, null, null); if (refrs.next()) { // test update rule if (refrs.getShort(11) != DatabaseMetaData.importedKeyRestrict) System.out.println("\ngetImportedKeys - update Restrict Failed - action = " + refrs.getShort(11) + " required value = " + DatabaseMetaData.importedKeyRestrict); else System.out.println("\ngetImportedKeys - update Restrict Passed"); } else System.out.println("\ngetImportedKeys - update Restrict Failed no rows"); refrs.close(); refrs = getMetaDataRS(met, GET_IMPORTED_KEYS, new String [] {"", "APP", "REFACTNOACTION"}, null, null, null); if (refrs.next()) { if (refrs.getShort(11) != DatabaseMetaData.importedKeyNoAction) System.out.println("\ngetImportedKeys - update NO ACTION Failed - action = " + refrs.getShort(11) + " required value = " + DatabaseMetaData.importedKeyNoAction); else System.out.println("\ngetImportedKeys - update NO ACTION Passed"); } else System.out.println("\ngetImportedKeys - update NO ACTION Failed no rows"); refrs.close(); System.out.println("\ngetExportedKeys('',null,null,'','APP','REFACTION1' ):"); dumpRS(GET_EXPORTED_KEYS, getMetaDataRS(met, GET_EXPORTED_KEYS, new String [] {"", "APP", "REFACTION1"}, null, null, null)); System.out.println("---------------------------------------"); // drop referential action test tables s.execute("drop table refactnone"); s.execute("drop table refactupdrestrict"); s.execute("drop table refactupdnoaction"); s.execute("drop table refactrestrict"); s.execute("drop table refactnoaction"); s.execute("drop table refactcascade"); s.execute("drop table refactsetnull"); s.execute("drop table inflight"); s.execute("drop table refaction1"); // test beetle 5195 s.execute("create table t1 (c1 int not null, c2 int, c3 int default null, c4 char(10) not null, c5 char(10) default null, c6 char(10) default 'NULL', c7 int default 88)"); String schema = "APP"; String tableName = "T1"; DatabaseMetaData dmd = con.getMetaData(); System.out.println("getColumns for '" + tableName + "'"); rs = getMetaDataRS(dmd, GET_COLUMNS, new String [] {null, schema, tableName, null}, null, null, null); try { while (rs.next()) { String col = rs.getString(4); String type = rs.getString(6); String defval = rs.getString(13); if (defval == null) System.out.println(" Next line is real null."); System.out.println("defval for col " + col + " type " + type + " DEFAULT '" + defval + "' wasnull " + rs.wasNull()); } } finally { if (rs != null) rs.close(); } s.execute("drop table t1"); // tiny test moved over from no longer used metadata2.sql // This checks for a bug where you get incorrect behavior on a nested connection. // if you do not get an error, the bug does not occur. if(HAVE_DRIVER_CLASS){ s.execute("create procedure isReadO() language java external name " + "'org.apache.derbyTesting.functionTests.tests.jdbcapi.metadata.isro'" + " parameter style java"); s.execute("call isReadO()"); } cleanUp(s); s.close(); if (con.getAutoCommit() == false) con.commit(); con.close(); } catch (SQLException e) { dumpSQLExceptions(e); } catch (Throwable e) { System.out.println("FAIL -- unexpected exception:"); e.printStackTrace(System.out); } System.out.println("Test metadata finished"); } |
|
RadioMatrixQuestion question = new RadioMatrixQuestion(columns.size(), answers.size()); | CheckBoxMatrixQuestion question = new CheckBoxMatrixQuestion(); | public void addMatrixQuestionToSection(HttpServletRequest request){ HttpSession session = request.getSession(); Section section = (Section) session.getAttribute("currentSection"); String name = request.getParameter("name"); String image = request.getParameter("image"); String questionText = request.getParameter("questionTxt"); Object obj = session.getAttribute("answers"); ArrayList<String> answers = null; if(obj instanceof PersistentList){ Iterator iter = ((PersistentList) obj).iterator(); answers = new ArrayList<String>(); while(iter.hasNext()){ answers.add((String) iter.next()); } } else answers = (ArrayList<String>) session.getAttribute("answers"); obj = session.getAttribute("columns"); ArrayList<String> columns = null; if(obj instanceof PersistentList){ Iterator iter = ((PersistentList) obj).iterator(); columns = new ArrayList<String>(); while(iter.hasNext()){ columns.add((String) iter.next()); } } else columns = (ArrayList<String>) session.getAttribute("columns"); // now parse different params depending on the type RadioMatrixQuestion question = new RadioMatrixQuestion(columns.size(), answers.size()); question.setDescription(questionText); question.setSection(section); question.setTitle(name); question.setItems(answers); question.setColumnsTitles(columns); question.setImage(image); List<Question> quests = section.getQuestions(); quests.add(question); section.setQuestions(quests); session.setAttribute("currentSection", section); session.removeAttribute("answers"); session.removeAttribute("columns"); } |
survey.setStatus(SurveyState.OPEN.getCode()); | survey.setStatus(SurveyState.DESIGN.getCode()); | public void createSessionSurvey(HttpServletRequest request){ HttpSession session = request.getSession(true); Survey survey = new Survey(); Calendar creationDate = Calendar.getInstance(); survey.setCreationDate(creationDate); survey.setStatus(SurveyState.OPEN.getCode()); session.setAttribute("currentSurvey", survey); session.setAttribute("surveyOp", "new"); } |
Collection answers = (Collection) session.getAttribute("answers"); answers.remove(rowId); session.setAttribute("answers", answers); | Object obj = session.getAttribute("answers"); if (obj instanceof PersistentList){ PersistentList answers = (PersistentList) obj; answers.remove(rowId); session.setAttribute("answers", answers); } else { ArrayList<String> answers = (ArrayList<String>) obj; answers.remove(rowId); session.setAttribute("answers", answers); } | public void removeAnswerFromSession(HttpServletRequest request){ HttpSession session = request.getSession(); int rowId = Integer.parseInt(request.getParameter("row")); rowId--; Collection answers = (Collection) session.getAttribute("answers"); answers.remove(rowId); session.setAttribute("answers", answers); } |
RadioMatrixQuestion question = new RadioMatrixQuestion(columns.size(), answers.size()); | CheckBoxMatrixQuestion question = new CheckBoxMatrixQuestion(); | public void updateMatrixQuestionInSection(HttpServletRequest request){ HttpSession session = request.getSession(); Section section = (Section) session.getAttribute("currentSection"); String name = request.getParameter("name"); String image = request.getParameter("image"); String questionText = request.getParameter("questionTxt"); int rowId = Integer.parseInt(request.getParameter("row")); rowId--; Object obj = session.getAttribute("answers"); ArrayList<String> answers = null; if(obj instanceof PersistentList){ Iterator iter = ((PersistentList) obj).iterator(); answers = new ArrayList<String>(); while(iter.hasNext()){ answers.add((String) iter.next()); } } else answers = (ArrayList<String>) session.getAttribute("answers"); obj = session.getAttribute("columns"); ArrayList<String> columns = null; if(obj instanceof PersistentList){ Iterator iter = ((PersistentList) obj).iterator(); columns = new ArrayList<String>(); while(iter.hasNext()){ columns.add((String) iter.next()); } } else columns = (ArrayList<String>) session.getAttribute("columns"); // now parse different params depending on the type RadioMatrixQuestion question = new RadioMatrixQuestion(columns.size(), answers.size()); question.setDescription(questionText); question.setSection(section); question.setTitle(name); question.setItems(answers); question.setColumnsTitles(columns); question.setImage(image); List<Question> quests = section.getQuestions(); quests.set(rowId, question); section.setQuestions(quests); session.setAttribute("currentSection", section); session.removeAttribute("answers"); session.removeAttribute("columns"); } |
survey.setRestrictionType(sform.getRestrictionType()); survey.setDescription(sform.getDescription()); | public void updatePersistedSurvey(HttpServletRequest request, SurveyForm sform){ Survey survey; HttpSession session = request.getSession(); if(sform.getSectionName()!=null && !sform.getSectionName().equals("")) survey = addSectionToSurvey(request, sform); else { survey = (Survey) session.getAttribute("currentSurvey"); survey.setName(sform.getName()); survey.setStartDate(Transformer.getCalendarFromString(sform.getStartDate())); survey.setFinishDate(Transformer.getCalendarFromString(sform.getEndDate())); survey.setStatus(sform.getState()); } surveyComponent.updateSurvey(survey); session.removeAttribute("currentSection"); session.removeAttribute("currentSurvey"); } |
|
survey.setFinishDate(Transformer.getCalendarFromString(sform.getEndDate())); survey.setStartDate(Transformer.getCalendarFromString(sform.getStartDate())); | survey.setFinishDate(Transformer.getCalendarFromString(sform .getEndDate())); survey.setStartDate(Transformer.getCalendarFromString(sform .getStartDate())); survey.setDescription(sform.getDescription()); survey.setRestrictionType(sform.getRestrictionType()); | private Survey updateSessionSurveyValues(HttpServletRequest request, SurveyForm sform){ HttpSession session = request.getSession(); Survey survey = (Survey) session.getAttribute("currentSurvey"); survey.setName(sform.getName()); survey.setCreationDate(Calendar.getInstance()); survey.setFinishDate(Transformer.getCalendarFromString(sform.getEndDate())); survey.setStartDate(Transformer.getCalendarFromString(sform.getStartDate())); return survey; } |
getJogador(numNotificado).vez(getJogadorDaVez(), isPodeFechada()); | getJogador(numNotificado).vez(jogadorDaVez, podeFechada); | private void notificaVez() { class ThreadNotifica extends Thread { public int numNotificado; public void run() { getJogador(numNotificado).vez(getJogadorDaVez(), isPodeFechada()); } } for (int i = 1; i <= 4; i++) { ThreadNotifica tn = new ThreadNotifica(); tn.numNotificado = i; tn.start(); } } |
tn.jogadorDaVez = j; tn.podeFechada = pf; | private void notificaVez() { class ThreadNotifica extends Thread { public int numNotificado; public void run() { getJogador(numNotificado).vez(getJogadorDaVez(), isPodeFechada()); } } for (int i = 1; i <= 4; i++) { ThreadNotifica tn = new ThreadNotifica(); tn.numNotificado = i; tn.start(); } } |
|
getJogador(numNotificado).vez(getJogadorDaVez(), isPodeFechada()); | getJogador(numNotificado).vez(jogadorDaVez, podeFechada); | public void run() { getJogador(numNotificado).vez(getJogadorDaVez(), isPodeFechada()); } |
} catch (SQLException ex) { | } catch (NoSuchMethodError nsme) { System.out.println("ResultSet.updateRef not present - correct for JSR169"); } catch (SQLException ex) { | public static void main(String[] args) { Connection con; ResultSet rs; Statement stmt; String[] columnNames = {"i", "s", "r", "d", "dt", "t", "ts", "c", "v", "tn", "dc"}; System.out.println("Test resultsetJdbc30 starting"); try { // use the ij utility to read the property file and // make the initial connection. ij.getPropertyArg(args); con = ij.startJBMS(); stmt = con.createStatement(); //create a table, insert a row, do a select from the table, stmt.execute("create table t (i int, s smallint, r real, "+ "d double precision, dt date, t time, ts timestamp, "+ "c char(10), v varchar(40) not null, dc dec(10,2))"); stmt.execute("insert into t values(1,2,3.3,4.4,date('1990-05-05'),"+ "time('12:06:06'),timestamp('1990-07-07 07:07:07.07'),"+ "'eight','nine', 11.1)"); rs = stmt.executeQuery("select * from t"); rs.next(); //following will give not implemented exceptions. try { System.out.println(); System.out.println("trying rs.getURL(int) :"); rs.getURL(8); System.out.println("Shouldn't reach here. Method not implemented yet."); } catch (SQLException ex) { System.out.println("Expected : " + ex.getMessage()); } try { System.out.println(); System.out.println("trying rs.getURL(String) :"); rs.getURL("c"); System.out.println("Shouldn't reach here. Method not implemented yet."); } catch (SQLException ex) { System.out.println("Expected : " + ex.getMessage()); } try { System.out.println(); System.out.println("trying rs.updateRef(int, Ref) :"); rs.updateRef(8,null); System.out.println("Shouldn't reach here. Method not implemented yet."); } catch (SQLException ex) { System.out.println("Expected : " + ex.getMessage()); } try { System.out.println(); System.out.println("trying rs.updateRef(String, Ref) :"); rs.updateRef("c",null); System.out.println("Shouldn't reach here. Method not implemented yet."); } catch (SQLException ex) { System.out.println("Expected : " + ex.getMessage()); } try { System.out.println(); System.out.println("trying rs.updateBlob(int, Blob) :"); rs.updateBlob(8,null); System.out.println("Shouldn't reach here because method is being invoked on a read only resultset"); } catch (SQLException ex) { System.out.println("Expected : " + ex.getMessage()); } try { System.out.println(); System.out.println("trying rs.updateBlob(String, Blob) :"); rs.updateBlob("c",null); System.out.println("Shouldn't reach here because method is being invoked on a read only resultset"); } catch (SQLException ex) { System.out.println("Expected : " + ex.getMessage()); } try { System.out.println(); System.out.println("trying rs.updateClob(int, Clob) :"); rs.updateClob(8,null); System.out.println("Shouldn't reach here because method is being invoked on a read only resultset"); } catch (SQLException ex) { System.out.println("Expected : " + ex.getMessage()); } try { System.out.println(); System.out.println("trying rs.updateClob(String, Clob) :"); rs.updateClob("c",null); System.out.println("Shouldn't reach here because method is being invoked on a read only resultset"); } catch (SQLException ex) { System.out.println("Expected : " + ex.getMessage()); } try { System.out.println(); System.out.println("trying rs.updateArray(int, Array) :"); rs.updateArray(8,null); System.out.println("Shouldn't reach here. Method not implemented yet."); } catch (SQLException ex) { System.out.println("Expected : " + ex.getMessage()); } try { System.out.println(); System.out.println("trying rs.updateClob(String, Array) :"); rs.updateArray("c",null); System.out.println("Shouldn't reach here. Method not implemented yet."); } catch (SQLException ex) { System.out.println("Expected : " + ex.getMessage()); } rs.close(); stmt.close(); con.close(); } catch (SQLException e) { dumpSQLExceptions(e); e.printStackTrace(); } catch (Throwable e) { System.out.println("FAIL -- unexpected exception: "+e); e.printStackTrace(); } System.out.println("Test resultsetJdbc30 finished"); } |
} catch (SQLException ex) { | } catch (NoSuchMethodError nsme) { System.out.println("ResultSet.updateArray not present - correct for JSR169"); } catch (SQLException ex) { | public static void main(String[] args) { Connection con; ResultSet rs; Statement stmt; String[] columnNames = {"i", "s", "r", "d", "dt", "t", "ts", "c", "v", "tn", "dc"}; System.out.println("Test resultsetJdbc30 starting"); try { // use the ij utility to read the property file and // make the initial connection. ij.getPropertyArg(args); con = ij.startJBMS(); stmt = con.createStatement(); //create a table, insert a row, do a select from the table, stmt.execute("create table t (i int, s smallint, r real, "+ "d double precision, dt date, t time, ts timestamp, "+ "c char(10), v varchar(40) not null, dc dec(10,2))"); stmt.execute("insert into t values(1,2,3.3,4.4,date('1990-05-05'),"+ "time('12:06:06'),timestamp('1990-07-07 07:07:07.07'),"+ "'eight','nine', 11.1)"); rs = stmt.executeQuery("select * from t"); rs.next(); //following will give not implemented exceptions. try { System.out.println(); System.out.println("trying rs.getURL(int) :"); rs.getURL(8); System.out.println("Shouldn't reach here. Method not implemented yet."); } catch (SQLException ex) { System.out.println("Expected : " + ex.getMessage()); } try { System.out.println(); System.out.println("trying rs.getURL(String) :"); rs.getURL("c"); System.out.println("Shouldn't reach here. Method not implemented yet."); } catch (SQLException ex) { System.out.println("Expected : " + ex.getMessage()); } try { System.out.println(); System.out.println("trying rs.updateRef(int, Ref) :"); rs.updateRef(8,null); System.out.println("Shouldn't reach here. Method not implemented yet."); } catch (SQLException ex) { System.out.println("Expected : " + ex.getMessage()); } try { System.out.println(); System.out.println("trying rs.updateRef(String, Ref) :"); rs.updateRef("c",null); System.out.println("Shouldn't reach here. Method not implemented yet."); } catch (SQLException ex) { System.out.println("Expected : " + ex.getMessage()); } try { System.out.println(); System.out.println("trying rs.updateBlob(int, Blob) :"); rs.updateBlob(8,null); System.out.println("Shouldn't reach here because method is being invoked on a read only resultset"); } catch (SQLException ex) { System.out.println("Expected : " + ex.getMessage()); } try { System.out.println(); System.out.println("trying rs.updateBlob(String, Blob) :"); rs.updateBlob("c",null); System.out.println("Shouldn't reach here because method is being invoked on a read only resultset"); } catch (SQLException ex) { System.out.println("Expected : " + ex.getMessage()); } try { System.out.println(); System.out.println("trying rs.updateClob(int, Clob) :"); rs.updateClob(8,null); System.out.println("Shouldn't reach here because method is being invoked on a read only resultset"); } catch (SQLException ex) { System.out.println("Expected : " + ex.getMessage()); } try { System.out.println(); System.out.println("trying rs.updateClob(String, Clob) :"); rs.updateClob("c",null); System.out.println("Shouldn't reach here because method is being invoked on a read only resultset"); } catch (SQLException ex) { System.out.println("Expected : " + ex.getMessage()); } try { System.out.println(); System.out.println("trying rs.updateArray(int, Array) :"); rs.updateArray(8,null); System.out.println("Shouldn't reach here. Method not implemented yet."); } catch (SQLException ex) { System.out.println("Expected : " + ex.getMessage()); } try { System.out.println(); System.out.println("trying rs.updateClob(String, Array) :"); rs.updateArray("c",null); System.out.println("Shouldn't reach here. Method not implemented yet."); } catch (SQLException ex) { System.out.println("Expected : " + ex.getMessage()); } rs.close(); stmt.close(); con.close(); } catch (SQLException e) { dumpSQLExceptions(e); e.printStackTrace(); } catch (Throwable e) { System.out.println("FAIL -- unexpected exception: "+e); e.printStackTrace(); } System.out.println("Test resultsetJdbc30 finished"); } |
System.out.println("trying rs.updateClob(String, Array) :"); | System.out.println("trying rs.updateArray(String, Array) :"); | public static void main(String[] args) { Connection con; ResultSet rs; Statement stmt; String[] columnNames = {"i", "s", "r", "d", "dt", "t", "ts", "c", "v", "tn", "dc"}; System.out.println("Test resultsetJdbc30 starting"); try { // use the ij utility to read the property file and // make the initial connection. ij.getPropertyArg(args); con = ij.startJBMS(); stmt = con.createStatement(); //create a table, insert a row, do a select from the table, stmt.execute("create table t (i int, s smallint, r real, "+ "d double precision, dt date, t time, ts timestamp, "+ "c char(10), v varchar(40) not null, dc dec(10,2))"); stmt.execute("insert into t values(1,2,3.3,4.4,date('1990-05-05'),"+ "time('12:06:06'),timestamp('1990-07-07 07:07:07.07'),"+ "'eight','nine', 11.1)"); rs = stmt.executeQuery("select * from t"); rs.next(); //following will give not implemented exceptions. try { System.out.println(); System.out.println("trying rs.getURL(int) :"); rs.getURL(8); System.out.println("Shouldn't reach here. Method not implemented yet."); } catch (SQLException ex) { System.out.println("Expected : " + ex.getMessage()); } try { System.out.println(); System.out.println("trying rs.getURL(String) :"); rs.getURL("c"); System.out.println("Shouldn't reach here. Method not implemented yet."); } catch (SQLException ex) { System.out.println("Expected : " + ex.getMessage()); } try { System.out.println(); System.out.println("trying rs.updateRef(int, Ref) :"); rs.updateRef(8,null); System.out.println("Shouldn't reach here. Method not implemented yet."); } catch (SQLException ex) { System.out.println("Expected : " + ex.getMessage()); } try { System.out.println(); System.out.println("trying rs.updateRef(String, Ref) :"); rs.updateRef("c",null); System.out.println("Shouldn't reach here. Method not implemented yet."); } catch (SQLException ex) { System.out.println("Expected : " + ex.getMessage()); } try { System.out.println(); System.out.println("trying rs.updateBlob(int, Blob) :"); rs.updateBlob(8,null); System.out.println("Shouldn't reach here because method is being invoked on a read only resultset"); } catch (SQLException ex) { System.out.println("Expected : " + ex.getMessage()); } try { System.out.println(); System.out.println("trying rs.updateBlob(String, Blob) :"); rs.updateBlob("c",null); System.out.println("Shouldn't reach here because method is being invoked on a read only resultset"); } catch (SQLException ex) { System.out.println("Expected : " + ex.getMessage()); } try { System.out.println(); System.out.println("trying rs.updateClob(int, Clob) :"); rs.updateClob(8,null); System.out.println("Shouldn't reach here because method is being invoked on a read only resultset"); } catch (SQLException ex) { System.out.println("Expected : " + ex.getMessage()); } try { System.out.println(); System.out.println("trying rs.updateClob(String, Clob) :"); rs.updateClob("c",null); System.out.println("Shouldn't reach here because method is being invoked on a read only resultset"); } catch (SQLException ex) { System.out.println("Expected : " + ex.getMessage()); } try { System.out.println(); System.out.println("trying rs.updateArray(int, Array) :"); rs.updateArray(8,null); System.out.println("Shouldn't reach here. Method not implemented yet."); } catch (SQLException ex) { System.out.println("Expected : " + ex.getMessage()); } try { System.out.println(); System.out.println("trying rs.updateClob(String, Array) :"); rs.updateArray("c",null); System.out.println("Shouldn't reach here. Method not implemented yet."); } catch (SQLException ex) { System.out.println("Expected : " + ex.getMessage()); } rs.close(); stmt.close(); con.close(); } catch (SQLException e) { dumpSQLExceptions(e); e.printStackTrace(); } catch (Throwable e) { System.out.println("FAIL -- unexpected exception: "+e); e.printStackTrace(); } System.out.println("Test resultsetJdbc30 finished"); } |
closeCleanup); | userSuppliedOptimizerOverrides, closeCleanup); | public NestedLoopLeftOuterJoinResultSet( NoPutResultSet leftResultSet, int leftNumCols, NoPutResultSet rightResultSet, int rightNumCols, Activation activation, GeneratedMethod restriction, int resultSetNumber, GeneratedMethod emptyRowFun, boolean wasRightOuterJoin, boolean oneRowRightSide, boolean notExistsRightSide, double optimizerEstimatedRowCount, double optimizerEstimatedCost, GeneratedMethod closeCleanup) { super(leftResultSet, leftNumCols, rightResultSet, rightNumCols, activation, restriction, resultSetNumber, oneRowRightSide, notExistsRightSide, optimizerEstimatedRowCount, optimizerEstimatedCost, closeCleanup); this.emptyRowFun = emptyRowFun; this.wasRightOuterJoin = wasRightOuterJoin; } |
BufferedReader bufferedReader = new BufferedReader(reader); while (true) { String line = bufferedReader.readLine(); if (line == null) { break; } else { buffer.append(line); buffer.append('\n'); } } | char[] charBuffer = new char[ 4096 ]; int read; do { read = reader.read( charBuffer ); if ( read > 0 ) { buffer.append( charBuffer, 0, read ); } } while ( read > 0); | protected String loadText(Reader reader) throws IOException { StringBuffer buffer = new StringBuffer(); // @todo its probably more efficient to use a fixed char[] buffer instead try { BufferedReader bufferedReader = new BufferedReader(reader); while (true) { String line = bufferedReader.readLine(); if (line == null) { break; } else { buffer.append(line); buffer.append('\n'); } } return buffer.toString(); } finally { try { reader.close(); } catch (Exception e) { log.error( "Caught exception closing Reader: " + e, e); } } } |
try { dumpRS(met.getFunctions(null, null, null)); dumpRS(met.getFunctions("Dummy Catalog", null, null)); dumpRS(met.getFunctions(null, "SYS%", null)); dumpRS(met.getFunctions(null, null, "%GET%")); checkEmptyRS(met.getFunctions("", "", null)); } catch (SQLException e) { System.out.println("getFunctions():"); dumpSQLExceptions(e); } catch (AbstractMethodError ame) { System.out.println("getClientInfoProperties():"); ame.printStackTrace(System.out); } | dumpRS(met.getFunctions(null, null, null)); dumpRS(met.getFunctions("Dummy Catalog", null, null)); dumpRS(met.getFunctions(null, "SYS%", null)); dumpRS(met.getFunctions(null, null, "%GET%")); checkEmptyRS(met.getFunctions("", "", null)); | private static void testDatabaseMetaDataMethods(Connection con) throws Exception { con.setAutoCommit(true); // make sure it is true Statement s = con.createStatement(); DatabaseMetaData met = con.getMetaData(); if (!met.supportsStoredFunctionsUsingCallSyntax()) { System.out.println ("FAIL: supportsStoredFunctionsUsingCallSyntax() " + "should return true"); } if (met.autoCommitFailureClosesAllResultSets()) { System.out.println ("FAIL: autoCommitFailureClosesAllResultSets() " + "should return false"); } if (met.providesQueryObjectGenerator()) { System.out.println ("FAIL: providesQueryObjectGenerator() should " + "return false"); } try { checkEmptyRS(met.getClientInfoProperties()); } catch (SQLException e) { // TODO: remove try/catch once method is implemented! System.out.println("getClientInfoProperties():"); dumpSQLExceptions(e); } // Create some functions in the default schema (app) to make // the output from getFunctions() and getFunctionParameters // more interesting s.execute("CREATE FUNCTION DUMMY1 ( X SMALLINT ) RETURNS SMALLINT "+ "PARAMETER STYLE JAVA NO SQL LANGUAGE JAVA EXTERNAL "+ "NAME 'java.some.func'"); s.execute("CREATE FUNCTION DUMMY2 ( X INTEGER, Y SMALLINT ) RETURNS"+ " INTEGER PARAMETER STYLE JAVA NO SQL LANGUAGE JAVA "+ "EXTERNAL NAME 'java.some.func'"); s.execute("CREATE FUNCTION DUMMY3 ( X VARCHAR(16), Y INTEGER ) "+ "RETURNS VARCHAR(16) PARAMETER STYLE JAVA NO SQL LANGUAGE"+ " JAVA EXTERNAL NAME 'java.some.func'"); s.execute("CREATE FUNCTION DUMMY4 ( X VARCHAR(128), Y INTEGER ) "+ "RETURNS INTEGER PARAMETER STYLE JAVA NO SQL LANGUAGE "+ "JAVA EXTERNAL NAME 'java.some.func'"); try { checkEmptyRS(met.getFunctionParameters(null,null,null,null)); } catch (SQLException e) { // TODO: remove try/catch once method is implemented! System.out.println("getFunctionParameters():"); dumpSQLExceptions(e); } catch (AbstractMethodError ame) { // TODO: No implementation on client yet, so catch // AbstractMethodError for now. Remove when implemented. System.out.println("getFunctionParameters():"); ame.printStackTrace(System.out); } try { // Any function in any schema in any catalog dumpRS(met.getFunctions(null, null, null)); // Any function in any schema in "Dummy // Catalog". Same as above since the catalog // argument is ignored (is always null) dumpRS(met.getFunctions("Dummy Catalog", null, null)); // Any function in a schema starting with "SYS" dumpRS(met.getFunctions(null, "SYS%", null)); // All functions containing "GET" in any schema // (and any catalog) dumpRS(met.getFunctions(null, null, "%GET%")); // Any function that belongs to NO schema and // NO catalog (none) checkEmptyRS(met.getFunctions("", "", null)); } catch (SQLException e) { // TODO: remove try/catch once method is implemented! System.out.println("getFunctions():"); dumpSQLExceptions(e); } catch (AbstractMethodError ame) { // TODO: No implementation on client yet, so catch // AbstractMethodError for now. Remove when implemented. System.out.println("getClientInfoProperties():"); ame.printStackTrace(System.out); } try { // // Test the new getSchemas() with no schema qualifiers // dumpRS(met.getSchemas(null, null)); // // Test the new getSchemas() with a schema wildcard qualifier // dumpRS(met.getSchemas(null, "SYS%")); // // Test the new getSchemas() with an exact match // dumpRS(met.getSchemas(null, "APP")); // // Make sure that getSchemas() returns an empty result // set when a schema is passed with no match // checkEmptyRS(met.getSchemas(null, "BLAH")); } catch (SQLException e) { // TODO: remove try/catch once method is implemented! System.out.println("getSchemas():"); dumpSQLExceptions(e); } if(usingEmbeddedClient()) t_wrapper(met); s.close(); } |
testSecMec tester = new testSecMec(); | testSecMec tester = new testSecMec(consoleLogStream, originalStream, shutdownLogStream, consoleErrLogStream, originalErrStream, shutdownErrLogStream); | public static void main(String[] args) throws Exception { // Load harness properties. ij.getPropertyArg(args); String hostName = TestUtil.getHostName(); if (hostName.equals("localhost")) NETWORKSERVER_PORT = 20000; else NETWORKSERVER_PORT = 1527; // "runTest()" is going to try to connect to the database through // the server at port NETWORKSERVER_PORT. Thus, we have to // start the server on that port before calling runTest. try { TestUtil.loadDriver(); } catch (Exception e) { e.printStackTrace(); } // Start the NetworkServer on another thread, unless it's a remote host if (hostName.equals("localhost")) { networkServer = new NetworkServerControl(InetAddress.getByName(hostName),NETWORKSERVER_PORT); networkServer.start(null); // Wait for the NetworkServer to start. if (!isServerStarted(networkServer, 60)) System.exit(-1); } // Now, go ahead and run the test. try { testSecMec tester = new testSecMec(); tester.runTest(); } catch (Exception e) { // if we catch an exception of some sort, we need to make sure to // close our streams before returning; otherwise, we can get // hangs in the harness. SO, catching all exceptions here keeps // us from exiting before closing the necessary streams. System.out.println("FAIL - Exiting due to unexpected error: " + e.getMessage()); e.printStackTrace(); } // Shutdown the server. if (hostName.equals("localhost")) { networkServer.shutdown(); // how do we do this with the new api? //networkServer.join(); Thread.sleep(5000); } System.out.println("Completed testSecMec"); System.out.close(); System.err.close(); } |
{ | { consoleLogStream.switchOutput( shutdownLogStream ); consoleErrLogStream.switchOutput( shutdownErrLogStream ); | public static void main(String[] args) throws Exception { // Load harness properties. ij.getPropertyArg(args); String hostName = TestUtil.getHostName(); if (hostName.equals("localhost")) NETWORKSERVER_PORT = 20000; else NETWORKSERVER_PORT = 1527; // "runTest()" is going to try to connect to the database through // the server at port NETWORKSERVER_PORT. Thus, we have to // start the server on that port before calling runTest. try { TestUtil.loadDriver(); } catch (Exception e) { e.printStackTrace(); } // Start the NetworkServer on another thread, unless it's a remote host if (hostName.equals("localhost")) { networkServer = new NetworkServerControl(InetAddress.getByName(hostName),NETWORKSERVER_PORT); networkServer.start(null); // Wait for the NetworkServer to start. if (!isServerStarted(networkServer, 60)) System.exit(-1); } // Now, go ahead and run the test. try { testSecMec tester = new testSecMec(); tester.runTest(); } catch (Exception e) { // if we catch an exception of some sort, we need to make sure to // close our streams before returning; otherwise, we can get // hangs in the harness. SO, catching all exceptions here keeps // us from exiting before closing the necessary streams. System.out.println("FAIL - Exiting due to unexpected error: " + e.getMessage()); e.printStackTrace(); } // Shutdown the server. if (hostName.equals("localhost")) { networkServer.shutdown(); // how do we do this with the new api? //networkServer.join(); Thread.sleep(5000); } System.out.println("Completed testSecMec"); System.out.close(); System.err.close(); } |
System.out.close(); System.err.close(); | originalStream.close(); shutdownLogStream.close(); originalErrStream.close(); shutdownErrLogStream.close(); | public static void main(String[] args) throws Exception { // Load harness properties. ij.getPropertyArg(args); String hostName = TestUtil.getHostName(); if (hostName.equals("localhost")) NETWORKSERVER_PORT = 20000; else NETWORKSERVER_PORT = 1527; // "runTest()" is going to try to connect to the database through // the server at port NETWORKSERVER_PORT. Thus, we have to // start the server on that port before calling runTest. try { TestUtil.loadDriver(); } catch (Exception e) { e.printStackTrace(); } // Start the NetworkServer on another thread, unless it's a remote host if (hostName.equals("localhost")) { networkServer = new NetworkServerControl(InetAddress.getByName(hostName),NETWORKSERVER_PORT); networkServer.start(null); // Wait for the NetworkServer to start. if (!isServerStarted(networkServer, 60)) System.exit(-1); } // Now, go ahead and run the test. try { testSecMec tester = new testSecMec(); tester.runTest(); } catch (Exception e) { // if we catch an exception of some sort, we need to make sure to // close our streams before returning; otherwise, we can get // hangs in the harness. SO, catching all exceptions here keeps // us from exiting before closing the necessary streams. System.out.println("FAIL - Exiting due to unexpected error: " + e.getMessage()); e.printStackTrace(); } // Shutdown the server. if (hostName.equals("localhost")) { networkServer.shutdown(); // how do we do this with the new api? //networkServer.join(); Thread.sleep(5000); } System.out.println("Completed testSecMec"); System.out.close(); System.err.close(); } |
public Volume( String volName, String volBaseDir ) { volumeName = volName; volumeBaseDir = new File( volBaseDir ); if ( !volumeBaseDir.exists() ) { volumeBaseDir.mkdir(); } registerVolume(); | public Volume() { | public Volume( String volName, String volBaseDir ) { volumeName = volName; volumeBaseDir = new File( volBaseDir ); if ( !volumeBaseDir.exists() ) { volumeBaseDir.mkdir(); } registerVolume(); } |
log.debug( "Mapped " + fname + " to " + archiveFile ); | public File mapFileName( String fname ) throws FileNotFoundException { File yearDir = new File( volumeBaseDir, fname.substring( 0, 4 ) ); File monthDir = new File ( yearDir, fname.substring( 0, 6 ) ); File archiveFile = new File( monthDir, fname ); if ( !archiveFile.exists() ) { throw new FileNotFoundException( archiveFile.getPath() + " does not exist in volume" ); } return archiveFile; } |
|
public Vector<Transaction> getTransactions(Date startDate, Date endDate){ Vector<Transaction> transactions = getTransactions(); Vector<Transaction> v = new Vector<Transaction>(); for (Transaction t : transactions) { if ((t.getDate().after(startDate) || t.getDate().equals(startDate)) && (t.getDate().before(endDate) || t.getDate().equals(endDate))){ v.add(t); } } Collections.sort(v); return v; | public Vector<Transaction> getTransactions(){ Vector<Transaction> transactions = new Vector<Transaction>(getDataModel().getAllTransactions().getTransactions()); Collections.sort(transactions); return transactions; | public Vector<Transaction> getTransactions(Date startDate, Date endDate){ Vector<Transaction> transactions = getTransactions(); Vector<Transaction> v = new Vector<Transaction>(); for (Transaction t : transactions) { if ((t.getDate().after(startDate) || t.getDate().equals(startDate)) && (t.getDate().before(endDate) || t.getDate().equals(endDate))){ v.add(t); } } Collections.sort(v); return v; } |
public void parseHapMap(Vector rawLines) throws PedFileException { | public void parseHapMap(Vector lines) throws PedFileException { | public void parseHapMap(Vector rawLines) throws PedFileException { int colNum = -1; int numLines = rawLines.size(); if (numLines < 2){ throw new PedFileException("Hapmap data format error: empty file"); } Individual ind; this.allIndividuals = new Vector(); //sort first Vector lines = new Vector(); Hashtable sortHelp = new Hashtable(numLines-1,1.0f); long[] pos = new long[numLines-1]; lines.add(rawLines.get(0)); for (int k = 1; k < numLines; k++){ StringTokenizer st = new StringTokenizer((String) rawLines.get(k)); //strip off 1st 3 cols st.nextToken();st.nextToken();st.nextToken(); pos[k-1] = new Long(st.nextToken()).longValue(); sortHelp.put(new Long(pos[k-1]),rawLines.get(k)); } Arrays.sort(pos); for (int i = 0; i < pos.length; i++){ lines.add(sortHelp.get(new Long(pos[i]))); } //enumerate indivs StringTokenizer st = new StringTokenizer((String)lines.get(0), "\n\t\" \""); int numMetaColumns = 0; boolean doneMeta = false; while(!doneMeta && st.hasMoreTokens()){ String thisfield = st.nextToken(); numMetaColumns++; //first indiv ID will be a string beginning with "NA" if (thisfield.startsWith("NA")){ doneMeta = true; } } numMetaColumns--; st = new StringTokenizer((String)lines.get(0), "\n\t\" \""); for (int i = 0; i < numMetaColumns; i++){ st.nextToken(); } Vector namesIncludingDups = new Vector(); StringTokenizer dt; while (st.hasMoreTokens()){ ind = new Individual(numLines); String name = st.nextToken(); namesIncludingDups.add(name); if (name.endsWith("dup")){ //skip dups (i.e. don't add 'em to ind array) continue; } String details = (String)hapMapTranslate.get(name); if (details == null){ throw new PedFileException("Hapmap data format error: " + name); } dt = new StringTokenizer(details, "\n\t\" \""); ind.setFamilyID(dt.nextToken().trim()); ind.setIndividualID(dt.nextToken().trim()); ind.setDadID(dt.nextToken().trim()); ind.setMomID(dt.nextToken().trim()); try { ind.setGender(Integer.parseInt(dt.nextToken().trim())); ind.setAffectedStatus(Integer.parseInt(dt.nextToken().trim())); }catch(NumberFormatException nfe) { throw new PedFileException("File error: invalid gender or affected status for indiv " + name); } //check if the family exists already in the Hashtable Family fam = (Family)this.families.get(ind.getFamilyID()); if(fam == null){ //it doesnt exist, so create a new Family object fam = new Family(ind.getFamilyID()); } fam.addMember(ind); this.families.put(ind.getFamilyID(),fam); this.allIndividuals.add(ind); } //start at k=1 to skip header which we just processed above. hminfo = new String[numLines-1][]; for(int k=1;k<numLines;k++){ StringTokenizer tokenizer = new StringTokenizer((String)lines.get(k)); //reading the first line if(colNum < 0){ //only check column number count for the first line colNum = tokenizer.countTokens(); } if(colNum != tokenizer.countTokens()) { //this line has a different number of columns //should send some sort of error message //TODO: add something which stores number of markers for all lines and checks that they're consistent throw new PedFileException("Line number mismatch in input file. line " + (k+1)); } if(tokenizer.hasMoreTokens()){ hminfo[k-1] = new String[2]; for (int skip = 0; skip < numMetaColumns; skip++){ //meta-data crap String s = tokenizer.nextToken().trim(); //get marker name, chrom and pos if (skip == 0){ hminfo[k-1][0] = s; } if (skip == 2){ String dc = Chromosome.getDataChrom(); if (dc != null){ if (!dc.equalsIgnoreCase(s)){ throw new PedFileException("Hapmap file format error on line " + (k+1) + ":\n The file appears to contain multiple chromosomes:" + "\n" + dc + ", " + s); } }else{ Chromosome.setDataChrom(s); } } if (skip == 3){ hminfo[k-1][1] = s; } } int index = 0; int indexIncludingDups = -1; while(tokenizer.hasMoreTokens()){ String alleles = tokenizer.nextToken(); indexIncludingDups++; //we've skipped the dups in the ind array, so we skip their genotypes if (((String)namesIncludingDups.elementAt(indexIncludingDups)).endsWith("dup")){ continue; } ind = (Individual)allIndividuals.elementAt(index); int allele1=0, allele2=0; if (alleles.substring(0,1).equals("A")){ allele1 = 1; }else if (alleles.substring(0,1).equals("C")){ allele1 = 2; }else if (alleles.substring(0,1).equals("G")){ allele1 = 3; }else if (alleles.substring(0,1).equals("T")){ allele1 = 4; } if (alleles.substring(1,2).equals("A")){ allele2 = 1; }else if (alleles.substring(1,2).equals("C")){ allele2 = 2; }else if (alleles.substring(1,2).equals("G")){ allele2 = 3; }else if (alleles.substring(1,2).equals("T")){ allele2 = 4; } byte[] markers = new byte[2]; markers[0] = (byte)allele1; markers[1]= (byte)allele2; ind.addMarker(markers); index++; } } } } |
int numLines = rawLines.size(); | int numLines = lines.size(); | public void parseHapMap(Vector rawLines) throws PedFileException { int colNum = -1; int numLines = rawLines.size(); if (numLines < 2){ throw new PedFileException("Hapmap data format error: empty file"); } Individual ind; this.allIndividuals = new Vector(); //sort first Vector lines = new Vector(); Hashtable sortHelp = new Hashtable(numLines-1,1.0f); long[] pos = new long[numLines-1]; lines.add(rawLines.get(0)); for (int k = 1; k < numLines; k++){ StringTokenizer st = new StringTokenizer((String) rawLines.get(k)); //strip off 1st 3 cols st.nextToken();st.nextToken();st.nextToken(); pos[k-1] = new Long(st.nextToken()).longValue(); sortHelp.put(new Long(pos[k-1]),rawLines.get(k)); } Arrays.sort(pos); for (int i = 0; i < pos.length; i++){ lines.add(sortHelp.get(new Long(pos[i]))); } //enumerate indivs StringTokenizer st = new StringTokenizer((String)lines.get(0), "\n\t\" \""); int numMetaColumns = 0; boolean doneMeta = false; while(!doneMeta && st.hasMoreTokens()){ String thisfield = st.nextToken(); numMetaColumns++; //first indiv ID will be a string beginning with "NA" if (thisfield.startsWith("NA")){ doneMeta = true; } } numMetaColumns--; st = new StringTokenizer((String)lines.get(0), "\n\t\" \""); for (int i = 0; i < numMetaColumns; i++){ st.nextToken(); } Vector namesIncludingDups = new Vector(); StringTokenizer dt; while (st.hasMoreTokens()){ ind = new Individual(numLines); String name = st.nextToken(); namesIncludingDups.add(name); if (name.endsWith("dup")){ //skip dups (i.e. don't add 'em to ind array) continue; } String details = (String)hapMapTranslate.get(name); if (details == null){ throw new PedFileException("Hapmap data format error: " + name); } dt = new StringTokenizer(details, "\n\t\" \""); ind.setFamilyID(dt.nextToken().trim()); ind.setIndividualID(dt.nextToken().trim()); ind.setDadID(dt.nextToken().trim()); ind.setMomID(dt.nextToken().trim()); try { ind.setGender(Integer.parseInt(dt.nextToken().trim())); ind.setAffectedStatus(Integer.parseInt(dt.nextToken().trim())); }catch(NumberFormatException nfe) { throw new PedFileException("File error: invalid gender or affected status for indiv " + name); } //check if the family exists already in the Hashtable Family fam = (Family)this.families.get(ind.getFamilyID()); if(fam == null){ //it doesnt exist, so create a new Family object fam = new Family(ind.getFamilyID()); } fam.addMember(ind); this.families.put(ind.getFamilyID(),fam); this.allIndividuals.add(ind); } //start at k=1 to skip header which we just processed above. hminfo = new String[numLines-1][]; for(int k=1;k<numLines;k++){ StringTokenizer tokenizer = new StringTokenizer((String)lines.get(k)); //reading the first line if(colNum < 0){ //only check column number count for the first line colNum = tokenizer.countTokens(); } if(colNum != tokenizer.countTokens()) { //this line has a different number of columns //should send some sort of error message //TODO: add something which stores number of markers for all lines and checks that they're consistent throw new PedFileException("Line number mismatch in input file. line " + (k+1)); } if(tokenizer.hasMoreTokens()){ hminfo[k-1] = new String[2]; for (int skip = 0; skip < numMetaColumns; skip++){ //meta-data crap String s = tokenizer.nextToken().trim(); //get marker name, chrom and pos if (skip == 0){ hminfo[k-1][0] = s; } if (skip == 2){ String dc = Chromosome.getDataChrom(); if (dc != null){ if (!dc.equalsIgnoreCase(s)){ throw new PedFileException("Hapmap file format error on line " + (k+1) + ":\n The file appears to contain multiple chromosomes:" + "\n" + dc + ", " + s); } }else{ Chromosome.setDataChrom(s); } } if (skip == 3){ hminfo[k-1][1] = s; } } int index = 0; int indexIncludingDups = -1; while(tokenizer.hasMoreTokens()){ String alleles = tokenizer.nextToken(); indexIncludingDups++; //we've skipped the dups in the ind array, so we skip their genotypes if (((String)namesIncludingDups.elementAt(indexIncludingDups)).endsWith("dup")){ continue; } ind = (Individual)allIndividuals.elementAt(index); int allele1=0, allele2=0; if (alleles.substring(0,1).equals("A")){ allele1 = 1; }else if (alleles.substring(0,1).equals("C")){ allele1 = 2; }else if (alleles.substring(0,1).equals("G")){ allele1 = 3; }else if (alleles.substring(0,1).equals("T")){ allele1 = 4; } if (alleles.substring(1,2).equals("A")){ allele2 = 1; }else if (alleles.substring(1,2).equals("C")){ allele2 = 2; }else if (alleles.substring(1,2).equals("G")){ allele2 = 3; }else if (alleles.substring(1,2).equals("T")){ allele2 = 4; } byte[] markers = new byte[2]; markers[0] = (byte)allele1; markers[1]= (byte)allele2; ind.addMarker(markers); index++; } } } } |
Vector lines = new Vector(); Hashtable sortHelp = new Hashtable(numLines-1,1.0f); long[] pos = new long[numLines-1]; lines.add(rawLines.get(0)); for (int k = 1; k < numLines; k++){ StringTokenizer st = new StringTokenizer((String) rawLines.get(k)); st.nextToken();st.nextToken();st.nextToken(); pos[k-1] = new Long(st.nextToken()).longValue(); sortHelp.put(new Long(pos[k-1]),rawLines.get(k)); } Arrays.sort(pos); for (int i = 0; i < pos.length; i++){ lines.add(sortHelp.get(new Long(pos[i]))); } | public void parseHapMap(Vector rawLines) throws PedFileException { int colNum = -1; int numLines = rawLines.size(); if (numLines < 2){ throw new PedFileException("Hapmap data format error: empty file"); } Individual ind; this.allIndividuals = new Vector(); //sort first Vector lines = new Vector(); Hashtable sortHelp = new Hashtable(numLines-1,1.0f); long[] pos = new long[numLines-1]; lines.add(rawLines.get(0)); for (int k = 1; k < numLines; k++){ StringTokenizer st = new StringTokenizer((String) rawLines.get(k)); //strip off 1st 3 cols st.nextToken();st.nextToken();st.nextToken(); pos[k-1] = new Long(st.nextToken()).longValue(); sortHelp.put(new Long(pos[k-1]),rawLines.get(k)); } Arrays.sort(pos); for (int i = 0; i < pos.length; i++){ lines.add(sortHelp.get(new Long(pos[i]))); } //enumerate indivs StringTokenizer st = new StringTokenizer((String)lines.get(0), "\n\t\" \""); int numMetaColumns = 0; boolean doneMeta = false; while(!doneMeta && st.hasMoreTokens()){ String thisfield = st.nextToken(); numMetaColumns++; //first indiv ID will be a string beginning with "NA" if (thisfield.startsWith("NA")){ doneMeta = true; } } numMetaColumns--; st = new StringTokenizer((String)lines.get(0), "\n\t\" \""); for (int i = 0; i < numMetaColumns; i++){ st.nextToken(); } Vector namesIncludingDups = new Vector(); StringTokenizer dt; while (st.hasMoreTokens()){ ind = new Individual(numLines); String name = st.nextToken(); namesIncludingDups.add(name); if (name.endsWith("dup")){ //skip dups (i.e. don't add 'em to ind array) continue; } String details = (String)hapMapTranslate.get(name); if (details == null){ throw new PedFileException("Hapmap data format error: " + name); } dt = new StringTokenizer(details, "\n\t\" \""); ind.setFamilyID(dt.nextToken().trim()); ind.setIndividualID(dt.nextToken().trim()); ind.setDadID(dt.nextToken().trim()); ind.setMomID(dt.nextToken().trim()); try { ind.setGender(Integer.parseInt(dt.nextToken().trim())); ind.setAffectedStatus(Integer.parseInt(dt.nextToken().trim())); }catch(NumberFormatException nfe) { throw new PedFileException("File error: invalid gender or affected status for indiv " + name); } //check if the family exists already in the Hashtable Family fam = (Family)this.families.get(ind.getFamilyID()); if(fam == null){ //it doesnt exist, so create a new Family object fam = new Family(ind.getFamilyID()); } fam.addMember(ind); this.families.put(ind.getFamilyID(),fam); this.allIndividuals.add(ind); } //start at k=1 to skip header which we just processed above. hminfo = new String[numLines-1][]; for(int k=1;k<numLines;k++){ StringTokenizer tokenizer = new StringTokenizer((String)lines.get(k)); //reading the first line if(colNum < 0){ //only check column number count for the first line colNum = tokenizer.countTokens(); } if(colNum != tokenizer.countTokens()) { //this line has a different number of columns //should send some sort of error message //TODO: add something which stores number of markers for all lines and checks that they're consistent throw new PedFileException("Line number mismatch in input file. line " + (k+1)); } if(tokenizer.hasMoreTokens()){ hminfo[k-1] = new String[2]; for (int skip = 0; skip < numMetaColumns; skip++){ //meta-data crap String s = tokenizer.nextToken().trim(); //get marker name, chrom and pos if (skip == 0){ hminfo[k-1][0] = s; } if (skip == 2){ String dc = Chromosome.getDataChrom(); if (dc != null){ if (!dc.equalsIgnoreCase(s)){ throw new PedFileException("Hapmap file format error on line " + (k+1) + ":\n The file appears to contain multiple chromosomes:" + "\n" + dc + ", " + s); } }else{ Chromosome.setDataChrom(s); } } if (skip == 3){ hminfo[k-1][1] = s; } } int index = 0; int indexIncludingDups = -1; while(tokenizer.hasMoreTokens()){ String alleles = tokenizer.nextToken(); indexIncludingDups++; //we've skipped the dups in the ind array, so we skip their genotypes if (((String)namesIncludingDups.elementAt(indexIncludingDups)).endsWith("dup")){ continue; } ind = (Individual)allIndividuals.elementAt(index); int allele1=0, allele2=0; if (alleles.substring(0,1).equals("A")){ allele1 = 1; }else if (alleles.substring(0,1).equals("C")){ allele1 = 2; }else if (alleles.substring(0,1).equals("G")){ allele1 = 3; }else if (alleles.substring(0,1).equals("T")){ allele1 = 4; } if (alleles.substring(1,2).equals("A")){ allele2 = 1; }else if (alleles.substring(1,2).equals("C")){ allele2 = 2; }else if (alleles.substring(1,2).equals("G")){ allele2 = 3; }else if (alleles.substring(1,2).equals("T")){ allele2 = 4; } byte[] markers = new byte[2]; markers[0] = (byte)allele1; markers[1]= (byte)allele2; ind.addMarker(markers); index++; } } } } |
|
public Family(String familyName){ | public Family(){ | public Family(String familyName){ this.members = new Hashtable(); this.familyName = familyName; } |
this.familyName = familyName; | public Family(String familyName){ this.members = new Hashtable(); this.familyName = familyName; } |
|
public void doTag(XMLOutput output) throws Exception { | public void doTag(XMLOutput output) throws JellyTagException { | public void doTag(XMLOutput output) throws Exception { String message = getMessage(); if ( message == null ) { message = getBodyText(); } fail( message ); } |
public void flushCache(XWikiContext context) { virtualWikiList = new ArrayList(); if (virtualWikiMap!=null) { virtualWikiMap.flushAll(); virtualWikiMap = null; } if (groupService != null) groupService.flushCache(); XWikiStoreInterface store = getStore(); if ((store != null) && (store instanceof XWikiCacheStoreInterface)) { ((XWikiCacheStoreInterface) getStore()).flushCache(); } XWikiRenderingEngine rengine = getRenderingEngine(); if (rengine != null) rengine.flushCache(); XWikiPluginManager pmanager = getPluginManager(); if (pmanager != null) pmanager.flushCache(context); | public void flushCache() { flushCache(null); | public void flushCache(XWikiContext context) { // We need to flush the virtual wiki list virtualWikiList = new ArrayList(); // We need to flush the server Cache if (virtualWikiMap!=null) { virtualWikiMap.flushAll(); virtualWikiMap = null; } // We need to flush the group service cache if (groupService != null) groupService.flushCache(); // If we use the Cache Store layer.. we need to flush it XWikiStoreInterface store = getStore(); if ((store != null) && (store instanceof XWikiCacheStoreInterface)) { ((XWikiCacheStoreInterface) getStore()).flushCache(); } // Flush renderers.. Groovy renderer has a cache XWikiRenderingEngine rengine = getRenderingEngine(); if (rengine != null) rengine.flushCache(); XWikiPluginManager pmanager = getPluginManager(); if (pmanager != null) pmanager.flushCache(context); } |
putValue(SHORT_DESCRIPTION, "Forward Engineer SQL Script"); | public ExportDDLAction() { super("Forward Engineer...", ASUtils.createIcon("ForwardEngineer", "Forward Engineer", ArchitectFrame.getMainInstance().sprefs.getInt(SwingUserSettings.ICON_SIZE, 24))); architectFrame = ArchitectFrame.getMainInstance(); } |
|
"Export DDL Script"); | "Forward Engineer SQL Script"); | public void actionPerformed(ActionEvent e) { final JDialog d = new JDialog(ArchitectFrame.getMainInstance(), "Export DDL Script"); JPanel cp = new JPanel(new BorderLayout(12,12)); cp.setBorder(BorderFactory.createEmptyBorder(12,12,12,12)); final DDLExportPanel ddlPanel = new DDLExportPanel(architectFrame.project); cp.add(ddlPanel, BorderLayout.CENTER); JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); JButton okButton = new JButton("Ok"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { try { ddlPanel.applyChanges(); architectFrame.project.getDDLGenerator().writeDDL (architectFrame.playpen.getDatabase()); } catch (Exception ex) { JOptionPane.showMessageDialog (architectFrame, "Can't export DDL: "+ex.getMessage()); logger.error("Got exception while exporting DDL", ex); } d.setVisible(false); } }); buttonPanel.add(okButton); JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { ddlPanel.discardChanges(); d.setVisible(false); } }); buttonPanel.add(cancelButton); cp.add(buttonPanel, BorderLayout.SOUTH); d.setContentPane(cp); d.pack(); d.setVisible(true); } |
architectFrame.project.getDDLGenerator().writeDDL (architectFrame.playpen.getDatabase()); | showPreview(architectFrame.project.getDDLGenerator(), d); | public void actionPerformed(ActionEvent e) { final JDialog d = new JDialog(ArchitectFrame.getMainInstance(), "Export DDL Script"); JPanel cp = new JPanel(new BorderLayout(12,12)); cp.setBorder(BorderFactory.createEmptyBorder(12,12,12,12)); final DDLExportPanel ddlPanel = new DDLExportPanel(architectFrame.project); cp.add(ddlPanel, BorderLayout.CENTER); JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); JButton okButton = new JButton("Ok"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { try { ddlPanel.applyChanges(); architectFrame.project.getDDLGenerator().writeDDL (architectFrame.playpen.getDatabase()); } catch (Exception ex) { JOptionPane.showMessageDialog (architectFrame, "Can't export DDL: "+ex.getMessage()); logger.error("Got exception while exporting DDL", ex); } d.setVisible(false); } }); buttonPanel.add(okButton); JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { ddlPanel.discardChanges(); d.setVisible(false); } }); buttonPanel.add(cancelButton); cp.add(buttonPanel, BorderLayout.SOUTH); d.setContentPane(cp); d.pack(); d.setVisible(true); } |
d.setVisible(false); | public void actionPerformed(ActionEvent e) { final JDialog d = new JDialog(ArchitectFrame.getMainInstance(), "Export DDL Script"); JPanel cp = new JPanel(new BorderLayout(12,12)); cp.setBorder(BorderFactory.createEmptyBorder(12,12,12,12)); final DDLExportPanel ddlPanel = new DDLExportPanel(architectFrame.project); cp.add(ddlPanel, BorderLayout.CENTER); JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); JButton okButton = new JButton("Ok"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { try { ddlPanel.applyChanges(); architectFrame.project.getDDLGenerator().writeDDL (architectFrame.playpen.getDatabase()); } catch (Exception ex) { JOptionPane.showMessageDialog (architectFrame, "Can't export DDL: "+ex.getMessage()); logger.error("Got exception while exporting DDL", ex); } d.setVisible(false); } }); buttonPanel.add(okButton); JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { ddlPanel.discardChanges(); d.setVisible(false); } }); buttonPanel.add(cancelButton); cp.add(buttonPanel, BorderLayout.SOUTH); d.setContentPane(cp); d.pack(); d.setVisible(true); } |
|
architectFrame.project.getDDLGenerator().writeDDL (architectFrame.playpen.getDatabase()); | showPreview(architectFrame.project.getDDLGenerator(), d); | public void actionPerformed(ActionEvent evt) { try { ddlPanel.applyChanges(); architectFrame.project.getDDLGenerator().writeDDL (architectFrame.playpen.getDatabase()); } catch (Exception ex) { JOptionPane.showMessageDialog (architectFrame, "Can't export DDL: "+ex.getMessage()); logger.error("Got exception while exporting DDL", ex); } d.setVisible(false); } |
d.setVisible(false); | public void actionPerformed(ActionEvent evt) { try { ddlPanel.applyChanges(); architectFrame.project.getDDLGenerator().writeDDL (architectFrame.playpen.getDatabase()); } catch (Exception ex) { JOptionPane.showMessageDialog (architectFrame, "Can't export DDL: "+ex.getMessage()); logger.error("Got exception while exporting DDL", ex); } d.setVisible(false); } |
|
public Object getTaskObject(); | public Object getTaskObject() throws Exception; | public Object getTaskObject(); |
getBody().run(context, output); | invokeBody( output); | public void doTag(XMLOutput output) throws Exception { output.startElement(uri, localName, qname, attributes); getBody().run(context, output); output.endElement(uri, localName, qname); } |
int scaleSize = theData.dPrimeTable.length*30; | void doExportDPrime(){ fc.setSelectedFile(null); int returnVal = fc.showSaveDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION){ try { int scaleSize = theData.dPrimeTable.length*30; DrawingMethods dm = new DrawingMethods(); BufferedImage image = new BufferedImage(scaleSize, scaleSize, BufferedImage.TYPE_3BYTE_BGR); dm.dPrimeDraw(theData.dPrimeTable, infoKnown, theData.markerInfo, image.getGraphics()); dm.saveImage(image, fc.getSelectedFile().getPath()); } catch (IOException ioexec){ JOptionPane.showMessageDialog(this, ioexec.getMessage(), "File Error", JOptionPane.ERROR_MESSAGE); } } } |
|
BufferedImage image = new BufferedImage(scaleSize, scaleSize, BufferedImage.TYPE_3BYTE_BGR); | Dimension theSize = dm.dPrimeGetPreferredSize(theData.dPrimeTable.length, infoKnown); BufferedImage image = new BufferedImage((int)theSize.getWidth(), (int)theSize.getHeight(), BufferedImage.TYPE_3BYTE_BGR); | void doExportDPrime(){ fc.setSelectedFile(null); int returnVal = fc.showSaveDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION){ try { int scaleSize = theData.dPrimeTable.length*30; DrawingMethods dm = new DrawingMethods(); BufferedImage image = new BufferedImage(scaleSize, scaleSize, BufferedImage.TYPE_3BYTE_BGR); dm.dPrimeDraw(theData.dPrimeTable, infoKnown, theData.markerInfo, image.getGraphics()); dm.saveImage(image, fc.getSelectedFile().getPath()); } catch (IOException ioexec){ JOptionPane.showMessageDialog(this, ioexec.getMessage(), "File Error", JOptionPane.ERROR_MESSAGE); } } } |
finished = true; | public void doMonitoredComputation(){ dPrimeTable = generateDPrimeTable(chromosomes); blocks = guessBlocks(dPrimeTable, 0); } |
|
public void dPrimeDraw(String[][] table, boolean info, Vector snps, Graphics g){ | public void dPrimeDraw(PairwiseLinkage[][] table, boolean info, Vector snps, Graphics g){ | public void dPrimeDraw(String[][] table, boolean info, Vector snps, Graphics g){ int scale = table.length*30; int activeOffset = 0; float d, l, blgr; Color myColor; int[] shifts; Font regFont = new Font("Lucida Sans Regular", Font.PLAIN, 10); FontMetrics regfm = g.getFontMetrics(regFont); Font boldFont = new Font("Lucida Sans Bold", Font.BOLD, 14); FontMetrics boldfm = g.getFontMetrics(boldFont); if (info) activeOffset = labeloffset; //background color g.setColor(new Color(192,192,192)); g.fillRect(0,0,scale+activeOffset,scale); //first label: g.setColor(Color.black); g.setFont(boldFont); shifts = centerString("1", boldfm); g.drawString("1", activeOffset + shifts[0], shifts[1]); //if we know the marker names, print them down the side, along with MAF if (info){ NumberFormat nf = NumberFormat.getInstance(); nf.setMinimumFractionDigits(2); nf.setMaximumFractionDigits(2); g.setFont(regFont); for (int y = 0; y < table.length; y++){ String name = ((SNP)snps.elementAt(y)).getName(); name += " ("; name += nf.format(((SNP)snps.elementAt(y)).getMAF()); name += ")"; g.drawString(name, labeloffset-3-regfm.stringWidth(name), y*30 + shifts[1]); } //now draw a diagonal bar showing marker spacings if (table.length > 3){ g.drawLine(labeloffset+95,0,labeloffset+scale,scale-95); double lineLength = Math.sqrt((scale-95)*(scale-95)*2); double start = ((SNP)snps.elementAt(0)).getPosition(); double totalLength = ((SNP)snps.elementAt(table.length-1)).getPosition() - start; int numKB = (int)(totalLength/1000); g.drawString(numKB+" Kb", labeloffset+150, 30); for (int y = 0; y < table.length; y++){ double fracLength = (((SNP)snps.elementAt(y)).getPosition() - start)/totalLength; double xOrYDist = Math.sqrt((fracLength*lineLength*fracLength*lineLength)/2); int xSpineCoord = (int)(labeloffset + 90 +xOrYDist); int ySpineCoord = (int)(5+xOrYDist); g.drawLine(labeloffset+25+y*30, 5+y*30,xSpineCoord,ySpineCoord); //add "ticks" to spine g.drawLine(xSpineCoord, ySpineCoord, (xSpineCoord+5), (ySpineCoord-5)); } } } //draw table column by column for (int x = 0; x < table.length-1; x++){ for (int y = x + 1; y < table.length; y++){ StringTokenizer st = new StringTokenizer(table[x][y]); d = Float.parseFloat(st.nextToken()); l = Float.parseFloat(st.nextToken()); //set coloring based on LOD and D' if (l > 2){ if (d < 0.5) { //high LOD, low D' bluish color myColor = new Color(255, 224, 224); } else { //high LOD, high D' shades of red blgr = (255-32)*2*(1-d); myColor = new Color(255, (int) blgr, (int) blgr); } }else if (d > 0.99){ //high D', low LOD gray color myColor = new Color(192, 192, 240); }else { //no LD myColor = Color.white; } //draw the boxes g.setColor(myColor); g.fillRect(x*30+1+activeOffset, y*30+1, 28, 28); g.setColor(Color.black); g.drawRect(x*30+activeOffset, y*30, 30, 30); g.setFont(regFont); shifts=centerString(Float.toString(d), regfm); g.drawString(Float.toString(d), shifts[0]+(x*30)+activeOffset,(y*30)+shifts[1]); } //draw the labels g.setColor(Color.black); g.setFont(boldFont); shifts = centerString(Integer.toString(x+2), boldfm); g.drawString(Integer.toString(x+2), shifts[0]+(x+1)*30+activeOffset, shifts[1]+(x+1)*30); } } |
float d, l, blgr; | double d, l, blgr; | public void dPrimeDraw(String[][] table, boolean info, Vector snps, Graphics g){ int scale = table.length*30; int activeOffset = 0; float d, l, blgr; Color myColor; int[] shifts; Font regFont = new Font("Lucida Sans Regular", Font.PLAIN, 10); FontMetrics regfm = g.getFontMetrics(regFont); Font boldFont = new Font("Lucida Sans Bold", Font.BOLD, 14); FontMetrics boldfm = g.getFontMetrics(boldFont); if (info) activeOffset = labeloffset; //background color g.setColor(new Color(192,192,192)); g.fillRect(0,0,scale+activeOffset,scale); //first label: g.setColor(Color.black); g.setFont(boldFont); shifts = centerString("1", boldfm); g.drawString("1", activeOffset + shifts[0], shifts[1]); //if we know the marker names, print them down the side, along with MAF if (info){ NumberFormat nf = NumberFormat.getInstance(); nf.setMinimumFractionDigits(2); nf.setMaximumFractionDigits(2); g.setFont(regFont); for (int y = 0; y < table.length; y++){ String name = ((SNP)snps.elementAt(y)).getName(); name += " ("; name += nf.format(((SNP)snps.elementAt(y)).getMAF()); name += ")"; g.drawString(name, labeloffset-3-regfm.stringWidth(name), y*30 + shifts[1]); } //now draw a diagonal bar showing marker spacings if (table.length > 3){ g.drawLine(labeloffset+95,0,labeloffset+scale,scale-95); double lineLength = Math.sqrt((scale-95)*(scale-95)*2); double start = ((SNP)snps.elementAt(0)).getPosition(); double totalLength = ((SNP)snps.elementAt(table.length-1)).getPosition() - start; int numKB = (int)(totalLength/1000); g.drawString(numKB+" Kb", labeloffset+150, 30); for (int y = 0; y < table.length; y++){ double fracLength = (((SNP)snps.elementAt(y)).getPosition() - start)/totalLength; double xOrYDist = Math.sqrt((fracLength*lineLength*fracLength*lineLength)/2); int xSpineCoord = (int)(labeloffset + 90 +xOrYDist); int ySpineCoord = (int)(5+xOrYDist); g.drawLine(labeloffset+25+y*30, 5+y*30,xSpineCoord,ySpineCoord); //add "ticks" to spine g.drawLine(xSpineCoord, ySpineCoord, (xSpineCoord+5), (ySpineCoord-5)); } } } //draw table column by column for (int x = 0; x < table.length-1; x++){ for (int y = x + 1; y < table.length; y++){ StringTokenizer st = new StringTokenizer(table[x][y]); d = Float.parseFloat(st.nextToken()); l = Float.parseFloat(st.nextToken()); //set coloring based on LOD and D' if (l > 2){ if (d < 0.5) { //high LOD, low D' bluish color myColor = new Color(255, 224, 224); } else { //high LOD, high D' shades of red blgr = (255-32)*2*(1-d); myColor = new Color(255, (int) blgr, (int) blgr); } }else if (d > 0.99){ //high D', low LOD gray color myColor = new Color(192, 192, 240); }else { //no LD myColor = Color.white; } //draw the boxes g.setColor(myColor); g.fillRect(x*30+1+activeOffset, y*30+1, 28, 28); g.setColor(Color.black); g.drawRect(x*30+activeOffset, y*30, 30, 30); g.setFont(regFont); shifts=centerString(Float.toString(d), regfm); g.drawString(Float.toString(d), shifts[0]+(x*30)+activeOffset,(y*30)+shifts[1]); } //draw the labels g.setColor(Color.black); g.setFont(boldFont); shifts = centerString(Integer.toString(x+2), boldfm); g.drawString(Integer.toString(x+2), shifts[0]+(x+1)*30+activeOffset, shifts[1]+(x+1)*30); } } |
if (info) activeOffset = labeloffset; g.setColor(new Color(192,192,192)); g.fillRect(0,0,scale+activeOffset,scale); g.setColor(Color.black); g.setFont(boldFont); shifts = centerString("1", boldfm); g.drawString("1", activeOffset + shifts[0], shifts[1]); if (info){ NumberFormat nf = NumberFormat.getInstance(); nf.setMinimumFractionDigits(2); nf.setMaximumFractionDigits(2); g.setFont(regFont); for (int y = 0; y < table.length; y++){ String name = ((SNP)snps.elementAt(y)).getName(); name += " ("; name += nf.format(((SNP)snps.elementAt(y)).getMAF()); name += ")"; g.drawString(name, labeloffset-3-regfm.stringWidth(name), y*30 + shifts[1]); | if (info) activeOffset = labeloffset; g.setColor(new Color(192,192,192)); g.fillRect(0,0,scale+activeOffset,scale); g.setColor(Color.black); g.setFont(boldFont); shifts = centerString("1", boldfm); g.drawString("1", activeOffset + shifts[0], shifts[1]); if (info){ NumberFormat nf = NumberFormat.getInstance(); nf.setMinimumFractionDigits(2); nf.setMaximumFractionDigits(2); g.setFont(regFont); for (int y = 0; y < table.length; y++){ String name = ((SNP)snps.elementAt(y)).getName(); name += " ("; name += nf.format(((SNP)snps.elementAt(y)).getMAF()); name += ")"; g.drawString(name, labeloffset-3-regfm.stringWidth(name), y*30 + shifts[1]); } if (table.length > 3){ g.drawLine(labeloffset+95,0,labeloffset+scale,scale-95); double lineLength = Math.sqrt((scale-95)*(scale-95)*2); double start = ((SNP)snps.elementAt(0)).getPosition(); double totalLength = ((SNP)snps.elementAt(table.length-1)).getPosition() - start; int numKB = (int)(totalLength/1000); g.drawString(numKB+" Kb", labeloffset+150, 30); for (int y = 0; y < table.length; y++){ double fracLength = (((SNP)snps.elementAt(y)).getPosition() - start)/totalLength; double xOrYDist = Math.sqrt((fracLength*lineLength*fracLength*lineLength)/2); int xSpineCoord = (int)(labeloffset + 90 +xOrYDist); int ySpineCoord = (int)(5+xOrYDist); g.drawLine(labeloffset+25+y*30, 5+y*30,xSpineCoord,ySpineCoord); g.drawLine(xSpineCoord, ySpineCoord, (xSpineCoord+5), (ySpineCoord-5)); } } | public void dPrimeDraw(String[][] table, boolean info, Vector snps, Graphics g){ int scale = table.length*30; int activeOffset = 0; float d, l, blgr; Color myColor; int[] shifts; Font regFont = new Font("Lucida Sans Regular", Font.PLAIN, 10); FontMetrics regfm = g.getFontMetrics(regFont); Font boldFont = new Font("Lucida Sans Bold", Font.BOLD, 14); FontMetrics boldfm = g.getFontMetrics(boldFont); if (info) activeOffset = labeloffset; //background color g.setColor(new Color(192,192,192)); g.fillRect(0,0,scale+activeOffset,scale); //first label: g.setColor(Color.black); g.setFont(boldFont); shifts = centerString("1", boldfm); g.drawString("1", activeOffset + shifts[0], shifts[1]); //if we know the marker names, print them down the side, along with MAF if (info){ NumberFormat nf = NumberFormat.getInstance(); nf.setMinimumFractionDigits(2); nf.setMaximumFractionDigits(2); g.setFont(regFont); for (int y = 0; y < table.length; y++){ String name = ((SNP)snps.elementAt(y)).getName(); name += " ("; name += nf.format(((SNP)snps.elementAt(y)).getMAF()); name += ")"; g.drawString(name, labeloffset-3-regfm.stringWidth(name), y*30 + shifts[1]); } //now draw a diagonal bar showing marker spacings if (table.length > 3){ g.drawLine(labeloffset+95,0,labeloffset+scale,scale-95); double lineLength = Math.sqrt((scale-95)*(scale-95)*2); double start = ((SNP)snps.elementAt(0)).getPosition(); double totalLength = ((SNP)snps.elementAt(table.length-1)).getPosition() - start; int numKB = (int)(totalLength/1000); g.drawString(numKB+" Kb", labeloffset+150, 30); for (int y = 0; y < table.length; y++){ double fracLength = (((SNP)snps.elementAt(y)).getPosition() - start)/totalLength; double xOrYDist = Math.sqrt((fracLength*lineLength*fracLength*lineLength)/2); int xSpineCoord = (int)(labeloffset + 90 +xOrYDist); int ySpineCoord = (int)(5+xOrYDist); g.drawLine(labeloffset+25+y*30, 5+y*30,xSpineCoord,ySpineCoord); //add "ticks" to spine g.drawLine(xSpineCoord, ySpineCoord, (xSpineCoord+5), (ySpineCoord-5)); } } } //draw table column by column for (int x = 0; x < table.length-1; x++){ for (int y = x + 1; y < table.length; y++){ StringTokenizer st = new StringTokenizer(table[x][y]); d = Float.parseFloat(st.nextToken()); l = Float.parseFloat(st.nextToken()); //set coloring based on LOD and D' if (l > 2){ if (d < 0.5) { //high LOD, low D' bluish color myColor = new Color(255, 224, 224); } else { //high LOD, high D' shades of red blgr = (255-32)*2*(1-d); myColor = new Color(255, (int) blgr, (int) blgr); } }else if (d > 0.99){ //high D', low LOD gray color myColor = new Color(192, 192, 240); }else { //no LD myColor = Color.white; } //draw the boxes g.setColor(myColor); g.fillRect(x*30+1+activeOffset, y*30+1, 28, 28); g.setColor(Color.black); g.drawRect(x*30+activeOffset, y*30, 30, 30); g.setFont(regFont); shifts=centerString(Float.toString(d), regfm); g.drawString(Float.toString(d), shifts[0]+(x*30)+activeOffset,(y*30)+shifts[1]); } //draw the labels g.setColor(Color.black); g.setFont(boldFont); shifts = centerString(Integer.toString(x+2), boldfm); g.drawString(Integer.toString(x+2), shifts[0]+(x+1)*30+activeOffset, shifts[1]+(x+1)*30); } } |
if (table.length > 3){ g.drawLine(labeloffset+95,0,labeloffset+scale,scale-95); double lineLength = Math.sqrt((scale-95)*(scale-95)*2); double start = ((SNP)snps.elementAt(0)).getPosition(); double totalLength = ((SNP)snps.elementAt(table.length-1)).getPosition() - start; int numKB = (int)(totalLength/1000); g.drawString(numKB+" Kb", labeloffset+150, 30); for (int y = 0; y < table.length; y++){ double fracLength = (((SNP)snps.elementAt(y)).getPosition() - start)/totalLength; double xOrYDist = Math.sqrt((fracLength*lineLength*fracLength*lineLength)/2); int xSpineCoord = (int)(labeloffset + 90 +xOrYDist); int ySpineCoord = (int)(5+xOrYDist); g.drawLine(labeloffset+25+y*30, 5+y*30,xSpineCoord,ySpineCoord); g.drawLine(xSpineCoord, ySpineCoord, (xSpineCoord+5), (ySpineCoord-5)); | for (int x = 0; x < table.length-1; x++){ for (int y = x + 1; y < table.length; y++){ PairwiseLinkage thisPair = table[x][y]; d = thisPair.getDPrime(); l = thisPair.getLOD(); if (l > 2){ if (d < 0.5) { myColor = new Color(255, 224, 224); } else { blgr = (255-32)*2*(1-d); myColor = new Color(255, (int) blgr, (int) blgr); } }else if (d > 0.99){ myColor = new Color(192, 192, 240); }else { myColor = Color.white; } g.setColor(myColor); g.fillRect(x*30+1+activeOffset, y*30+1, 29, 29); g.setColor(Color.black); g.drawRect(x*30+activeOffset, y*30, 30, 30); g.setFont(regFont); shifts=centerString(Double.toString(d), regfm); g.drawString(Double.toString(d), shifts[0]+(x*30)+activeOffset,(y*30)+shifts[1]); } g.setColor(Color.black); g.setFont(boldFont); shifts = centerString(Integer.toString(x+2), boldfm); g.drawString(Integer.toString(x+2), shifts[0]+(x+1)*30+activeOffset, shifts[1]+(x+1)*30); } /**}else{ int boxDimension = 600/table.length; scale = 600; if(info){ if (table.length > 3){ labeloffset=0; g.drawLine(labeloffset+95,0,labeloffset+scale,scale-95); double lineLength = Math.sqrt((scale-95)*(scale-95)*2); double start = ((SNP)snps.elementAt(0)).getPosition(); double totalLength = ((SNP)snps.elementAt(table.length-1)).getPosition() - start; int numKB = (int)(totalLength/1000); g.drawString(numKB+" Kb", labeloffset+150, boxDimension); for (int y = 0; y < table.length; y++){ double fracLength = (((SNP)snps.elementAt(y)).getPosition() - start)/totalLength; double xOrYDist = Math.sqrt((fracLength*lineLength*fracLength*lineLength)/2); int xSpineCoord = (int)(labeloffset + 90 +xOrYDist); int ySpineCoord = (int)(5+xOrYDist); g.drawLine(labeloffset+25+y*boxDimension, 5+y*boxDimension,xSpineCoord,ySpineCoord); g.drawLine(xSpineCoord, ySpineCoord, (xSpineCoord+5), (ySpineCoord-5)); } | public void dPrimeDraw(String[][] table, boolean info, Vector snps, Graphics g){ int scale = table.length*30; int activeOffset = 0; float d, l, blgr; Color myColor; int[] shifts; Font regFont = new Font("Lucida Sans Regular", Font.PLAIN, 10); FontMetrics regfm = g.getFontMetrics(regFont); Font boldFont = new Font("Lucida Sans Bold", Font.BOLD, 14); FontMetrics boldfm = g.getFontMetrics(boldFont); if (info) activeOffset = labeloffset; //background color g.setColor(new Color(192,192,192)); g.fillRect(0,0,scale+activeOffset,scale); //first label: g.setColor(Color.black); g.setFont(boldFont); shifts = centerString("1", boldfm); g.drawString("1", activeOffset + shifts[0], shifts[1]); //if we know the marker names, print them down the side, along with MAF if (info){ NumberFormat nf = NumberFormat.getInstance(); nf.setMinimumFractionDigits(2); nf.setMaximumFractionDigits(2); g.setFont(regFont); for (int y = 0; y < table.length; y++){ String name = ((SNP)snps.elementAt(y)).getName(); name += " ("; name += nf.format(((SNP)snps.elementAt(y)).getMAF()); name += ")"; g.drawString(name, labeloffset-3-regfm.stringWidth(name), y*30 + shifts[1]); } //now draw a diagonal bar showing marker spacings if (table.length > 3){ g.drawLine(labeloffset+95,0,labeloffset+scale,scale-95); double lineLength = Math.sqrt((scale-95)*(scale-95)*2); double start = ((SNP)snps.elementAt(0)).getPosition(); double totalLength = ((SNP)snps.elementAt(table.length-1)).getPosition() - start; int numKB = (int)(totalLength/1000); g.drawString(numKB+" Kb", labeloffset+150, 30); for (int y = 0; y < table.length; y++){ double fracLength = (((SNP)snps.elementAt(y)).getPosition() - start)/totalLength; double xOrYDist = Math.sqrt((fracLength*lineLength*fracLength*lineLength)/2); int xSpineCoord = (int)(labeloffset + 90 +xOrYDist); int ySpineCoord = (int)(5+xOrYDist); g.drawLine(labeloffset+25+y*30, 5+y*30,xSpineCoord,ySpineCoord); //add "ticks" to spine g.drawLine(xSpineCoord, ySpineCoord, (xSpineCoord+5), (ySpineCoord-5)); } } } //draw table column by column for (int x = 0; x < table.length-1; x++){ for (int y = x + 1; y < table.length; y++){ StringTokenizer st = new StringTokenizer(table[x][y]); d = Float.parseFloat(st.nextToken()); l = Float.parseFloat(st.nextToken()); //set coloring based on LOD and D' if (l > 2){ if (d < 0.5) { //high LOD, low D' bluish color myColor = new Color(255, 224, 224); } else { //high LOD, high D' shades of red blgr = (255-32)*2*(1-d); myColor = new Color(255, (int) blgr, (int) blgr); } }else if (d > 0.99){ //high D', low LOD gray color myColor = new Color(192, 192, 240); }else { //no LD myColor = Color.white; } //draw the boxes g.setColor(myColor); g.fillRect(x*30+1+activeOffset, y*30+1, 28, 28); g.setColor(Color.black); g.drawRect(x*30+activeOffset, y*30, 30, 30); g.setFont(regFont); shifts=centerString(Float.toString(d), regfm); g.drawString(Float.toString(d), shifts[0]+(x*30)+activeOffset,(y*30)+shifts[1]); } //draw the labels g.setColor(Color.black); g.setFont(boldFont); shifts = centerString(Integer.toString(x+2), boldfm); g.drawString(Integer.toString(x+2), shifts[0]+(x+1)*30+activeOffset, shifts[1]+(x+1)*30); } } |
} | for (int x = 0; x < table.length-1; x++){ for (int y = x + 1; y < table.length; y++){ StringTokenizer st = new StringTokenizer(table[x][y]); d = Float.parseFloat(st.nextToken()); l = Float.parseFloat(st.nextToken()); if (l > 2){ if (d < 0.5) { myColor = new Color(255, 224, 224); } else { blgr = (255-32)*2*(1-d); myColor = new Color(255, (int) blgr, (int) blgr); } }else if (d > 0.99){ myColor = new Color(192, 192, 240); }else { myColor = Color.white; } | public void dPrimeDraw(String[][] table, boolean info, Vector snps, Graphics g){ int scale = table.length*30; int activeOffset = 0; float d, l, blgr; Color myColor; int[] shifts; Font regFont = new Font("Lucida Sans Regular", Font.PLAIN, 10); FontMetrics regfm = g.getFontMetrics(regFont); Font boldFont = new Font("Lucida Sans Bold", Font.BOLD, 14); FontMetrics boldfm = g.getFontMetrics(boldFont); if (info) activeOffset = labeloffset; //background color g.setColor(new Color(192,192,192)); g.fillRect(0,0,scale+activeOffset,scale); //first label: g.setColor(Color.black); g.setFont(boldFont); shifts = centerString("1", boldfm); g.drawString("1", activeOffset + shifts[0], shifts[1]); //if we know the marker names, print them down the side, along with MAF if (info){ NumberFormat nf = NumberFormat.getInstance(); nf.setMinimumFractionDigits(2); nf.setMaximumFractionDigits(2); g.setFont(regFont); for (int y = 0; y < table.length; y++){ String name = ((SNP)snps.elementAt(y)).getName(); name += " ("; name += nf.format(((SNP)snps.elementAt(y)).getMAF()); name += ")"; g.drawString(name, labeloffset-3-regfm.stringWidth(name), y*30 + shifts[1]); } //now draw a diagonal bar showing marker spacings if (table.length > 3){ g.drawLine(labeloffset+95,0,labeloffset+scale,scale-95); double lineLength = Math.sqrt((scale-95)*(scale-95)*2); double start = ((SNP)snps.elementAt(0)).getPosition(); double totalLength = ((SNP)snps.elementAt(table.length-1)).getPosition() - start; int numKB = (int)(totalLength/1000); g.drawString(numKB+" Kb", labeloffset+150, 30); for (int y = 0; y < table.length; y++){ double fracLength = (((SNP)snps.elementAt(y)).getPosition() - start)/totalLength; double xOrYDist = Math.sqrt((fracLength*lineLength*fracLength*lineLength)/2); int xSpineCoord = (int)(labeloffset + 90 +xOrYDist); int ySpineCoord = (int)(5+xOrYDist); g.drawLine(labeloffset+25+y*30, 5+y*30,xSpineCoord,ySpineCoord); //add "ticks" to spine g.drawLine(xSpineCoord, ySpineCoord, (xSpineCoord+5), (ySpineCoord-5)); } } } //draw table column by column for (int x = 0; x < table.length-1; x++){ for (int y = x + 1; y < table.length; y++){ StringTokenizer st = new StringTokenizer(table[x][y]); d = Float.parseFloat(st.nextToken()); l = Float.parseFloat(st.nextToken()); //set coloring based on LOD and D' if (l > 2){ if (d < 0.5) { //high LOD, low D' bluish color myColor = new Color(255, 224, 224); } else { //high LOD, high D' shades of red blgr = (255-32)*2*(1-d); myColor = new Color(255, (int) blgr, (int) blgr); } }else if (d > 0.99){ //high D', low LOD gray color myColor = new Color(192, 192, 240); }else { //no LD myColor = Color.white; } //draw the boxes g.setColor(myColor); g.fillRect(x*30+1+activeOffset, y*30+1, 28, 28); g.setColor(Color.black); g.drawRect(x*30+activeOffset, y*30, 30, 30); g.setFont(regFont); shifts=centerString(Float.toString(d), regfm); g.drawString(Float.toString(d), shifts[0]+(x*30)+activeOffset,(y*30)+shifts[1]); } //draw the labels g.setColor(Color.black); g.setFont(boldFont); shifts = centerString(Integer.toString(x+2), boldfm); g.drawString(Integer.toString(x+2), shifts[0]+(x+1)*30+activeOffset, shifts[1]+(x+1)*30); } } |
for (int x = 0; x < table.length-1; x++){ for (int y = x + 1; y < table.length; y++){ StringTokenizer st = new StringTokenizer(table[x][y]); d = Float.parseFloat(st.nextToken()); l = Float.parseFloat(st.nextToken()); if (l > 2){ if (d < 0.5) { myColor = new Color(255, 224, 224); } else { blgr = (255-32)*2*(1-d); myColor = new Color(255, (int) blgr, (int) blgr); } }else if (d > 0.99){ myColor = new Color(192, 192, 240); }else { myColor = Color.white; | g.setColor(myColor); g.fillRect(x*boxDimension, y*boxDimension, boxDimension, boxDimension); | public void dPrimeDraw(String[][] table, boolean info, Vector snps, Graphics g){ int scale = table.length*30; int activeOffset = 0; float d, l, blgr; Color myColor; int[] shifts; Font regFont = new Font("Lucida Sans Regular", Font.PLAIN, 10); FontMetrics regfm = g.getFontMetrics(regFont); Font boldFont = new Font("Lucida Sans Bold", Font.BOLD, 14); FontMetrics boldfm = g.getFontMetrics(boldFont); if (info) activeOffset = labeloffset; //background color g.setColor(new Color(192,192,192)); g.fillRect(0,0,scale+activeOffset,scale); //first label: g.setColor(Color.black); g.setFont(boldFont); shifts = centerString("1", boldfm); g.drawString("1", activeOffset + shifts[0], shifts[1]); //if we know the marker names, print them down the side, along with MAF if (info){ NumberFormat nf = NumberFormat.getInstance(); nf.setMinimumFractionDigits(2); nf.setMaximumFractionDigits(2); g.setFont(regFont); for (int y = 0; y < table.length; y++){ String name = ((SNP)snps.elementAt(y)).getName(); name += " ("; name += nf.format(((SNP)snps.elementAt(y)).getMAF()); name += ")"; g.drawString(name, labeloffset-3-regfm.stringWidth(name), y*30 + shifts[1]); } //now draw a diagonal bar showing marker spacings if (table.length > 3){ g.drawLine(labeloffset+95,0,labeloffset+scale,scale-95); double lineLength = Math.sqrt((scale-95)*(scale-95)*2); double start = ((SNP)snps.elementAt(0)).getPosition(); double totalLength = ((SNP)snps.elementAt(table.length-1)).getPosition() - start; int numKB = (int)(totalLength/1000); g.drawString(numKB+" Kb", labeloffset+150, 30); for (int y = 0; y < table.length; y++){ double fracLength = (((SNP)snps.elementAt(y)).getPosition() - start)/totalLength; double xOrYDist = Math.sqrt((fracLength*lineLength*fracLength*lineLength)/2); int xSpineCoord = (int)(labeloffset + 90 +xOrYDist); int ySpineCoord = (int)(5+xOrYDist); g.drawLine(labeloffset+25+y*30, 5+y*30,xSpineCoord,ySpineCoord); //add "ticks" to spine g.drawLine(xSpineCoord, ySpineCoord, (xSpineCoord+5), (ySpineCoord-5)); } } } //draw table column by column for (int x = 0; x < table.length-1; x++){ for (int y = x + 1; y < table.length; y++){ StringTokenizer st = new StringTokenizer(table[x][y]); d = Float.parseFloat(st.nextToken()); l = Float.parseFloat(st.nextToken()); //set coloring based on LOD and D' if (l > 2){ if (d < 0.5) { //high LOD, low D' bluish color myColor = new Color(255, 224, 224); } else { //high LOD, high D' shades of red blgr = (255-32)*2*(1-d); myColor = new Color(255, (int) blgr, (int) blgr); } }else if (d > 0.99){ //high D', low LOD gray color myColor = new Color(192, 192, 240); }else { //no LD myColor = Color.white; } //draw the boxes g.setColor(myColor); g.fillRect(x*30+1+activeOffset, y*30+1, 28, 28); g.setColor(Color.black); g.drawRect(x*30+activeOffset, y*30, 30, 30); g.setFont(regFont); shifts=centerString(Float.toString(d), regfm); g.drawString(Float.toString(d), shifts[0]+(x*30)+activeOffset,(y*30)+shifts[1]); } //draw the labels g.setColor(Color.black); g.setFont(boldFont); shifts = centerString(Integer.toString(x+2), boldfm); g.drawString(Integer.toString(x+2), shifts[0]+(x+1)*30+activeOffset, shifts[1]+(x+1)*30); } } |
g.setColor(myColor); g.fillRect(x*30+1+activeOffset, y*30+1, 28, 28); g.setColor(Color.black); g.drawRect(x*30+activeOffset, y*30, 30, 30); g.setFont(regFont); shifts=centerString(Float.toString(d), regfm); g.drawString(Float.toString(d), shifts[0]+(x*30)+activeOffset,(y*30)+shifts[1]); | public void dPrimeDraw(String[][] table, boolean info, Vector snps, Graphics g){ int scale = table.length*30; int activeOffset = 0; float d, l, blgr; Color myColor; int[] shifts; Font regFont = new Font("Lucida Sans Regular", Font.PLAIN, 10); FontMetrics regfm = g.getFontMetrics(regFont); Font boldFont = new Font("Lucida Sans Bold", Font.BOLD, 14); FontMetrics boldfm = g.getFontMetrics(boldFont); if (info) activeOffset = labeloffset; //background color g.setColor(new Color(192,192,192)); g.fillRect(0,0,scale+activeOffset,scale); //first label: g.setColor(Color.black); g.setFont(boldFont); shifts = centerString("1", boldfm); g.drawString("1", activeOffset + shifts[0], shifts[1]); //if we know the marker names, print them down the side, along with MAF if (info){ NumberFormat nf = NumberFormat.getInstance(); nf.setMinimumFractionDigits(2); nf.setMaximumFractionDigits(2); g.setFont(regFont); for (int y = 0; y < table.length; y++){ String name = ((SNP)snps.elementAt(y)).getName(); name += " ("; name += nf.format(((SNP)snps.elementAt(y)).getMAF()); name += ")"; g.drawString(name, labeloffset-3-regfm.stringWidth(name), y*30 + shifts[1]); } //now draw a diagonal bar showing marker spacings if (table.length > 3){ g.drawLine(labeloffset+95,0,labeloffset+scale,scale-95); double lineLength = Math.sqrt((scale-95)*(scale-95)*2); double start = ((SNP)snps.elementAt(0)).getPosition(); double totalLength = ((SNP)snps.elementAt(table.length-1)).getPosition() - start; int numKB = (int)(totalLength/1000); g.drawString(numKB+" Kb", labeloffset+150, 30); for (int y = 0; y < table.length; y++){ double fracLength = (((SNP)snps.elementAt(y)).getPosition() - start)/totalLength; double xOrYDist = Math.sqrt((fracLength*lineLength*fracLength*lineLength)/2); int xSpineCoord = (int)(labeloffset + 90 +xOrYDist); int ySpineCoord = (int)(5+xOrYDist); g.drawLine(labeloffset+25+y*30, 5+y*30,xSpineCoord,ySpineCoord); //add "ticks" to spine g.drawLine(xSpineCoord, ySpineCoord, (xSpineCoord+5), (ySpineCoord-5)); } } } //draw table column by column for (int x = 0; x < table.length-1; x++){ for (int y = x + 1; y < table.length; y++){ StringTokenizer st = new StringTokenizer(table[x][y]); d = Float.parseFloat(st.nextToken()); l = Float.parseFloat(st.nextToken()); //set coloring based on LOD and D' if (l > 2){ if (d < 0.5) { //high LOD, low D' bluish color myColor = new Color(255, 224, 224); } else { //high LOD, high D' shades of red blgr = (255-32)*2*(1-d); myColor = new Color(255, (int) blgr, (int) blgr); } }else if (d > 0.99){ //high D', low LOD gray color myColor = new Color(192, 192, 240); }else { //no LD myColor = Color.white; } //draw the boxes g.setColor(myColor); g.fillRect(x*30+1+activeOffset, y*30+1, 28, 28); g.setColor(Color.black); g.drawRect(x*30+activeOffset, y*30, 30, 30); g.setFont(regFont); shifts=centerString(Float.toString(d), regfm); g.drawString(Float.toString(d), shifts[0]+(x*30)+activeOffset,(y*30)+shifts[1]); } //draw the labels g.setColor(Color.black); g.setFont(boldFont); shifts = centerString(Integer.toString(x+2), boldfm); g.drawString(Integer.toString(x+2), shifts[0]+(x+1)*30+activeOffset, shifts[1]+(x+1)*30); } } |
|
g.setColor(Color.black); g.setFont(boldFont); shifts = centerString(Integer.toString(x+2), boldfm); g.drawString(Integer.toString(x+2), shifts[0]+(x+1)*30+activeOffset, shifts[1]+(x+1)*30); } | }**/ | public void dPrimeDraw(String[][] table, boolean info, Vector snps, Graphics g){ int scale = table.length*30; int activeOffset = 0; float d, l, blgr; Color myColor; int[] shifts; Font regFont = new Font("Lucida Sans Regular", Font.PLAIN, 10); FontMetrics regfm = g.getFontMetrics(regFont); Font boldFont = new Font("Lucida Sans Bold", Font.BOLD, 14); FontMetrics boldfm = g.getFontMetrics(boldFont); if (info) activeOffset = labeloffset; //background color g.setColor(new Color(192,192,192)); g.fillRect(0,0,scale+activeOffset,scale); //first label: g.setColor(Color.black); g.setFont(boldFont); shifts = centerString("1", boldfm); g.drawString("1", activeOffset + shifts[0], shifts[1]); //if we know the marker names, print them down the side, along with MAF if (info){ NumberFormat nf = NumberFormat.getInstance(); nf.setMinimumFractionDigits(2); nf.setMaximumFractionDigits(2); g.setFont(regFont); for (int y = 0; y < table.length; y++){ String name = ((SNP)snps.elementAt(y)).getName(); name += " ("; name += nf.format(((SNP)snps.elementAt(y)).getMAF()); name += ")"; g.drawString(name, labeloffset-3-regfm.stringWidth(name), y*30 + shifts[1]); } //now draw a diagonal bar showing marker spacings if (table.length > 3){ g.drawLine(labeloffset+95,0,labeloffset+scale,scale-95); double lineLength = Math.sqrt((scale-95)*(scale-95)*2); double start = ((SNP)snps.elementAt(0)).getPosition(); double totalLength = ((SNP)snps.elementAt(table.length-1)).getPosition() - start; int numKB = (int)(totalLength/1000); g.drawString(numKB+" Kb", labeloffset+150, 30); for (int y = 0; y < table.length; y++){ double fracLength = (((SNP)snps.elementAt(y)).getPosition() - start)/totalLength; double xOrYDist = Math.sqrt((fracLength*lineLength*fracLength*lineLength)/2); int xSpineCoord = (int)(labeloffset + 90 +xOrYDist); int ySpineCoord = (int)(5+xOrYDist); g.drawLine(labeloffset+25+y*30, 5+y*30,xSpineCoord,ySpineCoord); //add "ticks" to spine g.drawLine(xSpineCoord, ySpineCoord, (xSpineCoord+5), (ySpineCoord-5)); } } } //draw table column by column for (int x = 0; x < table.length-1; x++){ for (int y = x + 1; y < table.length; y++){ StringTokenizer st = new StringTokenizer(table[x][y]); d = Float.parseFloat(st.nextToken()); l = Float.parseFloat(st.nextToken()); //set coloring based on LOD and D' if (l > 2){ if (d < 0.5) { //high LOD, low D' bluish color myColor = new Color(255, 224, 224); } else { //high LOD, high D' shades of red blgr = (255-32)*2*(1-d); myColor = new Color(255, (int) blgr, (int) blgr); } }else if (d > 0.99){ //high D', low LOD gray color myColor = new Color(192, 192, 240); }else { //no LD myColor = Color.white; } //draw the boxes g.setColor(myColor); g.fillRect(x*30+1+activeOffset, y*30+1, 28, 28); g.setColor(Color.black); g.drawRect(x*30+activeOffset, y*30, 30, 30); g.setFont(regFont); shifts=centerString(Float.toString(d), regfm); g.drawString(Float.toString(d), shifts[0]+(x*30)+activeOffset,(y*30)+shifts[1]); } //draw the labels g.setColor(Color.black); g.setFont(boldFont); shifts = centerString(Integer.toString(x+2), boldfm); g.drawString(Integer.toString(x+2), shifts[0]+(x+1)*30+activeOffset, shifts[1]+(x+1)*30); } } |
if (! (filename.endsWith(".jpg") || filename.endsWith(".JPG"))){ filename += ".jpg"; | if (! (filename.endsWith(".png") || filename.endsWith(".PNG"))){ filename += ".png"; | void saveImage(BufferedImage image, String filename) throws IOException{ try { if (! (filename.endsWith(".jpg") || filename.endsWith(".JPG"))){ filename += ".jpg"; } Jimi.putImage("image/jpg", (Image)image, filename); }catch (com.sun.jimi.core.JimiException e){ e.printStackTrace(); } } |
Jimi.putImage("image/jpg", (Image)image, filename); | Jimi.putImage("image/png", (Image)image, filename); | void saveImage(BufferedImage image, String filename) throws IOException{ try { if (! (filename.endsWith(".jpg") || filename.endsWith(".JPG"))){ filename += ".jpg"; } Jimi.putImage("image/jpg", (Image)image, filename); }catch (com.sun.jimi.core.JimiException e){ e.printStackTrace(); } } |
DPrimePanel(String[][] t){ | DPrimePanel(String[][] t, boolean b, Vector v){ | DPrimePanel(String[][] t){ table = t; } |
info = b; vec = v; | DPrimePanel(String[][] t){ table = t; } |
|
spacerScale = (((SNP)markers.lastElement()).getPosition() - ((SNP)markers.firstElement()).getPosition())/(780-(20*markers.size())); | spacerScale = (((SNP)markers.lastElement()).getPosition() - ((SNP)markers.firstElement()).getPosition())/(779-(20*markers.size())); | BlockDisplay(Vector ms, Vector bs, DPrimePanel dp, boolean ik){ markers = ms; blocks = bs; theDPrime = dp; infoKnown = ik; setBackground(Color.black); setLayout(gridbag); selected = new boolean[markers.size()]; markerButtons = new JButton[markers.size()]; spaceLabels = new JLabel[markers.size() - 1]; //create a button to represent each marker for (int i = 0; i < markers.size(); i++){ markerButtons[i] = new JButton(String.valueOf(i+1)); markerButtons[i].setBackground(Color.white); markerButtons[i].setForeground(Color.black); markerButtons[i].setPreferredSize(new Dimension(20,30)); markerButtons[i].setBorder(noBorder); selected[i] = false; markerButtons[i].addActionListener(this); } //scale the spacing to fit on the screen spacerScale = (((SNP)markers.lastElement()).getPosition() - ((SNP)markers.firstElement()).getPosition())/(780-(20*markers.size())); //System.out.println(spacerScale); //make sure markers are at least slightly separated (no more than 300 bp/pixel) //above formula generates a negative number for large datasets, hence: if (spacerScale < 0) spacerScale=300; //also don't want to spread them too far apart: if (spacerScale < 100) spacerScale = 100; //compute the total horizontal space used to display the markers usedSpace = (20 * markers.size()) + (((SNP)markers.lastElement()).getPosition() - ((SNP)markers.firstElement()).getPosition())/spacerScale; //crate a label for each space between markers for (int i = 0; i < (markers.size() - 1); i++){ spaceLabels[i] = new JLabel(); //length is the distance between the ith marker and the ith+1 long length = ((SNP)markers.elementAt(i+1)).getPosition() - ((SNP)markers.elementAt(i)).getPosition(); if (infoKnown) spaceLabels[i].setToolTipText(((int) length/1000) + "kb"); spaceLabels[i].setPreferredSize(new Dimension((int)(length/spacerScale), 4)); spaceLabels[i].setOpaque(true); spaceLabels[i].setBackground(Color.white); spaceLabels[i].setBorder(noBorder); } //draw the markers for (int i = 0; i < (markers.size() - 1); i++){ add(markerButtons[i]); add(spaceLabels[i]); } //this is done after the loop because there is no spacer to be drawn after the //last marker add(markerButtons[(markers.size() - 1)]); //now set up the initial haplotype blocks for (int i = 0; i < blocks.size(); i++){ int[] theBlock = (int[])blocks.elementAt(i); blockLabels.add(new JLabel()); drawBlock(theBlock, i); } addMouseListener(new ClickAndDrag()); } |
public void saveDprimeToText(String[][] dPrimeTable, File dumpDprimeFile, boolean info, Vector markerinfo) throws IOException{ | public void saveDprimeToText(PairwiseLinkage[][] dPrimeTable, File dumpDprimeFile, boolean info, Vector markerinfo) throws IOException{ | public void saveDprimeToText(String[][] dPrimeTable, File dumpDprimeFile, boolean info, Vector markerinfo) throws IOException{ FileWriter saveDprimeWriter = new FileWriter(dumpDprimeFile); if (info){ saveDprimeWriter.write("L1\tL2\tD'\tLOD\tr^2\tCIlow\tCIhi\tDist\n"); long dist; for (int i = 0; i < dPrimeTable.length; i++){ for (int j = 0; j < dPrimeTable[i].length; j++){ //many "slots" in table aren't filled in because it is a 1/2 matrix if (i < j){ dist = ((SNP)markerinfo.elementAt(j)).getPosition() - ((SNP)markerinfo.elementAt(i)).getPosition(); saveDprimeWriter.write((i+1) + "\t" + (j+1) + "\t" + dPrimeTable[i][j] + "\t" + dist + "\n"); } } } }else{ saveDprimeWriter.write("L1\tL2\tD'\tLOD\tr^2\tCIlow\tCIhi\n"); for (int i = 0; i < dPrimeTable.length; i++){ for (int j = 0; j < dPrimeTable[i].length; j++){ //many "slots" in table aren't filled in because it is a 1/2 matrix if (i < j){ saveDprimeWriter.write((i+1) + "\t" + (j+1) + "\t" + dPrimeTable[i][j] + "\n"); } } } } saveDprimeWriter.close(); } |
saveDprimeWriter.write((i+1) + "\t" + (j+1) + "\t" + dPrimeTable[i][j] + "\t" + dist + "\n"); | saveDprimeWriter.write((i+1) + "\t" + (j+1) + "\t" + dPrimeTable[i][j].toString() + "\t" + dist + "\n"); | public void saveDprimeToText(String[][] dPrimeTable, File dumpDprimeFile, boolean info, Vector markerinfo) throws IOException{ FileWriter saveDprimeWriter = new FileWriter(dumpDprimeFile); if (info){ saveDprimeWriter.write("L1\tL2\tD'\tLOD\tr^2\tCIlow\tCIhi\tDist\n"); long dist; for (int i = 0; i < dPrimeTable.length; i++){ for (int j = 0; j < dPrimeTable[i].length; j++){ //many "slots" in table aren't filled in because it is a 1/2 matrix if (i < j){ dist = ((SNP)markerinfo.elementAt(j)).getPosition() - ((SNP)markerinfo.elementAt(i)).getPosition(); saveDprimeWriter.write((i+1) + "\t" + (j+1) + "\t" + dPrimeTable[i][j] + "\t" + dist + "\n"); } } } }else{ saveDprimeWriter.write("L1\tL2\tD'\tLOD\tr^2\tCIlow\tCIhi\n"); for (int i = 0; i < dPrimeTable.length; i++){ for (int j = 0; j < dPrimeTable[i].length; j++){ //many "slots" in table aren't filled in because it is a 1/2 matrix if (i < j){ saveDprimeWriter.write((i+1) + "\t" + (j+1) + "\t" + dPrimeTable[i][j] + "\n"); } } } } saveDprimeWriter.close(); } |
public void setAttribute(String name, Object value) throws JellyTagException { int index = attributes.getIndex("", name); if (index >= 0) { attributes.removeAttribute(index); } if (value != null) { attributes.addAttribute("", name, name, "CDATA", value.toString()); } | public void setAttribute(String name, String prefix, String nsURI, Object value) { if(value==null) return; if(prefix!=null && prefix.length()>0) attributes.addAttribute(nsURI,name,prefix+":"+name,"CDATA",value.toString()); else attributes.addAttribute("",name,name,"CDATA",value.toString()); | public void setAttribute(String name, Object value) throws JellyTagException { // ### we'll assume that all attributes are in no namespace! // ### this is severely limiting! // ### - Tag attributes should allow for namespace aware int index = attributes.getIndex("", name); if (index >= 0) { attributes.removeAttribute(index); } // treat null values as no attribute if (value != null) { attributes.addAttribute("", name, name, "CDATA", value.toString()); } } |
public void startElement( String uri, String localName, String qName, Attributes atts) throws SAXException { int idx = qName.indexOf(':'); String attNsPrefix = ""; if (idx >= 0) { attNsPrefix = qName.substring(0, idx); } namespaceStack.pushNamespace(attNsPrefix, uri); for (int i = 0; i < atts.getLength(); i++) { String attQName = atts.getQName(i); idx = attQName.indexOf(':'); if (idx >= 0) { attNsPrefix = attQName.substring(0, idx); String attUri = atts.getURI(i); namespaceStack.pushNamespace(attNsPrefix, attUri); } } contentHandler.startElement(uri, localName, qName, atts); namespaceStack.increaseLevel(); | public void startElement(String localName) throws SAXException { startElement("", localName, localName, EMPTY_ATTRIBUTES); | public void startElement( String uri, String localName, String qName, Attributes atts) throws SAXException { int idx = qName.indexOf(':'); String attNsPrefix = ""; if (idx >= 0) { attNsPrefix = qName.substring(0, idx); } namespaceStack.pushNamespace(attNsPrefix, uri); for (int i = 0; i < atts.getLength(); i++) { String attQName = atts.getQName(i); // An attribute only has an namespace if has a prefix // If not, stays in namespace of containing node idx = attQName.indexOf(':'); if (idx >= 0) { attNsPrefix = attQName.substring(0, idx); String attUri = atts.getURI(i); namespaceStack.pushNamespace(attNsPrefix, attUri); } } contentHandler.startElement(uri, localName, qName, atts); // Inform namespaceStack of a new depth namespaceStack.increaseLevel(); } |
public void endElement(String uri, String localName, String qName) throws SAXException { contentHandler.endElement(uri, localName, qName); namespaceStack.decreaseLevel(); namespaceStack.popNamespaces(); | public void endElement(String localName) throws SAXException { endElement("", localName, localName); | public void endElement(String uri, String localName, String qName) throws SAXException { contentHandler.endElement(uri, localName, qName); // Inform namespaceStack to return to previous depth namespaceStack.decreaseLevel(); namespaceStack.popNamespaces(); } |
JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenuItem menuItem; JMenu fileMenu = new JMenu("File"); menuBar.add(fileMenu); | JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenuItem menuItem; | public HaploView(){ //menu setup JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenuItem menuItem; //file menu JMenu fileMenu = new JMenu("File"); menuBar.add(fileMenu); menuItem = new JMenuItem(READ_GENOTYPES); setAccelerator(menuItem, 'O', false); menuItem.addActionListener(this); fileMenu.add(menuItem); /* viewGenotypesItem = new JMenuItem(VIEW_GENOTYPES); viewGenotypesItem.addActionListener(this); //viewGenotypesItem.setEnabled(false); fileMenu.add(viewGenotypesItem); */ readMarkerItem = new JMenuItem(READ_MARKERS); setAccelerator(readMarkerItem, 'I', false); readMarkerItem.addActionListener(this); readMarkerItem.setEnabled(false); fileMenu.add(readMarkerItem); /* viewMarkerItem = new JMenuItem(VIEW_MARKERS); viewMarkerItem.addActionListener(this); //viewMarkerItem.setEnabled(false); fileMenu.add(viewMarkerItem); */ fileMenu.addSeparator(); exportMenuItems = new JMenuItem[exportItems.length]; for (int i = 0; i < exportItems.length; i++) { exportMenuItems[i] = new JMenuItem(exportItems[i]); exportMenuItems[i].addActionListener(this); exportMenuItems[i].setEnabled(false); fileMenu.add(exportMenuItems[i]); } fileMenu.addSeparator(); menuItem = new JMenuItem(QUIT); setAccelerator(menuItem, 'Q', false); menuItem.addActionListener(this); fileMenu.add(menuItem); /// display menu JMenu displayMenu = new JMenu("Display"); menuBar.add(displayMenu); ButtonGroup group = new ButtonGroup(); viewMenuItems = new JRadioButtonMenuItem[viewItems.length]; for (int i = 0; i < viewItems.length; i++) { viewMenuItems[i] = new JRadioButtonMenuItem(viewItems[i], i == 0); viewMenuItems[i].addActionListener(this); KeyStroke ks = KeyStroke.getKeyStroke('1' + i, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()); viewMenuItems[i].setAccelerator(ks); displayMenu.add(viewMenuItems[i]); group.add(viewMenuItems[i]); } //analysis menu JMenu analysisMenu = new JMenu("Analysis"); menuBar.add(analysisMenu); defineBlocksItem = new JMenuItem(DEFINE_BLOCKS); setAccelerator(defineBlocksItem, 'B', false); defineBlocksItem.addActionListener(this); defineBlocksItem.setEnabled(false); analysisMenu.add(defineBlocksItem); // maybe //displayMenu.addSeparator(); //displayOptionsItem = new JMenuItem(DISPLAY_OPTIONS); //setAccelerator(displayOptionsItem, 'D', false); /** NEEDS FIXING helpMenu = new JMenu("Help"); menuBar.add(Box.createHorizontalGlue()); menuBar.add(helpMenu); menuItem = new JMenuItem("Tutorial"); menuItem.addActionListener(this); helpMenu.add(menuItem); **/ /* clearBlocksMenuItem.addActionListener(this); clearBlocksMenuItem.setEnabled(false); toolMenu.add(clearBlocksMenuItem); guessBlocksMenuItem.addActionListener(this); guessBlocksMenuItem.setEnabled(false); toolMenu.add(guessBlocksMenuItem); toolMenu.addSeparator(); */ addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e){ quit(); } }); } |
menuItem = new JMenuItem(READ_GENOTYPES); setAccelerator(menuItem, 'O', false); menuItem.addActionListener(this); fileMenu.add(menuItem); | JMenu fileMenu = new JMenu("File"); menuBar.add(fileMenu); | public HaploView(){ //menu setup JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenuItem menuItem; //file menu JMenu fileMenu = new JMenu("File"); menuBar.add(fileMenu); menuItem = new JMenuItem(READ_GENOTYPES); setAccelerator(menuItem, 'O', false); menuItem.addActionListener(this); fileMenu.add(menuItem); /* viewGenotypesItem = new JMenuItem(VIEW_GENOTYPES); viewGenotypesItem.addActionListener(this); //viewGenotypesItem.setEnabled(false); fileMenu.add(viewGenotypesItem); */ readMarkerItem = new JMenuItem(READ_MARKERS); setAccelerator(readMarkerItem, 'I', false); readMarkerItem.addActionListener(this); readMarkerItem.setEnabled(false); fileMenu.add(readMarkerItem); /* viewMarkerItem = new JMenuItem(VIEW_MARKERS); viewMarkerItem.addActionListener(this); //viewMarkerItem.setEnabled(false); fileMenu.add(viewMarkerItem); */ fileMenu.addSeparator(); exportMenuItems = new JMenuItem[exportItems.length]; for (int i = 0; i < exportItems.length; i++) { exportMenuItems[i] = new JMenuItem(exportItems[i]); exportMenuItems[i].addActionListener(this); exportMenuItems[i].setEnabled(false); fileMenu.add(exportMenuItems[i]); } fileMenu.addSeparator(); menuItem = new JMenuItem(QUIT); setAccelerator(menuItem, 'Q', false); menuItem.addActionListener(this); fileMenu.add(menuItem); /// display menu JMenu displayMenu = new JMenu("Display"); menuBar.add(displayMenu); ButtonGroup group = new ButtonGroup(); viewMenuItems = new JRadioButtonMenuItem[viewItems.length]; for (int i = 0; i < viewItems.length; i++) { viewMenuItems[i] = new JRadioButtonMenuItem(viewItems[i], i == 0); viewMenuItems[i].addActionListener(this); KeyStroke ks = KeyStroke.getKeyStroke('1' + i, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()); viewMenuItems[i].setAccelerator(ks); displayMenu.add(viewMenuItems[i]); group.add(viewMenuItems[i]); } //analysis menu JMenu analysisMenu = new JMenu("Analysis"); menuBar.add(analysisMenu); defineBlocksItem = new JMenuItem(DEFINE_BLOCKS); setAccelerator(defineBlocksItem, 'B', false); defineBlocksItem.addActionListener(this); defineBlocksItem.setEnabled(false); analysisMenu.add(defineBlocksItem); // maybe //displayMenu.addSeparator(); //displayOptionsItem = new JMenuItem(DISPLAY_OPTIONS); //setAccelerator(displayOptionsItem, 'D', false); /** NEEDS FIXING helpMenu = new JMenu("Help"); menuBar.add(Box.createHorizontalGlue()); menuBar.add(helpMenu); menuItem = new JMenuItem("Tutorial"); menuItem.addActionListener(this); helpMenu.add(menuItem); **/ /* clearBlocksMenuItem.addActionListener(this); clearBlocksMenuItem.setEnabled(false); toolMenu.add(clearBlocksMenuItem); guessBlocksMenuItem.addActionListener(this); guessBlocksMenuItem.setEnabled(false); toolMenu.add(guessBlocksMenuItem); toolMenu.addSeparator(); */ addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e){ quit(); } }); } |
menuItem = new JMenuItem(READ_GENOTYPES); setAccelerator(menuItem, 'O', false); menuItem.addActionListener(this); fileMenu.add(menuItem); | public HaploView(){ //menu setup JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenuItem menuItem; //file menu JMenu fileMenu = new JMenu("File"); menuBar.add(fileMenu); menuItem = new JMenuItem(READ_GENOTYPES); setAccelerator(menuItem, 'O', false); menuItem.addActionListener(this); fileMenu.add(menuItem); /* viewGenotypesItem = new JMenuItem(VIEW_GENOTYPES); viewGenotypesItem.addActionListener(this); //viewGenotypesItem.setEnabled(false); fileMenu.add(viewGenotypesItem); */ readMarkerItem = new JMenuItem(READ_MARKERS); setAccelerator(readMarkerItem, 'I', false); readMarkerItem.addActionListener(this); readMarkerItem.setEnabled(false); fileMenu.add(readMarkerItem); /* viewMarkerItem = new JMenuItem(VIEW_MARKERS); viewMarkerItem.addActionListener(this); //viewMarkerItem.setEnabled(false); fileMenu.add(viewMarkerItem); */ fileMenu.addSeparator(); exportMenuItems = new JMenuItem[exportItems.length]; for (int i = 0; i < exportItems.length; i++) { exportMenuItems[i] = new JMenuItem(exportItems[i]); exportMenuItems[i].addActionListener(this); exportMenuItems[i].setEnabled(false); fileMenu.add(exportMenuItems[i]); } fileMenu.addSeparator(); menuItem = new JMenuItem(QUIT); setAccelerator(menuItem, 'Q', false); menuItem.addActionListener(this); fileMenu.add(menuItem); /// display menu JMenu displayMenu = new JMenu("Display"); menuBar.add(displayMenu); ButtonGroup group = new ButtonGroup(); viewMenuItems = new JRadioButtonMenuItem[viewItems.length]; for (int i = 0; i < viewItems.length; i++) { viewMenuItems[i] = new JRadioButtonMenuItem(viewItems[i], i == 0); viewMenuItems[i].addActionListener(this); KeyStroke ks = KeyStroke.getKeyStroke('1' + i, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()); viewMenuItems[i].setAccelerator(ks); displayMenu.add(viewMenuItems[i]); group.add(viewMenuItems[i]); } //analysis menu JMenu analysisMenu = new JMenu("Analysis"); menuBar.add(analysisMenu); defineBlocksItem = new JMenuItem(DEFINE_BLOCKS); setAccelerator(defineBlocksItem, 'B', false); defineBlocksItem.addActionListener(this); defineBlocksItem.setEnabled(false); analysisMenu.add(defineBlocksItem); // maybe //displayMenu.addSeparator(); //displayOptionsItem = new JMenuItem(DISPLAY_OPTIONS); //setAccelerator(displayOptionsItem, 'D', false); /** NEEDS FIXING helpMenu = new JMenu("Help"); menuBar.add(Box.createHorizontalGlue()); menuBar.add(helpMenu); menuItem = new JMenuItem("Tutorial"); menuItem.addActionListener(this); helpMenu.add(menuItem); **/ /* clearBlocksMenuItem.addActionListener(this); clearBlocksMenuItem.setEnabled(false); toolMenu.add(clearBlocksMenuItem); guessBlocksMenuItem.addActionListener(this); guessBlocksMenuItem.setEnabled(false); toolMenu.add(guessBlocksMenuItem); toolMenu.addSeparator(); */ addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e){ quit(); } }); } |
|
readMarkerItem = new JMenuItem(READ_MARKERS); setAccelerator(readMarkerItem, 'I', false); readMarkerItem.addActionListener(this); readMarkerItem.setEnabled(false); fileMenu.add(readMarkerItem); | public HaploView(){ //menu setup JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenuItem menuItem; //file menu JMenu fileMenu = new JMenu("File"); menuBar.add(fileMenu); menuItem = new JMenuItem(READ_GENOTYPES); setAccelerator(menuItem, 'O', false); menuItem.addActionListener(this); fileMenu.add(menuItem); /* viewGenotypesItem = new JMenuItem(VIEW_GENOTYPES); viewGenotypesItem.addActionListener(this); //viewGenotypesItem.setEnabled(false); fileMenu.add(viewGenotypesItem); */ readMarkerItem = new JMenuItem(READ_MARKERS); setAccelerator(readMarkerItem, 'I', false); readMarkerItem.addActionListener(this); readMarkerItem.setEnabled(false); fileMenu.add(readMarkerItem); /* viewMarkerItem = new JMenuItem(VIEW_MARKERS); viewMarkerItem.addActionListener(this); //viewMarkerItem.setEnabled(false); fileMenu.add(viewMarkerItem); */ fileMenu.addSeparator(); exportMenuItems = new JMenuItem[exportItems.length]; for (int i = 0; i < exportItems.length; i++) { exportMenuItems[i] = new JMenuItem(exportItems[i]); exportMenuItems[i].addActionListener(this); exportMenuItems[i].setEnabled(false); fileMenu.add(exportMenuItems[i]); } fileMenu.addSeparator(); menuItem = new JMenuItem(QUIT); setAccelerator(menuItem, 'Q', false); menuItem.addActionListener(this); fileMenu.add(menuItem); /// display menu JMenu displayMenu = new JMenu("Display"); menuBar.add(displayMenu); ButtonGroup group = new ButtonGroup(); viewMenuItems = new JRadioButtonMenuItem[viewItems.length]; for (int i = 0; i < viewItems.length; i++) { viewMenuItems[i] = new JRadioButtonMenuItem(viewItems[i], i == 0); viewMenuItems[i].addActionListener(this); KeyStroke ks = KeyStroke.getKeyStroke('1' + i, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()); viewMenuItems[i].setAccelerator(ks); displayMenu.add(viewMenuItems[i]); group.add(viewMenuItems[i]); } //analysis menu JMenu analysisMenu = new JMenu("Analysis"); menuBar.add(analysisMenu); defineBlocksItem = new JMenuItem(DEFINE_BLOCKS); setAccelerator(defineBlocksItem, 'B', false); defineBlocksItem.addActionListener(this); defineBlocksItem.setEnabled(false); analysisMenu.add(defineBlocksItem); // maybe //displayMenu.addSeparator(); //displayOptionsItem = new JMenuItem(DISPLAY_OPTIONS); //setAccelerator(displayOptionsItem, 'D', false); /** NEEDS FIXING helpMenu = new JMenu("Help"); menuBar.add(Box.createHorizontalGlue()); menuBar.add(helpMenu); menuItem = new JMenuItem("Tutorial"); menuItem.addActionListener(this); helpMenu.add(menuItem); **/ /* clearBlocksMenuItem.addActionListener(this); clearBlocksMenuItem.setEnabled(false); toolMenu.add(clearBlocksMenuItem); guessBlocksMenuItem.addActionListener(this); guessBlocksMenuItem.setEnabled(false); toolMenu.add(guessBlocksMenuItem); toolMenu.addSeparator(); */ addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e){ quit(); } }); } |
|
readMarkerItem = new JMenuItem(READ_MARKERS); setAccelerator(readMarkerItem, 'I', false); readMarkerItem.addActionListener(this); readMarkerItem.setEnabled(false); fileMenu.add(readMarkerItem); | public HaploView(){ //menu setup JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenuItem menuItem; //file menu JMenu fileMenu = new JMenu("File"); menuBar.add(fileMenu); menuItem = new JMenuItem(READ_GENOTYPES); setAccelerator(menuItem, 'O', false); menuItem.addActionListener(this); fileMenu.add(menuItem); /* viewGenotypesItem = new JMenuItem(VIEW_GENOTYPES); viewGenotypesItem.addActionListener(this); //viewGenotypesItem.setEnabled(false); fileMenu.add(viewGenotypesItem); */ readMarkerItem = new JMenuItem(READ_MARKERS); setAccelerator(readMarkerItem, 'I', false); readMarkerItem.addActionListener(this); readMarkerItem.setEnabled(false); fileMenu.add(readMarkerItem); /* viewMarkerItem = new JMenuItem(VIEW_MARKERS); viewMarkerItem.addActionListener(this); //viewMarkerItem.setEnabled(false); fileMenu.add(viewMarkerItem); */ fileMenu.addSeparator(); exportMenuItems = new JMenuItem[exportItems.length]; for (int i = 0; i < exportItems.length; i++) { exportMenuItems[i] = new JMenuItem(exportItems[i]); exportMenuItems[i].addActionListener(this); exportMenuItems[i].setEnabled(false); fileMenu.add(exportMenuItems[i]); } fileMenu.addSeparator(); menuItem = new JMenuItem(QUIT); setAccelerator(menuItem, 'Q', false); menuItem.addActionListener(this); fileMenu.add(menuItem); /// display menu JMenu displayMenu = new JMenu("Display"); menuBar.add(displayMenu); ButtonGroup group = new ButtonGroup(); viewMenuItems = new JRadioButtonMenuItem[viewItems.length]; for (int i = 0; i < viewItems.length; i++) { viewMenuItems[i] = new JRadioButtonMenuItem(viewItems[i], i == 0); viewMenuItems[i].addActionListener(this); KeyStroke ks = KeyStroke.getKeyStroke('1' + i, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()); viewMenuItems[i].setAccelerator(ks); displayMenu.add(viewMenuItems[i]); group.add(viewMenuItems[i]); } //analysis menu JMenu analysisMenu = new JMenu("Analysis"); menuBar.add(analysisMenu); defineBlocksItem = new JMenuItem(DEFINE_BLOCKS); setAccelerator(defineBlocksItem, 'B', false); defineBlocksItem.addActionListener(this); defineBlocksItem.setEnabled(false); analysisMenu.add(defineBlocksItem); // maybe //displayMenu.addSeparator(); //displayOptionsItem = new JMenuItem(DISPLAY_OPTIONS); //setAccelerator(displayOptionsItem, 'D', false); /** NEEDS FIXING helpMenu = new JMenu("Help"); menuBar.add(Box.createHorizontalGlue()); menuBar.add(helpMenu); menuItem = new JMenuItem("Tutorial"); menuItem.addActionListener(this); helpMenu.add(menuItem); **/ /* clearBlocksMenuItem.addActionListener(this); clearBlocksMenuItem.setEnabled(false); toolMenu.add(clearBlocksMenuItem); guessBlocksMenuItem.addActionListener(this); guessBlocksMenuItem.setEnabled(false); toolMenu.add(guessBlocksMenuItem); toolMenu.addSeparator(); */ addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e){ quit(); } }); } |
|
fileMenu.addSeparator(); | public HaploView(){ //menu setup JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenuItem menuItem; //file menu JMenu fileMenu = new JMenu("File"); menuBar.add(fileMenu); menuItem = new JMenuItem(READ_GENOTYPES); setAccelerator(menuItem, 'O', false); menuItem.addActionListener(this); fileMenu.add(menuItem); /* viewGenotypesItem = new JMenuItem(VIEW_GENOTYPES); viewGenotypesItem.addActionListener(this); //viewGenotypesItem.setEnabled(false); fileMenu.add(viewGenotypesItem); */ readMarkerItem = new JMenuItem(READ_MARKERS); setAccelerator(readMarkerItem, 'I', false); readMarkerItem.addActionListener(this); readMarkerItem.setEnabled(false); fileMenu.add(readMarkerItem); /* viewMarkerItem = new JMenuItem(VIEW_MARKERS); viewMarkerItem.addActionListener(this); //viewMarkerItem.setEnabled(false); fileMenu.add(viewMarkerItem); */ fileMenu.addSeparator(); exportMenuItems = new JMenuItem[exportItems.length]; for (int i = 0; i < exportItems.length; i++) { exportMenuItems[i] = new JMenuItem(exportItems[i]); exportMenuItems[i].addActionListener(this); exportMenuItems[i].setEnabled(false); fileMenu.add(exportMenuItems[i]); } fileMenu.addSeparator(); menuItem = new JMenuItem(QUIT); setAccelerator(menuItem, 'Q', false); menuItem.addActionListener(this); fileMenu.add(menuItem); /// display menu JMenu displayMenu = new JMenu("Display"); menuBar.add(displayMenu); ButtonGroup group = new ButtonGroup(); viewMenuItems = new JRadioButtonMenuItem[viewItems.length]; for (int i = 0; i < viewItems.length; i++) { viewMenuItems[i] = new JRadioButtonMenuItem(viewItems[i], i == 0); viewMenuItems[i].addActionListener(this); KeyStroke ks = KeyStroke.getKeyStroke('1' + i, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()); viewMenuItems[i].setAccelerator(ks); displayMenu.add(viewMenuItems[i]); group.add(viewMenuItems[i]); } //analysis menu JMenu analysisMenu = new JMenu("Analysis"); menuBar.add(analysisMenu); defineBlocksItem = new JMenuItem(DEFINE_BLOCKS); setAccelerator(defineBlocksItem, 'B', false); defineBlocksItem.addActionListener(this); defineBlocksItem.setEnabled(false); analysisMenu.add(defineBlocksItem); // maybe //displayMenu.addSeparator(); //displayOptionsItem = new JMenuItem(DISPLAY_OPTIONS); //setAccelerator(displayOptionsItem, 'D', false); /** NEEDS FIXING helpMenu = new JMenu("Help"); menuBar.add(Box.createHorizontalGlue()); menuBar.add(helpMenu); menuItem = new JMenuItem("Tutorial"); menuItem.addActionListener(this); helpMenu.add(menuItem); **/ /* clearBlocksMenuItem.addActionListener(this); clearBlocksMenuItem.setEnabled(false); toolMenu.add(clearBlocksMenuItem); guessBlocksMenuItem.addActionListener(this); guessBlocksMenuItem.setEnabled(false); toolMenu.add(guessBlocksMenuItem); toolMenu.addSeparator(); */ addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e){ quit(); } }); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.