bugged
stringlengths
6
599k
fixed
stringlengths
10
599k
__index_level_0__
int64
0
1.13M
public static void main( String args[] ) { JFrame frame = new JFrame( "PhotoInfoEditorTest" ); PhotoViewer viewer = new PhotoViewer(); frame.getContentPane().add( viewer, BorderLayout.CENTER ); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } } ); File f = new File("c:\\java\\photovault\\testfiles\\test1.jpg" ); try { BufferedImage bi = ImageIO.read(f); viewer.setImage( bi ); viewer.setScale( 0.3f ); System.out.println( "Succesfully loaded \""+ f.getPath() + "\"" ); } catch (IOException e ) { System.out.println( "Error loading image \""+ f.getPath() + "\"" ); } frame.pack(); frame.setVisible( true ); }
public static void main( String args[] ) { JFrame frame = new JFrame( "PhotoInfoEditorTest" ); PhotoViewer viewer = new PhotoViewer(); frame.getContentPane().add( viewer, BorderLayout.CENTER ); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } } ); File f = new File("c:\\java\\photovault\\testfiles\\test1.jpg" ); try { BufferedImage bi = ImageIO.read(f); viewer.setImage( bi ); viewer.setScale( 0.3f ); System.out.println( "Succesfully loaded \""+ f.getPath() + "\"" ); } catch (IOException e ) { System.out.println( "Error loading image \""+ f.getPath() + "\"" ); } frame.pack(); frame.setVisible( true ); }
1,111,041
void setScale( float scale ) { imageView.setScale(scale); }
public void setScale( float scale ) { imageView.setScale(scale); }
1,111,042
protected TagScript createStaticTag( String namespaceURI, String localName, Attributes list ) throws SAXException { try { StaticTag tag = new StaticTag( namespaceURI, localName ); DynaTagScript script = new DynaTagScript( tag ); // now iterate through through the expressions int size = list.getLength(); for ( int i = 0; i < size; i++ ) { String attributeName = list.getLocalName(i); String attributeValue = list.getValue(i); Expression expression = getExpressionFactory().createExpression( attributeValue ); if ( expression == null ) { expression = createConstantExpression( localName, attributeName, attributeValue ); } script.addAttribute( attributeName, expression ); } return script; } catch (Exception e) { log.warn( "Could not create static tag for URI: " + namespaceURI + " tag name: " + localName, e ); throw createSAXException(e); } }
protected TagScript createStaticTag( String namespaceURI, String localName, String qName, Attributes list ) throws SAXException { try { StaticTag tag = new StaticTag( namespaceURI, localName ); DynaTagScript script = new DynaTagScript( tag ); // now iterate through through the expressions int size = list.getLength(); for ( int i = 0; i < size; i++ ) { String attributeName = list.getLocalName(i); String attributeValue = list.getValue(i); Expression expression = getExpressionFactory().createExpression( attributeValue ); if ( expression == null ) { expression = createConstantExpression( localName, attributeName, attributeValue ); } script.addAttribute( attributeName, expression ); } return script; } catch (Exception e) { log.warn( "Could not create static tag for URI: " + namespaceURI + " tag name: " + localName, e ); throw createSAXException(e); } }
1,111,043
protected TagScript createStaticTag( String namespaceURI, String localName, Attributes list ) throws SAXException { try { StaticTag tag = new StaticTag( namespaceURI, localName ); DynaTagScript script = new DynaTagScript( tag ); // now iterate through through the expressions int size = list.getLength(); for ( int i = 0; i < size; i++ ) { String attributeName = list.getLocalName(i); String attributeValue = list.getValue(i); Expression expression = getExpressionFactory().createExpression( attributeValue ); if ( expression == null ) { expression = createConstantExpression( localName, attributeName, attributeValue ); } script.addAttribute( attributeName, expression ); } return script; } catch (Exception e) { log.warn( "Could not create static tag for URI: " + namespaceURI + " tag name: " + localName, e ); throw createSAXException(e); } }
protected TagScript createStaticTag( String namespaceURI, String localName, Attributes list ) throws SAXException { try { StaticTag tag = new StaticTag( namespaceURI, localName, qName ); DynaTagScript script = new DynaTagScript( tag ); // now iterate through through the expressions int size = list.getLength(); for ( int i = 0; i < size; i++ ) { String attributeName = list.getLocalName(i); String attributeValue = list.getValue(i); Expression expression = getExpressionFactory().createExpression( attributeValue ); if ( expression == null ) { expression = createConstantExpression( localName, attributeName, attributeValue ); } script.addAttribute( attributeName, expression ); } return script; } catch (Exception e) { log.warn( "Could not create static tag for URI: " + namespaceURI + " tag name: " + localName, e ); throw createSAXException(e); } }
1,111,044
public void startElement( String namespaceURI, String localName, String qName, Attributes list ) throws SAXException { // if this is a tag then create a script to run it // otherwise pass the text to the current body tagScript = createTag( namespaceURI, localName, list ); if ( tagScript == null ) { tagScript = createStaticTag( namespaceURI, localName, list ); } tagScriptStack.add( tagScript ); if ( tagScript != null ) { // set parent relationship... Tag tag = tagScript.getTag(); tag.setParent( parentTag ); parentTag = tag; if ( textBuffer.length() > 0 ) { script.addScript( new TextScript( textBuffer.toString() ) ); textBuffer.setLength(0); } script.addScript( tagScript ); // start a new body scriptStack.push( script ); script = new ScriptBlock(); tag.setBody( script ); } else { // XXXX: might wanna handle empty elements later... textBuffer.append( "<" ); textBuffer.append( qName ); int size = list.getLength(); for ( int i = 0; i < size; i++ ) { textBuffer.append( " " ); textBuffer.append( list.getQName(i) ); textBuffer.append( "=" ); textBuffer.append( "\"" ); textBuffer.append( list.getValue(i) ); textBuffer.append( "\"" ); } textBuffer.append( ">" ); } }
public void startElement( String namespaceURI, String localName, String qName, Attributes list ) throws SAXException { // if this is a tag then create a script to run it // otherwise pass the text to the current body tagScript = createTag( namespaceURI, localName, list ); if ( tagScript == null ) { tagScript = createStaticTag( namespaceURI, localName, qName, list ); } tagScriptStack.add( tagScript ); if ( tagScript != null ) { // set parent relationship... Tag tag = tagScript.getTag(); tag.setParent( parentTag ); parentTag = tag; if ( textBuffer.length() > 0 ) { script.addScript( new TextScript( textBuffer.toString() ) ); textBuffer.setLength(0); } script.addScript( tagScript ); // start a new body scriptStack.push( script ); script = new ScriptBlock(); tag.setBody( script ); } else { // XXXX: might wanna handle empty elements later... textBuffer.append( "<" ); textBuffer.append( qName ); int size = list.getLength(); for ( int i = 0; i < size; i++ ) { textBuffer.append( " " ); textBuffer.append( list.getQName(i) ); textBuffer.append( "=" ); textBuffer.append( "\"" ); textBuffer.append( list.getValue(i) ); textBuffer.append( "\"" ); } textBuffer.append( ">" ); } }
1,111,045
public void run(JellyContext context, XMLOutput output) throws JellyTagException { try { startNamespacePrefixes(output); } catch (SAXException e) { throw new JellyTagException("could not start namespace prefixes",e); } Tag tag = null; try { tag = getTag(context); // lets see if we have a dynamic tag if (tag instanceof StaticTag) { tag = findDynamicTag(context, (StaticTag) tag); } setTag(tag,context); } catch (JellyException e) { throw new JellyTagException(e); } URL rootURL = context.getRootURL(); URL currentURL = context.getCurrentURL(); try { if ( tag == null ) { return; } tag.setContext(context); setContextURLs(context); DynaTag dynaTag = (DynaTag) tag; // ### probably compiling this to 2 arrays might be quicker and smaller for (Iterator iter = attributes.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); String name = (String) entry.getKey(); if(name.indexOf(':')!=-1) name = name.substring(name.indexOf(':')+1); ExpressionAttribute expat = (ExpressionAttribute) entry.getValue(); Expression expression = expat.exp; Object value = null; if ( Expression.class.isAssignableFrom( dynaTag.getAttributeType(name) ) ) { value = expression; } else { value = expression.evaluate(context); } if(expat.prefix!=null || expat.prefix.length()>0 && tag instanceof StaticTag) ((StaticTag) dynaTag).setAttribute(name,expat.prefix, expat.nsURI,value); else dynaTag.setAttribute(name, value); } tag.doTag(output); } catch (JellyTagException e) { handleException(e); } catch (RuntimeException e) { handleException(e); } finally { context.setCurrentURL(currentURL); context.setRootURL(rootURL); } try { endNamespacePrefixes(output); } catch (SAXException e) { throw new JellyTagException("could not end namespace prefixes",e); } }
public void run(JellyContext context, XMLOutput output) throws JellyTagException { try { startNamespacePrefixes(output); } catch (SAXException e) { throw new JellyTagException("could not start namespace prefixes",e); } Tag tag; try { tag = getTag(context); // lets see if we have a dynamic tag if (tag instanceof StaticTag) { tag = findDynamicTag(context, (StaticTag) tag); } setTag(tag,context); } catch (JellyException e) { throw new JellyTagException(e); } URL rootURL = context.getRootURL(); URL currentURL = context.getCurrentURL(); try { if ( tag == null ) { return; } tag.setContext(context); setContextURLs(context); DynaTag dynaTag = (DynaTag) tag; // ### probably compiling this to 2 arrays might be quicker and smaller for (Iterator iter = attributes.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); String name = (String) entry.getKey(); if(name.indexOf(':')!=-1) name = name.substring(name.indexOf(':')+1); ExpressionAttribute expat = (ExpressionAttribute) entry.getValue(); Expression expression = expat.exp; Object value = null; if ( Expression.class.isAssignableFrom( dynaTag.getAttributeType(name) ) ) { value = expression; } else { value = expression.evaluate(context); } if(expat.prefix!=null || expat.prefix.length()>0 && tag instanceof StaticTag) ((StaticTag) dynaTag).setAttribute(name,expat.prefix, expat.nsURI,value); else dynaTag.setAttribute(name, value); } tag.doTag(output); } catch (JellyTagException e) { handleException(e); } catch (RuntimeException e) { handleException(e); } finally { context.setCurrentURL(currentURL); context.setRootURL(rootURL); } try { endNamespacePrefixes(output); } catch (SAXException e) { throw new JellyTagException("could not end namespace prefixes",e); } }
1,111,046
public void run(JellyContext context, XMLOutput output) throws JellyTagException { try { startNamespacePrefixes(output); } catch (SAXException e) { throw new JellyTagException("could not start namespace prefixes",e); } Tag tag = null; try { tag = getTag(context); // lets see if we have a dynamic tag if (tag instanceof StaticTag) { tag = findDynamicTag(context, (StaticTag) tag); } setTag(tag,context); } catch (JellyException e) { throw new JellyTagException(e); } URL rootURL = context.getRootURL(); URL currentURL = context.getCurrentURL(); try { if ( tag == null ) { return; } tag.setContext(context); setContextURLs(context); DynaTag dynaTag = (DynaTag) tag; // ### probably compiling this to 2 arrays might be quicker and smaller for (Iterator iter = attributes.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); String name = (String) entry.getKey(); if(name.indexOf(':')!=-1) name = name.substring(name.indexOf(':')+1); ExpressionAttribute expat = (ExpressionAttribute) entry.getValue(); Expression expression = expat.exp; Object value = null; if ( Expression.class.isAssignableFrom( dynaTag.getAttributeType(name) ) ) { value = expression; } else { value = expression.evaluate(context); } if(expat.prefix!=null || expat.prefix.length()>0 && tag instanceof StaticTag) ((StaticTag) dynaTag).setAttribute(name,expat.prefix, expat.nsURI,value); else dynaTag.setAttribute(name, value); } tag.doTag(output); } catch (JellyTagException e) { handleException(e); } catch (RuntimeException e) { handleException(e); } finally { context.setCurrentURL(currentURL); context.setRootURL(rootURL); } try { endNamespacePrefixes(output); } catch (SAXException e) { throw new JellyTagException("could not end namespace prefixes",e); } }
public void run(JellyContext context, XMLOutput output) throws JellyTagException { try { startNamespacePrefixes(output); } catch (SAXException e) { throw new JellyTagException("could not start namespace prefixes",e); } Tag tag = null; try { tag = getTag(context); // lets see if we have a dynamic tag if (tag instanceof StaticTag) { tag = findDynamicTag(context, (StaticTag) tag); } setTag(tag,context); } catch (JellyException e) { throw new JellyTagException(e); } URL rootURL = context.getRootURL(); URL currentURL = context.getCurrentURL(); try { if ( tag == null ) { return; } tag.setContext(context); setContextURLs(context); DynaTag dynaTag = (DynaTag) tag; // ### probably compiling this to 2 arrays might be quicker and smaller for (Iterator iter = attributes.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); String name = (String) entry.getKey(); if(name.indexOf(':')!=-1) name = name.substring(name.indexOf(':')+1); ExpressionAttribute expat = (ExpressionAttribute) entry.getValue(); Expression expression = expat.exp; Object value; if ( Expression.class.isAssignableFrom( dynaTag.getAttributeType(name) ) ) { value = expression; } else { value = expression.evaluate(context); } if(expat.prefix!=null || expat.prefix.length()>0 && tag instanceof StaticTag) ((StaticTag) dynaTag).setAttribute(name,expat.prefix, expat.nsURI,value); else dynaTag.setAttribute(name, value); } tag.doTag(output); } catch (JellyTagException e) { handleException(e); } catch (RuntimeException e) { handleException(e); } finally { context.setCurrentURL(currentURL); context.setRootURL(rootURL); } try { endNamespacePrefixes(output); } catch (SAXException e) { throw new JellyTagException("could not end namespace prefixes",e); } }
1,111,047
public void run(JellyContext context, XMLOutput output) throws JellyTagException { try { startNamespacePrefixes(output); } catch (SAXException e) { throw new JellyTagException("could not start namespace prefixes",e); } Tag tag = null; try { tag = getTag(context); // lets see if we have a dynamic tag if (tag instanceof StaticTag) { tag = findDynamicTag(context, (StaticTag) tag); } setTag(tag,context); } catch (JellyException e) { throw new JellyTagException(e); } URL rootURL = context.getRootURL(); URL currentURL = context.getCurrentURL(); try { if ( tag == null ) { return; } tag.setContext(context); setContextURLs(context); DynaTag dynaTag = (DynaTag) tag; // ### probably compiling this to 2 arrays might be quicker and smaller for (Iterator iter = attributes.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); String name = (String) entry.getKey(); if(name.indexOf(':')!=-1) name = name.substring(name.indexOf(':')+1); ExpressionAttribute expat = (ExpressionAttribute) entry.getValue(); Expression expression = expat.exp; Object value = null; if ( Expression.class.isAssignableFrom( dynaTag.getAttributeType(name) ) ) { value = expression; } else { value = expression.evaluate(context); } if(expat.prefix!=null || expat.prefix.length()>0 && tag instanceof StaticTag) ((StaticTag) dynaTag).setAttribute(name,expat.prefix, expat.nsURI,value); else dynaTag.setAttribute(name, value); } tag.doTag(output); } catch (JellyTagException e) { handleException(e); } catch (RuntimeException e) { handleException(e); } finally { context.setCurrentURL(currentURL); context.setRootURL(rootURL); } try { endNamespacePrefixes(output); } catch (SAXException e) { throw new JellyTagException("could not end namespace prefixes",e); } }
public void run(JellyContext context, XMLOutput output) throws JellyTagException { try { startNamespacePrefixes(output); } catch (SAXException e) { throw new JellyTagException("could not start namespace prefixes",e); } Tag tag = null; try { tag = getTag(context); // lets see if we have a dynamic tag if (tag instanceof StaticTag) { tag = findDynamicTag(context, (StaticTag) tag); } setTag(tag,context); } catch (JellyException e) { throw new JellyTagException(e); } URL rootURL = context.getRootURL(); URL currentURL = context.getCurrentURL(); try { if ( tag == null ) { return; } tag.setContext(context); setContextURLs(context); DynaTag dynaTag = (DynaTag) tag; // ### probably compiling this to 2 arrays might be quicker and smaller for (Iterator iter = attributes.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); String name = (String) entry.getKey(); if(name.indexOf(':')!=-1) name = name.substring(name.indexOf(':')+1); ExpressionAttribute expat = (ExpressionAttribute) entry.getValue(); Expression expression = expat.exp; Object value = null; if ( Expression.class.isAssignableFrom( dynaTag.getAttributeType(name) ) ) { value = expression; } else { value = expression.evaluate(context); } if( expat.prefix != null && expat.prefix.length() > 0 && tag instanceof StaticTag ) { ((StaticTag) dynaTag).setAttribute(name,expat.prefix, expat.nsURI,value); else dynaTag.setAttribute(name, value); } tag.doTag(output); } catch (JellyTagException e) { handleException(e); } catch (RuntimeException e) { handleException(e); } finally { context.setCurrentURL(currentURL); context.setRootURL(rootURL); } try { endNamespacePrefixes(output); } catch (SAXException e) { throw new JellyTagException("could not end namespace prefixes",e); } }
1,111,048
public void testPopulateTable() throws ArchitectException { assertFalse("Table should not have been populated already", table.isPopulated()); table.populate(); assertTrue("Table should been populated", table.isPopulated()); // spot-check that expected columns exist SQLColumn yearCol, teamCol, strikeoutsCol; assertNotNull("year column not found", yearCol = table.getColumnByName("year")); assertNotNull("team column not found", teamCol = table.getColumnByName("team")); assertNotNull("league column not found", table.getColumnByName("league")); assertNotNull("strikeouts column not found", strikeoutsCol = table.getColumnByName("strikeouts")); // check that all columns are owned by the correct table assertEquals("column doesn't belong to correct parent!", table, yearCol.getParent()); assertEquals("column doesn't belong to correct parent!", table, teamCol.getParent()); assertEquals("column doesn't belong to correct parent!", table, strikeoutsCol.getParent()); // check for PK vs non PK attributes assertTrue("year should have been flagged as PK", yearCol.isPrimaryKey()); assertEquals("year nullability incorrect", yearCol.getNullable(), DatabaseMetaData.columnNoNulls); assertFalse("year isNullable incorrect", yearCol.isNullable()); assertFalse("strikeouts should have been flagged as PK", strikeoutsCol.isPrimaryKey()); assertEquals("strikeouts nullability incorrect", strikeoutsCol.getNullable(), DatabaseMetaData.columnNullable); assertTrue("strikeouts isNullable incorrect", strikeoutsCol.isNullable()); // check column name comparator Comparator nameComp = new SQLColumn.ColumnNameComparator(); assertTrue(nameComp.compare(yearCol, strikeoutsCol) > 0); assertTrue(nameComp.compare(teamCol, strikeoutsCol) > 0); assertTrue(nameComp.compare(strikeoutsCol, yearCol) < 0); assertTrue(nameComp.compare(strikeoutsCol, teamCol) < 0); assertTrue(nameComp.compare(yearCol, yearCol) == 0); teamCol.setColumnName("year"); assertTrue(nameComp.compare(yearCol, teamCol) == 0); }
public void testPopulateTable() throws ArchitectException { assertFalse("Table should not have been populated already", table.isPopulated()); table.populate(); assertTrue("Table should been populated", table.isPopulated()); // spot-check that expected columns exist SQLColumn yearCol, teamCol, strikeoutsCol; assertNotNull("year column not found", yearCol = table.getColumnByName("year")); assertNotNull("team column not found", teamCol = table.getColumnByName("team")); assertNotNull("league column not found", table.getColumnByName("league")); assertNotNull("strikeouts column not found", strikeoutsCol = table.getColumnByName("strikeouts")); // check that all columns are owned by the correct table assertEquals("column doesn't belong to correct parent!", table, yearCol.getParent()); assertEquals("column doesn't belong to correct parent!", table, teamCol.getParent()); assertEquals("column doesn't belong to correct parent!", table, strikeoutsCol.getParent()); // check for PK vs non PK attributes assertTrue("year should have been flagged as PK", yearCol.isPrimaryKey()); assertEquals("year nullability incorrect", yearCol.getNullable(), DatabaseMetaData.columnNoNulls); assertFalse("year isDefinitelyNullable incorrect", yearCol.isDefinitelyNullable()); assertFalse("strikeouts should have been flagged as PK", strikeoutsCol.isPrimaryKey()); assertEquals("strikeouts nullability incorrect", strikeoutsCol.getNullable(), DatabaseMetaData.columnNullable); assertTrue("strikeouts isNullable incorrect", strikeoutsCol.isNullable()); // check column name comparator Comparator nameComp = new SQLColumn.ColumnNameComparator(); assertTrue(nameComp.compare(yearCol, strikeoutsCol) > 0); assertTrue(nameComp.compare(teamCol, strikeoutsCol) > 0); assertTrue(nameComp.compare(strikeoutsCol, yearCol) < 0); assertTrue(nameComp.compare(strikeoutsCol, teamCol) < 0); assertTrue(nameComp.compare(yearCol, yearCol) == 0); teamCol.setColumnName("year"); assertTrue(nameComp.compare(yearCol, teamCol) == 0); }
1,111,050
public void testPopulateTable() throws ArchitectException { assertFalse("Table should not have been populated already", table.isPopulated()); table.populate(); assertTrue("Table should been populated", table.isPopulated()); // spot-check that expected columns exist SQLColumn yearCol, teamCol, strikeoutsCol; assertNotNull("year column not found", yearCol = table.getColumnByName("year")); assertNotNull("team column not found", teamCol = table.getColumnByName("team")); assertNotNull("league column not found", table.getColumnByName("league")); assertNotNull("strikeouts column not found", strikeoutsCol = table.getColumnByName("strikeouts")); // check that all columns are owned by the correct table assertEquals("column doesn't belong to correct parent!", table, yearCol.getParent()); assertEquals("column doesn't belong to correct parent!", table, teamCol.getParent()); assertEquals("column doesn't belong to correct parent!", table, strikeoutsCol.getParent()); // check for PK vs non PK attributes assertTrue("year should have been flagged as PK", yearCol.isPrimaryKey()); assertEquals("year nullability incorrect", yearCol.getNullable(), DatabaseMetaData.columnNoNulls); assertFalse("year isNullable incorrect", yearCol.isNullable()); assertFalse("strikeouts should have been flagged as PK", strikeoutsCol.isPrimaryKey()); assertEquals("strikeouts nullability incorrect", strikeoutsCol.getNullable(), DatabaseMetaData.columnNullable); assertTrue("strikeouts isNullable incorrect", strikeoutsCol.isNullable()); // check column name comparator Comparator nameComp = new SQLColumn.ColumnNameComparator(); assertTrue(nameComp.compare(yearCol, strikeoutsCol) > 0); assertTrue(nameComp.compare(teamCol, strikeoutsCol) > 0); assertTrue(nameComp.compare(strikeoutsCol, yearCol) < 0); assertTrue(nameComp.compare(strikeoutsCol, teamCol) < 0); assertTrue(nameComp.compare(yearCol, yearCol) == 0); teamCol.setColumnName("year"); assertTrue(nameComp.compare(yearCol, teamCol) == 0); }
public void testPopulateTable() throws ArchitectException { assertFalse("Table should not have been populated already", table.isPopulated()); table.populate(); assertTrue("Table should been populated", table.isPopulated()); // spot-check that expected columns exist SQLColumn yearCol, teamCol, strikeoutsCol; assertNotNull("year column not found", yearCol = table.getColumnByName("year")); assertNotNull("team column not found", teamCol = table.getColumnByName("team")); assertNotNull("league column not found", table.getColumnByName("league")); assertNotNull("strikeouts column not found", strikeoutsCol = table.getColumnByName("strikeouts")); // check that all columns are owned by the correct table assertEquals("column doesn't belong to correct parent!", table, yearCol.getParent()); assertEquals("column doesn't belong to correct parent!", table, teamCol.getParent()); assertEquals("column doesn't belong to correct parent!", table, strikeoutsCol.getParent()); // check for PK vs non PK attributes assertTrue("year should have been flagged as PK", yearCol.isPrimaryKey()); assertEquals("year nullability incorrect", yearCol.getNullable(), DatabaseMetaData.columnNoNulls); assertFalse("year isNullable incorrect", yearCol.isNullable()); assertFalse("strikeouts should have been flagged as PK", strikeoutsCol.isPrimaryKey()); assertEquals("strikeouts nullability incorrect", strikeoutsCol.getNullable(), DatabaseMetaData.columnNullable); assertTrue("strikeouts isDefinitelyNullable incorrect", strikeoutsCol.isDefinitelyNullable()); // check column name comparator Comparator nameComp = new SQLColumn.ColumnNameComparator(); assertTrue(nameComp.compare(yearCol, strikeoutsCol) > 0); assertTrue(nameComp.compare(teamCol, strikeoutsCol) > 0); assertTrue(nameComp.compare(strikeoutsCol, yearCol) < 0); assertTrue(nameComp.compare(strikeoutsCol, teamCol) < 0); assertTrue(nameComp.compare(yearCol, yearCol) == 0); teamCol.setColumnName("year"); assertTrue(nameComp.compare(yearCol, teamCol) == 0); }
1,111,051
public String getRole() { return role; }
public String[] getRole() { return role; }
1,111,053
public void setRole(String role) { this.role = role; }
public void setRole(String[] role) { this.role = role; }
1,111,054
public void run(JellyContext context, XMLOutput output) throws JellyTagException { try { startNamespacePrefixes(output); } catch (SAXException e) { throw new JellyTagException("could not start namespace prefixes",e); } Tag tag = null; try { tag = getTag(); // lets see if we have a dynamic tag if (tag instanceof StaticTag) { tag = findDynamicTag(context, (StaticTag) tag); } setTag(tag); } catch (JellyException e) { throw new JellyTagException(e); } try { if ( tag == null ) { return; } tag.setContext(context); DynaTag dynaTag = (DynaTag) tag; // ### probably compiling this to 2 arrays might be quicker and smaller for (Iterator iter = attributes.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); String name = (String) entry.getKey(); Expression expression = (Expression) entry.getValue(); Object value = expression.evaluate(context); dynaTag.setAttribute(name, value); } tag.doTag(output); } catch (JellyTagException e) { handleException(e); } catch (RuntimeException e) { handleException(e); } try { endNamespacePrefixes(output); } catch (SAXException e) { throw new JellyTagException("could not end namespace prefixes",e); } }
public void run(JellyContext context, XMLOutput output) throws JellyTagException { try { startNamespacePrefixes(output); } catch (SAXException e) { throw new JellyTagException("could not start namespace prefixes",e); } Tag tag = null; try { tag = getTag(); // lets see if we have a dynamic tag if (tag instanceof StaticTag) { tag = findDynamicTag(context, (StaticTag) tag); } setTag(tag); } catch (JellyException e) { throw new JellyTagException(e); } try { if ( tag == null ) { return; } tag.setContext(context); DynaTag dynaTag = (DynaTag) tag; // ### probably compiling this to 2 arrays might be quicker and smaller for (Iterator iter = attributes.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); String name = (String) entry.getKey(); Expression expression = (Expression) entry.getValue(); Object value = null; if ( Expression.class.isAssignableFrom( dynaTag.getAttributeType(name) ) ) { value = expression; } else { value = expression.evaluate(context); } dynaTag.setAttribute(name, value); } tag.doTag(output); } catch (JellyTagException e) { handleException(e); } catch (RuntimeException e) { handleException(e); } try { endNamespacePrefixes(output); } catch (SAXException e) { throw new JellyTagException("could not end namespace prefixes",e); } }
1,111,055
generateAbstractClass(Class<S> storableClass, boolean isMaster) throws SupportException { EnumSet<MasterFeature> features; if (isMaster) { features = EnumSet.of(MasterFeature.VERSIONING, MasterFeature.UPDATE_FULL, MasterFeature.INSERT_SEQUENCES, MasterFeature.INSERT_CHECK_REQUIRED); } else { features = EnumSet.of(MasterFeature.UPDATE_FULL); } final Class<? extends S> abstractClass = MasterStorableGenerator.getAbstractClass(storableClass, features); ClassInjector ci = ClassInjector.create (storableClass.getName(), abstractClass.getClassLoader()); ClassFile cf = new ClassFile(ci.getClassName(), abstractClass); cf.setModifiers(cf.getModifiers().toAbstract(true)); cf.markSynthetic(); cf.setSourceFile(RawStorableGenerator.class.getName()); cf.setTarget("1.5"); // Declare some types. final TypeDesc storableType = TypeDesc.forClass(Storable.class); final TypeDesc triggerSupportType = TypeDesc.forClass(TriggerSupport.class); final TypeDesc masterSupportType = TypeDesc.forClass(MasterSupport.class); final TypeDesc rawSupportType = TypeDesc.forClass(RawSupport.class); final TypeDesc byteArrayType = TypeDesc.forClass(byte[].class); // Add constructors. // 1: Accepts a RawSupport. // 2: Accepts a RawSupport and an encoded key. // 3: Accepts a RawSupport, an encoded key and an encoded data. for (int i=1; i<=3; i++) { TypeDesc[] params = new TypeDesc[i]; params[0] = rawSupportType; if (i >= 2) { params[1] = byteArrayType; if (i == 3) { params[2] = byteArrayType; } } MethodInfo mi = cf.addConstructor(Modifiers.PUBLIC, params); CodeBuilder b = new CodeBuilder(mi); b.loadThis(); b.loadLocal(b.getParameter(0)); b.invokeSuperConstructor(new TypeDesc[] {masterSupportType}); if (i >= 2) { params = new TypeDesc[] {byteArrayType}; b.loadThis(); b.loadLocal(b.getParameter(1)); b.invokeVirtual(DECODE_KEY_METHOD_NAME, null, params); if (i == 3) { b.loadThis(); b.loadLocal(b.getParameter(2)); b.invokeVirtual(DECODE_DATA_METHOD_NAME, null, params); // Indicate that object is clean by calling markAllPropertiesClean. b.loadThis(); b.invokeVirtual(MARK_ALL_PROPERTIES_CLEAN, null, null); } else { // Only the primary key is clean. Calling // markPropertiesClean might have no effect since subclass // may set fields directly. Instead, set state bits directly. Collection<? extends StorableProperty<S>> properties = StorableIntrospector .examine(storableClass).getPrimaryKeyProperties().values(); final int count = properties.size(); int ordinal = 0; int andMask = ~0; int orMask = 0; for (StorableProperty property : properties) { orMask |= StorableGenerator.PROPERTY_STATE_CLEAN << ((ordinal & 0xf) * 2); andMask &= StorableGenerator.PROPERTY_STATE_MASK << ((ordinal & 0xf) * 2); ordinal++; if ((ordinal & 0xf) == 0 || ordinal >= count) { String stateFieldName = StorableGenerator.PROPERTY_STATE_FIELD_NAME + ((ordinal - 1) >> 4); b.loadThis(); if (andMask == 0) { b.loadConstant(orMask); } else { b.loadThis(); b.loadField(stateFieldName, TypeDesc.INT); b.loadConstant(andMask); b.math(Opcode.IAND); b.loadConstant(orMask); b.math(Opcode.IOR); } b.storeField(stateFieldName, TypeDesc.INT); andMask = ~0; orMask = 0; } } } } b.returnVoid(); } // Declare protected abstract methods. { cf.addMethod(Modifiers.PROTECTED.toAbstract(true), ENCODE_KEY_METHOD_NAME, byteArrayType, null); cf.addMethod(Modifiers.PROTECTED.toAbstract(true), DECODE_KEY_METHOD_NAME, null, new TypeDesc[]{byteArrayType}); cf.addMethod(Modifiers.PROTECTED.toAbstract(true), ENCODE_DATA_METHOD_NAME, byteArrayType, null); cf.addMethod(Modifiers.PROTECTED.toAbstract(true), DECODE_DATA_METHOD_NAME, null, new TypeDesc[]{byteArrayType}); } // Add required protected doTryLoad_master method, which delegates to RawSupport. { MethodInfo mi = cf.addMethod (Modifiers.PROTECTED.toFinal(true), MasterStorableGenerator.DO_TRY_LOAD_MASTER_METHOD_NAME, TypeDesc.BOOLEAN, null); mi.addException(TypeDesc.forClass(FetchException.class)); CodeBuilder b = new CodeBuilder(mi); b.loadThis(); b.loadField(StorableGenerator.SUPPORT_FIELD_NAME, triggerSupportType); b.checkCast(rawSupportType); b.loadThis(); b.invokeVirtual(ENCODE_KEY_METHOD_NAME, byteArrayType, null); TypeDesc[] params = {byteArrayType}; b.invokeInterface(rawSupportType, "tryLoad", byteArrayType, params); LocalVariable encodedDataVar = b.createLocalVariable(null, byteArrayType); b.storeLocal(encodedDataVar); b.loadLocal(encodedDataVar); Label notNull = b.createLabel(); b.ifNullBranch(notNull, false); b.loadConstant(false); b.returnValue(TypeDesc.BOOLEAN); notNull.setLocation(); b.loadThis(); b.loadLocal(encodedDataVar); params = new TypeDesc[] {byteArrayType}; b.invokeVirtual(DECODE_DATA_METHOD_NAME, null, params); b.loadConstant(true); b.returnValue(TypeDesc.BOOLEAN); } // Add required protected doTryInsert_master method, which delegates to RawSupport. { MethodInfo mi = cf.addMethod (Modifiers.PROTECTED.toFinal(true), MasterStorableGenerator.DO_TRY_INSERT_MASTER_METHOD_NAME, TypeDesc.BOOLEAN, null); mi.addException(TypeDesc.forClass(PersistException.class)); CodeBuilder b = new CodeBuilder(mi); // return rawSupport.tryInsert(this, this.encodeKey$(), this.encodeData$()); b.loadThis(); b.loadField(StorableGenerator.SUPPORT_FIELD_NAME, triggerSupportType); b.checkCast(rawSupportType); b.loadThis(); // pass this to tryInsert method b.loadThis(); b.invokeVirtual(ENCODE_KEY_METHOD_NAME, byteArrayType, null); b.loadThis(); b.invokeVirtual(ENCODE_DATA_METHOD_NAME, byteArrayType, null); TypeDesc[] params = {storableType, byteArrayType, byteArrayType}; b.invokeInterface(rawSupportType, "tryInsert", TypeDesc.BOOLEAN, params); b.returnValue(TypeDesc.BOOLEAN); } // Add required protected doTryUpdate_master method, which delegates to RawSupport. { MethodInfo mi = cf.addMethod (Modifiers.PROTECTED.toFinal(true), MasterStorableGenerator.DO_TRY_UPDATE_MASTER_METHOD_NAME, TypeDesc.BOOLEAN, null); mi.addException(TypeDesc.forClass(PersistException.class)); CodeBuilder b = new CodeBuilder(mi); // rawSupport.store(this, this.encodeKey$(), this.encodeData$()); // return true; b.loadThis(); b.loadField(StorableGenerator.SUPPORT_FIELD_NAME, triggerSupportType); b.checkCast(rawSupportType); b.loadThis(); // pass this to store method b.loadThis(); b.invokeVirtual(ENCODE_KEY_METHOD_NAME, byteArrayType, null); b.loadThis(); b.invokeVirtual(ENCODE_DATA_METHOD_NAME, byteArrayType, null); TypeDesc[] params = {storableType, byteArrayType, byteArrayType}; b.invokeInterface(rawSupportType, "store", null, params); b.loadConstant(true); b.returnValue(TypeDesc.BOOLEAN); } // Add required protected doTryDelete_master method, which delegates to RawSupport. { MethodInfo mi = cf.addMethod (Modifiers.PROTECTED.toFinal(true), MasterStorableGenerator.DO_TRY_DELETE_MASTER_METHOD_NAME, TypeDesc.BOOLEAN, null); mi.addException(TypeDesc.forClass(PersistException.class)); CodeBuilder b = new CodeBuilder(mi); // return rawSupport.tryDelete(this.encodeKey$()); b.loadThis(); b.loadField(StorableGenerator.SUPPORT_FIELD_NAME, triggerSupportType); b.checkCast(rawSupportType); b.loadThis(); b.invokeVirtual(ENCODE_KEY_METHOD_NAME, byteArrayType, null); TypeDesc[] params = {byteArrayType}; b.invokeInterface(rawSupportType, "tryDelete", TypeDesc.BOOLEAN, params); b.returnValue(TypeDesc.BOOLEAN); } return ci.defineClass(cf); }
generateAbstractClass(Class<S> storableClass, boolean isMaster) throws SupportException { EnumSet<MasterFeature> features; if (isMaster) { features = EnumSet.of(MasterFeature.VERSIONING, MasterFeature.UPDATE_FULL, MasterFeature.INSERT_SEQUENCES, MasterFeature.INSERT_CHECK_REQUIRED); } else { features = EnumSet.of(MasterFeature.UPDATE_FULL); } final Class<? extends S> abstractClass = MasterStorableGenerator.getAbstractClass(storableClass, features); ClassInjector ci = ClassInjector.create (storableClass.getName(), abstractClass.getClassLoader()); ClassFile cf = new ClassFile(ci.getClassName(), abstractClass); cf.setModifiers(cf.getModifiers().toAbstract(true)); cf.markSynthetic(); cf.setSourceFile(RawStorableGenerator.class.getName()); cf.setTarget("1.5"); // Declare some types. final TypeDesc storableType = TypeDesc.forClass(Storable.class); final TypeDesc triggerSupportType = TypeDesc.forClass(TriggerSupport.class); final TypeDesc masterSupportType = TypeDesc.forClass(MasterSupport.class); final TypeDesc rawSupportType = TypeDesc.forClass(RawSupport.class); final TypeDesc byteArrayType = TypeDesc.forClass(byte[].class); // Add constructors. // 1: Accepts a RawSupport. // 2: Accepts a RawSupport and an encoded key. // 3: Accepts a RawSupport, an encoded key and an encoded data. for (int i=1; i<=3; i++) { TypeDesc[] params = new TypeDesc[i]; params[0] = rawSupportType; if (i >= 2) { params[1] = byteArrayType; if (i == 3) { params[2] = byteArrayType; } } MethodInfo mi = cf.addConstructor(Modifiers.PUBLIC, params); CodeBuilder b = new CodeBuilder(mi); b.loadThis(); b.loadLocal(b.getParameter(0)); b.invokeSuperConstructor(new TypeDesc[] {masterSupportType}); if (i >= 2) { params = new TypeDesc[] {byteArrayType}; b.loadThis(); b.loadLocal(b.getParameter(1)); b.invokeVirtual(DECODE_KEY_METHOD_NAME, null, params); if (i == 3) { b.loadThis(); b.loadLocal(b.getParameter(2)); b.invokeVirtual(DECODE_DATA_METHOD_NAME, null, params); // Indicate that object is clean by calling markAllPropertiesClean. b.loadThis(); b.invokeVirtual(MARK_ALL_PROPERTIES_CLEAN, null, null); } else { // Only the primary key is clean. Calling // markPropertiesClean might have no effect since subclass // may set fields directly. Instead, set state bits directly. Collection<? extends StorableProperty<S>> properties = StorableIntrospector .examine(storableClass).getPrimaryKeyProperties().values(); final int count = properties.size(); int ordinal = 0; int andMask = ~0; int orMask = 0; for (StorableProperty property : properties) { orMask |= StorableGenerator.PROPERTY_STATE_CLEAN << ((ordinal & 0xf) * 2); andMask &= ~(StorableGenerator.PROPERTY_STATE_MASK << ((ordinal & 0xf) * 2)); ordinal++; if ((ordinal & 0xf) == 0 || ordinal >= count) { String stateFieldName = StorableGenerator.PROPERTY_STATE_FIELD_NAME + ((ordinal - 1) >> 4); b.loadThis(); if (andMask == 0) { b.loadConstant(orMask); } else { b.loadThis(); b.loadField(stateFieldName, TypeDesc.INT); b.loadConstant(andMask); b.math(Opcode.IAND); b.loadConstant(orMask); b.math(Opcode.IOR); } b.storeField(stateFieldName, TypeDesc.INT); andMask = ~0; orMask = 0; } } } } b.returnVoid(); } // Declare protected abstract methods. { cf.addMethod(Modifiers.PROTECTED.toAbstract(true), ENCODE_KEY_METHOD_NAME, byteArrayType, null); cf.addMethod(Modifiers.PROTECTED.toAbstract(true), DECODE_KEY_METHOD_NAME, null, new TypeDesc[]{byteArrayType}); cf.addMethod(Modifiers.PROTECTED.toAbstract(true), ENCODE_DATA_METHOD_NAME, byteArrayType, null); cf.addMethod(Modifiers.PROTECTED.toAbstract(true), DECODE_DATA_METHOD_NAME, null, new TypeDesc[]{byteArrayType}); } // Add required protected doTryLoad_master method, which delegates to RawSupport. { MethodInfo mi = cf.addMethod (Modifiers.PROTECTED.toFinal(true), MasterStorableGenerator.DO_TRY_LOAD_MASTER_METHOD_NAME, TypeDesc.BOOLEAN, null); mi.addException(TypeDesc.forClass(FetchException.class)); CodeBuilder b = new CodeBuilder(mi); b.loadThis(); b.loadField(StorableGenerator.SUPPORT_FIELD_NAME, triggerSupportType); b.checkCast(rawSupportType); b.loadThis(); b.invokeVirtual(ENCODE_KEY_METHOD_NAME, byteArrayType, null); TypeDesc[] params = {byteArrayType}; b.invokeInterface(rawSupportType, "tryLoad", byteArrayType, params); LocalVariable encodedDataVar = b.createLocalVariable(null, byteArrayType); b.storeLocal(encodedDataVar); b.loadLocal(encodedDataVar); Label notNull = b.createLabel(); b.ifNullBranch(notNull, false); b.loadConstant(false); b.returnValue(TypeDesc.BOOLEAN); notNull.setLocation(); b.loadThis(); b.loadLocal(encodedDataVar); params = new TypeDesc[] {byteArrayType}; b.invokeVirtual(DECODE_DATA_METHOD_NAME, null, params); b.loadConstant(true); b.returnValue(TypeDesc.BOOLEAN); } // Add required protected doTryInsert_master method, which delegates to RawSupport. { MethodInfo mi = cf.addMethod (Modifiers.PROTECTED.toFinal(true), MasterStorableGenerator.DO_TRY_INSERT_MASTER_METHOD_NAME, TypeDesc.BOOLEAN, null); mi.addException(TypeDesc.forClass(PersistException.class)); CodeBuilder b = new CodeBuilder(mi); // return rawSupport.tryInsert(this, this.encodeKey$(), this.encodeData$()); b.loadThis(); b.loadField(StorableGenerator.SUPPORT_FIELD_NAME, triggerSupportType); b.checkCast(rawSupportType); b.loadThis(); // pass this to tryInsert method b.loadThis(); b.invokeVirtual(ENCODE_KEY_METHOD_NAME, byteArrayType, null); b.loadThis(); b.invokeVirtual(ENCODE_DATA_METHOD_NAME, byteArrayType, null); TypeDesc[] params = {storableType, byteArrayType, byteArrayType}; b.invokeInterface(rawSupportType, "tryInsert", TypeDesc.BOOLEAN, params); b.returnValue(TypeDesc.BOOLEAN); } // Add required protected doTryUpdate_master method, which delegates to RawSupport. { MethodInfo mi = cf.addMethod (Modifiers.PROTECTED.toFinal(true), MasterStorableGenerator.DO_TRY_UPDATE_MASTER_METHOD_NAME, TypeDesc.BOOLEAN, null); mi.addException(TypeDesc.forClass(PersistException.class)); CodeBuilder b = new CodeBuilder(mi); // rawSupport.store(this, this.encodeKey$(), this.encodeData$()); // return true; b.loadThis(); b.loadField(StorableGenerator.SUPPORT_FIELD_NAME, triggerSupportType); b.checkCast(rawSupportType); b.loadThis(); // pass this to store method b.loadThis(); b.invokeVirtual(ENCODE_KEY_METHOD_NAME, byteArrayType, null); b.loadThis(); b.invokeVirtual(ENCODE_DATA_METHOD_NAME, byteArrayType, null); TypeDesc[] params = {storableType, byteArrayType, byteArrayType}; b.invokeInterface(rawSupportType, "store", null, params); b.loadConstant(true); b.returnValue(TypeDesc.BOOLEAN); } // Add required protected doTryDelete_master method, which delegates to RawSupport. { MethodInfo mi = cf.addMethod (Modifiers.PROTECTED.toFinal(true), MasterStorableGenerator.DO_TRY_DELETE_MASTER_METHOD_NAME, TypeDesc.BOOLEAN, null); mi.addException(TypeDesc.forClass(PersistException.class)); CodeBuilder b = new CodeBuilder(mi); // return rawSupport.tryDelete(this.encodeKey$()); b.loadThis(); b.loadField(StorableGenerator.SUPPORT_FIELD_NAME, triggerSupportType); b.checkCast(rawSupportType); b.loadThis(); b.invokeVirtual(ENCODE_KEY_METHOD_NAME, byteArrayType, null); TypeDesc[] params = {byteArrayType}; b.invokeInterface(rawSupportType, "tryDelete", TypeDesc.BOOLEAN, params); b.returnValue(TypeDesc.BOOLEAN); } return ci.defineClass(cf); }
1,111,056
public void paintComponent(Graphics graphics) { if (filteredHaplos == null){ super.paintComponent(graphics); return; } Graphics2D g = (Graphics2D) graphics; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //System.out.println(getSize()); Dimension size = getSize(); Dimension pref = getPreferredSize(); g.translate((size.width - pref.width) / 2, (size.height - pref.height) / 2); //g.drawRect(0, 0, pref.width, pref.height); final BasicStroke thinStroke = new BasicStroke(0.5f); final BasicStroke thickStroke = new BasicStroke(2.0f); // width of one letter of the haplotype block //int letterWidth = haploMetrics.charWidth('G'); //int percentWidth = pctMetrics.stringWidth(".000"); //final int verticalOffset = 43; // room for tags and diamonds int left = BORDER; int top = BORDER; //verticalOffset; //int totalWidth = 0; // percentages for each haplotype NumberFormat nf = NumberFormat.getInstance(); nf.setMinimumFractionDigits(3); nf.setMaximumFractionDigits(3); nf.setMinimumIntegerDigits(0); nf.setMaximumIntegerDigits(0); // multi reading, between the columns NumberFormat nfMulti = NumberFormat.getInstance(); nfMulti.setMinimumFractionDigits(2); nfMulti.setMaximumFractionDigits(2); nfMulti.setMinimumIntegerDigits(0); nfMulti.setMaximumIntegerDigits(0); int[][] lookupPos = new int[filteredHaplos.length][]; for (int p = 0; p < lookupPos.length; p++) { lookupPos[p] = new int[filteredHaplos[p].length]; for (int q = 0; q < lookupPos[p].length; q++){ lookupPos[p][filteredHaplos[p][q].getListOrder()] = q; } } // set number formatter to pad with appropriate number of zeroes NumberFormat nfMarker = NumberFormat.getInstance(); int markerCount = Chromosome.getSize(); // the +0.0000001 is because there is // some suckage where log(1000) / log(10) isn't actually 3 int markerDigits = (int) (0.0000001 + Math.log(markerCount) / Math.log(10)) + 1; nfMarker.setMinimumIntegerDigits(markerDigits); nfMarker.setMaximumIntegerDigits(markerDigits); //int tagShapeX[] = new int[3]; //int tagShapeY[] = new int[3]; //Polygon tagShape; int textRight = 0; // gets updated for scooting over // i = 0 to number of columns - 1 for (int i = 0; i < filteredHaplos.length; i++) { int[] markerNums = filteredHaplos[i][0].getMarkers(); boolean[] tags = filteredHaplos[i][0].getTags(); //int headerX = x; for (int z = 0; z < markerNums.length; z++) { //int tagMiddle = tagMetrics.getAscent() / 2; //int tagLeft = x + z*letterWidth + tagMiddle; //g.translate(tagLeft, 20); // if tag snp, draw little triangle pooper if (tags[z]) { g.drawImage(tagImage, left + z*CHAR_WIDTH, top + markerDigits*MARKER_CHAR_WIDTH + -(CHAR_HEIGHT - TAG_SPAN), null); } //g.rotate(-Math.PI / 2.0); //g.drawLine(0, 0, 0, 0); //g.setColor(Color.black); //g.drawString(nfMarker.format(markerNums[z]), 0, tagMiddle); char markerChars[] = nfMarker.format(markerNums[z]+1).toCharArray(); for (int m = 0; m < markerDigits; m++) { g.drawImage(markerNumImages[markerChars[m] - '0'], left + z*CHAR_WIDTH + (1 + CHAR_WIDTH - MARKER_CHAR_HEIGHT)/2, top + (markerDigits-m-1)*MARKER_CHAR_WIDTH, null); } // undo the transform.. no push/pop.. arrgh //g.rotate(Math.PI / 2.0); //g.translate(-tagLeft, -20); } // y position of the first image for the haplotype letter // top + the size of the marker digits + the size of the tag + // the character height centered in the row's height int above = top + markerDigits*MARKER_CHAR_WIDTH + TAG_SPAN + (ROW_HEIGHT - CHAR_HEIGHT) / 2; for (int j = 0; j < filteredHaplos[i].length; j++){ int curHapNum = lookupPos[i][j]; //String theHap = new String(); //String thePercentage = new String(); int[] theGeno = filteredHaplos[i][curHapNum].getGeno(); //getGeno(); // j is the row of haplotype for (int k = 0; k < theGeno.length; k++) { // theGeno[k] will be 1,2,3,4 (acgt) or 8 (for bad) g.drawImage(charImages[theGeno[k] - 1], left + k*CHAR_WIDTH, above + j*ROW_HEIGHT, null); } //draw the percentage value in non mono font double percent = filteredHaplos[i][curHapNum].getPercentage(); //thePercentage = " " + nf.format(percent); char percentChars[] = nf.format(percent).toCharArray(); // perhaps need an exceptional case for 1.0 being the percent for (int m = 0; m < percentChars.length; m++) { g.drawImage(grayNumImages[(m == 0) ? 10 : percentChars[m]-'0'], left + theGeno.length*CHAR_WIDTH + m*CHAR_WIDTH, above + j*ROW_HEIGHT, null); } // 4 is the number of chars in .999 for the percent textRight = left + theGeno.length*CHAR_WIDTH + 4*CHAR_WIDTH; g.setColor(Color.black); if (i < filteredHaplos.length - 1) { //draw crossovers for (int crossCount = 0; crossCount < filteredHaplos[i+1].length; crossCount++) { double crossVal = filteredHaplos[i][curHapNum].getCrossover(crossCount); //draw thin and thick lines int crossValue = (int) (crossVal*100); if (crossValue > thinThresh) { g.setStroke(crossValue > thickThresh ? thickStroke : thinStroke); int connectTo = filteredHaplos[i+1][crossCount].getListOrder(); g.drawLine(textRight + LINE_LEFT, above + j*ROW_HEIGHT + ROW_HEIGHT/2, textRight + LINE_RIGHT, above + connectTo*ROW_HEIGHT + ROW_HEIGHT/2); } } } } left = textRight; // add the multilocus d prime if appropriate if (i < filteredHaplos.length - 1) { //put the numbers in the right place vertically int depth; if (filteredHaplos[i].length > filteredHaplos[i+1].length){ depth = filteredHaplos[i].length; }else{ depth = filteredHaplos[i+1].length; } char multiChars[] = nfMulti.format(multidprimeArray[i]).toCharArray(); for (int m = 0; m < 3; m++) { // 7*CHAR_WIDTH/2 = CHAR_WIDTH*3.5 to center it better // since the . char is right-aligned, and visually off g.drawImage(blackNumImages[(m == 0) ? 10 : multiChars[m]-'0'], left + (LINE_SPAN - 7*CHAR_WIDTH/2)/2 + m*CHAR_WIDTH, above + (depth * ROW_HEIGHT), null); } //int multiX = x + totalWidth + 3; //g.drawString(nfMulti.format(multidprimeArray[i]), // multiX+2, windowY - 3); } left += LINE_SPAN; //x += (totalWidth + 40); //y = verticalOffset; //left = textRight + LINE_SPAN; } }
public void paintComponent(Graphics graphics) { if (filteredHaplos == null){ super.paintComponent(graphics); return; } Graphics2D g = (Graphics2D) graphics; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //System.out.println(getSize()); Dimension size = getSize(); Dimension pref = getPreferredSize(); g.translate((size.width - pref.width) / 2, (size.height - pref.height) / 2); //g.drawRect(0, 0, pref.width, pref.height); final BasicStroke thinStroke = new BasicStroke(0.5f); final BasicStroke thickStroke = new BasicStroke(2.0f); // width of one letter of the haplotype block //int letterWidth = haploMetrics.charWidth('G'); //int percentWidth = pctMetrics.stringWidth(".000"); //final int verticalOffset = 43; // room for tags and diamonds int left = BORDER; int top = BORDER; //verticalOffset; //int totalWidth = 0; // percentages for each haplotype NumberFormat nf = NumberFormat.getInstance(); nf.setMinimumFractionDigits(3); nf.setMaximumFractionDigits(3); nf.setMinimumIntegerDigits(0); nf.setMaximumIntegerDigits(0); // multi reading, between the columns NumberFormat nfMulti = NumberFormat.getInstance(); nfMulti.setMinimumFractionDigits(2); nfMulti.setMaximumFractionDigits(2); nfMulti.setMinimumIntegerDigits(0); nfMulti.setMaximumIntegerDigits(0); int[][] lookupPos = new int[filteredHaplos.length][]; for (int p = 0; p < lookupPos.length; p++) { lookupPos[p] = new int[filteredHaplos[p].length]; for (int q = 0; q < lookupPos[p].length; q++){ lookupPos[p][filteredHaplos[p][q].getListOrder()] = q; } } // set number formatter to pad with appropriate number of zeroes NumberFormat nfMarker = NumberFormat.getInstance(); int markerCount = Chromosome.getSize(); // the +0.0000001 is because there is // some suckage where log(1000) / log(10) isn't actually 3 int markerDigits = (int) (0.0000001 + Math.log(markerCount) / Math.log(10)) + 1; nfMarker.setMinimumIntegerDigits(markerDigits); nfMarker.setMaximumIntegerDigits(markerDigits); //int tagShapeX[] = new int[3]; //int tagShapeY[] = new int[3]; //Polygon tagShape; int textRight = 0; // gets updated for scooting over // i = 0 to number of columns - 1 for (int i = 0; i < filteredHaplos.length; i++) { int[] markerNums = filteredHaplos[i][0].getMarkers(); boolean[] tags = filteredHaplos[i][0].getTags(); //int headerX = x; for (int z = 0; z < markerNums.length; z++) { //int tagMiddle = tagMetrics.getAscent() / 2; //int tagLeft = x + z*letterWidth + tagMiddle; //g.translate(tagLeft, 20); // if tag snp, draw little triangle pooper if (tags[z]) { g.drawImage(tagImage, left + z*CHAR_WIDTH, top + markerDigits*MARKER_CHAR_WIDTH + -(CHAR_HEIGHT - TAG_SPAN), null); } //g.rotate(-Math.PI / 2.0); //g.drawLine(0, 0, 0, 0); //g.setColor(Color.black); //g.drawString(nfMarker.format(markerNums[z]), 0, tagMiddle); char markerChars[] = nfMarker.format(Chromosome.realIndex[markerNums[z]]+1).toCharArray(); for (int m = 0; m < markerDigits; m++) { g.drawImage(markerNumImages[markerChars[m] - '0'], left + z*CHAR_WIDTH + (1 + CHAR_WIDTH - MARKER_CHAR_HEIGHT)/2, top + (markerDigits-m-1)*MARKER_CHAR_WIDTH, null); } // undo the transform.. no push/pop.. arrgh //g.rotate(Math.PI / 2.0); //g.translate(-tagLeft, -20); } // y position of the first image for the haplotype letter // top + the size of the marker digits + the size of the tag + // the character height centered in the row's height int above = top + markerDigits*MARKER_CHAR_WIDTH + TAG_SPAN + (ROW_HEIGHT - CHAR_HEIGHT) / 2; for (int j = 0; j < filteredHaplos[i].length; j++){ int curHapNum = lookupPos[i][j]; //String theHap = new String(); //String thePercentage = new String(); int[] theGeno = filteredHaplos[i][curHapNum].getGeno(); //getGeno(); // j is the row of haplotype for (int k = 0; k < theGeno.length; k++) { // theGeno[k] will be 1,2,3,4 (acgt) or 8 (for bad) g.drawImage(charImages[theGeno[k] - 1], left + k*CHAR_WIDTH, above + j*ROW_HEIGHT, null); } //draw the percentage value in non mono font double percent = filteredHaplos[i][curHapNum].getPercentage(); //thePercentage = " " + nf.format(percent); char percentChars[] = nf.format(percent).toCharArray(); // perhaps need an exceptional case for 1.0 being the percent for (int m = 0; m < percentChars.length; m++) { g.drawImage(grayNumImages[(m == 0) ? 10 : percentChars[m]-'0'], left + theGeno.length*CHAR_WIDTH + m*CHAR_WIDTH, above + j*ROW_HEIGHT, null); } // 4 is the number of chars in .999 for the percent textRight = left + theGeno.length*CHAR_WIDTH + 4*CHAR_WIDTH; g.setColor(Color.black); if (i < filteredHaplos.length - 1) { //draw crossovers for (int crossCount = 0; crossCount < filteredHaplos[i+1].length; crossCount++) { double crossVal = filteredHaplos[i][curHapNum].getCrossover(crossCount); //draw thin and thick lines int crossValue = (int) (crossVal*100); if (crossValue > thinThresh) { g.setStroke(crossValue > thickThresh ? thickStroke : thinStroke); int connectTo = filteredHaplos[i+1][crossCount].getListOrder(); g.drawLine(textRight + LINE_LEFT, above + j*ROW_HEIGHT + ROW_HEIGHT/2, textRight + LINE_RIGHT, above + connectTo*ROW_HEIGHT + ROW_HEIGHT/2); } } } } left = textRight; // add the multilocus d prime if appropriate if (i < filteredHaplos.length - 1) { //put the numbers in the right place vertically int depth; if (filteredHaplos[i].length > filteredHaplos[i+1].length){ depth = filteredHaplos[i].length; }else{ depth = filteredHaplos[i+1].length; } char multiChars[] = nfMulti.format(multidprimeArray[i]).toCharArray(); for (int m = 0; m < 3; m++) { // 7*CHAR_WIDTH/2 = CHAR_WIDTH*3.5 to center it better // since the . char is right-aligned, and visually off g.drawImage(blackNumImages[(m == 0) ? 10 : multiChars[m]-'0'], left + (LINE_SPAN - 7*CHAR_WIDTH/2)/2 + m*CHAR_WIDTH, above + (depth * ROW_HEIGHT), null); } //int multiX = x + totalWidth + 3; //g.drawString(nfMulti.format(multidprimeArray[i]), // multiX+2, windowY - 3); } left += LINE_SPAN; //x += (totalWidth + 40); //y = verticalOffset; //left = textRight + LINE_SPAN; } }
1,111,058
private List<Set<ChainedProperty<S>>> getKeys() { StorableInfo<S> info = StorableIntrospector.examine(mIndexAnalyzer.getStorableType()); List<Set<ChainedProperty<S>>> keys = new ArrayList<Set<ChainedProperty<S>>>(); keys.add(stripOrdering(info.getPrimaryKey().getProperties())); for (StorableKey<S> altKey : info.getAlternateKeys()) { keys.add(stripOrdering(altKey.getProperties())); } return keys; }
private List<Set<ChainedProperty<S>>> getKeys() throws SupportException, RepositoryException { StorableInfo<S> info = StorableIntrospector.examine(mIndexAnalyzer.getStorableType()); List<Set<ChainedProperty<S>>> keys = new ArrayList<Set<ChainedProperty<S>>>(); keys.add(stripOrdering(info.getPrimaryKey().getProperties())); for (StorableKey<S> altKey : info.getAlternateKeys()) { keys.add(stripOrdering(altKey.getProperties())); } return keys; }
1,111,060
public void insertUpdate( DocumentEvent ev ) { Document changedDoc = ev.getDocument(); String changedField = null; Object newValue = null; if ( changedDoc == photographerDoc ) { changedField = PhotoInfoController.PHOTOGRAPHER; newValue = photographerField.getText(); System.err.println( "New photographer: " + newValue ); } else if ( changedDoc == shootingDayDoc ) { changedField = PhotoInfoController.SHOOTING_DATE; newValue = shootingDayField.getValue(); } else if ( changedDoc == shootingPlaceDoc ) { changedField = PhotoInfoController.SHOOTING_PLACE; newValue = shootingPlaceField.getText(); } else { System.err.println( "insertUpdate from unknown event!!!" ); } ctrl.setField( changedField, newValue ); }
public void insertUpdate( DocumentEvent ev ) { Document changedDoc = ev.getDocument(); String changedField = null; Object newValue = null; if ( changedDoc == photographerDoc ) { changedField = PhotoInfoController.PHOTOGRAPHER; newValue = photographerField.getText(); System.err.println( "New photographer: " + newValue ); } else if ( changedDoc == shootingDayDoc ) { changedField = PhotoInfoController.SHOOTING_DATE; newValue = shootingDayField.getValue(); } else if ( changedDoc == shootingPlaceDoc ) { changedField = PhotoInfoController.SHOOTING_PLACE; newValue = shootingPlaceField.getText(); } else { System.err.println( "insertUpdate from unknown event!!!" ); } ctrl.viewChanged( this, changedField, newValue ); }
1,111,066
public void format(OutputStream nout, List<ProfileResult> profileResult, ProfileManager pm) throws Exception { PrintWriter out = new PrintWriter(nout); // Print a header out.println(CSVExport.toString(Arrays.asList(ProfileColumn.values()))); DateFormat dateFormat = (DateFormat) new DateRendererFactory().getFormat(); DecimalFormat decFormat = (DecimalFormat) new DecimalRendererFactory().getFormat(); // Now print column profile for ( ProfileResult result : profileResult ) { if ( !(result instanceof ColumnProfileResult) ) continue; SQLColumn c = (SQLColumn) result.getProfiledObject(); SQLTable t = c.getParentTable(); TableProfileResult tpr = (TableProfileResult) pm.getResult(t); List<Object> commonData = new ArrayList<Object>(); commonData.add(t.getParentDatabase().getName()); commonData.add(t.getName()); commonData.add(t.getCatalog() != null ? t.getCatalog().getName() : ""); commonData.add(t.getSchema() != null ? t.getSchema().getName() : ""); commonData.add(c.getName()); Date date = new Date(tpr.getCreateStartTime()); commonData.add(dateFormat.format(date)); commonData.add(tpr.getRowCount()); commonData.add(c.getType()); ColumnProfileResult cpr = (ColumnProfileResult) pm.getResult(c); commonData.add(cpr.getNullCount()); commonData.add(cpr.getValueCount()); commonData.add(cpr.getMinLength()); commonData.add(cpr.getMaxLength()); commonData.add(decFormat.format(cpr.getAvgLength())); commonData.add(cpr.getMinValue()); commonData.add(cpr.getMaxValue()); commonData.add(cpr.getAvgValue()); out.println(CSVExport.toString(commonData)); } out.close(); }
public void format(OutputStream nout, List<ProfileResult> profileResult, ProfileManager pm) throws Exception { PrintWriter out = new PrintWriter(nout); // Print a header ProfileColumn[] columns = ProfileColumn.values(); out.println(CSVExport.toString(Arrays.asList(columns))); DateFormat dateFormat = (DateFormat) new DateRendererFactory().getFormat(); DecimalFormat decFormat = (DecimalFormat) new DecimalRendererFactory().getFormat(); // Now print column profile for ( ProfileResult result : profileResult ) { if ( !(result instanceof ColumnProfileResult) ) continue; SQLColumn c = (SQLColumn) result.getProfiledObject(); SQLTable t = c.getParentTable(); TableProfileResult tpr = (TableProfileResult) pm.getResult(t); List<Object> commonData = new ArrayList<Object>(); commonData.add(t.getParentDatabase().getName()); commonData.add(t.getName()); commonData.add(t.getCatalog() != null ? t.getCatalog().getName() : ""); commonData.add(t.getSchema() != null ? t.getSchema().getName() : ""); commonData.add(c.getName()); Date date = new Date(tpr.getCreateStartTime()); commonData.add(dateFormat.format(date)); commonData.add(tpr.getRowCount()); commonData.add(c.getType()); ColumnProfileResult cpr = (ColumnProfileResult) pm.getResult(c); commonData.add(cpr.getNullCount()); commonData.add(cpr.getValueCount()); commonData.add(cpr.getMinLength()); commonData.add(cpr.getMaxLength()); commonData.add(decFormat.format(cpr.getAvgLength())); commonData.add(cpr.getMinValue()); commonData.add(cpr.getMaxValue()); commonData.add(cpr.getAvgValue()); out.println(CSVExport.toString(commonData)); } out.close(); }
1,111,069
public void format(OutputStream nout, List<ProfileResult> profileResult, ProfileManager pm) throws Exception { PrintWriter out = new PrintWriter(nout); // Print a header out.println(CSVExport.toString(Arrays.asList(ProfileColumn.values()))); DateFormat dateFormat = (DateFormat) new DateRendererFactory().getFormat(); DecimalFormat decFormat = (DecimalFormat) new DecimalRendererFactory().getFormat(); // Now print column profile for ( ProfileResult result : profileResult ) { if ( !(result instanceof ColumnProfileResult) ) continue; SQLColumn c = (SQLColumn) result.getProfiledObject(); SQLTable t = c.getParentTable(); TableProfileResult tpr = (TableProfileResult) pm.getResult(t); List<Object> commonData = new ArrayList<Object>(); commonData.add(t.getParentDatabase().getName()); commonData.add(t.getName()); commonData.add(t.getCatalog() != null ? t.getCatalog().getName() : ""); commonData.add(t.getSchema() != null ? t.getSchema().getName() : ""); commonData.add(c.getName()); Date date = new Date(tpr.getCreateStartTime()); commonData.add(dateFormat.format(date)); commonData.add(tpr.getRowCount()); commonData.add(c.getType()); ColumnProfileResult cpr = (ColumnProfileResult) pm.getResult(c); commonData.add(cpr.getNullCount()); commonData.add(cpr.getValueCount()); commonData.add(cpr.getMinLength()); commonData.add(cpr.getMaxLength()); commonData.add(decFormat.format(cpr.getAvgLength())); commonData.add(cpr.getMinValue()); commonData.add(cpr.getMaxValue()); commonData.add(cpr.getAvgValue()); out.println(CSVExport.toString(commonData)); } out.close(); }
public void format(OutputStream nout, List<ProfileResult> profileResult, ProfileManager pm) throws Exception { PrintWriter out = new PrintWriter(nout); // Print a header out.println(CSVExport.toString(Arrays.asList(ProfileColumn.values()))); DateFormat dateFormat = (DateFormat) new DateRendererFactory().getFormat(); DecimalFormat decFormat = (DecimalFormat) new DecimalRendererFactory().getFormat(); // Now print column profile for ( ProfileResult result : profileResult ) { if ( !(result instanceof ColumnProfileResult) ) continue; SQLColumn c = (SQLColumn) result.getProfiledObject(); SQLTable t = c.getParentTable(); TableProfileResult tpr = (TableProfileResult) pm.getResult(t); List<Object> commonData = new ArrayList<Object>(); commonData.add(t.getParentDatabase().getName()); commonData.add(t.getName()); commonData.add(t.getCatalog() != null ? t.getCatalog().getName() : ""); commonData.add(t.getSchema() != null ? t.getSchema().getName() : ""); commonData.add(c.getName()); Date date = new Date(tpr.getCreateStartTime()); commonData.add(dateFormat.format(date)); commonData.add(tpr.getRowCount()); commonData.add(c.getType()); ColumnProfileResult cpr = (ColumnProfileResult) pm.getResult(c); commonData.add(cpr.getNullCount()); commonData.add(cpr.getValueCount()); commonData.add(cpr.getMinLength()); commonData.add(cpr.getMaxLength()); commonData.add(decFormat.format(cpr.getAvgLength())); commonData.add(cpr.getMinValue()); commonData.add(cpr.getMaxValue()); commonData.add(cpr.getAvgValue()); out.println(CSVExport.toString(commonData)); } out.close(); }
1,111,071
public void testIdentityAndRangeMatch() throws Exception { // These tests are not as exhaustive, as I don't expect the combination // of identity and ranges to interfere with each other. StorableIndex<StorableTestBasic> index; Filter<StorableTestBasic> filter; FilterValues<StorableTestBasic> values; CompositeScore<StorableTestBasic> score; Mock<StorableTestBasic> executor; index = makeIndex(StorableTestBasic.class, "intProp", "-doubleProp", "stringProp"); filter = Filter.filterFor(StorableTestBasic.class, "intProp = ? & doubleProp > ? & doubleProp < ?"); values = filter.initialFilterValues(); filter = values.getFilter(); score = CompositeScore.evaluate(index, filter, null); executor = new Mock(index, score); executor.fetch(values.with(3).with(56.5).with(200.2)); assertEquals(3, executor.mIdentityValues[0]); assertEquals(BoundaryType.EXCLUSIVE, executor.mRangeStartBoundary); assertEquals(56.5, executor.mRangeStartValue); assertEquals(BoundaryType.EXCLUSIVE, executor.mRangeEndBoundary); assertEquals(200.2, executor.mRangeEndValue); assertTrue(executor.mReverseRange); assertFalse(executor.mReverseOrder); /////// score = CompositeScore.evaluate(index, filter, makeOrdering(StorableTestBasic.class, "doubleProp")); executor = new Mock(index, score); executor.fetch(values.with(3).with(56.5).with(200.2)); assertEquals(3, executor.mIdentityValues[0]); assertEquals(BoundaryType.EXCLUSIVE, executor.mRangeStartBoundary); assertEquals(56.5, executor.mRangeStartValue); assertEquals(BoundaryType.EXCLUSIVE, executor.mRangeEndBoundary); assertEquals(200.2, executor.mRangeEndValue); assertTrue(executor.mReverseRange); assertTrue(executor.mReverseOrder); /////// score = CompositeScore.evaluate(index, filter, makeOrdering(StorableTestBasic.class, "stringProp")); executor = new Mock(index, score); executor.fetch(values.with(3).with(56.5).with(200.2)); assertEquals(3, executor.mIdentityValues[0]); assertEquals(BoundaryType.EXCLUSIVE, executor.mRangeStartBoundary); assertEquals(56.5, executor.mRangeStartValue); assertEquals(BoundaryType.EXCLUSIVE, executor.mRangeEndBoundary); assertEquals(200.2, executor.mRangeEndValue); assertTrue(executor.mReverseRange); assertFalse(executor.mReverseOrder); /////// filter = Filter.filterFor(StorableTestBasic.class, "intProp = ? & doubleProp = ? & stringProp < ?"); values = filter.initialFilterValues(); filter = values.getFilter(); score = CompositeScore.evaluate(index, filter, makeOrdering(StorableTestBasic.class, "-stringProp")); executor = new Mock(index, score); executor.fetch(values.with(3).with(56.5).with("foo")); assertEquals(3, executor.mIdentityValues[0]); assertEquals(56.5, executor.mIdentityValues[1]); assertEquals(BoundaryType.OPEN, executor.mRangeStartBoundary); assertEquals(null, executor.mRangeStartValue); assertEquals(BoundaryType.EXCLUSIVE, executor.mRangeEndBoundary); assertEquals("foo", executor.mRangeEndValue); assertFalse(executor.mReverseRange); assertTrue(executor.mReverseOrder); assertEquals(values.getFilter(), executor.getFilter()); List<OrderedProperty<StorableTestBasic>> expectedOrdering = makeOrdering(StorableTestBasic.class, "stringProp"); assertEquals(expectedOrdering, executor.getOrdering()); }
public void testIdentityAndRangeMatch() throws Exception { // These tests are not as exhaustive, as I don't expect the combination // of identity and ranges to interfere with each other. StorableIndex<StorableTestBasic> index; Filter<StorableTestBasic> filter; FilterValues<StorableTestBasic> values; CompositeScore<StorableTestBasic> score; Mock<StorableTestBasic> executor; index = makeIndex(StorableTestBasic.class, "intProp", "-doubleProp", "stringProp"); filter = Filter.filterFor(StorableTestBasic.class, "intProp = ? & doubleProp > ? & doubleProp < ?"); values = filter.initialFilterValues(); filter = values.getFilter(); score = CompositeScore.evaluate(index, filter, null); executor = new Mock(index, score); executor.fetch(values.with(3).with(56.5).with(200.2)); assertEquals(3, executor.mIdentityValues[0]); assertEquals(BoundaryType.EXCLUSIVE, executor.mRangeStartBoundary); assertEquals(56.5, executor.mRangeStartValue); assertEquals(BoundaryType.EXCLUSIVE, executor.mRangeEndBoundary); assertEquals(200.2, executor.mRangeEndValue); assertTrue(executor.mReverseRange); assertFalse(executor.mReverseOrder); /////// score = CompositeScore.evaluate(index, filter, makeOrdering(StorableTestBasic.class, "doubleProp")); executor = new Mock(index, score); executor.fetch(values.with(3).with(56.5).with(200.2)); assertEquals(3, executor.mIdentityValues[0]); assertEquals(BoundaryType.EXCLUSIVE, executor.mRangeStartBoundary); assertEquals(56.5, executor.mRangeStartValue); assertEquals(BoundaryType.EXCLUSIVE, executor.mRangeEndBoundary); assertEquals(200.2, executor.mRangeEndValue); assertTrue(executor.mReverseRange); assertTrue(executor.mReverseOrder); /////// score = CompositeScore.evaluate(index, filter, makeOrdering(StorableTestBasic.class, "stringProp")); executor = new Mock(index, score); executor.fetch(values.with(3).with(56.5).with(200.2)); assertEquals(3, executor.mIdentityValues[0]); assertEquals(BoundaryType.EXCLUSIVE, executor.mRangeStartBoundary); assertEquals(56.5, executor.mRangeStartValue); assertEquals(BoundaryType.EXCLUSIVE, executor.mRangeEndBoundary); assertEquals(200.2, executor.mRangeEndValue); assertTrue(executor.mReverseRange); assertFalse(executor.mReverseOrder); /////// filter = Filter.filterFor(StorableTestBasic.class, "intProp = ? & doubleProp = ? & stringProp < ?"); values = filter.initialFilterValues(); filter = values.getFilter(); score = CompositeScore.evaluate(index, filter, makeOrdering(StorableTestBasic.class, "-stringProp")); executor = new Mock(index, score); executor.fetch(values.with(3).with(56.5).with("foo")); assertEquals(3, executor.mIdentityValues[0]); assertEquals(56.5, executor.mIdentityValues[1]); assertEquals(BoundaryType.OPEN, executor.mRangeStartBoundary); assertEquals(null, executor.mRangeStartValue); assertEquals(BoundaryType.EXCLUSIVE, executor.mRangeEndBoundary); assertEquals("foo", executor.mRangeEndValue); assertFalse(executor.mReverseRange); assertTrue(executor.mReverseOrder); assertEquals(values.getFilter(), executor.getFilter()); List<OrderedProperty<StorableTestBasic>> expectedOrdering = makeOrdering(StorableTestBasic.class, "-stringProp"); assertEquals(expectedOrdering, executor.getOrdering()); }
1,111,073
public void export(List<SQLTable> tablesToExport) throws SQLException, ArchitectException { logger.debug("Starting export of tables: "+tablesToExport); finished = false; hasStarted = true; Connection con = null; try { currentDB = tablesToExport; // first, set the logWriter logWriter = new LogWriter(ArchitectSession.getInstance().getUserSettings().getETLUserSettings().getString( ETLUserSettings.PROP_ETL_LOG_PATH, "")); SQLDatabase repository = new SQLDatabase(repositoryDataSource); // we // are // exporting // db // into // this con = repository.getConnection(); try { defParam = new DefaultParameters(con); } catch (PLSchemaException p) { throw new ArchitectException("couldn't load default parameters", p); } SQLDatabase target = new SQLDatabase(targetDataSource); Connection tCon = target.getConnection(); exportResultList.add(new LabelValueBean("\n Creating Power Loader Job", "\n")); sm = null; for (int tryNum = 0; tryNum < 3 && sm == null; tryNum++) { String username; if (tryNum == 1) { username = repositoryDataSource.get(ArchitectDataSource.PL_UID).toUpperCase(); } else if (tryNum == 2) { username = repositoryDataSource.get(ArchitectDataSource.PL_UID).toLowerCase(); } else { username = repositoryDataSource.get(ArchitectDataSource.PL_UID); } try { // don't need to verify passwords in client apps (as opposed // to webapps) sm = new PLSecurityManager(con, username, repositoryDataSource.get(ArchitectDataSource.PL_PWD), false); } catch (PLSecurityException se) { logger.debug("Couldn't find pl user " + username, se); } } if (sm == null) { throw new ArchitectException("Could not find login for: " + repositoryDataSource.get(ArchitectDataSource.PL_UID)); } logWriter.info("Starting creation of job <" + jobId + "> at " + new java.util.Date(System.currentTimeMillis())); logWriter.info("Connected to database: " + repositoryDataSource.toString()); maybeInsertFolder(con); PLJob job = new PLJob(jobId); insertJob(con); insertFolderDetail(con, job.getObjectType(), job.getObjectName()); // This will order the target tables so that the parent tables are // loaded // before their children DepthFirstSearch targetDFS = new DepthFirstSearch(tablesToExport); List tables = targetDFS.getFinishOrder(); if (logger.isDebugEnabled()) { StringBuffer tableOrder = new StringBuffer(); Iterator dit = tables.iterator(); while (dit.hasNext()) { tableOrder.append(((SQLTable) dit.next()).getName()).append(", "); } logger.debug("Safe load order for job is: " + tableOrder); } int outputTableNum = 1; Hashtable inputTables = new Hashtable(); Iterator targetTableIt = tables.iterator(); while (targetTableIt.hasNext()) { tableCount++; SQLTable outputTable = (SQLTable) targetTableIt.next(); // reset loop variables for each output table boolean createdOutputTableMetaData = false; int transNum = 0; int seqNum = 1; // borrowed from insertColumnMappings, not sure // if this is significant... String transName = null; String outputTableId = null; String inputTableId = null; // Iterator cols = outputTable.getColumns().iterator(); while (cols.hasNext()) { SQLColumn outputCol = (SQLColumn) cols.next(); SQLColumn inputCol = outputCol.getSourceColumn(); if (inputCol != null && !inputTables.keySet().contains(inputCol.getParentTable())) { // create transaction and input table meta data here if // we need to SQLTable inputTable = inputCol.getParentTable(); String baseTransName = PLUtils.toPLIdentifier("LOAD_" + outputTable.getName()); transNum = generateUniqueTransIdx(con, baseTransName); transName = baseTransName + "_" + transNum; logger.debug("transName: " + transName); insertTrans(con, transName, outputTable.getRemarks()); insertFolderDetail(con, "TRANSACTION", transName); insertTransExceptHandler(con, "A", transName, tCon); // error // handling // is // w.r.t. // target // database insertTransExceptHandler(con, "U", transName, tCon); // error // handling // is // w.r.t. // target // database insertTransExceptHandler(con, "D", transName, tCon); // error // handling // is // w.r.t. // target // database insertJobDetail(con, outputTableNum * 10, "TRANSACTION", transName); inputTableId = PLUtils.toPLIdentifier(inputTable.getName() + "_IN_" + transNum); logger.debug("inputTableId: " + inputTableId); insertTransTableFile(con, transName, inputTableId, inputTable, false, transNum); inputTables.put(inputTable, new PLTransaction(transName, inputTableId, transNum)); } else { // restore input/transaction variables PLTransaction plt = (PLTransaction) inputTables.get(inputCol.getParentTable()); transName = plt.getName(); inputTableId = plt.getInputTableId(); transNum = plt.getTransNum(); } if (!createdOutputTableMetaData) { // create output table meta data once logger.debug("outputTableNum: " + outputTableNum); outputTableId = PLUtils.toPLIdentifier(outputTable.getName() + "_OUT_" + outputTableNum); logger.debug("outputTableId: " + outputTableId); insertTransTableFile(con, transName, outputTableId, outputTable, true, transNum); createdOutputTableMetaData = true; } // finally, insert the mapping for this column if (inputCol != null) { // note: output proc seq num appears to be meaningless // based on what the Power Loader // does after you view generated transaction in the VB // Front end. insertTransColMap(con, transName, outputTableId, outputCol, inputTableId, seqNum * 10); } seqNum++; } outputTableNum++; // moved out of inner loop } } finally { hasStarted = false; finished = true; currentDB = null; // close and flush the logWriter (and set the reference to null) logWriter.flush(); logWriter.close(); logWriter = null; try { if (con != null) con.close(); } catch (SQLException e) { logger.error("Couldn't close connection", e); } } }
public void export(List<SQLTable> tablesToExport) throws SQLException, ArchitectException { logger.debug("Starting export of tables: "+tablesToExport); finished = false; hasStarted = true; Connection con = null; Connection tCon = null; try { currentDB = tablesToExport; // first, set the logWriter logWriter = new LogWriter(ArchitectSession.getInstance().getUserSettings().getETLUserSettings().getString( ETLUserSettings.PROP_ETL_LOG_PATH, "")); SQLDatabase repository = new SQLDatabase(repositoryDataSource); // we // are // exporting // db // into // this con = repository.getConnection(); try { defParam = new DefaultParameters(con); } catch (PLSchemaException p) { throw new ArchitectException("couldn't load default parameters", p); } SQLDatabase target = new SQLDatabase(targetDataSource); Connection tCon = target.getConnection(); exportResultList.add(new LabelValueBean("\n Creating Power Loader Job", "\n")); sm = null; for (int tryNum = 0; tryNum < 3 && sm == null; tryNum++) { String username; if (tryNum == 1) { username = repositoryDataSource.get(ArchitectDataSource.PL_UID).toUpperCase(); } else if (tryNum == 2) { username = repositoryDataSource.get(ArchitectDataSource.PL_UID).toLowerCase(); } else { username = repositoryDataSource.get(ArchitectDataSource.PL_UID); } try { // don't need to verify passwords in client apps (as opposed // to webapps) sm = new PLSecurityManager(con, username, repositoryDataSource.get(ArchitectDataSource.PL_PWD), false); } catch (PLSecurityException se) { logger.debug("Couldn't find pl user " + username, se); } } if (sm == null) { throw new ArchitectException("Could not find login for: " + repositoryDataSource.get(ArchitectDataSource.PL_UID)); } logWriter.info("Starting creation of job <" + jobId + "> at " + new java.util.Date(System.currentTimeMillis())); logWriter.info("Connected to database: " + repositoryDataSource.toString()); maybeInsertFolder(con); PLJob job = new PLJob(jobId); insertJob(con); insertFolderDetail(con, job.getObjectType(), job.getObjectName()); // This will order the target tables so that the parent tables are // loaded // before their children DepthFirstSearch targetDFS = new DepthFirstSearch(tablesToExport); List tables = targetDFS.getFinishOrder(); if (logger.isDebugEnabled()) { StringBuffer tableOrder = new StringBuffer(); Iterator dit = tables.iterator(); while (dit.hasNext()) { tableOrder.append(((SQLTable) dit.next()).getName()).append(", "); } logger.debug("Safe load order for job is: " + tableOrder); } int outputTableNum = 1; Hashtable inputTables = new Hashtable(); Iterator targetTableIt = tables.iterator(); while (targetTableIt.hasNext()) { tableCount++; SQLTable outputTable = (SQLTable) targetTableIt.next(); // reset loop variables for each output table boolean createdOutputTableMetaData = false; int transNum = 0; int seqNum = 1; // borrowed from insertColumnMappings, not sure // if this is significant... String transName = null; String outputTableId = null; String inputTableId = null; // Iterator cols = outputTable.getColumns().iterator(); while (cols.hasNext()) { SQLColumn outputCol = (SQLColumn) cols.next(); SQLColumn inputCol = outputCol.getSourceColumn(); if (inputCol != null && !inputTables.keySet().contains(inputCol.getParentTable())) { // create transaction and input table meta data here if // we need to SQLTable inputTable = inputCol.getParentTable(); String baseTransName = PLUtils.toPLIdentifier("LOAD_" + outputTable.getName()); transNum = generateUniqueTransIdx(con, baseTransName); transName = baseTransName + "_" + transNum; logger.debug("transName: " + transName); insertTrans(con, transName, outputTable.getRemarks()); insertFolderDetail(con, "TRANSACTION", transName); insertTransExceptHandler(con, "A", transName, tCon); // error // handling // is // w.r.t. // target // database insertTransExceptHandler(con, "U", transName, tCon); // error // handling // is // w.r.t. // target // database insertTransExceptHandler(con, "D", transName, tCon); // error // handling // is // w.r.t. // target // database insertJobDetail(con, outputTableNum * 10, "TRANSACTION", transName); inputTableId = PLUtils.toPLIdentifier(inputTable.getName() + "_IN_" + transNum); logger.debug("inputTableId: " + inputTableId); insertTransTableFile(con, transName, inputTableId, inputTable, false, transNum); inputTables.put(inputTable, new PLTransaction(transName, inputTableId, transNum)); } else { // restore input/transaction variables PLTransaction plt = (PLTransaction) inputTables.get(inputCol.getParentTable()); transName = plt.getName(); inputTableId = plt.getInputTableId(); transNum = plt.getTransNum(); } if (!createdOutputTableMetaData) { // create output table meta data once logger.debug("outputTableNum: " + outputTableNum); outputTableId = PLUtils.toPLIdentifier(outputTable.getName() + "_OUT_" + outputTableNum); logger.debug("outputTableId: " + outputTableId); insertTransTableFile(con, transName, outputTableId, outputTable, true, transNum); createdOutputTableMetaData = true; } // finally, insert the mapping for this column if (inputCol != null) { // note: output proc seq num appears to be meaningless // based on what the Power Loader // does after you view generated transaction in the VB // Front end. insertTransColMap(con, transName, outputTableId, outputCol, inputTableId, seqNum * 10); } seqNum++; } outputTableNum++; // moved out of inner loop } } finally { hasStarted = false; finished = true; currentDB = null; // close and flush the logWriter (and set the reference to null) logWriter.flush(); logWriter.close(); logWriter = null; try { if (con != null) con.close(); } catch (SQLException e) { logger.error("Couldn't close connection", e); } } }
1,111,074
public void export(List<SQLTable> tablesToExport) throws SQLException, ArchitectException { logger.debug("Starting export of tables: "+tablesToExport); finished = false; hasStarted = true; Connection con = null; try { currentDB = tablesToExport; // first, set the logWriter logWriter = new LogWriter(ArchitectSession.getInstance().getUserSettings().getETLUserSettings().getString( ETLUserSettings.PROP_ETL_LOG_PATH, "")); SQLDatabase repository = new SQLDatabase(repositoryDataSource); // we // are // exporting // db // into // this con = repository.getConnection(); try { defParam = new DefaultParameters(con); } catch (PLSchemaException p) { throw new ArchitectException("couldn't load default parameters", p); } SQLDatabase target = new SQLDatabase(targetDataSource); Connection tCon = target.getConnection(); exportResultList.add(new LabelValueBean("\n Creating Power Loader Job", "\n")); sm = null; for (int tryNum = 0; tryNum < 3 && sm == null; tryNum++) { String username; if (tryNum == 1) { username = repositoryDataSource.get(ArchitectDataSource.PL_UID).toUpperCase(); } else if (tryNum == 2) { username = repositoryDataSource.get(ArchitectDataSource.PL_UID).toLowerCase(); } else { username = repositoryDataSource.get(ArchitectDataSource.PL_UID); } try { // don't need to verify passwords in client apps (as opposed // to webapps) sm = new PLSecurityManager(con, username, repositoryDataSource.get(ArchitectDataSource.PL_PWD), false); } catch (PLSecurityException se) { logger.debug("Couldn't find pl user " + username, se); } } if (sm == null) { throw new ArchitectException("Could not find login for: " + repositoryDataSource.get(ArchitectDataSource.PL_UID)); } logWriter.info("Starting creation of job <" + jobId + "> at " + new java.util.Date(System.currentTimeMillis())); logWriter.info("Connected to database: " + repositoryDataSource.toString()); maybeInsertFolder(con); PLJob job = new PLJob(jobId); insertJob(con); insertFolderDetail(con, job.getObjectType(), job.getObjectName()); // This will order the target tables so that the parent tables are // loaded // before their children DepthFirstSearch targetDFS = new DepthFirstSearch(tablesToExport); List tables = targetDFS.getFinishOrder(); if (logger.isDebugEnabled()) { StringBuffer tableOrder = new StringBuffer(); Iterator dit = tables.iterator(); while (dit.hasNext()) { tableOrder.append(((SQLTable) dit.next()).getName()).append(", "); } logger.debug("Safe load order for job is: " + tableOrder); } int outputTableNum = 1; Hashtable inputTables = new Hashtable(); Iterator targetTableIt = tables.iterator(); while (targetTableIt.hasNext()) { tableCount++; SQLTable outputTable = (SQLTable) targetTableIt.next(); // reset loop variables for each output table boolean createdOutputTableMetaData = false; int transNum = 0; int seqNum = 1; // borrowed from insertColumnMappings, not sure // if this is significant... String transName = null; String outputTableId = null; String inputTableId = null; // Iterator cols = outputTable.getColumns().iterator(); while (cols.hasNext()) { SQLColumn outputCol = (SQLColumn) cols.next(); SQLColumn inputCol = outputCol.getSourceColumn(); if (inputCol != null && !inputTables.keySet().contains(inputCol.getParentTable())) { // create transaction and input table meta data here if // we need to SQLTable inputTable = inputCol.getParentTable(); String baseTransName = PLUtils.toPLIdentifier("LOAD_" + outputTable.getName()); transNum = generateUniqueTransIdx(con, baseTransName); transName = baseTransName + "_" + transNum; logger.debug("transName: " + transName); insertTrans(con, transName, outputTable.getRemarks()); insertFolderDetail(con, "TRANSACTION", transName); insertTransExceptHandler(con, "A", transName, tCon); // error // handling // is // w.r.t. // target // database insertTransExceptHandler(con, "U", transName, tCon); // error // handling // is // w.r.t. // target // database insertTransExceptHandler(con, "D", transName, tCon); // error // handling // is // w.r.t. // target // database insertJobDetail(con, outputTableNum * 10, "TRANSACTION", transName); inputTableId = PLUtils.toPLIdentifier(inputTable.getName() + "_IN_" + transNum); logger.debug("inputTableId: " + inputTableId); insertTransTableFile(con, transName, inputTableId, inputTable, false, transNum); inputTables.put(inputTable, new PLTransaction(transName, inputTableId, transNum)); } else { // restore input/transaction variables PLTransaction plt = (PLTransaction) inputTables.get(inputCol.getParentTable()); transName = plt.getName(); inputTableId = plt.getInputTableId(); transNum = plt.getTransNum(); } if (!createdOutputTableMetaData) { // create output table meta data once logger.debug("outputTableNum: " + outputTableNum); outputTableId = PLUtils.toPLIdentifier(outputTable.getName() + "_OUT_" + outputTableNum); logger.debug("outputTableId: " + outputTableId); insertTransTableFile(con, transName, outputTableId, outputTable, true, transNum); createdOutputTableMetaData = true; } // finally, insert the mapping for this column if (inputCol != null) { // note: output proc seq num appears to be meaningless // based on what the Power Loader // does after you view generated transaction in the VB // Front end. insertTransColMap(con, transName, outputTableId, outputCol, inputTableId, seqNum * 10); } seqNum++; } outputTableNum++; // moved out of inner loop } } finally { hasStarted = false; finished = true; currentDB = null; // close and flush the logWriter (and set the reference to null) logWriter.flush(); logWriter.close(); logWriter = null; try { if (con != null) con.close(); } catch (SQLException e) { logger.error("Couldn't close connection", e); } } }
public void export(List<SQLTable> tablesToExport) throws SQLException, ArchitectException { logger.debug("Starting export of tables: "+tablesToExport); finished = false; hasStarted = true; Connection con = null; try { currentDB = tablesToExport; // first, set the logWriter logWriter = new LogWriter(ArchitectSession.getInstance().getUserSettings().getETLUserSettings().getString( ETLUserSettings.PROP_ETL_LOG_PATH, "")); SQLDatabase repository = new SQLDatabase(repositoryDataSource); // we // are // exporting // db // into // this con = repository.getConnection(); try { defParam = new DefaultParameters(con); } catch (PLSchemaException p) { throw new ArchitectException("couldn't load default parameters", p); } SQLDatabase target = new SQLDatabase(targetDataSource); tCon = target.getConnection(); exportResultList.add(new LabelValueBean("\n Creating Power Loader Job", "\n")); sm = null; for (int tryNum = 0; tryNum < 3 && sm == null; tryNum++) { String username; if (tryNum == 1) { username = repositoryDataSource.get(ArchitectDataSource.PL_UID).toUpperCase(); } else if (tryNum == 2) { username = repositoryDataSource.get(ArchitectDataSource.PL_UID).toLowerCase(); } else { username = repositoryDataSource.get(ArchitectDataSource.PL_UID); } try { // don't need to verify passwords in client apps (as opposed // to webapps) sm = new PLSecurityManager(con, username, repositoryDataSource.get(ArchitectDataSource.PL_PWD), false); } catch (PLSecurityException se) { logger.debug("Couldn't find pl user " + username, se); } } if (sm == null) { throw new ArchitectException("Could not find login for: " + repositoryDataSource.get(ArchitectDataSource.PL_UID)); } logWriter.info("Starting creation of job <" + jobId + "> at " + new java.util.Date(System.currentTimeMillis())); logWriter.info("Connected to database: " + repositoryDataSource.toString()); maybeInsertFolder(con); PLJob job = new PLJob(jobId); insertJob(con); insertFolderDetail(con, job.getObjectType(), job.getObjectName()); // This will order the target tables so that the parent tables are // loaded // before their children DepthFirstSearch targetDFS = new DepthFirstSearch(tablesToExport); List tables = targetDFS.getFinishOrder(); if (logger.isDebugEnabled()) { StringBuffer tableOrder = new StringBuffer(); Iterator dit = tables.iterator(); while (dit.hasNext()) { tableOrder.append(((SQLTable) dit.next()).getName()).append(", "); } logger.debug("Safe load order for job is: " + tableOrder); } int outputTableNum = 1; Hashtable inputTables = new Hashtable(); Iterator targetTableIt = tables.iterator(); while (targetTableIt.hasNext()) { tableCount++; SQLTable outputTable = (SQLTable) targetTableIt.next(); // reset loop variables for each output table boolean createdOutputTableMetaData = false; int transNum = 0; int seqNum = 1; // borrowed from insertColumnMappings, not sure // if this is significant... String transName = null; String outputTableId = null; String inputTableId = null; // Iterator cols = outputTable.getColumns().iterator(); while (cols.hasNext()) { SQLColumn outputCol = (SQLColumn) cols.next(); SQLColumn inputCol = outputCol.getSourceColumn(); if (inputCol != null && !inputTables.keySet().contains(inputCol.getParentTable())) { // create transaction and input table meta data here if // we need to SQLTable inputTable = inputCol.getParentTable(); String baseTransName = PLUtils.toPLIdentifier("LOAD_" + outputTable.getName()); transNum = generateUniqueTransIdx(con, baseTransName); transName = baseTransName + "_" + transNum; logger.debug("transName: " + transName); insertTrans(con, transName, outputTable.getRemarks()); insertFolderDetail(con, "TRANSACTION", transName); insertTransExceptHandler(con, "A", transName, tCon); // error // handling // is // w.r.t. // target // database insertTransExceptHandler(con, "U", transName, tCon); // error // handling // is // w.r.t. // target // database insertTransExceptHandler(con, "D", transName, tCon); // error // handling // is // w.r.t. // target // database insertJobDetail(con, outputTableNum * 10, "TRANSACTION", transName); inputTableId = PLUtils.toPLIdentifier(inputTable.getName() + "_IN_" + transNum); logger.debug("inputTableId: " + inputTableId); insertTransTableFile(con, transName, inputTableId, inputTable, false, transNum); inputTables.put(inputTable, new PLTransaction(transName, inputTableId, transNum)); } else { // restore input/transaction variables PLTransaction plt = (PLTransaction) inputTables.get(inputCol.getParentTable()); transName = plt.getName(); inputTableId = plt.getInputTableId(); transNum = plt.getTransNum(); } if (!createdOutputTableMetaData) { // create output table meta data once logger.debug("outputTableNum: " + outputTableNum); outputTableId = PLUtils.toPLIdentifier(outputTable.getName() + "_OUT_" + outputTableNum); logger.debug("outputTableId: " + outputTableId); insertTransTableFile(con, transName, outputTableId, outputTable, true, transNum); createdOutputTableMetaData = true; } // finally, insert the mapping for this column if (inputCol != null) { // note: output proc seq num appears to be meaningless // based on what the Power Loader // does after you view generated transaction in the VB // Front end. insertTransColMap(con, transName, outputTableId, outputCol, inputTableId, seqNum * 10); } seqNum++; } outputTableNum++; // moved out of inner loop } } finally { hasStarted = false; finished = true; currentDB = null; // close and flush the logWriter (and set the reference to null) logWriter.flush(); logWriter.close(); logWriter = null; try { if (con != null) con.close(); } catch (SQLException e) { logger.error("Couldn't close connection", e); } } }
1,111,075
public void export(List<SQLTable> tablesToExport) throws SQLException, ArchitectException { logger.debug("Starting export of tables: "+tablesToExport); finished = false; hasStarted = true; Connection con = null; try { currentDB = tablesToExport; // first, set the logWriter logWriter = new LogWriter(ArchitectSession.getInstance().getUserSettings().getETLUserSettings().getString( ETLUserSettings.PROP_ETL_LOG_PATH, "")); SQLDatabase repository = new SQLDatabase(repositoryDataSource); // we // are // exporting // db // into // this con = repository.getConnection(); try { defParam = new DefaultParameters(con); } catch (PLSchemaException p) { throw new ArchitectException("couldn't load default parameters", p); } SQLDatabase target = new SQLDatabase(targetDataSource); Connection tCon = target.getConnection(); exportResultList.add(new LabelValueBean("\n Creating Power Loader Job", "\n")); sm = null; for (int tryNum = 0; tryNum < 3 && sm == null; tryNum++) { String username; if (tryNum == 1) { username = repositoryDataSource.get(ArchitectDataSource.PL_UID).toUpperCase(); } else if (tryNum == 2) { username = repositoryDataSource.get(ArchitectDataSource.PL_UID).toLowerCase(); } else { username = repositoryDataSource.get(ArchitectDataSource.PL_UID); } try { // don't need to verify passwords in client apps (as opposed // to webapps) sm = new PLSecurityManager(con, username, repositoryDataSource.get(ArchitectDataSource.PL_PWD), false); } catch (PLSecurityException se) { logger.debug("Couldn't find pl user " + username, se); } } if (sm == null) { throw new ArchitectException("Could not find login for: " + repositoryDataSource.get(ArchitectDataSource.PL_UID)); } logWriter.info("Starting creation of job <" + jobId + "> at " + new java.util.Date(System.currentTimeMillis())); logWriter.info("Connected to database: " + repositoryDataSource.toString()); maybeInsertFolder(con); PLJob job = new PLJob(jobId); insertJob(con); insertFolderDetail(con, job.getObjectType(), job.getObjectName()); // This will order the target tables so that the parent tables are // loaded // before their children DepthFirstSearch targetDFS = new DepthFirstSearch(tablesToExport); List tables = targetDFS.getFinishOrder(); if (logger.isDebugEnabled()) { StringBuffer tableOrder = new StringBuffer(); Iterator dit = tables.iterator(); while (dit.hasNext()) { tableOrder.append(((SQLTable) dit.next()).getName()).append(", "); } logger.debug("Safe load order for job is: " + tableOrder); } int outputTableNum = 1; Hashtable inputTables = new Hashtable(); Iterator targetTableIt = tables.iterator(); while (targetTableIt.hasNext()) { tableCount++; SQLTable outputTable = (SQLTable) targetTableIt.next(); // reset loop variables for each output table boolean createdOutputTableMetaData = false; int transNum = 0; int seqNum = 1; // borrowed from insertColumnMappings, not sure // if this is significant... String transName = null; String outputTableId = null; String inputTableId = null; // Iterator cols = outputTable.getColumns().iterator(); while (cols.hasNext()) { SQLColumn outputCol = (SQLColumn) cols.next(); SQLColumn inputCol = outputCol.getSourceColumn(); if (inputCol != null && !inputTables.keySet().contains(inputCol.getParentTable())) { // create transaction and input table meta data here if // we need to SQLTable inputTable = inputCol.getParentTable(); String baseTransName = PLUtils.toPLIdentifier("LOAD_" + outputTable.getName()); transNum = generateUniqueTransIdx(con, baseTransName); transName = baseTransName + "_" + transNum; logger.debug("transName: " + transName); insertTrans(con, transName, outputTable.getRemarks()); insertFolderDetail(con, "TRANSACTION", transName); insertTransExceptHandler(con, "A", transName, tCon); // error // handling // is // w.r.t. // target // database insertTransExceptHandler(con, "U", transName, tCon); // error // handling // is // w.r.t. // target // database insertTransExceptHandler(con, "D", transName, tCon); // error // handling // is // w.r.t. // target // database insertJobDetail(con, outputTableNum * 10, "TRANSACTION", transName); inputTableId = PLUtils.toPLIdentifier(inputTable.getName() + "_IN_" + transNum); logger.debug("inputTableId: " + inputTableId); insertTransTableFile(con, transName, inputTableId, inputTable, false, transNum); inputTables.put(inputTable, new PLTransaction(transName, inputTableId, transNum)); } else { // restore input/transaction variables PLTransaction plt = (PLTransaction) inputTables.get(inputCol.getParentTable()); transName = plt.getName(); inputTableId = plt.getInputTableId(); transNum = plt.getTransNum(); } if (!createdOutputTableMetaData) { // create output table meta data once logger.debug("outputTableNum: " + outputTableNum); outputTableId = PLUtils.toPLIdentifier(outputTable.getName() + "_OUT_" + outputTableNum); logger.debug("outputTableId: " + outputTableId); insertTransTableFile(con, transName, outputTableId, outputTable, true, transNum); createdOutputTableMetaData = true; } // finally, insert the mapping for this column if (inputCol != null) { // note: output proc seq num appears to be meaningless // based on what the Power Loader // does after you view generated transaction in the VB // Front end. insertTransColMap(con, transName, outputTableId, outputCol, inputTableId, seqNum * 10); } seqNum++; } outputTableNum++; // moved out of inner loop } } finally { hasStarted = false; finished = true; currentDB = null; // close and flush the logWriter (and set the reference to null) logWriter.flush(); logWriter.close(); logWriter = null; try { if (con != null) con.close(); } catch (SQLException e) { logger.error("Couldn't close connection", e); } } }
public void export(List<SQLTable> tablesToExport) throws SQLException, ArchitectException { logger.debug("Starting export of tables: "+tablesToExport); finished = false; hasStarted = true; Connection con = null; try { currentDB = tablesToExport; // first, set the logWriter logWriter = new LogWriter(ArchitectSession.getInstance().getUserSettings().getETLUserSettings().getString( ETLUserSettings.PROP_ETL_LOG_PATH, "")); SQLDatabase repository = new SQLDatabase(repositoryDataSource); // we // are // exporting // db // into // this con = repository.getConnection(); try { defParam = new DefaultParameters(con); } catch (PLSchemaException p) { throw new ArchitectException("couldn't load default parameters", p); } SQLDatabase target = new SQLDatabase(targetDataSource); Connection tCon = target.getConnection(); exportResultList.add(new LabelValueBean("\n Creating Power Loader Job", "\n")); sm = null; for (int tryNum = 0; tryNum < 3 && sm == null; tryNum++) { String username; if (tryNum == 1) { username = repositoryDataSource.get(ArchitectDataSource.PL_UID).toUpperCase(); } else if (tryNum == 2) { username = repositoryDataSource.get(ArchitectDataSource.PL_UID).toLowerCase(); } else { username = repositoryDataSource.get(ArchitectDataSource.PL_UID); } try { // don't need to verify passwords in client apps (as opposed // to webapps) sm = new PLSecurityManager(con, username, repositoryDataSource.get(ArchitectDataSource.PL_PWD), false); } catch (PLSecurityException se) { logger.debug("Couldn't find pl user " + username, se); } } if (sm == null) { throw new ArchitectException("Could not find login for: " + repositoryDataSource.get(ArchitectDataSource.PL_UID)); } logWriter.info("Starting creation of job <" + jobId + "> at " + new java.util.Date(System.currentTimeMillis())); logWriter.info("Connected to database: " + repositoryDataSource.toString()); maybeInsertFolder(con); PLJob job = new PLJob(jobId); insertJob(con); insertFolderDetail(con, job.getObjectType(), job.getObjectName()); // This will order the target tables so that the parent tables are // loaded // before their children DepthFirstSearch targetDFS = new DepthFirstSearch(tablesToExport); List tables = targetDFS.getFinishOrder(); if (logger.isDebugEnabled()) { StringBuffer tableOrder = new StringBuffer(); Iterator dit = tables.iterator(); while (dit.hasNext()) { tableOrder.append(((SQLTable) dit.next()).getName()).append(", "); } logger.debug("Safe load order for job is: " + tableOrder); } int outputTableNum = 1; Hashtable inputTables = new Hashtable(); Iterator targetTableIt = tables.iterator(); while (targetTableIt.hasNext()) { tableCount++; SQLTable outputTable = (SQLTable) targetTableIt.next(); // reset loop variables for each output table boolean createdOutputTableMetaData = false; int transNum = 0; int seqNum = 1; // borrowed from insertColumnMappings, not sure // if this is significant... String transName = null; String outputTableId = null; String inputTableId = null; // Iterator cols = outputTable.getColumns().iterator(); while (cols.hasNext()) { SQLColumn outputCol = (SQLColumn) cols.next(); SQLColumn inputCol = outputCol.getSourceColumn(); if (inputCol != null && !inputTables.keySet().contains(inputCol.getParentTable())) { // create transaction and input table meta data here if // we need to SQLTable inputTable = inputCol.getParentTable(); String baseTransName = PLUtils.toPLIdentifier("LOAD_" + outputTable.getName()); transNum = generateUniqueTransIdx(con, baseTransName); transName = baseTransName + "_" + transNum; logger.debug("transName: " + transName); insertTrans(con, transName, outputTable.getRemarks()); insertFolderDetail(con, "TRANSACTION", transName); insertTransExceptHandler(con, "A", transName, tCon); // error // handling // is // w.r.t. // target // database insertTransExceptHandler(con, "U", transName, tCon); // error // handling // is // w.r.t. // target // database insertTransExceptHandler(con, "D", transName, tCon); // error // handling // is // w.r.t. // target // database insertJobDetail(con, outputTableNum * 10, "TRANSACTION", transName); inputTableId = PLUtils.toPLIdentifier(inputTable.getName() + "_IN_" + transNum); logger.debug("inputTableId: " + inputTableId); insertTransTableFile(con, transName, inputTableId, inputTable, false, transNum); inputTables.put(inputTable, new PLTransaction(transName, inputTableId, transNum)); } else { // restore input/transaction variables PLTransaction plt = (PLTransaction) inputTables.get(inputCol.getParentTable()); transName = plt.getName(); inputTableId = plt.getInputTableId(); transNum = plt.getTransNum(); } if (!createdOutputTableMetaData) { // create output table meta data once logger.debug("outputTableNum: " + outputTableNum); outputTableId = PLUtils.toPLIdentifier(outputTable.getName() + "_OUT_" + outputTableNum); logger.debug("outputTableId: " + outputTableId); insertTransTableFile(con, transName, outputTableId, outputTable, true, transNum); createdOutputTableMetaData = true; } // finally, insert the mapping for this column if (inputCol != null) { // note: output proc seq num appears to be meaningless // based on what the Power Loader // does after you view generated transaction in the VB // Front end. insertTransColMap(con, transName, outputTableId, outputCol, inputTableId, seqNum * 10); } seqNum++; } outputTableNum++; // moved out of inner loop } } finally { hasStarted = false; finished = true; currentDB = null; // close and flush the logWriter (and set the reference to null) logWriter.flush(); logWriter.close(); logWriter = null; try { if (con != null) con.close(); } catch (SQLException e) { logger.error("Couldn't close connection", e); } } }
1,111,076
public void export(List<SQLTable> tablesToExport) throws SQLException, ArchitectException { logger.debug("Starting export of tables: "+tablesToExport); finished = false; hasStarted = true; Connection con = null; try { currentDB = tablesToExport; // first, set the logWriter logWriter = new LogWriter(ArchitectSession.getInstance().getUserSettings().getETLUserSettings().getString( ETLUserSettings.PROP_ETL_LOG_PATH, "")); SQLDatabase repository = new SQLDatabase(repositoryDataSource); // we // are // exporting // db // into // this con = repository.getConnection(); try { defParam = new DefaultParameters(con); } catch (PLSchemaException p) { throw new ArchitectException("couldn't load default parameters", p); } SQLDatabase target = new SQLDatabase(targetDataSource); Connection tCon = target.getConnection(); exportResultList.add(new LabelValueBean("\n Creating Power Loader Job", "\n")); sm = null; for (int tryNum = 0; tryNum < 3 && sm == null; tryNum++) { String username; if (tryNum == 1) { username = repositoryDataSource.get(ArchitectDataSource.PL_UID).toUpperCase(); } else if (tryNum == 2) { username = repositoryDataSource.get(ArchitectDataSource.PL_UID).toLowerCase(); } else { username = repositoryDataSource.get(ArchitectDataSource.PL_UID); } try { // don't need to verify passwords in client apps (as opposed // to webapps) sm = new PLSecurityManager(con, username, repositoryDataSource.get(ArchitectDataSource.PL_PWD), false); } catch (PLSecurityException se) { logger.debug("Couldn't find pl user " + username, se); } } if (sm == null) { throw new ArchitectException("Could not find login for: " + repositoryDataSource.get(ArchitectDataSource.PL_UID)); } logWriter.info("Starting creation of job <" + jobId + "> at " + new java.util.Date(System.currentTimeMillis())); logWriter.info("Connected to database: " + repositoryDataSource.toString()); maybeInsertFolder(con); PLJob job = new PLJob(jobId); insertJob(con); insertFolderDetail(con, job.getObjectType(), job.getObjectName()); // This will order the target tables so that the parent tables are // loaded // before their children DepthFirstSearch targetDFS = new DepthFirstSearch(tablesToExport); List tables = targetDFS.getFinishOrder(); if (logger.isDebugEnabled()) { StringBuffer tableOrder = new StringBuffer(); Iterator dit = tables.iterator(); while (dit.hasNext()) { tableOrder.append(((SQLTable) dit.next()).getName()).append(", "); } logger.debug("Safe load order for job is: " + tableOrder); } int outputTableNum = 1; Hashtable inputTables = new Hashtable(); Iterator targetTableIt = tables.iterator(); while (targetTableIt.hasNext()) { tableCount++; SQLTable outputTable = (SQLTable) targetTableIt.next(); // reset loop variables for each output table boolean createdOutputTableMetaData = false; int transNum = 0; int seqNum = 1; // borrowed from insertColumnMappings, not sure // if this is significant... String transName = null; String outputTableId = null; String inputTableId = null; // Iterator cols = outputTable.getColumns().iterator(); while (cols.hasNext()) { SQLColumn outputCol = (SQLColumn) cols.next(); SQLColumn inputCol = outputCol.getSourceColumn(); if (inputCol != null && !inputTables.keySet().contains(inputCol.getParentTable())) { // create transaction and input table meta data here if // we need to SQLTable inputTable = inputCol.getParentTable(); String baseTransName = PLUtils.toPLIdentifier("LOAD_" + outputTable.getName()); transNum = generateUniqueTransIdx(con, baseTransName); transName = baseTransName + "_" + transNum; logger.debug("transName: " + transName); insertTrans(con, transName, outputTable.getRemarks()); insertFolderDetail(con, "TRANSACTION", transName); insertTransExceptHandler(con, "A", transName, tCon); // error // handling // is // w.r.t. // target // database insertTransExceptHandler(con, "U", transName, tCon); // error // handling // is // w.r.t. // target // database insertTransExceptHandler(con, "D", transName, tCon); // error // handling // is // w.r.t. // target // database insertJobDetail(con, outputTableNum * 10, "TRANSACTION", transName); inputTableId = PLUtils.toPLIdentifier(inputTable.getName() + "_IN_" + transNum); logger.debug("inputTableId: " + inputTableId); insertTransTableFile(con, transName, inputTableId, inputTable, false, transNum); inputTables.put(inputTable, new PLTransaction(transName, inputTableId, transNum)); } else { // restore input/transaction variables PLTransaction plt = (PLTransaction) inputTables.get(inputCol.getParentTable()); transName = plt.getName(); inputTableId = plt.getInputTableId(); transNum = plt.getTransNum(); } if (!createdOutputTableMetaData) { // create output table meta data once logger.debug("outputTableNum: " + outputTableNum); outputTableId = PLUtils.toPLIdentifier(outputTable.getName() + "_OUT_" + outputTableNum); logger.debug("outputTableId: " + outputTableId); insertTransTableFile(con, transName, outputTableId, outputTable, true, transNum); createdOutputTableMetaData = true; } // finally, insert the mapping for this column if (inputCol != null) { // note: output proc seq num appears to be meaningless // based on what the Power Loader // does after you view generated transaction in the VB // Front end. insertTransColMap(con, transName, outputTableId, outputCol, inputTableId, seqNum * 10); } seqNum++; } outputTableNum++; // moved out of inner loop } } finally { hasStarted = false; finished = true; currentDB = null; // close and flush the logWriter (and set the reference to null) logWriter.flush(); logWriter.close(); logWriter = null; try { if (con != null) con.close(); } catch (SQLException e) { logger.error("Couldn't close connection", e); } } }
public void export(List<SQLTable> tablesToExport) throws SQLException, ArchitectException { logger.debug("Starting export of tables: "+tablesToExport); finished = false; hasStarted = true; Connection con = null; try { currentDB = tablesToExport; // first, set the logWriter logWriter = new LogWriter(ArchitectSession.getInstance().getUserSettings().getETLUserSettings().getString( ETLUserSettings.PROP_ETL_LOG_PATH, "")); SQLDatabase repository = new SQLDatabase(repositoryDataSource); // we // are // exporting // db // into // this con = repository.getConnection(); try { defParam = new DefaultParameters(con); } catch (PLSchemaException p) { throw new ArchitectException("couldn't load default parameters", p); } SQLDatabase target = new SQLDatabase(targetDataSource); Connection tCon = target.getConnection(); exportResultList.add(new LabelValueBean("\n Creating Power Loader Job", "\n")); sm = null; for (int tryNum = 0; tryNum < 3 && sm == null; tryNum++) { String username; if (tryNum == 1) { username = repositoryDataSource.get(ArchitectDataSource.PL_UID).toUpperCase(); } else if (tryNum == 2) { username = repositoryDataSource.get(ArchitectDataSource.PL_UID).toLowerCase(); } else { username = repositoryDataSource.get(ArchitectDataSource.PL_UID); } try { // don't need to verify passwords in client apps (as opposed // to webapps) sm = new PLSecurityManager(con, username, repositoryDataSource.get(ArchitectDataSource.PL_PWD), false); } catch (PLSecurityException se) { logger.debug("Couldn't find pl user " + username, se); } } if (sm == null) { throw new ArchitectException("Could not find login for: " + repositoryDataSource.get(ArchitectDataSource.PL_UID)); } logWriter.info("Starting creation of job <" + jobId + "> at " + new java.util.Date(System.currentTimeMillis())); logWriter.info("Connected to database: " + repositoryDataSource.toString()); maybeInsertFolder(con); PLJob job = new PLJob(jobId); insertJob(con); insertFolderDetail(con, job.getObjectType(), job.getObjectName()); // This will order the target tables so that the parent tables are // loaded // before their children DepthFirstSearch targetDFS = new DepthFirstSearch(tablesToExport); List tables = targetDFS.getFinishOrder(); if (logger.isDebugEnabled()) { StringBuffer tableOrder = new StringBuffer(); Iterator dit = tables.iterator(); while (dit.hasNext()) { tableOrder.append(((SQLTable) dit.next()).getName()).append(", "); } logger.debug("Safe load order for job is: " + tableOrder); } int outputTableNum = 1; Hashtable inputTables = new Hashtable(); Iterator targetTableIt = tables.iterator(); while (targetTableIt.hasNext()) { tableCount++; SQLTable outputTable = (SQLTable) targetTableIt.next(); // reset loop variables for each output table boolean createdOutputTableMetaData = false; int transNum = 0; int seqNum = 1; // borrowed from insertColumnMappings, not sure // if this is significant... String transName = null; String outputTableId = null; String inputTableId = null; // Iterator cols = outputTable.getColumns().iterator(); while (cols.hasNext()) { SQLColumn outputCol = (SQLColumn) cols.next(); SQLColumn inputCol = outputCol.getSourceColumn(); if (inputCol != null && !inputTables.keySet().contains(inputCol.getParentTable())) { // create transaction and input table meta data here if // we need to SQLTable inputTable = inputCol.getParentTable(); String baseTransName = PLUtils.toPLIdentifier("LOAD_" + outputTable.getName()); transNum = generateUniqueTransIdx(con, baseTransName); transName = baseTransName + "_" + transNum; logger.debug("transName: " + transName); insertTrans(con, transName, outputTable.getRemarks()); insertFolderDetail(con, "TRANSACTION", transName); insertTransExceptHandler(con, "A", transName, tCon); // error // handling // is // w.r.t. // target // database insertTransExceptHandler(con, "U", transName, tCon); // error // handling // is // w.r.t. // target // database insertTransExceptHandler(con, "D", transName, tCon); // error // handling // is // w.r.t. // target // database insertJobDetail(con, outputTableNum * 10, "TRANSACTION", transName); inputTableId = PLUtils.toPLIdentifier(inputTable.getName() + "_IN_" + transNum); logger.debug("inputTableId: " + inputTableId); insertTransTableFile(con, transName, inputTableId, inputTable, false, transNum); inputTables.put(inputTable, new PLTransaction(transName, inputTableId, transNum)); } else { // restore input/transaction variables PLTransaction plt = (PLTransaction) inputTables.get(inputCol.getParentTable()); transName = plt.getName(); inputTableId = plt.getInputTableId(); transNum = plt.getTransNum(); } if (!createdOutputTableMetaData) { // create output table meta data once logger.debug("outputTableNum: " + outputTableNum); outputTableId = PLUtils.toPLIdentifier(outputTable.getName() + "_OUT_" + outputTableNum); logger.debug("outputTableId: " + outputTableId); insertTransTableFile(con, transName, outputTableId, outputTable, true, transNum); createdOutputTableMetaData = true; } // finally, insert the mapping for this column if (inputCol != null) { // note: output proc seq num appears to be meaningless // based on what the Power Loader // does after you view generated transaction in the VB // Front end. insertTransColMap(con, transName, outputTableId, outputCol, inputTableId, seqNum * 10); } seqNum++; } outputTableNum++; // moved out of inner loop } } finally { hasStarted = false; finished = true; currentDB = null; // close and flush the logWriter (and set the reference to null) logWriter.flush(); logWriter.close(); logWriter = null; try { if (con != null) con.close(); } catch (SQLException e) { logger.error("Couldn't close connection", e); } } }
1,111,077
public void export(List<SQLTable> tablesToExport) throws SQLException, ArchitectException { logger.debug("Starting export of tables: "+tablesToExport); finished = false; hasStarted = true; Connection con = null; try { currentDB = tablesToExport; // first, set the logWriter logWriter = new LogWriter(ArchitectSession.getInstance().getUserSettings().getETLUserSettings().getString( ETLUserSettings.PROP_ETL_LOG_PATH, "")); SQLDatabase repository = new SQLDatabase(repositoryDataSource); // we // are // exporting // db // into // this con = repository.getConnection(); try { defParam = new DefaultParameters(con); } catch (PLSchemaException p) { throw new ArchitectException("couldn't load default parameters", p); } SQLDatabase target = new SQLDatabase(targetDataSource); Connection tCon = target.getConnection(); exportResultList.add(new LabelValueBean("\n Creating Power Loader Job", "\n")); sm = null; for (int tryNum = 0; tryNum < 3 && sm == null; tryNum++) { String username; if (tryNum == 1) { username = repositoryDataSource.get(ArchitectDataSource.PL_UID).toUpperCase(); } else if (tryNum == 2) { username = repositoryDataSource.get(ArchitectDataSource.PL_UID).toLowerCase(); } else { username = repositoryDataSource.get(ArchitectDataSource.PL_UID); } try { // don't need to verify passwords in client apps (as opposed // to webapps) sm = new PLSecurityManager(con, username, repositoryDataSource.get(ArchitectDataSource.PL_PWD), false); } catch (PLSecurityException se) { logger.debug("Couldn't find pl user " + username, se); } } if (sm == null) { throw new ArchitectException("Could not find login for: " + repositoryDataSource.get(ArchitectDataSource.PL_UID)); } logWriter.info("Starting creation of job <" + jobId + "> at " + new java.util.Date(System.currentTimeMillis())); logWriter.info("Connected to database: " + repositoryDataSource.toString()); maybeInsertFolder(con); PLJob job = new PLJob(jobId); insertJob(con); insertFolderDetail(con, job.getObjectType(), job.getObjectName()); // This will order the target tables so that the parent tables are // loaded // before their children DepthFirstSearch targetDFS = new DepthFirstSearch(tablesToExport); List tables = targetDFS.getFinishOrder(); if (logger.isDebugEnabled()) { StringBuffer tableOrder = new StringBuffer(); Iterator dit = tables.iterator(); while (dit.hasNext()) { tableOrder.append(((SQLTable) dit.next()).getName()).append(", "); } logger.debug("Safe load order for job is: " + tableOrder); } int outputTableNum = 1; Hashtable inputTables = new Hashtable(); Iterator targetTableIt = tables.iterator(); while (targetTableIt.hasNext()) { tableCount++; SQLTable outputTable = (SQLTable) targetTableIt.next(); // reset loop variables for each output table boolean createdOutputTableMetaData = false; int transNum = 0; int seqNum = 1; // borrowed from insertColumnMappings, not sure // if this is significant... String transName = null; String outputTableId = null; String inputTableId = null; // Iterator cols = outputTable.getColumns().iterator(); while (cols.hasNext()) { SQLColumn outputCol = (SQLColumn) cols.next(); SQLColumn inputCol = outputCol.getSourceColumn(); if (inputCol != null && !inputTables.keySet().contains(inputCol.getParentTable())) { // create transaction and input table meta data here if // we need to SQLTable inputTable = inputCol.getParentTable(); String baseTransName = PLUtils.toPLIdentifier("LOAD_" + outputTable.getName()); transNum = generateUniqueTransIdx(con, baseTransName); transName = baseTransName + "_" + transNum; logger.debug("transName: " + transName); insertTrans(con, transName, outputTable.getRemarks()); insertFolderDetail(con, "TRANSACTION", transName); insertTransExceptHandler(con, "A", transName, tCon); // error // handling // is // w.r.t. // target // database insertTransExceptHandler(con, "U", transName, tCon); // error // handling // is // w.r.t. // target // database insertTransExceptHandler(con, "D", transName, tCon); // error // handling // is // w.r.t. // target // database insertJobDetail(con, outputTableNum * 10, "TRANSACTION", transName); inputTableId = PLUtils.toPLIdentifier(inputTable.getName() + "_IN_" + transNum); logger.debug("inputTableId: " + inputTableId); insertTransTableFile(con, transName, inputTableId, inputTable, false, transNum); inputTables.put(inputTable, new PLTransaction(transName, inputTableId, transNum)); } else { // restore input/transaction variables PLTransaction plt = (PLTransaction) inputTables.get(inputCol.getParentTable()); transName = plt.getName(); inputTableId = plt.getInputTableId(); transNum = plt.getTransNum(); } if (!createdOutputTableMetaData) { // create output table meta data once logger.debug("outputTableNum: " + outputTableNum); outputTableId = PLUtils.toPLIdentifier(outputTable.getName() + "_OUT_" + outputTableNum); logger.debug("outputTableId: " + outputTableId); insertTransTableFile(con, transName, outputTableId, outputTable, true, transNum); createdOutputTableMetaData = true; } // finally, insert the mapping for this column if (inputCol != null) { // note: output proc seq num appears to be meaningless // based on what the Power Loader // does after you view generated transaction in the VB // Front end. insertTransColMap(con, transName, outputTableId, outputCol, inputTableId, seqNum * 10); } seqNum++; } outputTableNum++; // moved out of inner loop } } finally { hasStarted = false; finished = true; currentDB = null; // close and flush the logWriter (and set the reference to null) logWriter.flush(); logWriter.close(); logWriter = null; try { if (con != null) con.close(); } catch (SQLException e) { logger.error("Couldn't close connection", e); } } }
public void export(List<SQLTable> tablesToExport) throws SQLException, ArchitectException { logger.debug("Starting export of tables: "+tablesToExport); finished = false; hasStarted = true; Connection con = null; try { currentDB = tablesToExport; // first, set the logWriter logWriter = new LogWriter(ArchitectSession.getInstance().getUserSettings().getETLUserSettings().getString( ETLUserSettings.PROP_ETL_LOG_PATH, "")); SQLDatabase repository = new SQLDatabase(repositoryDataSource); // we // are // exporting // db // into // this con = repository.getConnection(); try { defParam = new DefaultParameters(con); } catch (PLSchemaException p) { throw new ArchitectException("couldn't load default parameters", p); } SQLDatabase target = new SQLDatabase(targetDataSource); Connection tCon = target.getConnection(); exportResultList.add(new LabelValueBean("\n Creating Power Loader Job", "\n")); sm = null; for (int tryNum = 0; tryNum < 3 && sm == null; tryNum++) { String username; if (tryNum == 1) { username = repositoryDataSource.get(ArchitectDataSource.PL_UID).toUpperCase(); } else if (tryNum == 2) { username = repositoryDataSource.get(ArchitectDataSource.PL_UID).toLowerCase(); } else { username = repositoryDataSource.get(ArchitectDataSource.PL_UID); } try { // don't need to verify passwords in client apps (as opposed // to webapps) sm = new PLSecurityManager(con, username, repositoryDataSource.get(ArchitectDataSource.PL_PWD), false); } catch (PLSecurityException se) { logger.debug("Couldn't find pl user " + username, se); } } if (sm == null) { throw new ArchitectException("Could not find login for: " + repositoryDataSource.get(ArchitectDataSource.PL_UID)); } logWriter.info("Starting creation of job <" + jobId + "> at " + new java.util.Date(System.currentTimeMillis())); logWriter.info("Connected to database: " + repositoryDataSource.toString()); maybeInsertFolder(con); PLJob job = new PLJob(jobId); insertJob(con); insertFolderDetail(con, job.getObjectType(), job.getObjectName()); // This will order the target tables so that the parent tables are // loaded // before their children DepthFirstSearch targetDFS = new DepthFirstSearch(tablesToExport); List tables = targetDFS.getFinishOrder(); if (logger.isDebugEnabled()) { StringBuffer tableOrder = new StringBuffer(); Iterator dit = tables.iterator(); while (dit.hasNext()) { tableOrder.append(((SQLTable) dit.next()).getName()).append(", "); } logger.debug("Safe load order for job is: " + tableOrder); } int outputTableNum = 1; Hashtable inputTables = new Hashtable(); Iterator targetTableIt = tables.iterator(); while (targetTableIt.hasNext()) { tableCount++; SQLTable outputTable = (SQLTable) targetTableIt.next(); // reset loop variables for each output table boolean createdOutputTableMetaData = false; int transNum = 0; int seqNum = 1; // borrowed from insertColumnMappings, not sure // if this is significant... String transName = null; String outputTableId = null; String inputTableId = null; // Iterator cols = outputTable.getColumns().iterator(); while (cols.hasNext()) { SQLColumn outputCol = (SQLColumn) cols.next(); SQLColumn inputCol = outputCol.getSourceColumn(); if (inputCol != null && !inputTables.keySet().contains(inputCol.getParentTable())) { // create transaction and input table meta data here if // we need to SQLTable inputTable = inputCol.getParentTable(); String baseTransName = PLUtils.toPLIdentifier("LOAD_" + outputTable.getName()); transNum = generateUniqueTransIdx(con, baseTransName); transName = baseTransName + "_" + transNum; logger.debug("transName: " + transName); insertTrans(con, transName, outputTable.getRemarks()); insertFolderDetail(con, "TRANSACTION", transName); insertTransExceptHandler(con, "A", transName, tCon); // error // handling // is // w.r.t. // target // database insertTransExceptHandler(con, "U", transName, tCon); // error // handling // is // w.r.t. // target // database insertTransExceptHandler(con, "D", transName, tCon); // error // handling // is // w.r.t. // target // database insertJobDetail(con, outputTableNum * 10, "TRANSACTION", transName); inputTableId = PLUtils.toPLIdentifier(inputTable.getName() + "_IN_" + transNum); logger.debug("inputTableId: " + inputTableId); insertTransTableFile(con, transName, inputTableId, inputTable, false, transNum); inputTables.put(inputTable, new PLTransaction(transName, inputTableId, transNum)); } else { // restore input/transaction variables PLTransaction plt = (PLTransaction) inputTables.get(inputCol.getParentTable()); transName = plt.getName(); inputTableId = plt.getInputTableId(); transNum = plt.getTransNum(); } if (!createdOutputTableMetaData) { // create output table meta data once logger.debug("outputTableNum: " + outputTableNum); outputTableId = PLUtils.toPLIdentifier(outputTable.getName() + "_OUT_" + outputTableNum); logger.debug("outputTableId: " + outputTableId); insertTransTableFile(con, transName, outputTableId, outputTable, true, transNum); createdOutputTableMetaData = true; } // finally, insert the mapping for this column if (inputCol != null) { // note: output proc seq num appears to be meaningless // based on what the Power Loader // does after you view generated transaction in the VB // Front end. insertTransColMap(con, transName, outputTableId, outputCol, inputTableId, seqNum * 10); } seqNum++; } // moved out of inner loop } } finally { hasStarted = false; finished = true; currentDB = null; // close and flush the logWriter (and set the reference to null) logWriter.flush(); logWriter.close(); logWriter = null; try { if (con != null) con.close(); } catch (SQLException e) { logger.error("Couldn't close connection", e); } } }
1,111,078
public void export(List<SQLTable> tablesToExport) throws SQLException, ArchitectException { logger.debug("Starting export of tables: "+tablesToExport); finished = false; hasStarted = true; Connection con = null; try { currentDB = tablesToExport; // first, set the logWriter logWriter = new LogWriter(ArchitectSession.getInstance().getUserSettings().getETLUserSettings().getString( ETLUserSettings.PROP_ETL_LOG_PATH, "")); SQLDatabase repository = new SQLDatabase(repositoryDataSource); // we // are // exporting // db // into // this con = repository.getConnection(); try { defParam = new DefaultParameters(con); } catch (PLSchemaException p) { throw new ArchitectException("couldn't load default parameters", p); } SQLDatabase target = new SQLDatabase(targetDataSource); Connection tCon = target.getConnection(); exportResultList.add(new LabelValueBean("\n Creating Power Loader Job", "\n")); sm = null; for (int tryNum = 0; tryNum < 3 && sm == null; tryNum++) { String username; if (tryNum == 1) { username = repositoryDataSource.get(ArchitectDataSource.PL_UID).toUpperCase(); } else if (tryNum == 2) { username = repositoryDataSource.get(ArchitectDataSource.PL_UID).toLowerCase(); } else { username = repositoryDataSource.get(ArchitectDataSource.PL_UID); } try { // don't need to verify passwords in client apps (as opposed // to webapps) sm = new PLSecurityManager(con, username, repositoryDataSource.get(ArchitectDataSource.PL_PWD), false); } catch (PLSecurityException se) { logger.debug("Couldn't find pl user " + username, se); } } if (sm == null) { throw new ArchitectException("Could not find login for: " + repositoryDataSource.get(ArchitectDataSource.PL_UID)); } logWriter.info("Starting creation of job <" + jobId + "> at " + new java.util.Date(System.currentTimeMillis())); logWriter.info("Connected to database: " + repositoryDataSource.toString()); maybeInsertFolder(con); PLJob job = new PLJob(jobId); insertJob(con); insertFolderDetail(con, job.getObjectType(), job.getObjectName()); // This will order the target tables so that the parent tables are // loaded // before their children DepthFirstSearch targetDFS = new DepthFirstSearch(tablesToExport); List tables = targetDFS.getFinishOrder(); if (logger.isDebugEnabled()) { StringBuffer tableOrder = new StringBuffer(); Iterator dit = tables.iterator(); while (dit.hasNext()) { tableOrder.append(((SQLTable) dit.next()).getName()).append(", "); } logger.debug("Safe load order for job is: " + tableOrder); } int outputTableNum = 1; Hashtable inputTables = new Hashtable(); Iterator targetTableIt = tables.iterator(); while (targetTableIt.hasNext()) { tableCount++; SQLTable outputTable = (SQLTable) targetTableIt.next(); // reset loop variables for each output table boolean createdOutputTableMetaData = false; int transNum = 0; int seqNum = 1; // borrowed from insertColumnMappings, not sure // if this is significant... String transName = null; String outputTableId = null; String inputTableId = null; // Iterator cols = outputTable.getColumns().iterator(); while (cols.hasNext()) { SQLColumn outputCol = (SQLColumn) cols.next(); SQLColumn inputCol = outputCol.getSourceColumn(); if (inputCol != null && !inputTables.keySet().contains(inputCol.getParentTable())) { // create transaction and input table meta data here if // we need to SQLTable inputTable = inputCol.getParentTable(); String baseTransName = PLUtils.toPLIdentifier("LOAD_" + outputTable.getName()); transNum = generateUniqueTransIdx(con, baseTransName); transName = baseTransName + "_" + transNum; logger.debug("transName: " + transName); insertTrans(con, transName, outputTable.getRemarks()); insertFolderDetail(con, "TRANSACTION", transName); insertTransExceptHandler(con, "A", transName, tCon); // error // handling // is // w.r.t. // target // database insertTransExceptHandler(con, "U", transName, tCon); // error // handling // is // w.r.t. // target // database insertTransExceptHandler(con, "D", transName, tCon); // error // handling // is // w.r.t. // target // database insertJobDetail(con, outputTableNum * 10, "TRANSACTION", transName); inputTableId = PLUtils.toPLIdentifier(inputTable.getName() + "_IN_" + transNum); logger.debug("inputTableId: " + inputTableId); insertTransTableFile(con, transName, inputTableId, inputTable, false, transNum); inputTables.put(inputTable, new PLTransaction(transName, inputTableId, transNum)); } else { // restore input/transaction variables PLTransaction plt = (PLTransaction) inputTables.get(inputCol.getParentTable()); transName = plt.getName(); inputTableId = plt.getInputTableId(); transNum = plt.getTransNum(); } if (!createdOutputTableMetaData) { // create output table meta data once logger.debug("outputTableNum: " + outputTableNum); outputTableId = PLUtils.toPLIdentifier(outputTable.getName() + "_OUT_" + outputTableNum); logger.debug("outputTableId: " + outputTableId); insertTransTableFile(con, transName, outputTableId, outputTable, true, transNum); createdOutputTableMetaData = true; } // finally, insert the mapping for this column if (inputCol != null) { // note: output proc seq num appears to be meaningless // based on what the Power Loader // does after you view generated transaction in the VB // Front end. insertTransColMap(con, transName, outputTableId, outputCol, inputTableId, seqNum * 10); } seqNum++; } outputTableNum++; // moved out of inner loop } } finally { hasStarted = false; finished = true; currentDB = null; // close and flush the logWriter (and set the reference to null) logWriter.flush(); logWriter.close(); logWriter = null; try { if (con != null) con.close(); } catch (SQLException e) { logger.error("Couldn't close connection", e); } } }
public void export(List<SQLTable> tablesToExport) throws SQLException, ArchitectException { logger.debug("Starting export of tables: "+tablesToExport); finished = false; hasStarted = true; Connection con = null; try { currentDB = tablesToExport; // first, set the logWriter logWriter = new LogWriter(ArchitectSession.getInstance().getUserSettings().getETLUserSettings().getString( ETLUserSettings.PROP_ETL_LOG_PATH, "")); SQLDatabase repository = new SQLDatabase(repositoryDataSource); // we // are // exporting // db // into // this con = repository.getConnection(); try { defParam = new DefaultParameters(con); } catch (PLSchemaException p) { throw new ArchitectException("couldn't load default parameters", p); } SQLDatabase target = new SQLDatabase(targetDataSource); Connection tCon = target.getConnection(); exportResultList.add(new LabelValueBean("\n Creating Power Loader Job", "\n")); sm = null; for (int tryNum = 0; tryNum < 3 && sm == null; tryNum++) { String username; if (tryNum == 1) { username = repositoryDataSource.get(ArchitectDataSource.PL_UID).toUpperCase(); } else if (tryNum == 2) { username = repositoryDataSource.get(ArchitectDataSource.PL_UID).toLowerCase(); } else { username = repositoryDataSource.get(ArchitectDataSource.PL_UID); } try { // don't need to verify passwords in client apps (as opposed // to webapps) sm = new PLSecurityManager(con, username, repositoryDataSource.get(ArchitectDataSource.PL_PWD), false); } catch (PLSecurityException se) { logger.debug("Couldn't find pl user " + username, se); } } if (sm == null) { throw new ArchitectException("Could not find login for: " + repositoryDataSource.get(ArchitectDataSource.PL_UID)); } logWriter.info("Starting creation of job <" + jobId + "> at " + new java.util.Date(System.currentTimeMillis())); logWriter.info("Connected to database: " + repositoryDataSource.toString()); maybeInsertFolder(con); PLJob job = new PLJob(jobId); insertJob(con); insertFolderDetail(con, job.getObjectType(), job.getObjectName()); // This will order the target tables so that the parent tables are // loaded // before their children DepthFirstSearch targetDFS = new DepthFirstSearch(tablesToExport); List tables = targetDFS.getFinishOrder(); if (logger.isDebugEnabled()) { StringBuffer tableOrder = new StringBuffer(); Iterator dit = tables.iterator(); while (dit.hasNext()) { tableOrder.append(((SQLTable) dit.next()).getName()).append(", "); } logger.debug("Safe load order for job is: " + tableOrder); } int outputTableNum = 1; Hashtable inputTables = new Hashtable(); Iterator targetTableIt = tables.iterator(); while (targetTableIt.hasNext()) { tableCount++; SQLTable outputTable = (SQLTable) targetTableIt.next(); // reset loop variables for each output table boolean createdOutputTableMetaData = false; int transNum = 0; int seqNum = 1; // borrowed from insertColumnMappings, not sure // if this is significant... String transName = null; String outputTableId = null; String inputTableId = null; // Iterator cols = outputTable.getColumns().iterator(); while (cols.hasNext()) { SQLColumn outputCol = (SQLColumn) cols.next(); SQLColumn inputCol = outputCol.getSourceColumn(); if (inputCol != null && !inputTables.keySet().contains(inputCol.getParentTable())) { // create transaction and input table meta data here if // we need to SQLTable inputTable = inputCol.getParentTable(); String baseTransName = PLUtils.toPLIdentifier("LOAD_" + outputTable.getName()); transNum = generateUniqueTransIdx(con, baseTransName); transName = baseTransName + "_" + transNum; logger.debug("transName: " + transName); insertTrans(con, transName, outputTable.getRemarks()); insertFolderDetail(con, "TRANSACTION", transName); insertTransExceptHandler(con, "A", transName, tCon); // error // handling // is // w.r.t. // target // database insertTransExceptHandler(con, "U", transName, tCon); // error // handling // is // w.r.t. // target // database insertTransExceptHandler(con, "D", transName, tCon); // error // handling // is // w.r.t. // target // database insertJobDetail(con, outputTableNum * 10, "TRANSACTION", transName); inputTableId = PLUtils.toPLIdentifier(inputTable.getName() + "_IN_" + transNum); logger.debug("inputTableId: " + inputTableId); insertTransTableFile(con, transName, inputTableId, inputTable, false, transNum); inputTables.put(inputTable, new PLTransaction(transName, inputTableId, transNum)); } else { // restore input/transaction variables PLTransaction plt = (PLTransaction) inputTables.get(inputCol.getParentTable()); transName = plt.getName(); inputTableId = plt.getInputTableId(); transNum = plt.getTransNum(); } if (!createdOutputTableMetaData) { // create output table meta data once logger.debug("outputTableNum: " + outputTableNum); outputTableId = PLUtils.toPLIdentifier(outputTable.getName() + "_OUT_" + outputTableNum); logger.debug("outputTableId: " + outputTableId); insertTransTableFile(con, transName, outputTableId, outputTable, true, transNum); createdOutputTableMetaData = true; } // finally, insert the mapping for this column if (inputCol != null) { // note: output proc seq num appears to be meaningless // based on what the Power Loader // does after you view generated transaction in the VB // Front end. insertTransColMap(con, transName, outputTableId, outputCol, inputTableId, seqNum * 10); } seqNum++; } outputTableNum++; // moved out of inner loop } } finally { hasStarted = false; finished = true; currentDB = null; // close and flush the logWriter (and set the reference to null) logWriter.flush(); logWriter.close(); logWriter = null; try { if (con != null) con.close(); } catch (SQLException e) { logger.error("Couldn't close repository connection", e); } try { if (tCon != null) tCon.close(); } catch (SQLException e) { logger.error("Couldn't close target connection", e); } } }
1,111,079
public void insertJobDetail(Connection con, int seqNo, String objectType, String objectName) throws SQLException { String status = "Unknown"; StringBuffer sql = new StringBuffer("INSERT INTO "); sql.append(DDLUtils.toQualifiedName(repositoryCatalog, repositorySchema, "JOB_DETAIL")); sql .append(" (JOB_ID, JOB_PROCESS_SEQ_NO, OBJECT_TYPE, OBJECT_NAME, JOB_DETAIL_COMMENT, LAST_update_DATE, LAST_update_USER, FAILURE_ABORT_IND, WARNING_ABORT_IND, PKG_PARAM, ACTIVE_IND, LAST_update_OS_USER )"); sql.append(" VALUES ("); sql.append(SQL.quote(jobId)); // JOB_ID sql.append(",").append(seqNo); // JOB_PROCESS_SEQ_NO sql.append(",").append(SQL.quote(objectType)); // OBJECT_TYPE sql.append(",").append(SQL.quote(objectName)); // OBJECT_NAME sql.append(",").append(SQL.quote("Generated by POWER*Architect " + PL_GENERATOR_VERSION)); // JOB_DETAIL_COMMENT sql.append(",").append(SQL.escapeDate(con, new java.util.Date())); // LAST_update_DATE sql.append(",").append(SQL.quote(con.getMetaData().getUserName())); // LAST_update_USER sql.append(",").append(SQL.quote("N")); // FAILURE_ABORT_IND sql.append(",").append(SQL.quote("N")); // WARNING_ABORT_IND sql.append(",").append(SQL.quote(null)); // PKG_PARAM sql.append(",").append(SQL.quote("Y")); // ACTIVE_IND sql.append(",").append(SQL.quote(System.getProperty("user.name"))); // LAST_update_OS_USER sql.append(")"); logWriter.info("INSERT into JOB DETAIL, PK=" + jobId + "|" + seqNo); Statement s = con.createStatement(); try { logger.debug("INSERT JOB DETAIL: " + sql.toString()); s.executeUpdate(sql.toString()); status = "OK"; } catch (SQLException e) { status = "Error"; throw e; } finally { if (s != null) { s.close(); } exportResultList.add(new LabelValueBean("Create Job Step " + seqNo + objectName, status)); } }
public void insertJobDetail(Connection con, int seqNo, String objectType, String objectName) throws SQLException { String status = "Unknown"; StringBuffer sql = new StringBuffer("INSERT INTO "); sql.append(DDLUtils.toQualifiedName(repositoryCatalog, repositorySchema, "JOB_DETAIL")); sql .append(" (JOB_ID, JOB_PROCESS_SEQ_NO, OBJECT_TYPE, OBJECT_NAME, JOB_DETAIL_COMMENT, LAST_update_DATE, LAST_update_USER, FAILURE_ABORT_IND, WARNING_ABORT_IND, PKG_PARAM, ACTIVE_IND, LAST_update_OS_USER )"); sql.append(" VALUES ("); sql.append(SQL.quote(jobId)); // JOB_ID sql.append(",").append(seqNo); // JOB_PROCESS_SEQ_NO sql.append(",").append(SQL.quote(objectType)); // OBJECT_TYPE sql.append(",").append(SQL.quote(objectName)); // OBJECT_NAME sql.append(",").append(SQL.quote("Generated by Power*Architect " + PL_GENERATOR_VERSION)); // JOB_DETAIL_COMMENT sql.append(",").append(SQL.escapeDate(con, new java.util.Date())); // LAST_update_DATE sql.append(",").append(SQL.quote(con.getMetaData().getUserName())); // LAST_update_USER sql.append(",").append(SQL.quote("N")); // FAILURE_ABORT_IND sql.append(",").append(SQL.quote("N")); // WARNING_ABORT_IND sql.append(",").append(SQL.quote(null)); // PKG_PARAM sql.append(",").append(SQL.quote("Y")); // ACTIVE_IND sql.append(",").append(SQL.quote(System.getProperty("user.name"))); // LAST_update_OS_USER sql.append(")"); logWriter.info("INSERT into JOB DETAIL, PK=" + jobId + "|" + seqNo); Statement s = con.createStatement(); try { logger.debug("INSERT JOB DETAIL: " + sql.toString()); s.executeUpdate(sql.toString()); status = "OK"; } catch (SQLException e) { status = "Error"; throw e; } finally { if (s != null) { s.close(); } exportResultList.add(new LabelValueBean("Create Job Step " + seqNo + objectName, status)); } }
1,111,080
public Expression createExpression( ExpressionFactory factory, String tagName, String attributeName, String attributeValue) throws Exception { ExpressionFactory myFactory = getExpressionFactory(); if (myFactory == null) { myFactory = factory; } if (myFactory != null) { return CompositeExpression.parse(attributeValue, myFactory); } // will use a constant expression instead return new ConstantExpression(attributeValue); }
public Expression createExpression( ExpressionFactory factory, TagScript tagScript, String attributeName, String attributeValue) throws Exception { ExpressionFactory myFactory = getExpressionFactory(); if (myFactory == null) { myFactory = factory; } if (myFactory != null) { return CompositeExpression.parse(attributeValue, myFactory); } // will use a constant expression instead return new ConstantExpression(attributeValue); }
1,111,081
public void setUp() { String volumeRoot = "c:\\temp\\photoVaultVolumeTest"; volume = new Volume( "testVolume", volumeRoot ); PhotovaultSettings settings = PhotovaultSettings.getSettings(); db = settings.getCurrentDatabase(); db.addVolume( volume ); }
public void setUp() { String volumeRoot = "c:\\temp\\photoVaultVolumeTest"; volume = new Volume( "testVolume", volumeRoot ); PhotovaultSettings settings = PhotovaultSettings.getSettings(); db = settings.getCurrentDatabase(); try { db.addVolume( volume ); } catch (PhotovaultException ex) { ex.printStackTrace(); } }
1,111,082
public void testGetVolumeOfFile() { try { File testVolPath = File.createTempFile( "pv_voltest", "" ); VolumeBase extVolume = new ExternalVolume( "extvol", testVolPath.getAbsolutePath() ); db.addVolume( extVolume ); File test1 = new File( volume.getBaseDir(), "testfile" ); assertEquals( test1.getAbsolutePath() + " belongs to volume", volume, VolumeBase.getVolumeOfFile( test1 ) ); File test2 = new File( testVolPath, "testfile" ); assertEquals( test2.getAbsolutePath() + " belongs to volume", extVolume, VolumeBase.getVolumeOfFile( test2 ) ); File test3 = new File( testVolPath.getParentFile(), "testfile" ); this.assertNull( test3.getAbsoluteFile() + " does not belong to volume", VolumeBase.getVolumeOfFile( test3 ) ); // Test that null argument does not cause error VolumeBase.getVolumeOfFile( null ); } catch (IOException ex) { fail( "IOError: " + ex.getMessage() ); } }
public void testGetVolumeOfFile() { try { File testVolPath = File.createTempFile( "pv_voltest", "" ); VolumeBase extVolume = new ExternalVolume( "extvol", testVolPath.getAbsolutePath() ); try { db.addVolume( extVolume ); } catch (PhotovaultException ex) { fail( ex.getMessage() ); } File test1 = new File( volume.getBaseDir(), "testfile" ); assertEquals( test1.getAbsolutePath() + " belongs to volume", volume, VolumeBase.getVolumeOfFile( test1 ) ); File test2 = new File( testVolPath, "testfile" ); assertEquals( test2.getAbsolutePath() + " belongs to volume", extVolume, VolumeBase.getVolumeOfFile( test2 ) ); File test3 = new File( testVolPath.getParentFile(), "testfile" ); this.assertNull( test3.getAbsoluteFile() + " does not belong to volume", VolumeBase.getVolumeOfFile( test3 ) ); // Test that null argument does not cause error VolumeBase.getVolumeOfFile( null ); } catch (IOException ex) { fail( "IOError: " + ex.getMessage() ); } }
1,111,083
public void actionPerformed(ActionEvent e) { final List<ProfileResult> objectToSave = new ArrayList<ProfileResult>(); TableModelSortDecorator tmsd = (TableModelSortDecorator) viewTable.getModel(); ProfileTableModel model = (ProfileTableModel) tmsd.getTableModel(); if ( viewTable.getSelectedRowCount() > 1 ) { int selectedRows[] = viewTable.getSelectedRows(); Set<SQLTable> selectedTable = new HashSet<SQLTable>(); Set<SQLColumn> selectedColumn = new HashSet<SQLColumn>(); for ( int i=0; i<selectedRows.length; i++ ) { int rowid = selectedRows[i]; ColumnProfileResult result = (ColumnProfileResult) model.getResultForRow(rowid); selectedTable.add(result.getProfiledObject().getParentTable()); selectedColumn.add(result.getProfiledObject()); } boolean fullSelection = true; for ( SQLTable t : selectedTable ) { try { for ( SQLColumn c : t.getColumns() ) { if ( !selectedColumn.contains(c) ) { fullSelection = false; break; } } } catch (ArchitectException e1) { ASUtils.showExceptionDialog(parent, "Could not get column from table",e1); } } int response = JOptionPane.YES_OPTION; if ( !fullSelection ) { response = JOptionPane.showConfirmDialog( parent, "You have selected partical table, Do you want to save only this portion? No to save the whole table", "Your selection contains partical table(s)", JOptionPane.YES_NO_OPTION ); } if (response == JOptionPane.NO_OPTION) { for ( SQLTable t : selectedTable ) { objectToSave.add(pm.getResult(t)); try { for ( SQLColumn c : t.getColumns() ) { objectToSave.add(pm.getResult(c)); } } catch (ArchitectException e1) { ASUtils.showExceptionDialog(parent, "Could not get column from table",e1); } } } else { for ( int i=0; i<selectedRows.length; i++ ) { int rowid = selectedRows[i]; ColumnProfileResult result = (ColumnProfileResult) model.getResultForRow(rowid); SQLColumn column = result.getProfiledObject(); SQLTable table = column.getParentTable(); TableProfileResult tpr = (TableProfileResult) pm.getResult(table); if ( !objectToSave.contains(tpr) ) objectToSave.add(tpr); objectToSave.add(result); } } } else { for ( int i=0; i<viewTable.getRowCount(); i++ ) { ColumnProfileResult result = (ColumnProfileResult) model.getResultForRow(i); SQLColumn column = result.getProfiledObject(); SQLTable table = column.getParentTable(); TableProfileResult tpr = (TableProfileResult) pm.getResult(table); if ( !objectToSave.contains(tpr) ) objectToSave.add(tpr); objectToSave.add(result); } } JFileChooser chooser = new JFileChooser(); chooser.addChoosableFileFilter(ASUtils.HTML_FILE_FILTER); chooser.addChoosableFileFilter(ASUtils.PDF_FILE_FILTER); chooser.addChoosableFileFilter(ASUtils.CSV_FILE_FILTER); chooser.removeChoosableFileFilter(chooser.getAcceptAllFileFilter()); // Ask the user to pick a file int response = chooser.showSaveDialog(parent); if (response != JFileChooser.APPROVE_OPTION) { return; } File file = chooser.getSelectedFile(); final FileFilter fileFilter = chooser.getFileFilter(); final SaveableFileType type; String fileName = file.getName(); int x = fileName.lastIndexOf('.'); boolean gotType = false; SaveableFileType ntype = null; if (x != -1) { // pick file by filename the user typed String ext = fileName.substring(x+1); try { ntype = SaveableFileType.valueOf(ext.toUpperCase()); gotType = true; } catch (IllegalArgumentException iex) { gotType = false; } } if (gotType) { type = ntype; } else { // force filename to end with correct extention if (fileFilter == ASUtils.HTML_FILE_FILTER) { if (!fileName.endsWith(".html")) { file = new File(file.getPath()+".html"); } type = SaveableFileType.HTML; } else if (fileFilter == ASUtils.PDF_FILE_FILTER){ if (!fileName.endsWith(".pdf")) { file = new File(file.getPath()+".pdf"); } type = SaveableFileType.PDF; } else if (fileFilter == ASUtils.CSV_FILE_FILTER){ if (!fileName.endsWith(".csv")) { file = new File(file.getPath()+".csv"); } type = SaveableFileType.CSV; } else { throw new IllegalStateException("Unexpected file filter chosen"); } } if (file.exists()) { response = JOptionPane.showConfirmDialog( parent, "The file\n"+file.getPath()+"\nalready exists. Do you want to overwrite it?", "File Exists", JOptionPane.YES_NO_OPTION); if (response == JOptionPane.NO_OPTION) { actionPerformed(e); return; } } // Clone file object for use in inner class, can not make "file" final as we change it to add extension final File file2 = new File(file.getPath()); Runnable saveTask = new Runnable() { public void run() { OutputStream out = null; try { ProfileFormat prf = null; out = new BufferedOutputStream(new FileOutputStream(file2)); switch(type) { case HTML: final String encoding = "utf-8"; prf = new ProfileHTMLFormat(encoding); break; case PDF: prf = new ProfilePDFFormat(); break; case CSV: prf = new ProfileCSVFormat(); break; default: throw new IllegalArgumentException("Unknown type"); } prf.format(out, objectToSave, pm); } catch (Exception ex) { ASUtils.showExceptionDialog(parent,"Could not generate/save report file", ex); } finally { if ( out != null ) { try { out.flush(); out.close(); } catch (IOException ex) { ASUtils.showExceptionDialog(parent,"Could not close report file", ex); } } } } }; new Thread(saveTask).start(); }
public void actionPerformed(ActionEvent e) { final List<ProfileResult> objectToSave = new ArrayList<ProfileResult>(); TableModelSortDecorator tmsd = (TableModelSortDecorator) viewTable.getModel(); ProfileTableModel model = (ProfileTableModel) tmsd.getTableModel(); if ( viewTable.getSelectedRowCount() > 1 ) { int selectedRows[] = viewTable.getSelectedRows(); Set<SQLTable> selectedTable = new HashSet<SQLTable>(); Set<SQLColumn> selectedColumn = new HashSet<SQLColumn>(); for ( int i=0; i<selectedRows.length; i++ ) { int rowid = selectedRows[i]; ColumnProfileResult result = (ColumnProfileResult) model.getResultForRow(rowid); selectedTable.add(result.getProfiledObject().getParentTable()); selectedColumn.add(result.getProfiledObject()); } boolean fullSelection = true; for ( SQLTable t : selectedTable ) { try { for ( SQLColumn c : t.getColumns() ) { if ( !selectedColumn.contains(c) ) { fullSelection = false; break; } } } catch (ArchitectException e1) { ASUtils.showExceptionDialog(parent, "Could not get column from table",e1); } } int response = JOptionPane.YES_OPTION; if ( !fullSelection ) { response = JOptionPane.showConfirmDialog( parent, "You have selected partical table, Do you want to save only this portion? No to save the whole table", "Your selection contains partical table(s)", JOptionPane.YES_NO_OPTION ); } if (response == JOptionPane.NO_OPTION) { for ( SQLTable t : selectedTable ) { objectToSave.add(pm.getResult(t)); try { for ( SQLColumn c : t.getColumns() ) { objectToSave.add(pm.getResult(c)); } } catch (ArchitectException e1) { ASUtils.showExceptionDialog(parent, "Could not get column from table",e1); } } } else { for ( int i=0; i<selectedRows.length; i++ ) { int rowid = selectedRows[i]; ColumnProfileResult result = (ColumnProfileResult) model.getResultForRow(rowid); SQLColumn column = result.getProfiledObject(); SQLTable table = column.getParentTable(); TableProfileResult tpr = (TableProfileResult) pm.getResult(table); if ( !objectToSave.contains(tpr) ) objectToSave.add(tpr); objectToSave.add(result); } } } else { for ( int i=0; i<viewTable.getRowCount(); i++ ) { ColumnProfileResult result = (ColumnProfileResult) model.getResultForRow(i); SQLColumn column = result.getProfiledObject(); SQLTable table = column.getParentTable(); TableProfileResult tpr = (TableProfileResult) pm.getResult(table); if ( !objectToSave.contains(tpr) ) objectToSave.add(tpr); objectToSave.add(result); } } JFileChooser chooser = new JFileChooser(); chooser.addChoosableFileFilter(ASUtils.HTML_FILE_FILTER); chooser.addChoosableFileFilter(ASUtils.PDF_FILE_FILTER); chooser.addChoosableFileFilter(ASUtils.CSV_FILE_FILTER); chooser.removeChoosableFileFilter(chooser.getAcceptAllFileFilter()); // Ask the user to pick a file File file = null; SaveableFileType type; while ( true ) { int response = chooser.showSaveDialog(parent); if (response != JFileChooser.APPROVE_OPTION) { return; } File file = chooser.getSelectedFile(); final FileFilter fileFilter = chooser.getFileFilter(); final SaveableFileType type; String fileName = file.getName(); int x = fileName.lastIndexOf('.'); boolean gotType = false; SaveableFileType ntype = null; if (x != -1) { // pick file by filename the user typed String ext = fileName.substring(x+1); try { ntype = SaveableFileType.valueOf(ext.toUpperCase()); gotType = true; } catch (IllegalArgumentException iex) { gotType = false; } } if (gotType) { type = ntype; } else { // force filename to end with correct extention if (fileFilter == ASUtils.HTML_FILE_FILTER) { if (!fileName.endsWith(".html")) { file = new File(file.getPath()+".html"); } type = SaveableFileType.HTML; } else if (fileFilter == ASUtils.PDF_FILE_FILTER){ if (!fileName.endsWith(".pdf")) { file = new File(file.getPath()+".pdf"); } type = SaveableFileType.PDF; } else if (fileFilter == ASUtils.CSV_FILE_FILTER){ if (!fileName.endsWith(".csv")) { file = new File(file.getPath()+".csv"); } type = SaveableFileType.CSV; } else { throw new IllegalStateException("Unexpected file filter chosen"); } } if (file.exists()) { response = JOptionPane.showConfirmDialog( parent, "The file\n"+file.getPath()+"\nalready exists. Do you want to overwrite it?", "File Exists", JOptionPane.YES_NO_OPTION); if (response == JOptionPane.NO_OPTION) { actionPerformed(e); return; } } // Clone file object for use in inner class, can not make "file" final as we change it to add extension final File file2 = new File(file.getPath()); Runnable saveTask = new Runnable() { public void run() { OutputStream out = null; try { ProfileFormat prf = null; out = new BufferedOutputStream(new FileOutputStream(file2)); switch(type) { case HTML: final String encoding = "utf-8"; prf = new ProfileHTMLFormat(encoding); break; case PDF: prf = new ProfilePDFFormat(); break; case CSV: prf = new ProfileCSVFormat(); break; default: throw new IllegalArgumentException("Unknown type"); } prf.format(out, objectToSave, pm); } catch (Exception ex) { ASUtils.showExceptionDialog(parent,"Could not generate/save report file", ex); } finally { if ( out != null ) { try { out.flush(); out.close(); } catch (IOException ex) { ASUtils.showExceptionDialog(parent,"Could not close report file", ex); } } } } }; new Thread(saveTask).start(); }
1,111,084
public void actionPerformed(ActionEvent e) { final List<ProfileResult> objectToSave = new ArrayList<ProfileResult>(); TableModelSortDecorator tmsd = (TableModelSortDecorator) viewTable.getModel(); ProfileTableModel model = (ProfileTableModel) tmsd.getTableModel(); if ( viewTable.getSelectedRowCount() > 1 ) { int selectedRows[] = viewTable.getSelectedRows(); Set<SQLTable> selectedTable = new HashSet<SQLTable>(); Set<SQLColumn> selectedColumn = new HashSet<SQLColumn>(); for ( int i=0; i<selectedRows.length; i++ ) { int rowid = selectedRows[i]; ColumnProfileResult result = (ColumnProfileResult) model.getResultForRow(rowid); selectedTable.add(result.getProfiledObject().getParentTable()); selectedColumn.add(result.getProfiledObject()); } boolean fullSelection = true; for ( SQLTable t : selectedTable ) { try { for ( SQLColumn c : t.getColumns() ) { if ( !selectedColumn.contains(c) ) { fullSelection = false; break; } } } catch (ArchitectException e1) { ASUtils.showExceptionDialog(parent, "Could not get column from table",e1); } } int response = JOptionPane.YES_OPTION; if ( !fullSelection ) { response = JOptionPane.showConfirmDialog( parent, "You have selected partical table, Do you want to save only this portion? No to save the whole table", "Your selection contains partical table(s)", JOptionPane.YES_NO_OPTION ); } if (response == JOptionPane.NO_OPTION) { for ( SQLTable t : selectedTable ) { objectToSave.add(pm.getResult(t)); try { for ( SQLColumn c : t.getColumns() ) { objectToSave.add(pm.getResult(c)); } } catch (ArchitectException e1) { ASUtils.showExceptionDialog(parent, "Could not get column from table",e1); } } } else { for ( int i=0; i<selectedRows.length; i++ ) { int rowid = selectedRows[i]; ColumnProfileResult result = (ColumnProfileResult) model.getResultForRow(rowid); SQLColumn column = result.getProfiledObject(); SQLTable table = column.getParentTable(); TableProfileResult tpr = (TableProfileResult) pm.getResult(table); if ( !objectToSave.contains(tpr) ) objectToSave.add(tpr); objectToSave.add(result); } } } else { for ( int i=0; i<viewTable.getRowCount(); i++ ) { ColumnProfileResult result = (ColumnProfileResult) model.getResultForRow(i); SQLColumn column = result.getProfiledObject(); SQLTable table = column.getParentTable(); TableProfileResult tpr = (TableProfileResult) pm.getResult(table); if ( !objectToSave.contains(tpr) ) objectToSave.add(tpr); objectToSave.add(result); } } JFileChooser chooser = new JFileChooser(); chooser.addChoosableFileFilter(ASUtils.HTML_FILE_FILTER); chooser.addChoosableFileFilter(ASUtils.PDF_FILE_FILTER); chooser.addChoosableFileFilter(ASUtils.CSV_FILE_FILTER); chooser.removeChoosableFileFilter(chooser.getAcceptAllFileFilter()); // Ask the user to pick a file int response = chooser.showSaveDialog(parent); if (response != JFileChooser.APPROVE_OPTION) { return; } File file = chooser.getSelectedFile(); final FileFilter fileFilter = chooser.getFileFilter(); final SaveableFileType type; String fileName = file.getName(); int x = fileName.lastIndexOf('.'); boolean gotType = false; SaveableFileType ntype = null; if (x != -1) { // pick file by filename the user typed String ext = fileName.substring(x+1); try { ntype = SaveableFileType.valueOf(ext.toUpperCase()); gotType = true; } catch (IllegalArgumentException iex) { gotType = false; } } if (gotType) { type = ntype; } else { // force filename to end with correct extention if (fileFilter == ASUtils.HTML_FILE_FILTER) { if (!fileName.endsWith(".html")) { file = new File(file.getPath()+".html"); } type = SaveableFileType.HTML; } else if (fileFilter == ASUtils.PDF_FILE_FILTER){ if (!fileName.endsWith(".pdf")) { file = new File(file.getPath()+".pdf"); } type = SaveableFileType.PDF; } else if (fileFilter == ASUtils.CSV_FILE_FILTER){ if (!fileName.endsWith(".csv")) { file = new File(file.getPath()+".csv"); } type = SaveableFileType.CSV; } else { throw new IllegalStateException("Unexpected file filter chosen"); } } if (file.exists()) { response = JOptionPane.showConfirmDialog( parent, "The file\n"+file.getPath()+"\nalready exists. Do you want to overwrite it?", "File Exists", JOptionPane.YES_NO_OPTION); if (response == JOptionPane.NO_OPTION) { actionPerformed(e); return; } } // Clone file object for use in inner class, can not make "file" final as we change it to add extension final File file2 = new File(file.getPath()); Runnable saveTask = new Runnable() { public void run() { OutputStream out = null; try { ProfileFormat prf = null; out = new BufferedOutputStream(new FileOutputStream(file2)); switch(type) { case HTML: final String encoding = "utf-8"; prf = new ProfileHTMLFormat(encoding); break; case PDF: prf = new ProfilePDFFormat(); break; case CSV: prf = new ProfileCSVFormat(); break; default: throw new IllegalArgumentException("Unknown type"); } prf.format(out, objectToSave, pm); } catch (Exception ex) { ASUtils.showExceptionDialog(parent,"Could not generate/save report file", ex); } finally { if ( out != null ) { try { out.flush(); out.close(); } catch (IOException ex) { ASUtils.showExceptionDialog(parent,"Could not close report file", ex); } } } } }; new Thread(saveTask).start(); }
public void actionPerformed(ActionEvent e) { final List<ProfileResult> objectToSave = new ArrayList<ProfileResult>(); TableModelSortDecorator tmsd = (TableModelSortDecorator) viewTable.getModel(); ProfileTableModel model = (ProfileTableModel) tmsd.getTableModel(); if ( viewTable.getSelectedRowCount() > 1 ) { int selectedRows[] = viewTable.getSelectedRows(); Set<SQLTable> selectedTable = new HashSet<SQLTable>(); Set<SQLColumn> selectedColumn = new HashSet<SQLColumn>(); for ( int i=0; i<selectedRows.length; i++ ) { int rowid = selectedRows[i]; ColumnProfileResult result = (ColumnProfileResult) model.getResultForRow(rowid); selectedTable.add(result.getProfiledObject().getParentTable()); selectedColumn.add(result.getProfiledObject()); } boolean fullSelection = true; for ( SQLTable t : selectedTable ) { try { for ( SQLColumn c : t.getColumns() ) { if ( !selectedColumn.contains(c) ) { fullSelection = false; break; } } } catch (ArchitectException e1) { ASUtils.showExceptionDialog(parent, "Could not get column from table",e1); } } int response = JOptionPane.YES_OPTION; if ( !fullSelection ) { response = JOptionPane.showConfirmDialog( parent, "You have selected partical table, Do you want to save only this portion? No to save the whole table", "Your selection contains partical table(s)", JOptionPane.YES_NO_OPTION ); } if (response == JOptionPane.NO_OPTION) { for ( SQLTable t : selectedTable ) { objectToSave.add(pm.getResult(t)); try { for ( SQLColumn c : t.getColumns() ) { objectToSave.add(pm.getResult(c)); } } catch (ArchitectException e1) { ASUtils.showExceptionDialog(parent, "Could not get column from table",e1); } } } else { for ( int i=0; i<selectedRows.length; i++ ) { int rowid = selectedRows[i]; ColumnProfileResult result = (ColumnProfileResult) model.getResultForRow(rowid); SQLColumn column = result.getProfiledObject(); SQLTable table = column.getParentTable(); TableProfileResult tpr = (TableProfileResult) pm.getResult(table); if ( !objectToSave.contains(tpr) ) objectToSave.add(tpr); objectToSave.add(result); } } } else { for ( int i=0; i<viewTable.getRowCount(); i++ ) { ColumnProfileResult result = (ColumnProfileResult) model.getResultForRow(i); SQLColumn column = result.getProfiledObject(); SQLTable table = column.getParentTable(); TableProfileResult tpr = (TableProfileResult) pm.getResult(table); if ( !objectToSave.contains(tpr) ) objectToSave.add(tpr); objectToSave.add(result); } } JFileChooser chooser = new JFileChooser(); chooser.addChoosableFileFilter(ASUtils.HTML_FILE_FILTER); chooser.addChoosableFileFilter(ASUtils.PDF_FILE_FILTER); chooser.addChoosableFileFilter(ASUtils.CSV_FILE_FILTER); chooser.removeChoosableFileFilter(chooser.getAcceptAllFileFilter()); // Ask the user to pick a file int response = chooser.showSaveDialog(parent); if (response != JFileChooser.APPROVE_OPTION) { return; } File file = chooser.getSelectedFile(); final FileFilter fileFilter = chooser.getFileFilter(); final SaveableFileType type; String fileName = file.getName(); int x = fileName.lastIndexOf('.'); boolean gotType = false; SaveableFileType ntype = null; if (x != -1) { // pick file by filename the user typed String ext = fileName.substring(x+1); try { ntype = SaveableFileType.valueOf(ext.toUpperCase()); gotType = true; } catch (IllegalArgumentException iex) { gotType = false; } } if (gotType) { type = ntype; } else { // force filename to end with correct extention if (fileFilter == ASUtils.HTML_FILE_FILTER) { if (!fileName.endsWith(".html")) { file = new File(file.getPath()+".html"); } type = SaveableFileType.HTML; } else if (fileFilter == ASUtils.PDF_FILE_FILTER){ if (!fileName.endsWith(".pdf")) { file = new File(file.getPath()+".pdf"); } type = SaveableFileType.PDF; } else if (fileFilter == ASUtils.CSV_FILE_FILTER){ if (!fileName.endsWith(".csv")) { file = new File(file.getPath()+".csv"); } type = SaveableFileType.CSV; } else { throw new IllegalStateException("Unexpected file filter chosen"); } } if (file.exists()) { response = JOptionPane.showConfirmDialog( parent, "The file\n"+file.getPath()+"\nalready exists. Do you want to overwrite it?", "File Exists", JOptionPane.YES_NO_OPTION); if (response == JOptionPane.NO_OPTION) { actionPerformed(e); return; } } // Clone file object for use in inner class, can not make "file" final as we change it to add extension final File file2 = new File(file.getPath()); Runnable saveTask = new Runnable() { public void run() { OutputStream out = null; try { ProfileFormat prf = null; out = new BufferedOutputStream(new FileOutputStream(file2)); switch(type) { case HTML: final String encoding = "utf-8"; prf = new ProfileHTMLFormat(encoding); break; case PDF: prf = new ProfilePDFFormat(); break; case CSV: prf = new ProfileCSVFormat(); break; default: throw new IllegalArgumentException("Unknown type"); } prf.format(out, objectToSave, pm); } catch (Exception ex) { ASUtils.showExceptionDialog(parent,"Could not generate/save report file", ex); } finally { if ( out != null ) { try { out.flush(); out.close(); } catch (IOException ex) { ASUtils.showExceptionDialog(parent,"Could not close report file", ex); } } } } }; new Thread(saveTask).start(); }
1,111,085
public void actionPerformed(ActionEvent e) { final List<ProfileResult> objectToSave = new ArrayList<ProfileResult>(); TableModelSortDecorator tmsd = (TableModelSortDecorator) viewTable.getModel(); ProfileTableModel model = (ProfileTableModel) tmsd.getTableModel(); if ( viewTable.getSelectedRowCount() > 1 ) { int selectedRows[] = viewTable.getSelectedRows(); Set<SQLTable> selectedTable = new HashSet<SQLTable>(); Set<SQLColumn> selectedColumn = new HashSet<SQLColumn>(); for ( int i=0; i<selectedRows.length; i++ ) { int rowid = selectedRows[i]; ColumnProfileResult result = (ColumnProfileResult) model.getResultForRow(rowid); selectedTable.add(result.getProfiledObject().getParentTable()); selectedColumn.add(result.getProfiledObject()); } boolean fullSelection = true; for ( SQLTable t : selectedTable ) { try { for ( SQLColumn c : t.getColumns() ) { if ( !selectedColumn.contains(c) ) { fullSelection = false; break; } } } catch (ArchitectException e1) { ASUtils.showExceptionDialog(parent, "Could not get column from table",e1); } } int response = JOptionPane.YES_OPTION; if ( !fullSelection ) { response = JOptionPane.showConfirmDialog( parent, "You have selected partical table, Do you want to save only this portion? No to save the whole table", "Your selection contains partical table(s)", JOptionPane.YES_NO_OPTION ); } if (response == JOptionPane.NO_OPTION) { for ( SQLTable t : selectedTable ) { objectToSave.add(pm.getResult(t)); try { for ( SQLColumn c : t.getColumns() ) { objectToSave.add(pm.getResult(c)); } } catch (ArchitectException e1) { ASUtils.showExceptionDialog(parent, "Could not get column from table",e1); } } } else { for ( int i=0; i<selectedRows.length; i++ ) { int rowid = selectedRows[i]; ColumnProfileResult result = (ColumnProfileResult) model.getResultForRow(rowid); SQLColumn column = result.getProfiledObject(); SQLTable table = column.getParentTable(); TableProfileResult tpr = (TableProfileResult) pm.getResult(table); if ( !objectToSave.contains(tpr) ) objectToSave.add(tpr); objectToSave.add(result); } } } else { for ( int i=0; i<viewTable.getRowCount(); i++ ) { ColumnProfileResult result = (ColumnProfileResult) model.getResultForRow(i); SQLColumn column = result.getProfiledObject(); SQLTable table = column.getParentTable(); TableProfileResult tpr = (TableProfileResult) pm.getResult(table); if ( !objectToSave.contains(tpr) ) objectToSave.add(tpr); objectToSave.add(result); } } JFileChooser chooser = new JFileChooser(); chooser.addChoosableFileFilter(ASUtils.HTML_FILE_FILTER); chooser.addChoosableFileFilter(ASUtils.PDF_FILE_FILTER); chooser.addChoosableFileFilter(ASUtils.CSV_FILE_FILTER); chooser.removeChoosableFileFilter(chooser.getAcceptAllFileFilter()); // Ask the user to pick a file int response = chooser.showSaveDialog(parent); if (response != JFileChooser.APPROVE_OPTION) { return; } File file = chooser.getSelectedFile(); final FileFilter fileFilter = chooser.getFileFilter(); final SaveableFileType type; String fileName = file.getName(); int x = fileName.lastIndexOf('.'); boolean gotType = false; SaveableFileType ntype = null; if (x != -1) { // pick file by filename the user typed String ext = fileName.substring(x+1); try { ntype = SaveableFileType.valueOf(ext.toUpperCase()); gotType = true; } catch (IllegalArgumentException iex) { gotType = false; } } if (gotType) { type = ntype; } else { // force filename to end with correct extention if (fileFilter == ASUtils.HTML_FILE_FILTER) { if (!fileName.endsWith(".html")) { file = new File(file.getPath()+".html"); } type = SaveableFileType.HTML; } else if (fileFilter == ASUtils.PDF_FILE_FILTER){ if (!fileName.endsWith(".pdf")) { file = new File(file.getPath()+".pdf"); } type = SaveableFileType.PDF; } else if (fileFilter == ASUtils.CSV_FILE_FILTER){ if (!fileName.endsWith(".csv")) { file = new File(file.getPath()+".csv"); } type = SaveableFileType.CSV; } else { throw new IllegalStateException("Unexpected file filter chosen"); } } if (file.exists()) { response = JOptionPane.showConfirmDialog( parent, "The file\n"+file.getPath()+"\nalready exists. Do you want to overwrite it?", "File Exists", JOptionPane.YES_NO_OPTION); if (response == JOptionPane.NO_OPTION) { actionPerformed(e); return; } } // Clone file object for use in inner class, can not make "file" final as we change it to add extension final File file2 = new File(file.getPath()); Runnable saveTask = new Runnable() { public void run() { OutputStream out = null; try { ProfileFormat prf = null; out = new BufferedOutputStream(new FileOutputStream(file2)); switch(type) { case HTML: final String encoding = "utf-8"; prf = new ProfileHTMLFormat(encoding); break; case PDF: prf = new ProfilePDFFormat(); break; case CSV: prf = new ProfileCSVFormat(); break; default: throw new IllegalArgumentException("Unknown type"); } prf.format(out, objectToSave, pm); } catch (Exception ex) { ASUtils.showExceptionDialog(parent,"Could not generate/save report file", ex); } finally { if ( out != null ) { try { out.flush(); out.close(); } catch (IOException ex) { ASUtils.showExceptionDialog(parent,"Could not close report file", ex); } } } } }; new Thread(saveTask).start(); }
public void actionPerformed(ActionEvent e) { final List<ProfileResult> objectToSave = new ArrayList<ProfileResult>(); TableModelSortDecorator tmsd = (TableModelSortDecorator) viewTable.getModel(); ProfileTableModel model = (ProfileTableModel) tmsd.getTableModel(); if ( viewTable.getSelectedRowCount() > 1 ) { int selectedRows[] = viewTable.getSelectedRows(); Set<SQLTable> selectedTable = new HashSet<SQLTable>(); Set<SQLColumn> selectedColumn = new HashSet<SQLColumn>(); for ( int i=0; i<selectedRows.length; i++ ) { int rowid = selectedRows[i]; ColumnProfileResult result = (ColumnProfileResult) model.getResultForRow(rowid); selectedTable.add(result.getProfiledObject().getParentTable()); selectedColumn.add(result.getProfiledObject()); } boolean fullSelection = true; for ( SQLTable t : selectedTable ) { try { for ( SQLColumn c : t.getColumns() ) { if ( !selectedColumn.contains(c) ) { fullSelection = false; break; } } } catch (ArchitectException e1) { ASUtils.showExceptionDialog(parent, "Could not get column from table",e1); } } int response = JOptionPane.YES_OPTION; if ( !fullSelection ) { response = JOptionPane.showConfirmDialog( parent, "You have selected partical table, Do you want to save only this portion? No to save the whole table", "Your selection contains partical table(s)", JOptionPane.YES_NO_OPTION ); } if (response == JOptionPane.NO_OPTION) { for ( SQLTable t : selectedTable ) { objectToSave.add(pm.getResult(t)); try { for ( SQLColumn c : t.getColumns() ) { objectToSave.add(pm.getResult(c)); } } catch (ArchitectException e1) { ASUtils.showExceptionDialog(parent, "Could not get column from table",e1); } } } else { for ( int i=0; i<selectedRows.length; i++ ) { int rowid = selectedRows[i]; ColumnProfileResult result = (ColumnProfileResult) model.getResultForRow(rowid); SQLColumn column = result.getProfiledObject(); SQLTable table = column.getParentTable(); TableProfileResult tpr = (TableProfileResult) pm.getResult(table); if ( !objectToSave.contains(tpr) ) objectToSave.add(tpr); objectToSave.add(result); } } } else { for ( int i=0; i<viewTable.getRowCount(); i++ ) { ColumnProfileResult result = (ColumnProfileResult) model.getResultForRow(i); SQLColumn column = result.getProfiledObject(); SQLTable table = column.getParentTable(); TableProfileResult tpr = (TableProfileResult) pm.getResult(table); if ( !objectToSave.contains(tpr) ) objectToSave.add(tpr); objectToSave.add(result); } } JFileChooser chooser = new JFileChooser(); chooser.addChoosableFileFilter(ASUtils.HTML_FILE_FILTER); chooser.addChoosableFileFilter(ASUtils.PDF_FILE_FILTER); chooser.addChoosableFileFilter(ASUtils.CSV_FILE_FILTER); chooser.removeChoosableFileFilter(chooser.getAcceptAllFileFilter()); // Ask the user to pick a file int response = chooser.showSaveDialog(parent); if (response != JFileChooser.APPROVE_OPTION) { return; } File file = chooser.getSelectedFile(); final FileFilter fileFilter = chooser.getFileFilter(); final SaveableFileType type; String fileName = file.getName(); int x = fileName.lastIndexOf('.'); boolean gotType = false; SaveableFileType ntype = null; if (x != -1) { // pick file by filename the user typed String ext = fileName.substring(x+1); try { ntype = SaveableFileType.valueOf(ext.toUpperCase()); gotType = true; } catch (IllegalArgumentException iex) { gotType = false; } } if (gotType) { type = ntype; } else { // force filename to end with correct extention if (fileFilter == ASUtils.HTML_FILE_FILTER) { if (!fileName.endsWith(".html")) { file = new File(file.getPath()+".html"); } type = SaveableFileType.HTML; } else if (fileFilter == ASUtils.PDF_FILE_FILTER){ if (!fileName.endsWith(".pdf")) { file = new File(file.getPath()+".pdf"); } type = SaveableFileType.PDF; } else if (fileFilter == ASUtils.CSV_FILE_FILTER){ if (!fileName.endsWith(".csv")) { file = new File(file.getPath()+".csv"); } type = SaveableFileType.CSV; } else { throw new IllegalStateException("Unexpected file filter chosen"); } } if (file.exists()) { response = JOptionPane.showConfirmDialog( parent, "The file\n"+file.getPath()+"\nalready exists. Do you want to overwrite it?", "File Exists", JOptionPane.YES_NO_OPTION); if (response == JOptionPane.NO_OPTION) { actionPerformed(e); return; } } // Clone file object for use in inner class, can not make "file" final as we change it to add extension final File file2 = new File(file.getPath()); Runnable saveTask = new Runnable() { public void run() { OutputStream out = null; try { ProfileFormat prf = null; out = new BufferedOutputStream(new FileOutputStream(file2)); switch(type2) { case HTML: final String encoding = "utf-8"; prf = new ProfileHTMLFormat(encoding); break; case PDF: prf = new ProfilePDFFormat(); break; case CSV: prf = new ProfileCSVFormat(); break; default: throw new IllegalArgumentException("Unknown type"); } prf.format(out, objectToSave, pm); } catch (Exception ex) { ASUtils.showExceptionDialog(parent,"Could not generate/save report file", ex); } finally { if ( out != null ) { try { out.flush(); out.close(); } catch (IOException ex) { ASUtils.showExceptionDialog(parent,"Could not close report file", ex); } } } } }; new Thread(saveTask).start(); }
1,111,086
public void run() { OutputStream out = null; try { ProfileFormat prf = null; out = new BufferedOutputStream(new FileOutputStream(file2)); switch(type) { case HTML: final String encoding = "utf-8"; prf = new ProfileHTMLFormat(encoding); break; case PDF: prf = new ProfilePDFFormat(); break; case CSV: prf = new ProfileCSVFormat(); break; default: throw new IllegalArgumentException("Unknown type"); } prf.format(out, objectToSave, pm); } catch (Exception ex) { ASUtils.showExceptionDialog(parent,"Could not generate/save report file", ex); } finally { if ( out != null ) { try { out.flush(); out.close(); } catch (IOException ex) { ASUtils.showExceptionDialog(parent,"Could not close report file", ex); } } } }
public void run() { OutputStream out = null; try { ProfileFormat prf = null; out = new BufferedOutputStream(new FileOutputStream(file2)); switch(type2) { case HTML: final String encoding = "utf-8"; prf = new ProfileHTMLFormat(encoding); break; case PDF: prf = new ProfilePDFFormat(); break; case CSV: prf = new ProfileCSVFormat(); break; default: throw new IllegalArgumentException("Unknown type"); } prf.format(out, objectToSave, pm); } catch (Exception ex) { ASUtils.showExceptionDialog(parent,"Could not generate/save report file", ex); } finally { if ( out != null ) { try { out.flush(); out.close(); } catch (IOException ex) { ASUtils.showExceptionDialog(parent,"Could not close report file", ex); } } } }
1,111,087
public void intervalRemoved(ListDataEvent e) { try { if (model.getColumns().size() == 0) { Component c = getParent(); while ( ! (c instanceof Window)) { c = c.getParent(); } c.setVisible(false); } else { editColumn(0); } } catch (ArchitectException ex) { JOptionPane.showMessageDialog(this, "Can't edit the selected column"); logger.error("Can't edit the selected column", ex); } }
public void intervalRemoved(ListDataEvent e) { try { if (model.getColumns().size() == 0) { Component c = getParent(); while ( ! (c instanceof Window)) { c = c.getParent(); } c.setVisible(false); } else { editColumn(columns.getSelectedIndex()); } } catch (ArchitectException ex) { JOptionPane.showMessageDialog(this, "Can't edit the selected column"); logger.error("Can't edit the selected column", ex); } }
1,111,089
public void paintComponent(Graphics g){ DPrimeTable dPrimeTable = theData.dpTable; if (Chromosome.getSize() < 2){ //if there zero or only one valid marker return; } Vector blocks = theData.blocks; Rectangle visRect = getVisibleRect(); //deal with zooming if (chartSize.getWidth() > (3*visRect.width)){ showWM = true; }else{ showWM = false; } boolean printValues = true; if (zoomLevel != 0 || Options.getPrintWhat() == LD_NONE){ printValues = false; } printWhat = Options.getPrintWhat(); Graphics2D g2 = (Graphics2D) g; Dimension size = getSize(); Dimension pref = getPreferredSize(); g2.setColor(BG_GREY); //if it's a big dataset, resize properly, if it's small make sure to fill whole background if (size.height < pref.height){ g2.fillRect(0,0,pref.width,pref.height); setSize(pref); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); //okay so this dumb if block is to prevent the ugly repainting //bug when loading markers after the data are already being displayed, //results in a little off-centering for small datasets, but not too bad. if (!forExport){ if (!theData.infoKnown){ g2.translate((size.width - pref.width) / 2, (size.height - pref.height) / 2); } else { g2.translate((size.width - pref.width) / 2, 0); } } FontMetrics boxFontMetrics = g2.getFontMetrics(boxFont); int diamondX[] = new int[4]; int diamondY[] = new int[4]; Polygon diamond; double lineSpan = alignedPositions[alignedPositions.length-1] - alignedPositions[0]; long minpos = Chromosome.getMarker(0).getPosition(); long maxpos = Chromosome.getMarker(Chromosome.getSize()-1).getPosition(); double spanpos = maxpos - minpos; //See http://www.hapmap.org/cgi-perl/gbrowse/gbrowse_img //for more info on GBrowse img. int imgHeight = 0; if (Options.isGBrowseShown() && Chromosome.getDataChrom() != null){ g2.drawImage(gBrowseImage,H_BORDER-GBROWSE_MARGIN,V_BORDER,this); imgHeight = gBrowseImage.getHeight(this) + TRACK_GAP; // get height so we can shift everything down } left = H_BORDER; top = V_BORDER + imgHeight; // push the haplotype display down to make room for gbrowse image. if (forExport){ left -= exportStart * boxSize; } FontMetrics metrics; int ascent; g2.setFont(boldMarkerNameFont); metrics = g2.getFontMetrics(); ascent = metrics.getAscent(); //the following values are the bounds on the boxes we want to //display given that the current window is 'visRect' lowX = getBoundaryMarker(visRect.x-clickXShift-(visRect.y +visRect.height-clickYShift)) - 1; highX = getBoundaryMarker(visRect.x + visRect.width); lowY = getBoundaryMarker((visRect.x-clickXShift)+(visRect.y-clickYShift)) - 1; highY = getBoundaryMarker((visRect.x-clickXShift+visRect.width) + (visRect.y-clickYShift+visRect.height)); if (lowX < 0) { lowX = 0; } if (highX > Chromosome.getSize()-1){ highX = Chromosome.getSize()-1; } if (lowY < lowX+1){ lowY = lowX+1; } if (highY > Chromosome.getSize()){ highY = Chromosome.getSize(); } if (forExport){ lowX = exportStart; lowY = exportStart; highX = exportStop; highY = exportStop+1; } if (theData.trackExists){ //draw the analysis track above where the marker positions will be marked JFreeChart jfc = ChartFactory.createXYLineChart(null,null,null, theData.analysisTracks, PlotOrientation.VERTICAL,false,false,false); //customise the analysis track XYPlot xyp = (XYPlot)jfc.getPlot(); //no x axis, since it takes up too much space. xyp.getDomainAxis().setAxisLineVisible(false); xyp.getDomainAxis().setTickLabelsVisible(false); xyp.getDomainAxis().setTickMarksVisible(false); //x range must align with markers xyp.getDomainAxis().setRange(minpos,maxpos); //size of the axis and graph inset double axisWidth = xyp.getRangeAxis(). reserveSpace(g2,xyp,new Rectangle(0,TRACK_HEIGHT),RectangleEdge.LEFT,null).getLeft(); RectangleInsets insets = xyp.getInsets(); jfc.setBackgroundPaint(BG_GREY); BufferedImage bi = jfc.createBufferedImage( (int)(lineSpan + axisWidth + insets.getLeft() + insets.getRight()),TRACK_HEIGHT); //hide the axis in the margin so everything lines up. g2.drawImage(bi,(int)(left - axisWidth - insets.getLeft()),top,this); top += TRACK_HEIGHT + TRACK_GAP; } if (theData.infoKnown) { Color green = new Color(0, 127, 0); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //// draw the marker locations g2.setStroke(thinnerStroke); g2.setColor(Color.white); g2.fill(new Rectangle2D.Double(left+1, top+1, lineSpan-1, TICK_HEIGHT-1)); g2.setColor(Color.black); g2.draw(new Rectangle2D.Double(left, top, lineSpan, TICK_HEIGHT)); for (int i = 0; i < Chromosome.getSize(); i++){ double pos = (Chromosome.getMarker(i).getPosition() - minpos) / spanpos; double xx = left + lineSpan*pos; // if we're zoomed, use the line color to indicate whether there is extra data available // (since the marker names are not displayed when zoomed) if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setColor(green); //draw tick g2.setStroke(thickerStroke); g2.draw(new Line2D.Double(xx, top, xx, top + TICK_HEIGHT)); if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setStroke(thickerStroke); else g2.setStroke(thinnerStroke); //draw connecting line g2.draw(new Line2D.Double(xx, top + TICK_HEIGHT, left + alignedPositions[i], top+TICK_BOTTOM)); if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setColor(Color.black); } top += TICK_BOTTOM + TICK_HEIGHT; //// draw the marker names if (printMarkerNames){ widestMarkerName = metrics.stringWidth(Chromosome.getMarker(0).getDisplayName()); for (int x = 1; x < Chromosome.getSize(); x++) { int thiswide = metrics.stringWidth(Chromosome.getMarker(x).getDisplayName()); if (thiswide > widestMarkerName) widestMarkerName = thiswide; } g2.translate(left, top + widestMarkerName); g2.rotate(-Math.PI / 2.0); boolean foundSNP = false; for (int x = 0; x < Chromosome.getSize(); x++) { if (theData.isInBlock[x]){ g2.setFont(boldMarkerNameFont); }else{ g2.setFont(markerNameFont); } if (Chromosome.getMarker(x).getExtra() != null) g2.setColor(green); if (Chromosome.getMarker(x).getDisplayName().equals(theHV.getChosenMarker())){ g2.setColor(Color.blue); foundSNP = true; } g2.drawString(Chromosome.getMarker(x).getDisplayName(),(float)TEXT_GAP, (float)alignedPositions[x] + ascent/3); if (Chromosome.getMarker(x).getExtra() != null) g2.setColor(Color.black); if (foundSNP){ g2.setColor(Color.BLACK); foundSNP = false; } } g2.rotate(Math.PI / 2.0); g2.translate(-left, -(top + widestMarkerName)); // move everybody down top += widestMarkerName + TEXT_GAP; } g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } top += blockDispHeight; //// draw the marker numbers if (printMarkerNames){ g2.setFont(markerNumFont); metrics = g2.getFontMetrics(); ascent = metrics.getAscent(); for (int x = 0; x < Chromosome.getSize(); x++) { String mark = String.valueOf(Chromosome.realIndex[x] + 1); g2.drawString(mark, (float)(left + alignedPositions[x] - metrics.stringWidth(mark)/2), (float)(top + ascent)); } top += boxRadius/2; // give a little space between numbers and boxes } //clickxshift and clickyshift are used later to translate from x,y coords //to the pair of markers comparison at those coords if (!(theData.infoKnown)){ clickXShift = left + (size.width-pref.width)/2; clickYShift = top + (size.height - pref.height)/2; } else { clickXShift = left + (size.width-pref.width)/2; clickYShift = top; } // draw table column by column for (int x = lowX; x < highX; x++) { //always draw the fewest possible boxes if (lowY < x+1){ lowY = x+1; } for (int y = lowY; y < highY; y++) { if (dPrimeTable.getLDStats(x,y) == null){ continue; } double d = dPrimeTable.getLDStats(x,y).getDPrime(); double r = dPrimeTable.getLDStats(x,y).getRSquared(); //double l = dPrimeTable.getLDStats(x,y).getLOD(); Color boxColor = dPrimeTable.getLDStats(x,y).getColor(); // draw markers above int xx = left + (int)((alignedPositions[x] + alignedPositions[y])/2); int yy = top + (int)((alignedPositions[y] - alignedPositions[x]) / 2); diamondX[0] = xx; diamondY[0] = yy - boxRadius; diamondX[1] = xx + boxRadius; diamondY[1] = yy; diamondX[2] = xx; diamondY[2] = yy + boxRadius; diamondX[3] = xx - boxRadius; diamondY[3] = yy; diamond = new Polygon(diamondX, diamondY, 4); g2.setColor(boxColor); g2.fillPolygon(diamond); if(printValues){ g2.setFont(boxFont); ascent = boxFontMetrics.getAscent(); int val; if (printWhat == D_PRIME){ val = (int) (d * 100); }else if (printWhat == R_SQ){ val = (int) (r * 100); }else{ val = 100; } g2.setColor((val < 50) ? Color.gray : Color.black); if (boxColor.getGreen() < 100 && boxColor.getBlue() < 100 && boxColor.getRed() < 100){ g2.setColor(Color.white); } if (val != 100) { String valu = String.valueOf(val); int widf = boxFontMetrics.stringWidth(valu); g.drawString(valu, xx - widf/2, yy + ascent/2); } } } } //highlight blocks g2.setFont(markerNameFont); ascent = g2.getFontMetrics().getAscent(); //g.setColor(new Color(153,255,153)); g2.setColor(Color.black); //g.setColor(new Color(51,153,51)); for (int i = 0; i < blocks.size(); i++){ int[] theBlock = (int[])blocks.elementAt(i); int first = theBlock[0]; int last = theBlock[theBlock.length-1]; //big vee around whole thing g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left + alignedPositions[first] - boxRadius, top, left + (alignedPositions[first] + alignedPositions[last])/2, top + (alignedPositions[last] - alignedPositions[first])/2 + boxRadius)); g2.draw(new Line2D.Double(left + (alignedPositions[first] + alignedPositions[last])/2, top + (alignedPositions[last] - alignedPositions[first])/2 + boxRadius, left + alignedPositions[last] + boxRadius, top)); for (int j = first; j < last; j++){ g2.setStroke(fatStroke); if (theData.isInBlock[j]){ g2.draw(new Line2D.Double(left+alignedPositions[j]-boxSize/2, top-blockDispHeight, left+alignedPositions[j+1]-boxSize/2, top-blockDispHeight)); }else{ g2.draw(new Line2D.Double(left + alignedPositions[j] + boxSize/2, top-blockDispHeight, left+alignedPositions[j+1]-boxSize/2, top-blockDispHeight)); g2.setStroke(dashedFatStroke); g2.draw(new Line2D.Double(left+alignedPositions[j] - boxSize/2, top-blockDispHeight, left+alignedPositions[j] + boxSize/2, top-blockDispHeight)); } } //cap off the end of the block g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left+alignedPositions[last]-boxSize/2, top-blockDispHeight, left+alignedPositions[last]+boxSize/2, top-blockDispHeight)); //lines to connect to block display g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left + alignedPositions[first]-boxSize/2, top-1, left+alignedPositions[first]-boxSize/2, top-blockDispHeight)); g2.draw(new Line2D.Double(left+alignedPositions[last]+boxSize/2, top-1, left+alignedPositions[last]+boxSize/2, top-blockDispHeight)); if (printMarkerNames){ String labelString = new String ("Block " + (i+1)); if (theData.infoKnown){ long blockSize = Chromosome.getMarker(last).getPosition() - Chromosome.getMarker(first).getPosition(); labelString += " (" + blockSize/1000 + " kb)"; } g2.drawString(labelString, (float)(left+alignedPositions[first]-boxSize/2+TEXT_GAP), (float)(top-boxSize/3)); } } g2.setStroke(thickerStroke); if (showWM && !forExport){ //dataset is big enough to require worldmap if (wmMaxWidth == 0){ wmMaxWidth = visRect.width/3; } double scalefactor; scalefactor = (double)(chartSize.width)/wmMaxWidth; double prefBoxSize = boxSize/(scalefactor*((double)wmMaxWidth/(double)(wmMaxWidth))); //stick WM_BD in the middle of the blank space at the top of the worldmap final int WM_BD_GAP = (int)(infoHeight/(scalefactor*2)); final int WM_BD_HEIGHT = 2; CompoundBorder wmBorder = new CompoundBorder(BorderFactory.createRaisedBevelBorder(), BorderFactory.createLoweredBevelBorder()); if (noImage){ //first time through draw a worldmap if dataset is big: worldmap = new BufferedImage((int)(chartSize.width/scalefactor)+wmBorder.getBorderInsets(this).left*2, (int)(chartSize.height/scalefactor)+wmBorder.getBorderInsets(this).top*2, BufferedImage.TYPE_3BYTE_BGR); Graphics gw = worldmap.getGraphics(); Graphics2D gw2 = (Graphics2D)(gw); gw2.setColor(BG_GREY); gw2.fillRect(1,1,worldmap.getWidth()-1,worldmap.getHeight()-1); //make a pretty border gw2.setColor(Color.black); wmBorder.paintBorder(this,gw2,0,0,worldmap.getWidth(),worldmap.getHeight()); wmInteriorRect = wmBorder.getInteriorRectangle(this,0,0,worldmap.getWidth(), worldmap.getHeight()); float[] smallDiamondX = new float[4]; float[] smallDiamondY = new float[4]; GeneralPath gp; for (int x = 0; x < Chromosome.getSize()-1; x++){ for (int y = x+1; y < Chromosome.getSize(); y++){ if (dPrimeTable.getLDStats(x,y) == null){ continue; } double xx = ((alignedPositions[y] + alignedPositions[x])/(scalefactor*2)) + wmBorder.getBorderInsets(this).left; double yy = ((alignedPositions[y] - alignedPositions[x] + infoHeight*2)/(scalefactor*2)) + wmBorder.getBorderInsets(this).top; smallDiamondX[0] = (float)xx; smallDiamondY[0] = (float)(yy - prefBoxSize/2); smallDiamondX[1] = (float)(xx + prefBoxSize/2); smallDiamondY[1] = (float)yy; smallDiamondX[2] = (float)xx; smallDiamondY[2] = (float)(yy + prefBoxSize/2); smallDiamondX[3] = (float)(xx - prefBoxSize/2); smallDiamondY[3] = (float)yy; gp = new GeneralPath(GeneralPath.WIND_EVEN_ODD, smallDiamondX.length); gp.moveTo(smallDiamondX[0],smallDiamondY[0]); for (int i = 1; i < smallDiamondX.length; i++){ gp.lineTo(smallDiamondX[i], smallDiamondY[i]); } gp.closePath(); gw2.setColor(dPrimeTable.getLDStats(x,y).getColor()); gw2.fill(gp); } } noImage = false; } //draw block display in worldmap Graphics gw = worldmap.getGraphics(); Graphics2D gw2 = (Graphics2D)(gw); gw2.setColor(BG_GREY); gw2.fillRect(wmBorder.getBorderInsets(this).left, wmBorder.getBorderInsets(this).top+WM_BD_GAP, wmInteriorRect.width, WM_BD_HEIGHT); gw2.setColor(Color.black); boolean even = true; for (int i = 0; i < blocks.size(); i++){ int first = ((int[])blocks.elementAt(i))[0]; int last = ((int[])blocks.elementAt(i))[((int[])blocks.elementAt(i)).length-1]; int voffset; if (even){ voffset = 0; }else{ voffset = WM_BD_HEIGHT/2; } gw2.fillRect(wmBorder.getBorderInsets(this).left - (int)prefBoxSize/2 + (int)(alignedPositions[first]/scalefactor), wmBorder.getBorderInsets(this).top+voffset+WM_BD_GAP, (int)(prefBoxSize + (alignedPositions[last] - alignedPositions[first])/scalefactor), WM_BD_HEIGHT/2); even = !even; } wmResizeCorner = new Rectangle(visRect.x + worldmap.getWidth() - (worldmap.getWidth()-wmInteriorRect.width)/2, visRect.y + visRect.height - worldmap.getHeight(), (worldmap.getWidth()-wmInteriorRect.width)/2, (worldmap.getHeight() -wmInteriorRect.height)/2); g2.drawImage(worldmap,visRect.x, visRect.y + visRect.height - worldmap.getHeight(), this); wmInteriorRect.x = visRect.x + (worldmap.getWidth() - wmInteriorRect.width)/2; wmInteriorRect.y = visRect.y+visRect.height-worldmap.getHeight() + (worldmap.getHeight() - wmInteriorRect.height)/2; //draw the outline of the viewport g2.setColor(Color.black); double hRatio = wmInteriorRect.getWidth()/pref.getWidth(); double vRatio = wmInteriorRect.getHeight()/pref.getHeight(); int hBump = worldmap.getWidth()-wmInteriorRect.width; int vBump = worldmap.getHeight()-wmInteriorRect.height; //bump a few pixels to avoid drawing on the border g2.drawRect((int)(visRect.x*hRatio)+hBump/2+visRect.x, (int)(visRect.y*vRatio)+vBump/2+(visRect.y + visRect.height - worldmap.getHeight()), (int)(visRect.width*hRatio), (int)(visRect.height*vRatio)); } //see if the user has right-clicked to popup some marker info if(popupDrawRect != null){ //dumb bug where little datasets popup the box in the wrong place int smallDatasetSlopH = 0; int smallDatasetSlopV = 0; if (pref.getHeight() < visRect.height){ smallDatasetSlopV = (int)(visRect.height - pref.getHeight())/2; } if (pref.getWidth() < visRect.width){ smallDatasetSlopH = (int)(visRect.width - pref.getWidth())/2; } g2.setColor(Color.white); g2.fillRect(popupDrawRect.x+1-smallDatasetSlopH, popupDrawRect.y+1-smallDatasetSlopV, popupDrawRect.width-1, popupDrawRect.height-1); g2.setColor(Color.black); g2.drawRect(popupDrawRect.x-smallDatasetSlopH, popupDrawRect.y-smallDatasetSlopV, popupDrawRect.width, popupDrawRect.height); g.setFont(popupFont); for (int x = 0; x < displayStrings.size(); x++){ g.drawString((String)displayStrings.elementAt(x),popupDrawRect.x + popupLeftMargin-smallDatasetSlopH, popupDrawRect.y+((x+1)*metrics.getHeight())-smallDatasetSlopV); } } // draw the cached last right-click selection // The purpose of testing for empty string is just to avoid an 2-unit empty white box if ((zoomLevel == 0) && (!lastSelection.equals("")) && (!forExport)) { g2.setFont(boxFont); // a bit extra on all side int last_descent = g2.getFontMetrics().getDescent(); int last_box_x = (visRect.x + LAST_SELECTION_LEFT) - 2; int last_box_y = (visRect.y - g2.getFontMetrics().getHeight() + LAST_SELECTION_TOP + last_descent) - 1 ; int last_box_width = g2.getFontMetrics().stringWidth(lastSelection) + 4; int last_box_height = g2.getFontMetrics().getHeight() + 2; g2.setColor(Color.white); g2.fillRect(last_box_x, last_box_y, last_box_width, last_box_height); g2.setColor(Color.black); g2.drawRect(last_box_x, last_box_y, last_box_width, last_box_height); g2.drawString(lastSelection, LAST_SELECTION_LEFT + visRect.x, LAST_SELECTION_TOP + visRect.y); } //see if we're drawing a worldmap resize rect if (resizeWMRect != null){ g2.setColor(Color.black); g2.drawRect(resizeWMRect.x, resizeWMRect.y, resizeWMRect.width, resizeWMRect.height); } //see if we're drawing a block selector rect if (blockRect != null){ g2.setColor(Color.black); g2.setStroke(dashedThinStroke); g2.drawRect(blockRect.x, blockRect.y, blockRect.width, blockRect.height); } }
public void paintComponent(Graphics g){ DPrimeTable dPrimeTable = theData.dpTable; if (Chromosome.getSize() < 2){ //if there zero or only one valid marker return; } Vector blocks = theData.blocks; Rectangle visRect = getVisibleRect(); //deal with zooming if (chartSize.getWidth() > (3*visRect.width)){ showWM = true; }else{ showWM = false; } boolean printValues = true; if (zoomLevel != 0 || Options.getPrintWhat() == LD_NONE){ printValues = false; } printWhat = Options.getPrintWhat(); Graphics2D g2 = (Graphics2D) g; Dimension size = getSize(); Dimension pref = getPreferredSize(); g2.setColor(BG_GREY); //if it's a big dataset, resize properly, if it's small make sure to fill whole background if (size.height < pref.height){ g2.fillRect(0,0,pref.width,pref.height); setSize(pref); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); //okay so this dumb if block is to prevent the ugly repainting //bug when loading markers after the data are already being displayed, //results in a little off-centering for small datasets, but not too bad. if (!forExport){ if (!theData.infoKnown){ g2.translate((size.width - pref.width) / 2, (size.height - pref.height) / 2); } else { g2.translate((size.width - pref.width) / 2, 0); } } FontMetrics boxFontMetrics = g2.getFontMetrics(boxFont); int diamondX[] = new int[4]; int diamondY[] = new int[4]; Polygon diamond; double lineSpan = alignedPositions[alignedPositions.length-1] - alignedPositions[0]; long minpos = Chromosome.getMarker(0).getPosition(); long maxpos = Chromosome.getMarker(Chromosome.getSize()-1).getPosition(); double spanpos = maxpos - minpos; //See http://www.hapmap.org/cgi-perl/gbrowse/gbrowse_img //for more info on GBrowse img. int imgHeight = 0; if (Options.isGBrowseShown() && Chromosome.getDataChrom() != null){ g2.drawImage(gBrowseImage,H_BORDER-GBROWSE_MARGIN,V_BORDER,this); imgHeight = gBrowseImage.getHeight(this) + TRACK_GAP; // get height so we can shift everything down } left = H_BORDER; top = V_BORDER + imgHeight; // push the haplotype display down to make room for gbrowse image. if (forExport){ left -= exportStart * boxSize; } FontMetrics metrics; int ascent; g2.setFont(boldMarkerNameFont); metrics = g2.getFontMetrics(); ascent = metrics.getAscent(); //the following values are the bounds on the boxes we want to //display given that the current window is 'visRect' lowX = getBoundaryMarker(visRect.x-clickXShift-(visRect.y +visRect.height-clickYShift)) - 1; highX = getBoundaryMarker(visRect.x + visRect.width); lowY = getBoundaryMarker((visRect.x-clickXShift)+(visRect.y-clickYShift)) - 1; highY = getBoundaryMarker((visRect.x-clickXShift+visRect.width) + (visRect.y-clickYShift+visRect.height)); if (lowX < 0) { lowX = 0; } if (highX > Chromosome.getSize()-1){ highX = Chromosome.getSize()-1; } if (lowY < lowX+1){ lowY = lowX+1; } if (highY > Chromosome.getSize()){ highY = Chromosome.getSize(); } if (forExport){ lowX = exportStart; lowY = exportStart; highX = exportStop; highY = exportStop+1; } if (theData.trackExists){ //draw the analysis track above where the marker positions will be marked JFreeChart jfc = ChartFactory.createXYLineChart(null,null,null, theData.analysisTracks, PlotOrientation.VERTICAL,false,false,false); //customise the analysis track XYPlot xyp = (XYPlot)jfc.getPlot(); //no x axis, since it takes up too much space. xyp.getDomainAxis().setAxisLineVisible(false); xyp.getDomainAxis().setTickLabelsVisible(false); xyp.getDomainAxis().setTickMarksVisible(false); //x range must align with markers xyp.getDomainAxis().setRange(minpos,maxpos); //size of the axis and graph inset double axisWidth = xyp.getRangeAxis(). reserveSpace(g2,xyp,new Rectangle(0,TRACK_HEIGHT),RectangleEdge.LEFT,null).getLeft(); RectangleInsets insets = xyp.getInsets(); jfc.setBackgroundPaint(BG_GREY); BufferedImage bi = jfc.createBufferedImage( (int)(lineSpan + axisWidth + insets.getLeft() + insets.getRight()),TRACK_HEIGHT); //hide the axis in the margin so everything lines up. g2.drawImage(bi,(int)(left - axisWidth - insets.getLeft()),top,this); top += TRACK_HEIGHT + TRACK_GAP; } if (theData.infoKnown) { Color green = new Color(0, 127, 0); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //// draw the marker locations g2.setStroke(thinnerStroke); g2.setColor(Color.white); g2.fill(new Rectangle2D.Double(left+1, top+1, lineSpan-1, TICK_HEIGHT-1)); g2.setColor(Color.black); g2.draw(new Rectangle2D.Double(left, top, lineSpan, TICK_HEIGHT)); for (int i = 0; i < Chromosome.getSize(); i++){ double pos = (Chromosome.getMarker(i).getPosition() - minpos) / spanpos; double xx = left + lineSpan*pos; // if we're zoomed, use the line color to indicate whether there is extra data available // (since the marker names are not displayed when zoomed) if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setColor(green); //draw tick g2.setStroke(thickerStroke); g2.draw(new Line2D.Double(xx, top, xx, top + TICK_HEIGHT)); if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setStroke(thickerStroke); else g2.setStroke(thinnerStroke); //draw connecting line g2.draw(new Line2D.Double(xx, top + TICK_HEIGHT, left + alignedPositions[i], top+TICK_BOTTOM)); if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setColor(Color.black); } top += TICK_BOTTOM + TICK_HEIGHT; //// draw the marker names if (printMarkerNames){ widestMarkerName = metrics.stringWidth(Chromosome.getMarker(0).getDisplayName()); for (int x = 1; x < Chromosome.getSize(); x++) { int thiswide = metrics.stringWidth(Chromosome.getMarker(x).getDisplayName()); if (thiswide > widestMarkerName) widestMarkerName = thiswide; } g2.translate(left, top + widestMarkerName); g2.rotate(-Math.PI / 2.0); boolean foundSNP = false; for (int x = 0; x < Chromosome.getSize(); x++) { if (theData.isInBlock[x]){ g2.setFont(boldMarkerNameFont); }else{ g2.setFont(markerNameFont); } if (Chromosome.getMarker(x).getExtra() != null) g2.setColor(green); if (Chromosome.getMarker(x).getDisplayName().equals(theHV.getChosenMarker())){ g2.setColor(Color.blue); foundSNP = true; } g2.drawString(Chromosome.getMarker(x).getDisplayName(),(float)TEXT_GAP, (float)alignedPositions[x] + ascent/3); if (Chromosome.getMarker(x).getExtra() != null) g2.setColor(Color.black); if (foundSNP){ g2.setColor(Color.BLACK); foundSNP = false; } } g2.rotate(Math.PI / 2.0); g2.translate(-left, -(top + widestMarkerName)); // move everybody down top += widestMarkerName + TEXT_GAP; } g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } top += blockDispHeight; //// draw the marker numbers if (printMarkerNames){ g2.setFont(markerNumFont); metrics = g2.getFontMetrics(); ascent = metrics.getAscent(); for (int x = 0; x < Chromosome.getSize(); x++) { String mark = String.valueOf(Chromosome.realIndex[x] + 1); g2.drawString(mark, (float)(left + alignedPositions[x] - metrics.stringWidth(mark)/2), (float)(top + ascent)); } top += boxRadius/2; // give a little space between numbers and boxes } //clickxshift and clickyshift are used later to translate from x,y coords //to the pair of markers comparison at those coords if (!(theData.infoKnown)){ clickXShift = left + (size.width-pref.width)/2; clickYShift = top + (size.height - pref.height)/2; } else { clickXShift = left + (size.width-pref.width)/2; clickYShift = top; } // draw table column by column for (int x = lowX; x < highX; x++) { //always draw the fewest possible boxes if (lowY < x+1){ lowY = x+1; } for (int y = lowY; y < highY; y++) { if (dPrimeTable.getLDStats(x,y) == null){ continue; } double d = dPrimeTable.getLDStats(x,y).getDPrime(); double r = dPrimeTable.getLDStats(x,y).getRSquared(); //double l = dPrimeTable.getLDStats(x,y).getLOD(); Color boxColor = dPrimeTable.getLDStats(x,y).getColor(); // draw markers above int xx = left + (int)((alignedPositions[x] + alignedPositions[y])/2); int yy = top + (int)((alignedPositions[y] - alignedPositions[x]) / 2); diamondX[0] = xx; diamondY[0] = yy - boxRadius; diamondX[1] = xx + boxRadius; diamondY[1] = yy; diamondX[2] = xx; diamondY[2] = yy + boxRadius; diamondX[3] = xx - boxRadius; diamondY[3] = yy; diamond = new Polygon(diamondX, diamondY, 4); g2.setColor(boxColor); g2.fillPolygon(diamond); if(printValues){ g2.setFont(boxFont); ascent = boxFontMetrics.getAscent(); int val; if (printWhat == D_PRIME){ val = (int) (d * 100); }else if (printWhat == R_SQ){ val = (int) (r * 100); }else{ val = 100; } g2.setColor((val < 50) ? Color.gray : Color.black); if (boxColor.getGreen() < 100 && boxColor.getBlue() < 100 && boxColor.getRed() < 100){ g2.setColor(Color.white); } if (val != 100) { String valu = String.valueOf(val); int widf = boxFontMetrics.stringWidth(valu); g.drawString(valu, xx - widf/2, yy + ascent/2); } } } } //highlight blocks g2.setFont(markerNameFont); ascent = g2.getFontMetrics().getAscent(); //g.setColor(new Color(153,255,153)); g2.setColor(Color.black); //g.setColor(new Color(51,153,51)); for (int i = 0; i < blocks.size(); i++){ int[] theBlock = (int[])blocks.elementAt(i); int first = theBlock[0]; int last = theBlock[theBlock.length-1]; //big vee around whole thing g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left + alignedPositions[first] - boxRadius, top, left + (alignedPositions[first] + alignedPositions[last])/2, top + (alignedPositions[last] - alignedPositions[first])/2 + boxRadius)); g2.draw(new Line2D.Double(left + (alignedPositions[first] + alignedPositions[last])/2, top + (alignedPositions[last] - alignedPositions[first])/2 + boxRadius, left + alignedPositions[last] + boxRadius, top)); for (int j = first; j < last; j++){ g2.setStroke(fatStroke); if (theData.isInBlock[j]){ g2.draw(new Line2D.Double(left+alignedPositions[j]-boxSize/2, top-blockDispHeight, left+alignedPositions[j+1]-boxSize/2, top-blockDispHeight)); }else{ g2.draw(new Line2D.Double(left + alignedPositions[j] + boxSize/2, top-blockDispHeight, left+alignedPositions[j+1]-boxSize/2, top-blockDispHeight)); g2.setStroke(dashedFatStroke); g2.draw(new Line2D.Double(left+alignedPositions[j] - boxSize/2, top-blockDispHeight, left+alignedPositions[j] + boxSize/2, top-blockDispHeight)); } } //cap off the end of the block g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left+alignedPositions[last]-boxSize/2, top-blockDispHeight, left+alignedPositions[last]+boxSize/2, top-blockDispHeight)); //lines to connect to block display g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left + alignedPositions[first]-boxSize/2, top-1, left+alignedPositions[first]-boxSize/2, top-blockDispHeight)); g2.draw(new Line2D.Double(left+alignedPositions[last]+boxSize/2, top-1, left+alignedPositions[last]+boxSize/2, top-blockDispHeight)); if (printMarkerNames){ String labelString = new String ("Block " + (i+1)); if (theData.infoKnown){ long blockSize = Chromosome.getMarker(last).getPosition() - Chromosome.getMarker(first).getPosition(); labelString += " (" + blockSize/1000 + " kb)"; } g2.drawString(labelString, (float)(left+alignedPositions[first]-boxSize/2+TEXT_GAP), (float)(top-boxSize/3)); } } g2.setStroke(thickerStroke); if (showWM && !forExport){ //dataset is big enough to require worldmap if (wmMaxWidth == 0){ wmMaxWidth = visRect.width/3; } double scalefactor; scalefactor = (double)(chartSize.width)/wmMaxWidth; double prefBoxSize = boxSize/(scalefactor*((double)wmMaxWidth/(double)(wmMaxWidth))); //stick WM_BD in the middle of the blank space at the top of the worldmap final int WM_BD_GAP = (int)(infoHeight/(scalefactor*2)); final int WM_BD_HEIGHT = 2; CompoundBorder wmBorder = new CompoundBorder(BorderFactory.createRaisedBevelBorder(), BorderFactory.createLoweredBevelBorder()); if (noImage){ //first time through draw a worldmap if dataset is big: worldmap = new BufferedImage((int)(chartSize.width/scalefactor)+wmBorder.getBorderInsets(this).left*2, (int)(chartSize.height/scalefactor)+wmBorder.getBorderInsets(this).top*2, BufferedImage.TYPE_3BYTE_BGR); Graphics gw = worldmap.getGraphics(); Graphics2D gw2 = (Graphics2D)(gw); gw2.setColor(BG_GREY); gw2.fillRect(1,1,worldmap.getWidth()-1,worldmap.getHeight()-1); //make a pretty border gw2.setColor(Color.black); wmBorder.paintBorder(this,gw2,0,0,worldmap.getWidth(),worldmap.getHeight()); wmInteriorRect = wmBorder.getInteriorRectangle(this,0,0,worldmap.getWidth(), worldmap.getHeight()); float[] smallDiamondX = new float[4]; float[] smallDiamondY = new float[4]; GeneralPath gp; for (int x = 0; x < Chromosome.getSize()-1; x++){ for (int y = x+1; y < Chromosome.getSize(); y++){ if (dPrimeTable.getLDStats(x,y) == null){ continue; } double xx = ((alignedPositions[y] + alignedPositions[x])/(scalefactor*2)) + wmBorder.getBorderInsets(this).left; double yy = ((alignedPositions[y] - alignedPositions[x] + infoHeight*2)/(scalefactor*2)) + wmBorder.getBorderInsets(this).top; smallDiamondX[0] = (float)xx; smallDiamondY[0] = (float)(yy - prefBoxSize/2); smallDiamondX[1] = (float)(xx + prefBoxSize/2); smallDiamondY[1] = (float)yy; smallDiamondX[2] = (float)xx; smallDiamondY[2] = (float)(yy + prefBoxSize/2); smallDiamondX[3] = (float)(xx - prefBoxSize/2); smallDiamondY[3] = (float)yy; gp = new GeneralPath(GeneralPath.WIND_EVEN_ODD, smallDiamondX.length); gp.moveTo(smallDiamondX[0],smallDiamondY[0]); for (int i = 1; i < smallDiamondX.length; i++){ gp.lineTo(smallDiamondX[i], smallDiamondY[i]); } gp.closePath(); gw2.setColor(dPrimeTable.getLDStats(x,y).getColor()); gw2.fill(gp); } } noImage = false; } //draw block display in worldmap Graphics gw = worldmap.getGraphics(); Graphics2D gw2 = (Graphics2D)(gw); gw2.setColor(BG_GREY); gw2.fillRect(wmBorder.getBorderInsets(this).left, wmBorder.getBorderInsets(this).top+WM_BD_GAP, wmInteriorRect.width, WM_BD_HEIGHT); gw2.setColor(Color.black); boolean even = true; for (int i = 0; i < blocks.size(); i++){ int first = ((int[])blocks.elementAt(i))[0]; int last = ((int[])blocks.elementAt(i))[((int[])blocks.elementAt(i)).length-1]; int voffset; if (even){ voffset = 0; }else{ voffset = WM_BD_HEIGHT/2; } gw2.fillRect(wmBorder.getBorderInsets(this).left - (int)prefBoxSize/2 + (int)(alignedPositions[first]/scalefactor), wmBorder.getBorderInsets(this).top+voffset+WM_BD_GAP, (int)(prefBoxSize + (alignedPositions[last] - alignedPositions[first])/scalefactor), WM_BD_HEIGHT/2); even = !even; } wmResizeCorner = new Rectangle(visRect.x + worldmap.getWidth() - (worldmap.getWidth()-wmInteriorRect.width)/2, visRect.y + visRect.height - worldmap.getHeight(), (worldmap.getWidth()-wmInteriorRect.width)/2, (worldmap.getHeight() -wmInteriorRect.height)/2); g2.drawImage(worldmap,visRect.x, visRect.y + visRect.height - worldmap.getHeight(), this); wmInteriorRect.x = visRect.x + (worldmap.getWidth() - wmInteriorRect.width)/2; wmInteriorRect.y = visRect.y+visRect.height-worldmap.getHeight() + (worldmap.getHeight() - wmInteriorRect.height)/2; //draw the outline of the viewport g2.setColor(Color.black); double hRatio = wmInteriorRect.getWidth()/pref.getWidth(); double vRatio = wmInteriorRect.getHeight()/pref.getHeight(); int hBump = worldmap.getWidth()-wmInteriorRect.width; int vBump = worldmap.getHeight()-wmInteriorRect.height; //bump a few pixels to avoid drawing on the border g2.drawRect((int)(visRect.x*hRatio)+hBump/2+visRect.x, (int)(visRect.y*vRatio)+vBump/2+(visRect.y + visRect.height - worldmap.getHeight()), (int)(visRect.width*hRatio), (int)(visRect.height*vRatio)); } //see if the user has right-clicked to popup some marker info if(popupDrawRect != null){ //dumb bug where little datasets popup the box in the wrong place int smallDatasetSlopH = 0; int smallDatasetSlopV = 0; if (pref.getHeight() < visRect.height){ smallDatasetSlopV = (int)(visRect.height - pref.getHeight())/2; } if (pref.getWidth() < visRect.width){ smallDatasetSlopH = (int)(visRect.width - pref.getWidth())/2; } g2.setColor(Color.white); g2.fillRect(popupDrawRect.x+1-smallDatasetSlopH, popupDrawRect.y+1-smallDatasetSlopV, popupDrawRect.width-1, popupDrawRect.height-1); g2.setColor(Color.black); g2.drawRect(popupDrawRect.x-smallDatasetSlopH, popupDrawRect.y-smallDatasetSlopV, popupDrawRect.width, popupDrawRect.height); g.setFont(popupFont); for (int x = 0; x < displayStrings.size(); x++){ g.drawString((String)displayStrings.elementAt(x),popupDrawRect.x + popupLeftMargin-smallDatasetSlopH, popupDrawRect.y+((x+1)*metrics.getHeight())-smallDatasetSlopV); } } // draw the cached last right-click selection // The purpose of testing for empty string is just to avoid an 2-unit empty white box if ((zoomLevel == 0) && (!lastSelection.equals("")) && (!forExport)) { g2.setFont(boxFont); // a bit extra on all side int last_descent = g2.getFontMetrics().getDescent(); int last_box_x = (visRect.x + LAST_SELECTION_LEFT) - 2; int last_box_y = (visRect.y - g2.getFontMetrics().getHeight() + LAST_SELECTION_TOP + last_descent) - 1 ; int last_box_width = g2.getFontMetrics().stringWidth(lastSelection) + 4; int last_box_height = g2.getFontMetrics().getHeight() + 2; g2.setColor(Color.white); g2.fillRect(last_box_x, last_box_y, last_box_width, last_box_height); g2.setColor(Color.black); g2.drawRect(last_box_x, last_box_y, last_box_width, last_box_height); g2.drawString(lastSelection, LAST_SELECTION_LEFT + visRect.x, LAST_SELECTION_TOP + visRect.y); } //see if we're drawing a worldmap resize rect if (resizeWMRect != null){ g2.setColor(Color.black); g2.drawRect(resizeWMRect.x, resizeWMRect.y, resizeWMRect.width, resizeWMRect.height); } //see if we're drawing a block selector rect if (blockRect != null){ g2.setColor(Color.black); g2.setStroke(dashedThinStroke); g2.drawRect(blockRect.x, blockRect.y, blockRect.width, blockRect.height); } }
1,111,090
public void testFieldModification() { view1.setField( "View1" ); // Generate a bbogus event to demonstrate that this should propagate to view2 but not to view1 fieldCtrl.setValue( view1, "View2" ); assertEquals( "View2 not changed by updating view1", "View2", view2.getField() ); assertEquals( "View1 should not be changed", "View1", view1.getField() ); }
public void testFieldModification() { view1.setField( "View1" ); // Generate a bbogus event to demonstrate that this should propagate to view2 but not to view1 fieldCtrl.viewChanged( view1, "View2" ); assertEquals( "View2 not changed by updating view1", "View2", view2.getField() ); assertEquals( "View1 should not be changed", "View1", view1.getField() ); }
1,111,092
public final String draw(DashboardContext context) { String applicationId = context.getWebContext().getApplicationConfig().getApplicationId(); StringBuffer output = new StringBuffer(); if(event != null){ output.append("<script>"); output.append("addEventHandler(''" + event.source + "'', ''" + event.name + "'', ''" + getId() + "'', ''" + event.dataVariable + "'', ''" + applicationId + "'')"); output.append("</script>"); } // wrap wih div tag output.append("<div id=\"" + getId() + "\">"); try{ properties.context = context; if(!properties.hasUnresolvedVariable()) drawInternal(context, output); }finally{ properties.context = null; } output.append("</div>"); return output.toString(); }
public final String draw(DashboardContext context) { String applicationId = context.getWebContext().getApplicationConfig().getApplicationId(); StringBuffer output = new StringBuffer(); if(event != null){ output.append("<script>"); output.append("addEventHandler(''" + event.source + "'', ''" + event.name + "'', ''" + getId() + "'', ''" + event.dataVariable + "'', ''" + applicationId + "'')"); output.append("</script>"); } // wrap wih div tag if(!context.isRefreshRequest()){ output.append("<div id=\"" + getId() + "\">"); } try{ properties.context = context; if(!properties.hasUnresolvedVariable()) drawInternal(context, output); }finally{ properties.context = null; } output.append("</div>"); return output.toString(); }
1,111,093
public final String draw(DashboardContext context) { String applicationId = context.getWebContext().getApplicationConfig().getApplicationId(); StringBuffer output = new StringBuffer(); if(event != null){ output.append("<script>"); output.append("addEventHandler(''" + event.source + "'', ''" + event.name + "'', ''" + getId() + "'', ''" + event.dataVariable + "'', ''" + applicationId + "'')"); output.append("</script>"); } // wrap wih div tag output.append("<div id=\"" + getId() + "\">"); try{ properties.context = context; if(!properties.hasUnresolvedVariable()) drawInternal(context, output); }finally{ properties.context = null; } output.append("</div>"); return output.toString(); }
public final String draw(DashboardContext context) { String applicationId = context.getWebContext().getApplicationConfig().getApplicationId(); StringBuffer output = new StringBuffer(); if(event != null){ output.append("<script>"); output.append("addEventHandler(''" + event.source + "'', ''" + event.name + "'', ''" + getId() + "'', ''" + event.dataVariable + "'', ''" + applicationId + "'')"); output.append("</script>"); } // wrap wih div tag output.append("<div id=\"" + getId() + "\">"); try{ properties.context = context; if(!properties.hasUnresolvedVariable()) drawInternal(context, output); }finally{ properties.context = null; } if(!context.isRefreshRequest()){ output.append("</div>"); } return output.toString(); }
1,111,094
public void doTag(XMLOutput output) throws MissingAttributeException, JellyTagException { if (var == null) { throw new MissingAttributeException( "var" ); } if (select == null) { throw new MissingAttributeException( "select" ); } Object xpathContext = getXPathContext(); Object value = null; try { if(single!=null && single.booleanValue()==true) { value = select.selectSingleNode(xpathContext); } else { value = select.evaluate(xpathContext); } } catch (JaxenException e) { throw new JellyTagException(e); } if (value instanceof List) { // sort the list if xpCmp is set. if (xpCmp != null && (xpCmp.getXpath() != null)) { Collections.sort((List)value, xpCmp); } } if (single!=null) { if (single.booleanValue()==true) { if(value instanceof List) { List l = (List) value; if (l.size()==0) value=null; else value=l.get(0); } if(asString!=null && asString.booleanValue() && value instanceof Node) value = ((Node) value).getStringValue(); } else { // single == false if(! (value instanceof List) ) { List l = null; if (value==null) { l = new ArrayList(0); } else { l = new ArrayList(1); l.add(value); } value = l; } } } //log.info( "Evaluated xpath: " + select + " as: " + value + " of type: " + value.getClass().getName() ); context.setVariable(var, value); }
public void doTag(XMLOutput output) throws MissingAttributeException, JellyTagException { if (var == null) { throw new MissingAttributeException( "var" ); } if (select == null) { throw new MissingAttributeException( "select" ); } Object xpathContext = getXPathContext(); Object value = null; try { if(single!=null && single.booleanValue()==true) { value = select.selectSingleNode(xpathContext); } else { value = select.evaluate(xpathContext); } } catch (JaxenException e) { throw new JellyTagException(e); } if (value instanceof List) { // sort the list if xpCmp is set. if (xpCmp != null && (xpCmp.getXpath() != null)) { Collections.sort((List)value, xpCmp); } } if (single!=null) { if (single.booleanValue()==true) { if(value instanceof List) { List l = (List) value; if (l.size()==0) value=null; else value=l.get(0); } if(asString!=null && asString.booleanValue() && value instanceof Node) value = ((Node) value).getStringValue(); } else { // single == false if(! (value instanceof List) ) { List l = null; if (value==null) { l = new ArrayList(0); } else { l = new ArrayList(1); l.add(value); } value = l; } } } //log.info( "Evaluated xpath: " + select + " as: " + value + " of type: " + value.getClass().getName() ); context.setVariable(var, value); }
1,111,095
public void setAsString(boolean asString) { if(asString) this.single = new Boolean(asString); this.asString = new Boolean(asString); }
public void setAsString(boolean asString) { if(asString) this.single = new Boolean(asString); this.asString = new Boolean(asString); }
1,111,096
public TagLibrary getTagLibrary(String namespaceURI) { Object answer = null; if ( getInherit() && getParent() != null ) { answer = getParent().getTagLibrary( namespaceURI ); } if ( answer == null ) { answer = taglibs.get(namespaceURI); } if ( answer instanceof TagLibrary ) { return (TagLibrary) answer; } else if ( answer instanceof String ) { String className = (String) answer; Class theClass = null; try { theClass = getClassLoader().loadClass(className); } catch (ClassNotFoundException e) { log.error("Could not find the class: " + className, e); } if ( theClass != null ) { try { Object object = theClass.newInstance(); if (object instanceof TagLibrary) { taglibs.put(namespaceURI, object); return (TagLibrary) object; } else { log.error( "The tag library object mapped to: " + namespaceURI + " is not a TagLibrary. Object = " + object); } } catch (Exception e) { log.error( "Could not instantiate instance of class: " + className + ". Reason: " + e, e); } } } return null; }
public TagLibrary getTagLibrary(String namespaceURI) { Object answer = taglibs.get(namespaceURI); if ( getInherit() && getParent() != null ) { answer = getParent().getTagLibrary( namespaceURI ); } if ( answer == null ) { answer = taglibs.get(namespaceURI); } if ( answer instanceof TagLibrary ) { return (TagLibrary) answer; } else if ( answer instanceof String ) { String className = (String) answer; Class theClass = null; try { theClass = getClassLoader().loadClass(className); } catch (ClassNotFoundException e) { log.error("Could not find the class: " + className, e); } if ( theClass != null ) { try { Object object = theClass.newInstance(); if (object instanceof TagLibrary) { taglibs.put(namespaceURI, object); return (TagLibrary) object; } else { log.error( "The tag library object mapped to: " + namespaceURI + " is not a TagLibrary. Object = " + object); } } catch (Exception e) { log.error( "Could not instantiate instance of class: " + className + ". Reason: " + e, e); } } } return null; }
1,111,097
public TagLibrary getTagLibrary(String namespaceURI) { Object answer = null; if ( getInherit() && getParent() != null ) { answer = getParent().getTagLibrary( namespaceURI ); } if ( answer == null ) { answer = taglibs.get(namespaceURI); } if ( answer instanceof TagLibrary ) { return (TagLibrary) answer; } else if ( answer instanceof String ) { String className = (String) answer; Class theClass = null; try { theClass = getClassLoader().loadClass(className); } catch (ClassNotFoundException e) { log.error("Could not find the class: " + className, e); } if ( theClass != null ) { try { Object object = theClass.newInstance(); if (object instanceof TagLibrary) { taglibs.put(namespaceURI, object); return (TagLibrary) object; } else { log.error( "The tag library object mapped to: " + namespaceURI + " is not a TagLibrary. Object = " + object); } } catch (Exception e) { log.error( "Could not instantiate instance of class: " + className + ". Reason: " + e, e); } } } return null; }
public TagLibrary getTagLibrary(String namespaceURI) { Object answer = null; if ( getInherit() && getParent() != null ) { answer = getParent().getTagLibrary( namespaceURI ); } if ( answer == null ) { answer = taglibs.get(namespaceURI); } if ( answer instanceof TagLibrary ) { return (TagLibrary) answer; } else if ( answer instanceof String ) { String className = (String) answer; Class theClass = null; try { theClass = getClassLoader().loadClass(className); } catch (ClassNotFoundException e) { log.error("Could not find the class: " + className, e); } if ( theClass != null ) { try { Object object = theClass.newInstance(); if (object instanceof TagLibrary) { taglibs.put(namespaceURI, object); return (TagLibrary) object; } else { log.error( "The tag library object mapped to: " + namespaceURI + " is not a TagLibrary. Object = " + object); } } catch (Exception e) { log.error( "Could not instantiate instance of class: " + className + ". Reason: " + e, e); } } } return null; }
1,111,098
public boolean isTagLibraryRegistered(String namespaceURI) { return taglibs.containsKey( namespaceURI ); }
public boolean isTagLibraryRegistered(String namespaceURI) { boolean answer = taglibs.containsKey( namespaceURI ); if (answer) { return true; } else if ( parent != null ) { return parent.isTagLibraryRegistered(namespaceURI); } else { return false; } }
1,111,099
public void doTag(XMLOutput output) throws Exception { tagLibrary = new DynamicTagLibrary( getUri() ); context.registerTagLibrary( getUri(), tagLibrary ); getBody().run(context, output); tagLibrary = null; }
public void doTag(XMLOutput output) throws Exception { tagLibrary = new DynamicTagLibrary( getUri() ); context.registerTagLibrary( getUri(), tagLibrary ); invokeBody(output); tagLibrary = null; }
1,111,100
public void run(Context context, XMLOutput output) throws Exception { if ( log.isDebugEnabled() ) { log.debug( "running with items: " + items ); } if ( items != null ) { Iterator iter = items.evaluateAsIterator( context ); if ( log.isDebugEnabled() ) { log.debug( "Iterating through: " + iter ); } for ( index = begin; iter.hasNext() && index < end; index += step ) { Object value = iter.next(); if (var != null) { context.setVariable( var, value ); } if ( indexVar != null ) { context.setVariable( indexVar, new Integer(index) ); } getBody().run( context, output ); } } }
public void run(Context context, XMLOutput output) throws Exception { if ( log.isDebugEnabled() ) { log.debug( "running with items: " + items ); } if ( items != null ) { Iterator iter = items.evaluateAsIterator( context ); if ( log.isDebugEnabled() ) { log.debug( "Iterating through: " + iter ); } for ( index = begin; iter.hasNext() && index < end; index += step ) { Object value = iter.next(); if (var != null) { context.setVariable( var, value ); } if ( indexVar != null ) { context.setVariable( indexVar, new Integer(index) ); } getBody().run( context, output ); } } }
1,111,101
private List parse(String attributes){ List exprList = new LinkedList(); StringTokenizer tokenizer = new StringTokenizer(attributes, ","); while(tokenizer.hasMoreTokens()){ String expression = tokenizer.nextToken(); assert expression.startsWith("["); while(!expression.endsWith("]")){ assert tokenizer.hasMoreTokens(); expression += tokenizer.nextToken(); } expression = expression.substring(1, expression.length()-1); exprList.add(new Expression(expression)); } return exprList; }
private List parse(String attributes){ List exprList = new LinkedList(); StringTokenizer tokenizer = new StringTokenizer(attributes, ","); while(tokenizer.hasMoreTokens()){ String expression = tokenizer.nextToken(); assert expression.startsWith("["); while(!expression.endsWith("]")){ assert tokenizer.hasMoreTokens(); expression += "," + tokenizer.nextToken(); } expression = expression.substring(1, expression.length()-1); exprList.add(new Expression(expression)); } return exprList; }
1,111,102
public void doTag(XMLOutput xmlOutput) throws JellyTagException { if (isProxyAvailable()) { _httpClient = new HttpClient(); _httpClient.getHostConfiguration().setProxy(getProxyHost(), getProxyPort()); } else { _httpClient = new HttpClient(); } invokeBody(xmlOutput); }
public void doTag(XMLOutput xmlOutput) throws JellyTagException { if (isProxyAvailable()) { _httpClient.getHostConfiguration().setProxy(getProxyHost(), getProxyPort()); } else { } invokeBody(xmlOutput); }
1,111,103
public void doTag(XMLOutput xmlOutput) throws JellyTagException { if (isProxyAvailable()) { _httpClient = new HttpClient(); _httpClient.getHostConfiguration().setProxy(getProxyHost(), getProxyPort()); } else { _httpClient = new HttpClient(); } invokeBody(xmlOutput); }
public void doTag(XMLOutput xmlOutput) throws JellyTagException { if (isProxyAvailable()) { _httpClient = new HttpClient(); _httpClient.getHostConfiguration().setProxy(getProxyHost(), getProxyPort()); } else { _httpClient = new HttpClient(); } invokeBody(xmlOutput); }
1,111,104
public void writeCreateDB(SQLDatabase db) { out.println("-- Would Create Database "+db.getName()+" here. --"); }
public void writeCreateDB(SQLDatabase db) { println("-- Would Create Database "+db.getName()+" here. --"); }
1,111,105
protected void writeExportedRelationships(SQLTable t) throws ArchitectException { Iterator it = t.getExportedKeys().iterator(); while (it.hasNext()) { SQLRelationship rel = (SQLRelationship) it.next(); out.println(""); out.println("ALTER TABLE "+rel.getFkTable().getName() +" ADD CONSTRAINT "+rel.getName()); out.print("FOREIGN KEY ("); StringBuffer pkCols = new StringBuffer(); StringBuffer fkCols = new StringBuffer(); boolean firstCol = true; Iterator mappings = rel.getChildren().iterator(); while (mappings.hasNext()) { SQLRelationship.ColumnMapping cmap = (SQLRelationship.ColumnMapping) mappings.next(); if (!firstCol) { pkCols.append(", "); fkCols.append(", "); } pkCols.append(cmap.getPkColumn().getName()); fkCols.append(cmap.getFkColumn().getName()); firstCol = false; } out.print(fkCols.toString()); out.println(")"); out.print("REFERENCES "+rel.getPkTable().getName()+" ("); out.print(pkCols.toString()); out.print(")"); writeStatementTerminator(); out.println(""); } }
protected void writeExportedRelationships(SQLTable t) throws ArchitectException { Iterator it = t.getExportedKeys().iterator(); while (it.hasNext()) { SQLRelationship rel = (SQLRelationship) it.next(); out.println(""); out.println("ALTER TABLE "+rel.getFkTable().getName() +" ADD CONSTRAINT "+rel.getName()); out.print("FOREIGN KEY ("); StringBuffer pkCols = new StringBuffer(); StringBuffer fkCols = new StringBuffer(); boolean firstCol = true; Iterator mappings = rel.getChildren().iterator(); while (mappings.hasNext()) { SQLRelationship.ColumnMapping cmap = (SQLRelationship.ColumnMapping) mappings.next(); if (!firstCol) { pkCols.append(", "); fkCols.append(", "); } pkCols.append(cmap.getPkColumn().getName()); fkCols.append(cmap.getFkColumn().getName()); firstCol = false; } out.print(fkCols.toString()); out.println(")"); out.print("REFERENCES "+rel.getPkTable().getName()+" ("); out.print(pkCols.toString()); out.print(")"); writeStatementTerminator(); out.println(""); } }
1,111,106
protected void writeExportedRelationships(SQLTable t) throws ArchitectException { Iterator it = t.getExportedKeys().iterator(); while (it.hasNext()) { SQLRelationship rel = (SQLRelationship) it.next(); out.println(""); out.println("ALTER TABLE "+rel.getFkTable().getName() +" ADD CONSTRAINT "+rel.getName()); out.print("FOREIGN KEY ("); StringBuffer pkCols = new StringBuffer(); StringBuffer fkCols = new StringBuffer(); boolean firstCol = true; Iterator mappings = rel.getChildren().iterator(); while (mappings.hasNext()) { SQLRelationship.ColumnMapping cmap = (SQLRelationship.ColumnMapping) mappings.next(); if (!firstCol) { pkCols.append(", "); fkCols.append(", "); } pkCols.append(cmap.getPkColumn().getName()); fkCols.append(cmap.getFkColumn().getName()); firstCol = false; } out.print(fkCols.toString()); out.println(")"); out.print("REFERENCES "+rel.getPkTable().getName()+" ("); out.print(pkCols.toString()); out.print(")"); writeStatementTerminator(); out.println(""); } }
protected void writeExportedRelationships(SQLTable t) throws ArchitectException { Iterator it = t.getExportedKeys().iterator(); while (it.hasNext()) { SQLRelationship rel = (SQLRelationship) it.next(); out.println(""); out.println("ALTER TABLE "+rel.getFkTable().getName() +" ADD CONSTRAINT "+rel.getName()); print("FOREIGN KEY ("); StringBuffer pkCols = new StringBuffer(); StringBuffer fkCols = new StringBuffer(); boolean firstCol = true; Iterator mappings = rel.getChildren().iterator(); while (mappings.hasNext()) { SQLRelationship.ColumnMapping cmap = (SQLRelationship.ColumnMapping) mappings.next(); if (!firstCol) { pkCols.append(", "); fkCols.append(", "); } pkCols.append(cmap.getPkColumn().getName()); fkCols.append(cmap.getFkColumn().getName()); firstCol = false; } out.print(fkCols.toString()); out.println(")"); out.print("REFERENCES "+rel.getPkTable().getName()+" ("); out.print(pkCols.toString()); out.print(")"); writeStatementTerminator(); out.println(""); } }
1,111,107
protected void writeExportedRelationships(SQLTable t) throws ArchitectException { Iterator it = t.getExportedKeys().iterator(); while (it.hasNext()) { SQLRelationship rel = (SQLRelationship) it.next(); out.println(""); out.println("ALTER TABLE "+rel.getFkTable().getName() +" ADD CONSTRAINT "+rel.getName()); out.print("FOREIGN KEY ("); StringBuffer pkCols = new StringBuffer(); StringBuffer fkCols = new StringBuffer(); boolean firstCol = true; Iterator mappings = rel.getChildren().iterator(); while (mappings.hasNext()) { SQLRelationship.ColumnMapping cmap = (SQLRelationship.ColumnMapping) mappings.next(); if (!firstCol) { pkCols.append(", "); fkCols.append(", "); } pkCols.append(cmap.getPkColumn().getName()); fkCols.append(cmap.getFkColumn().getName()); firstCol = false; } out.print(fkCols.toString()); out.println(")"); out.print("REFERENCES "+rel.getPkTable().getName()+" ("); out.print(pkCols.toString()); out.print(")"); writeStatementTerminator(); out.println(""); } }
protected void writeExportedRelationships(SQLTable t) throws ArchitectException { Iterator it = t.getExportedKeys().iterator(); while (it.hasNext()) { SQLRelationship rel = (SQLRelationship) it.next(); out.println(""); out.println("ALTER TABLE "+rel.getFkTable().getName() +" ADD CONSTRAINT "+rel.getName()); out.print("FOREIGN KEY ("); StringBuffer pkCols = new StringBuffer(); StringBuffer fkCols = new StringBuffer(); boolean firstCol = true; Iterator mappings = rel.getChildren().iterator(); while (mappings.hasNext()) { SQLRelationship.ColumnMapping cmap = (SQLRelationship.ColumnMapping) mappings.next(); if (!firstCol) { pkCols.append(", "); fkCols.append(", "); } pkCols.append(cmap.getPkColumn().getName()); fkCols.append(cmap.getFkColumn().getName()); firstCol = false; } out.print(fkCols.toString()); out.println(")"); out.print("REFERENCES "+rel.getPkTable().getName()+" ("); out.print(pkCols.toString()); out.print(")"); writeStatementTerminator(); out.println(""); } }
1,111,108
protected void writeExportedRelationships(SQLTable t) throws ArchitectException { Iterator it = t.getExportedKeys().iterator(); while (it.hasNext()) { SQLRelationship rel = (SQLRelationship) it.next(); out.println(""); out.println("ALTER TABLE "+rel.getFkTable().getName() +" ADD CONSTRAINT "+rel.getName()); out.print("FOREIGN KEY ("); StringBuffer pkCols = new StringBuffer(); StringBuffer fkCols = new StringBuffer(); boolean firstCol = true; Iterator mappings = rel.getChildren().iterator(); while (mappings.hasNext()) { SQLRelationship.ColumnMapping cmap = (SQLRelationship.ColumnMapping) mappings.next(); if (!firstCol) { pkCols.append(", "); fkCols.append(", "); } pkCols.append(cmap.getPkColumn().getName()); fkCols.append(cmap.getFkColumn().getName()); firstCol = false; } out.print(fkCols.toString()); out.println(")"); out.print("REFERENCES "+rel.getPkTable().getName()+" ("); out.print(pkCols.toString()); out.print(")"); writeStatementTerminator(); out.println(""); } }
protected void writeExportedRelationships(SQLTable t) throws ArchitectException { Iterator it = t.getExportedKeys().iterator(); while (it.hasNext()) { SQLRelationship rel = (SQLRelationship) it.next(); println(""); out.println("ALTER TABLE "+rel.getFkTable().getName() +" ADD CONSTRAINT "+rel.getName()); out.print("FOREIGN KEY ("); StringBuffer pkCols = new StringBuffer(); StringBuffer fkCols = new StringBuffer(); boolean firstCol = true; Iterator mappings = rel.getChildren().iterator(); while (mappings.hasNext()) { SQLRelationship.ColumnMapping cmap = (SQLRelationship.ColumnMapping) mappings.next(); if (!firstCol) { pkCols.append(", "); fkCols.append(", "); } pkCols.append(cmap.getPkColumn().getName()); fkCols.append(cmap.getFkColumn().getName()); firstCol = false; } out.print(fkCols.toString()); out.println(")"); out.print("REFERENCES "+rel.getPkTable().getName()+" ("); out.print(pkCols.toString()); out.print(")"); writeStatementTerminator(); println(""); } }
1,111,109
public void writeHeader() { out.println("-- Created by SQLPower Generic DDL Generator "+GENERATOR_VERSION+" --"); }
public void writeHeader() { println("-- Created by SQLPower Generic DDL Generator "+GENERATOR_VERSION+" --"); }
1,111,110
protected void writePrimaryKey(SQLTable t) throws ArchitectException { boolean firstCol = true; Iterator it = t.getColumns().iterator(); while (it.hasNext()) { SQLColumn col = (SQLColumn) it.next(); if (col.getPrimaryKeySeq() == null) break; if (firstCol) { out.println(""); out.println("ALTER TABLE "+t.getName() +" ADD CONSTRAINT "+t.getPrimaryKeyName()); out.print("PRIMARY KEY ("); firstCol = false; } else { out.print(", "); } out.print(col.getName()); } out.print(")"); writeStatementTerminator(); out.println(""); }
protected void writePrimaryKey(SQLTable t) throws ArchitectException { boolean firstCol = true; Iterator it = t.getColumns().iterator(); while (it.hasNext()) { SQLColumn col = (SQLColumn) it.next(); if (col.getPrimaryKeySeq() == null) break; if (firstCol) { out.println(""); out.println("ALTER TABLE "+t.getName() +" ADD CONSTRAINT "+t.getPrimaryKeyName()); out.print("PRIMARY KEY ("); firstCol = false; } else { out.print(", "); } out.print(col.getName()); } out.print(")"); writeStatementTerminator(); out.println(""); }
1,111,111
protected void writePrimaryKey(SQLTable t) throws ArchitectException { boolean firstCol = true; Iterator it = t.getColumns().iterator(); while (it.hasNext()) { SQLColumn col = (SQLColumn) it.next(); if (col.getPrimaryKeySeq() == null) break; if (firstCol) { out.println(""); out.println("ALTER TABLE "+t.getName() +" ADD CONSTRAINT "+t.getPrimaryKeyName()); out.print("PRIMARY KEY ("); firstCol = false; } else { out.print(", "); } out.print(col.getName()); } out.print(")"); writeStatementTerminator(); out.println(""); }
protected void writePrimaryKey(SQLTable t) throws ArchitectException { boolean firstCol = true; Iterator it = t.getColumns().iterator(); while (it.hasNext()) { SQLColumn col = (SQLColumn) it.next(); if (col.getPrimaryKeySeq() == null) break; if (firstCol) { out.println(""); out.println("ALTER TABLE "+t.getName() +" ADD CONSTRAINT "+t.getPrimaryKeyName()); print("PRIMARY KEY ("); firstCol = false; } else { out.print(", "); } out.print(col.getName()); } out.print(")"); writeStatementTerminator(); out.println(""); }
1,111,112
protected void writePrimaryKey(SQLTable t) throws ArchitectException { boolean firstCol = true; Iterator it = t.getColumns().iterator(); while (it.hasNext()) { SQLColumn col = (SQLColumn) it.next(); if (col.getPrimaryKeySeq() == null) break; if (firstCol) { out.println(""); out.println("ALTER TABLE "+t.getName() +" ADD CONSTRAINT "+t.getPrimaryKeyName()); out.print("PRIMARY KEY ("); firstCol = false; } else { out.print(", "); } out.print(col.getName()); } out.print(")"); writeStatementTerminator(); out.println(""); }
protected void writePrimaryKey(SQLTable t) throws ArchitectException { boolean firstCol = true; Iterator it = t.getColumns().iterator(); while (it.hasNext()) { SQLColumn col = (SQLColumn) it.next(); if (col.getPrimaryKeySeq() == null) break; if (firstCol) { out.println(""); out.println("ALTER TABLE "+t.getName() +" ADD CONSTRAINT "+t.getPrimaryKeyName()); out.print("PRIMARY KEY ("); firstCol = false; } else { print(", "); } out.print(col.getName()); } out.print(")"); writeStatementTerminator(); out.println(""); }
1,111,113
protected void writePrimaryKey(SQLTable t) throws ArchitectException { boolean firstCol = true; Iterator it = t.getColumns().iterator(); while (it.hasNext()) { SQLColumn col = (SQLColumn) it.next(); if (col.getPrimaryKeySeq() == null) break; if (firstCol) { out.println(""); out.println("ALTER TABLE "+t.getName() +" ADD CONSTRAINT "+t.getPrimaryKeyName()); out.print("PRIMARY KEY ("); firstCol = false; } else { out.print(", "); } out.print(col.getName()); } out.print(")"); writeStatementTerminator(); out.println(""); }
protected void writePrimaryKey(SQLTable t) throws ArchitectException { boolean firstCol = true; Iterator it = t.getColumns().iterator(); while (it.hasNext()) { SQLColumn col = (SQLColumn) it.next(); if (col.getPrimaryKeySeq() == null) break; if (firstCol) { out.println(""); out.println("ALTER TABLE "+t.getName() +" ADD CONSTRAINT "+t.getPrimaryKeyName()); out.print("PRIMARY KEY ("); firstCol = false; } else { out.print(", "); } print(col.getName()); } out.print(")"); writeStatementTerminator(); out.println(""); }
1,111,114
protected void writePrimaryKey(SQLTable t) throws ArchitectException { boolean firstCol = true; Iterator it = t.getColumns().iterator(); while (it.hasNext()) { SQLColumn col = (SQLColumn) it.next(); if (col.getPrimaryKeySeq() == null) break; if (firstCol) { out.println(""); out.println("ALTER TABLE "+t.getName() +" ADD CONSTRAINT "+t.getPrimaryKeyName()); out.print("PRIMARY KEY ("); firstCol = false; } else { out.print(", "); } out.print(col.getName()); } out.print(")"); writeStatementTerminator(); out.println(""); }
protected void writePrimaryKey(SQLTable t) throws ArchitectException { boolean firstCol = true; Iterator it = t.getColumns().iterator(); while (it.hasNext()) { SQLColumn col = (SQLColumn) it.next(); if (col.getPrimaryKeySeq() == null) break; if (firstCol) { out.println(""); out.println("ALTER TABLE "+t.getName() +" ADD CONSTRAINT "+t.getPrimaryKeyName()); out.print("PRIMARY KEY ("); firstCol = false; } else { out.print(", "); } out.print(col.getName()); } print(")"); writeStatementTerminator(); out.println(""); }
1,111,115
protected void writePrimaryKey(SQLTable t) throws ArchitectException { boolean firstCol = true; Iterator it = t.getColumns().iterator(); while (it.hasNext()) { SQLColumn col = (SQLColumn) it.next(); if (col.getPrimaryKeySeq() == null) break; if (firstCol) { out.println(""); out.println("ALTER TABLE "+t.getName() +" ADD CONSTRAINT "+t.getPrimaryKeyName()); out.print("PRIMARY KEY ("); firstCol = false; } else { out.print(", "); } out.print(col.getName()); } out.print(")"); writeStatementTerminator(); out.println(""); }
protected void writePrimaryKey(SQLTable t) throws ArchitectException { boolean firstCol = true; Iterator it = t.getColumns().iterator(); while (it.hasNext()) { SQLColumn col = (SQLColumn) it.next(); if (col.getPrimaryKeySeq() == null) break; if (firstCol) { println(""); out.println("ALTER TABLE "+t.getName() +" ADD CONSTRAINT "+t.getPrimaryKeyName()); out.print("PRIMARY KEY ("); firstCol = false; } else { out.print(", "); } out.print(col.getName()); } out.print(")"); writeStatementTerminator(); println(""); }
1,111,116
public void writeStatementTerminator() { out.print(";"); }
public void writeStatementTerminator() { print(";"); }
1,111,117
public void writeTable(SQLTable t) throws SQLException, IOException, ArchitectException { out.println("\nCREATE TABLE "+t.getName()+" ("); boolean firstCol = true; Iterator it = t.getColumns().iterator(); while (it.hasNext()) { SQLColumn c = (SQLColumn) it.next(); GenericTypeDescriptor td = (GenericTypeDescriptor) typeMap.get(new Integer(c.getType())); if (td == null) { throw new UnsupportedOperationException ("No type for "+c.getType()+" is available in the target database platform." +"\nPlease choose a different type."); } if (!firstCol) out.println(","); out.print(" "); out.print(c.getName()); out.print(" "); out.print(td.getName()); if (td.getHasScale()) { out.print("("+c.getScale()); if (td.getHasPrecision()) { out.print(","+c.getPrecision()); } out.print(")"); } if (c.isNullable()) { if (! td.isNullable()) { throw new UnsupportedOperationException ("The data type "+td.getName()+" is not nullable on the target database platform."); } out.print(" NULL"); } else { out.print(" NOT NULL"); } // XXX: default values? firstCol = false; } out.println(); out.print(")"); writeStatementTerminator(); out.println(""); }
public void writeTable(SQLTable t) throws SQLException, IOException, ArchitectException { out.println("\nCREATE TABLE "+t.getName()+" ("); boolean firstCol = true; Iterator it = t.getColumns().iterator(); while (it.hasNext()) { SQLColumn c = (SQLColumn) it.next(); GenericTypeDescriptor td = (GenericTypeDescriptor) typeMap.get(new Integer(c.getType())); if (td == null) { throw new UnsupportedOperationException ("No type for "+c.getType()+" is available in the target database platform." +"\nPlease choose a different type."); } if (!firstCol) out.println(","); out.print(" "); out.print(c.getName()); out.print(" "); out.print(td.getName()); if (td.getHasScale()) { out.print("("+c.getScale()); if (td.getHasPrecision()) { out.print(","+c.getPrecision()); } out.print(")"); } if (c.isNullable()) { if (! td.isNullable()) { throw new UnsupportedOperationException ("The data type "+td.getName()+" is not nullable on the target database platform."); } out.print(" NULL"); } else { out.print(" NOT NULL"); } // XXX: default values? firstCol = false; } out.println(); out.print(")"); writeStatementTerminator(); out.println(""); }
1,111,118
public void writeTable(SQLTable t) throws SQLException, IOException, ArchitectException { out.println("\nCREATE TABLE "+t.getName()+" ("); boolean firstCol = true; Iterator it = t.getColumns().iterator(); while (it.hasNext()) { SQLColumn c = (SQLColumn) it.next(); GenericTypeDescriptor td = (GenericTypeDescriptor) typeMap.get(new Integer(c.getType())); if (td == null) { throw new UnsupportedOperationException ("No type for "+c.getType()+" is available in the target database platform." +"\nPlease choose a different type."); } if (!firstCol) out.println(","); out.print(" "); out.print(c.getName()); out.print(" "); out.print(td.getName()); if (td.getHasScale()) { out.print("("+c.getScale()); if (td.getHasPrecision()) { out.print(","+c.getPrecision()); } out.print(")"); } if (c.isNullable()) { if (! td.isNullable()) { throw new UnsupportedOperationException ("The data type "+td.getName()+" is not nullable on the target database platform."); } out.print(" NULL"); } else { out.print(" NOT NULL"); } // XXX: default values? firstCol = false; } out.println(); out.print(")"); writeStatementTerminator(); out.println(""); }
public void writeTable(SQLTable t) throws SQLException, IOException, ArchitectException { out.println("\nCREATE TABLE "+t.getName()+" ("); boolean firstCol = true; Iterator it = t.getColumns().iterator(); while (it.hasNext()) { SQLColumn c = (SQLColumn) it.next(); GenericTypeDescriptor td = (GenericTypeDescriptor) typeMap.get(new Integer(c.getType())); if (td == null) { throw new UnsupportedOperationException ("No type for "+c.getType()+" is available in the target database platform." +"\nPlease choose a different type."); } if (!firstCol) out.println(","); out.print(" "); out.print(c.getName()); out.print(" "); out.print(td.getName()); if (td.getHasScale()) { out.print("("+c.getScale()); if (td.getHasPrecision()) { out.print(","+c.getPrecision()); } out.print(")"); } if (c.isNullable()) { if (! td.isNullable()) { throw new UnsupportedOperationException ("The data type "+td.getName()+" is not nullable on the target database platform."); } out.print(" NULL"); } else { out.print(" NOT NULL"); } // XXX: default values? firstCol = false; } out.println(); out.print(")"); writeStatementTerminator(); out.println(""); }
1,111,119
public void writeTable(SQLTable t) throws SQLException, IOException, ArchitectException { out.println("\nCREATE TABLE "+t.getName()+" ("); boolean firstCol = true; Iterator it = t.getColumns().iterator(); while (it.hasNext()) { SQLColumn c = (SQLColumn) it.next(); GenericTypeDescriptor td = (GenericTypeDescriptor) typeMap.get(new Integer(c.getType())); if (td == null) { throw new UnsupportedOperationException ("No type for "+c.getType()+" is available in the target database platform." +"\nPlease choose a different type."); } if (!firstCol) out.println(","); out.print(" "); out.print(c.getName()); out.print(" "); out.print(td.getName()); if (td.getHasScale()) { out.print("("+c.getScale()); if (td.getHasPrecision()) { out.print(","+c.getPrecision()); } out.print(")"); } if (c.isNullable()) { if (! td.isNullable()) { throw new UnsupportedOperationException ("The data type "+td.getName()+" is not nullable on the target database platform."); } out.print(" NULL"); } else { out.print(" NOT NULL"); } // XXX: default values? firstCol = false; } out.println(); out.print(")"); writeStatementTerminator(); out.println(""); }
public void writeTable(SQLTable t) throws SQLException, IOException, ArchitectException { out.println("\nCREATE TABLE "+t.getName()+" ("); boolean firstCol = true; Iterator it = t.getColumns().iterator(); while (it.hasNext()) { SQLColumn c = (SQLColumn) it.next(); GenericTypeDescriptor td = (GenericTypeDescriptor) typeMap.get(new Integer(c.getType())); if (td == null) { throw new UnsupportedOperationException ("No type for "+c.getType()+" is available in the target database platform." +"\nPlease choose a different type."); } if (!firstCol) out.println(","); out.print(" "); out.print(c.getName()); out.print(" "); out.print(td.getName()); if (td.getHasScale()) { print("("+c.getScale()); if (td.getHasPrecision()) { out.print(","+c.getPrecision()); } out.print(")"); } if (c.isNullable()) { if (! td.isNullable()) { throw new UnsupportedOperationException ("The data type "+td.getName()+" is not nullable on the target database platform."); } out.print(" NULL"); } else { out.print(" NOT NULL"); } // XXX: default values? firstCol = false; } out.println(); out.print(")"); writeStatementTerminator(); out.println(""); }
1,111,120
public void writeTable(SQLTable t) throws SQLException, IOException, ArchitectException { out.println("\nCREATE TABLE "+t.getName()+" ("); boolean firstCol = true; Iterator it = t.getColumns().iterator(); while (it.hasNext()) { SQLColumn c = (SQLColumn) it.next(); GenericTypeDescriptor td = (GenericTypeDescriptor) typeMap.get(new Integer(c.getType())); if (td == null) { throw new UnsupportedOperationException ("No type for "+c.getType()+" is available in the target database platform." +"\nPlease choose a different type."); } if (!firstCol) out.println(","); out.print(" "); out.print(c.getName()); out.print(" "); out.print(td.getName()); if (td.getHasScale()) { out.print("("+c.getScale()); if (td.getHasPrecision()) { out.print(","+c.getPrecision()); } out.print(")"); } if (c.isNullable()) { if (! td.isNullable()) { throw new UnsupportedOperationException ("The data type "+td.getName()+" is not nullable on the target database platform."); } out.print(" NULL"); } else { out.print(" NOT NULL"); } // XXX: default values? firstCol = false; } out.println(); out.print(")"); writeStatementTerminator(); out.println(""); }
public void writeTable(SQLTable t) throws SQLException, IOException, ArchitectException { out.println("\nCREATE TABLE "+t.getName()+" ("); boolean firstCol = true; Iterator it = t.getColumns().iterator(); while (it.hasNext()) { SQLColumn c = (SQLColumn) it.next(); GenericTypeDescriptor td = (GenericTypeDescriptor) typeMap.get(new Integer(c.getType())); if (td == null) { throw new UnsupportedOperationException ("No type for "+c.getType()+" is available in the target database platform." +"\nPlease choose a different type."); } if (!firstCol) out.println(","); out.print(" "); out.print(c.getName()); out.print(" "); out.print(td.getName()); if (td.getHasScale()) { out.print("("+c.getScale()); if (td.getHasPrecision()) { print(","+c.getPrecision()); } out.print(")"); } if (c.isNullable()) { if (! td.isNullable()) { throw new UnsupportedOperationException ("The data type "+td.getName()+" is not nullable on the target database platform."); } out.print(" NULL"); } else { out.print(" NOT NULL"); } // XXX: default values? firstCol = false; } out.println(); out.print(")"); writeStatementTerminator(); out.println(""); }
1,111,121
public void writeTable(SQLTable t) throws SQLException, IOException, ArchitectException { out.println("\nCREATE TABLE "+t.getName()+" ("); boolean firstCol = true; Iterator it = t.getColumns().iterator(); while (it.hasNext()) { SQLColumn c = (SQLColumn) it.next(); GenericTypeDescriptor td = (GenericTypeDescriptor) typeMap.get(new Integer(c.getType())); if (td == null) { throw new UnsupportedOperationException ("No type for "+c.getType()+" is available in the target database platform." +"\nPlease choose a different type."); } if (!firstCol) out.println(","); out.print(" "); out.print(c.getName()); out.print(" "); out.print(td.getName()); if (td.getHasScale()) { out.print("("+c.getScale()); if (td.getHasPrecision()) { out.print(","+c.getPrecision()); } out.print(")"); } if (c.isNullable()) { if (! td.isNullable()) { throw new UnsupportedOperationException ("The data type "+td.getName()+" is not nullable on the target database platform."); } out.print(" NULL"); } else { out.print(" NOT NULL"); } // XXX: default values? firstCol = false; } out.println(); out.print(")"); writeStatementTerminator(); out.println(""); }
public void writeTable(SQLTable t) throws SQLException, IOException, ArchitectException { out.println("\nCREATE TABLE "+t.getName()+" ("); boolean firstCol = true; Iterator it = t.getColumns().iterator(); while (it.hasNext()) { SQLColumn c = (SQLColumn) it.next(); GenericTypeDescriptor td = (GenericTypeDescriptor) typeMap.get(new Integer(c.getType())); if (td == null) { throw new UnsupportedOperationException ("No type for "+c.getType()+" is available in the target database platform." +"\nPlease choose a different type."); } if (!firstCol) out.println(","); out.print(" "); out.print(c.getName()); out.print(" "); out.print(td.getName()); if (td.getHasScale()) { out.print("("+c.getScale()); if (td.getHasPrecision()) { out.print(","+c.getPrecision()); } print(")"); } if (c.isNullable()) { if (! td.isNullable()) { throw new UnsupportedOperationException ("The data type "+td.getName()+" is not nullable on the target database platform."); } out.print(" NULL"); } else { out.print(" NOT NULL"); } // XXX: default values? firstCol = false; } out.println(); print(")"); writeStatementTerminator(); out.println(""); }
1,111,122
public void writeTable(SQLTable t) throws SQLException, IOException, ArchitectException { out.println("\nCREATE TABLE "+t.getName()+" ("); boolean firstCol = true; Iterator it = t.getColumns().iterator(); while (it.hasNext()) { SQLColumn c = (SQLColumn) it.next(); GenericTypeDescriptor td = (GenericTypeDescriptor) typeMap.get(new Integer(c.getType())); if (td == null) { throw new UnsupportedOperationException ("No type for "+c.getType()+" is available in the target database platform." +"\nPlease choose a different type."); } if (!firstCol) out.println(","); out.print(" "); out.print(c.getName()); out.print(" "); out.print(td.getName()); if (td.getHasScale()) { out.print("("+c.getScale()); if (td.getHasPrecision()) { out.print(","+c.getPrecision()); } out.print(")"); } if (c.isNullable()) { if (! td.isNullable()) { throw new UnsupportedOperationException ("The data type "+td.getName()+" is not nullable on the target database platform."); } out.print(" NULL"); } else { out.print(" NOT NULL"); } // XXX: default values? firstCol = false; } out.println(); out.print(")"); writeStatementTerminator(); out.println(""); }
public void writeTable(SQLTable t) throws SQLException, IOException, ArchitectException { out.println("\nCREATE TABLE "+t.getName()+" ("); boolean firstCol = true; Iterator it = t.getColumns().iterator(); while (it.hasNext()) { SQLColumn c = (SQLColumn) it.next(); GenericTypeDescriptor td = (GenericTypeDescriptor) typeMap.get(new Integer(c.getType())); if (td == null) { throw new UnsupportedOperationException ("No type for "+c.getType()+" is available in the target database platform." +"\nPlease choose a different type."); } if (!firstCol) out.println(","); out.print(" "); out.print(c.getName()); out.print(" "); out.print(td.getName()); if (td.getHasScale()) { out.print("("+c.getScale()); if (td.getHasPrecision()) { out.print(","+c.getPrecision()); } out.print(")"); } if (c.isNullable()) { if (! td.isNullable()) { throw new UnsupportedOperationException ("The data type "+td.getName()+" is not nullable on the target database platform."); } print(" NULL"); } else { out.print(" NOT NULL"); } // XXX: default values? firstCol = false; } out.println(); out.print(")"); writeStatementTerminator(); out.println(""); }
1,111,123
public void writeTable(SQLTable t) throws SQLException, IOException, ArchitectException { out.println("\nCREATE TABLE "+t.getName()+" ("); boolean firstCol = true; Iterator it = t.getColumns().iterator(); while (it.hasNext()) { SQLColumn c = (SQLColumn) it.next(); GenericTypeDescriptor td = (GenericTypeDescriptor) typeMap.get(new Integer(c.getType())); if (td == null) { throw new UnsupportedOperationException ("No type for "+c.getType()+" is available in the target database platform." +"\nPlease choose a different type."); } if (!firstCol) out.println(","); out.print(" "); out.print(c.getName()); out.print(" "); out.print(td.getName()); if (td.getHasScale()) { out.print("("+c.getScale()); if (td.getHasPrecision()) { out.print(","+c.getPrecision()); } out.print(")"); } if (c.isNullable()) { if (! td.isNullable()) { throw new UnsupportedOperationException ("The data type "+td.getName()+" is not nullable on the target database platform."); } out.print(" NULL"); } else { out.print(" NOT NULL"); } // XXX: default values? firstCol = false; } out.println(); out.print(")"); writeStatementTerminator(); out.println(""); }
public void writeTable(SQLTable t) throws SQLException, IOException, ArchitectException { out.println("\nCREATE TABLE "+t.getName()+" ("); boolean firstCol = true; Iterator it = t.getColumns().iterator(); while (it.hasNext()) { SQLColumn c = (SQLColumn) it.next(); GenericTypeDescriptor td = (GenericTypeDescriptor) typeMap.get(new Integer(c.getType())); if (td == null) { throw new UnsupportedOperationException ("No type for "+c.getType()+" is available in the target database platform." +"\nPlease choose a different type."); } if (!firstCol) out.println(","); out.print(" "); out.print(c.getName()); out.print(" "); out.print(td.getName()); if (td.getHasScale()) { out.print("("+c.getScale()); if (td.getHasPrecision()) { out.print(","+c.getPrecision()); } out.print(")"); } if (c.isNullable()) { if (! td.isNullable()) { throw new UnsupportedOperationException ("The data type "+td.getName()+" is not nullable on the target database platform."); } out.print(" NULL"); } else { print(" NOT NULL"); } // XXX: default values? firstCol = false; } out.println(); out.print(")"); writeStatementTerminator(); out.println(""); }
1,111,124
public void writeTable(SQLTable t) throws SQLException, IOException, ArchitectException { out.println("\nCREATE TABLE "+t.getName()+" ("); boolean firstCol = true; Iterator it = t.getColumns().iterator(); while (it.hasNext()) { SQLColumn c = (SQLColumn) it.next(); GenericTypeDescriptor td = (GenericTypeDescriptor) typeMap.get(new Integer(c.getType())); if (td == null) { throw new UnsupportedOperationException ("No type for "+c.getType()+" is available in the target database platform." +"\nPlease choose a different type."); } if (!firstCol) out.println(","); out.print(" "); out.print(c.getName()); out.print(" "); out.print(td.getName()); if (td.getHasScale()) { out.print("("+c.getScale()); if (td.getHasPrecision()) { out.print(","+c.getPrecision()); } out.print(")"); } if (c.isNullable()) { if (! td.isNullable()) { throw new UnsupportedOperationException ("The data type "+td.getName()+" is not nullable on the target database platform."); } out.print(" NULL"); } else { out.print(" NOT NULL"); } // XXX: default values? firstCol = false; } out.println(); out.print(")"); writeStatementTerminator(); out.println(""); }
public void writeTable(SQLTable t) throws SQLException, IOException, ArchitectException { out.println("\nCREATE TABLE "+t.getName()+" ("); boolean firstCol = true; Iterator it = t.getColumns().iterator(); while (it.hasNext()) { SQLColumn c = (SQLColumn) it.next(); GenericTypeDescriptor td = (GenericTypeDescriptor) typeMap.get(new Integer(c.getType())); if (td == null) { throw new UnsupportedOperationException ("No type for "+c.getType()+" is available in the target database platform." +"\nPlease choose a different type."); } if (!firstCol) out.println(","); out.print(" "); out.print(c.getName()); out.print(" "); out.print(td.getName()); if (td.getHasScale()) { out.print("("+c.getScale()); if (td.getHasPrecision()) { out.print(","+c.getPrecision()); } out.print(")"); } if (c.isNullable()) { if (! td.isNullable()) { throw new UnsupportedOperationException ("The data type "+td.getName()+" is not nullable on the target database platform."); } out.print(" NULL"); } else { out.print(" NOT NULL"); } // XXX: default values? firstCol = false; } out.println(); out.print(")"); writeStatementTerminator(); out.println(""); }
1,111,125
public void writeTable(SQLTable t) throws SQLException, IOException, ArchitectException { out.println("\nCREATE TABLE "+t.getName()+" ("); boolean firstCol = true; Iterator it = t.getColumns().iterator(); while (it.hasNext()) { SQLColumn c = (SQLColumn) it.next(); GenericTypeDescriptor td = (GenericTypeDescriptor) typeMap.get(new Integer(c.getType())); if (td == null) { throw new UnsupportedOperationException ("No type for "+c.getType()+" is available in the target database platform." +"\nPlease choose a different type."); } if (!firstCol) out.println(","); out.print(" "); out.print(c.getName()); out.print(" "); out.print(td.getName()); if (td.getHasScale()) { out.print("("+c.getScale()); if (td.getHasPrecision()) { out.print(","+c.getPrecision()); } out.print(")"); } if (c.isNullable()) { if (! td.isNullable()) { throw new UnsupportedOperationException ("The data type "+td.getName()+" is not nullable on the target database platform."); } out.print(" NULL"); } else { out.print(" NOT NULL"); } // XXX: default values? firstCol = false; } out.println(); out.print(")"); writeStatementTerminator(); out.println(""); }
public void writeTable(SQLTable t) throws SQLException, IOException, ArchitectException { out.println("\nCREATE TABLE "+t.getName()+" ("); boolean firstCol = true; Iterator it = t.getColumns().iterator(); while (it.hasNext()) { SQLColumn c = (SQLColumn) it.next(); GenericTypeDescriptor td = (GenericTypeDescriptor) typeMap.get(new Integer(c.getType())); if (td == null) { throw new UnsupportedOperationException ("No type for "+c.getType()+" is available in the target database platform." +"\nPlease choose a different type."); } if (!firstCol) out.println(","); out.print(" "); out.print(c.getName()); out.print(" "); out.print(td.getName()); if (td.getHasScale()) { out.print("("+c.getScale()); if (td.getHasPrecision()) { out.print(","+c.getPrecision()); } out.print(")"); } if (c.isNullable()) { if (! td.isNullable()) { throw new UnsupportedOperationException ("The data type "+td.getName()+" is not nullable on the target database platform."); } out.print(" NULL"); } else { out.print(" NOT NULL"); } // XXX: default values? firstCol = false; } out.println(); out.print(")"); writeStatementTerminator(); println(""); }
1,111,126
void processData(final String[][] hminfo, String[] in) { final String[] inputOptions = in; if (inputOptions[2].equals("")){ inputOptions[2] = "0"; } maxCompDist = Long.parseLong(inputOptions[2])*1000; this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); final SwingWorker worker = new SwingWorker(){ public Object construct(){ dPrimeDisplay=null; theData.infoKnown = false; File markerFile; if (inputOptions[1].equals("")){ markerFile = null; }else{ markerFile = new File(inputOptions[1]); } readMarkers(markerFile, hminfo); theData.generateDPrimeTable(maxCompDist); theData.guessBlocks(BLOX_GABRIEL); //theData.guessBlocks(BLOX_NONE); //for debugging, doesn't call blocks at first colorMenuItems[0].setSelected(true); blockMenuItems[0].setSelected(true); zoomMenuItems[0].setSelected(true); theData.blocksChanged = false; Container contents = getContentPane(); contents.removeAll(); int currentTab = VIEW_D_NUM; /*if (!(tabs == null)){ currentTab = tabs.getSelectedIndex(); } */ tabs = new JTabbedPane(); tabs.addChangeListener(new TabChangeListener()); //first, draw the D' picture JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); dPrimeDisplay = new DPrimeDisplay(theData); JScrollPane dPrimeScroller = new JScrollPane(dPrimeDisplay); dPrimeScroller.getViewport().setScrollMode(JViewport.BLIT_SCROLL_MODE); dPrimeScroller.getVerticalScrollBar().setUnitIncrement(60); dPrimeScroller.getHorizontalScrollBar().setUnitIncrement(60); panel.add(dPrimeScroller); tabs.addTab(viewItems[VIEW_D_NUM], panel); viewMenuItems[VIEW_D_NUM].setEnabled(true); //compute and show haps on next tab panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); try { hapDisplay = new HaplotypeDisplay(theData); } catch(HaploViewException e) { JOptionPane.showMessageDialog(window, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } HaplotypeDisplayController hdc = new HaplotypeDisplayController(hapDisplay); hapScroller = new JScrollPane(hapDisplay); hapScroller.getVerticalScrollBar().setUnitIncrement(60); hapScroller.getHorizontalScrollBar().setUnitIncrement(60); panel.add(hapScroller); panel.add(hdc); tabs.addTab(viewItems[VIEW_HAP_NUM], panel); viewMenuItems[VIEW_HAP_NUM].setEnabled(true); //LOD panel /*panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); LODDisplay ld = new LODDisplay(theData); JScrollPane lodScroller = new JScrollPane(ld); panel.add(lodScroller); tabs.addTab(viewItems[VIEW_LOD_NUM], panel); viewMenuItems[VIEW_LOD_NUM].setEnabled(true);*/ //int optionalTabCount = 1; //check data panel if (checkPanel != null){ //optionalTabCount++; //VIEW_CHECK_NUM = optionalTabCount; //viewItems[VIEW_CHECK_NUM] = VIEW_CHECK_PANEL; JPanel metaCheckPanel = new JPanel(); metaCheckPanel.setLayout(new BoxLayout(metaCheckPanel, BoxLayout.Y_AXIS)); JLabel countsLabel = new JLabel("Using " + theData.numSingletons + " singletons and " + theData.numTrios + " trios from " + theData.numPeds + " families."); if (theData.numTrios + theData.numSingletons == 0){ countsLabel.setForeground(Color.red); } countsLabel.setAlignmentX(Component.CENTER_ALIGNMENT); metaCheckPanel.add(countsLabel); metaCheckPanel.add(checkPanel); cdc = new CheckDataController(window); metaCheckPanel.add(cdc); tabs.addTab(viewItems[VIEW_CHECK_NUM], metaCheckPanel); viewMenuItems[VIEW_CHECK_NUM].setEnabled(true); currentTab=VIEW_CHECK_NUM; } //TDT panel if(assocTest > 0) { //optionalTabCount++; //VIEW_TDT_NUM = optionalTabCount; //viewItems[VIEW_TDT_NUM] = VIEW_TDT; tdtPanel = new TDTPanel(theData.chromosomes, assocTest); tabs.addTab(viewItems[VIEW_TDT_NUM], tdtPanel); viewMenuItems[VIEW_TDT_NUM].setEnabled(true); } tabs.setSelectedIndex(currentTab); contents.add(tabs); repaint(); setVisible(true); theData.finished = true; setTitle(TITLE_STRING + " -- " + inputOptions[0]); return null; } }; timer = new javax.swing.Timer(50, new ActionListener(){ public void actionPerformed(ActionEvent evt){ if (theData.finished){ timer.stop(); for (int i = 0; i < blockMenuItems.length; i++){ blockMenuItems[i].setEnabled(true); } clearBlocksItem.setEnabled(true); readMarkerItem.setEnabled(true); setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } } }); worker.start(); timer.start(); }
void processData(final String[][] hminfo, String[] in) { final String[] inputOptions = in; if (inputOptions[2].equals("")){ inputOptions[2] = "0"; } maxCompDist = Long.parseLong(inputOptions[2])*1000; this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); final SwingWorker worker = new SwingWorker(){ public Object construct(){ dPrimeDisplay=null; theData.infoKnown = false; File markerFile; if (inputOptions[1].equals("")){ markerFile = null; }else{ markerFile = new File(inputOptions[1]); } readMarkers(markerFile, hminfo); theData.generateDPrimeTable(maxCompDist); theData.guessBlocks(BLOX_GABRIEL); //theData.guessBlocks(BLOX_NONE); //for debugging, doesn't call blocks at first colorMenuItems[0].setSelected(true); blockMenuItems[0].setSelected(true); zoomMenuItems[0].setSelected(true); theData.blocksChanged = false; Container contents = getContentPane(); contents.removeAll(); int currentTab = VIEW_D_NUM; /*if (!(tabs == null)){ currentTab = tabs.getSelectedIndex(); } */ tabs = new JTabbedPane(); tabs.addChangeListener(new TabChangeListener()); //first, draw the D' picture JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); dPrimeDisplay = new DPrimeDisplay(theData); JScrollPane dPrimeScroller = new JScrollPane(dPrimeDisplay); dPrimeScroller.getViewport().setScrollMode(JViewport.BLIT_SCROLL_MODE); dPrimeScroller.getVerticalScrollBar().setUnitIncrement(60); dPrimeScroller.getHorizontalScrollBar().setUnitIncrement(60); panel.add(dPrimeScroller); tabs.addTab(viewItems[VIEW_D_NUM], panel); viewMenuItems[VIEW_D_NUM].setEnabled(true); //compute and show haps on next tab panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); try { hapDisplay = new HaplotypeDisplay(theData); } catch(HaploViewException e) { JOptionPane.showMessageDialog(window, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } HaplotypeDisplayController hdc = new HaplotypeDisplayController(hapDisplay); hapScroller = new JScrollPane(hapDisplay); hapScroller.getVerticalScrollBar().setUnitIncrement(60); hapScroller.getHorizontalScrollBar().setUnitIncrement(60); panel.add(hapScroller); panel.add(hdc); tabs.addTab(viewItems[VIEW_HAP_NUM], panel); viewMenuItems[VIEW_HAP_NUM].setEnabled(true); //LOD panel /*panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); LODDisplay ld = new LODDisplay(theData); JScrollPane lodScroller = new JScrollPane(ld); panel.add(lodScroller); tabs.addTab(viewItems[VIEW_LOD_NUM], panel); viewMenuItems[VIEW_LOD_NUM].setEnabled(true);*/ //int optionalTabCount = 1; //check data panel if (checkPanel != null){ //optionalTabCount++; //VIEW_CHECK_NUM = optionalTabCount; //viewItems[VIEW_CHECK_NUM] = VIEW_CHECK_PANEL; JPanel metaCheckPanel = new JPanel(); metaCheckPanel.setLayout(new BoxLayout(metaCheckPanel, BoxLayout.Y_AXIS)); JLabel countsLabel = new JLabel("Using " + theData.numSingletons + " singletons and " + theData.numTrios + " trios from " + theData.numPeds + " families."); if (theData.numTrios + theData.numSingletons == 0){ countsLabel.setForeground(Color.red); } countsLabel.setAlignmentX(Component.CENTER_ALIGNMENT); metaCheckPanel.add(countsLabel); metaCheckPanel.add(checkPanel); cdc = new CheckDataController(window); metaCheckPanel.add(cdc); tabs.addTab(viewItems[VIEW_CHECK_NUM], metaCheckPanel); viewMenuItems[VIEW_CHECK_NUM].setEnabled(true); currentTab=VIEW_CHECK_NUM; } //TDT panel if(assocTest > 0) { //optionalTabCount++; //VIEW_TDT_NUM = optionalTabCount; //viewItems[VIEW_TDT_NUM] = VIEW_TDT; tdtPanel = new TDTPanel(theData.chromosomes, assocTest); tabs.addTab(viewItems[VIEW_TDT_NUM], tdtPanel); viewMenuItems[VIEW_TDT_NUM].setEnabled(true); } tabs.setSelectedIndex(currentTab); contents.add(tabs); repaint(); setVisible(true); theData.finished = true; setTitle(TITLE_STRING + " -- " + inputOptions[0]); return null; } }; timer = new javax.swing.Timer(50, new ActionListener(){ public void actionPerformed(ActionEvent evt){ if (theData.finished){ timer.stop(); for (int i = 0; i < blockMenuItems.length; i++){ blockMenuItems[i].setEnabled(true); } clearBlocksItem.setEnabled(true); readMarkerItem.setEnabled(true); setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } } }); worker.start(); timer.start(); }
1,111,127
public Object construct(){ dPrimeDisplay=null; theData.infoKnown = false; File markerFile; if (inputOptions[1].equals("")){ markerFile = null; }else{ markerFile = new File(inputOptions[1]); } readMarkers(markerFile, hminfo); theData.generateDPrimeTable(maxCompDist); theData.guessBlocks(BLOX_GABRIEL); //theData.guessBlocks(BLOX_NONE); //for debugging, doesn't call blocks at first colorMenuItems[0].setSelected(true); blockMenuItems[0].setSelected(true); zoomMenuItems[0].setSelected(true); theData.blocksChanged = false; Container contents = getContentPane(); contents.removeAll(); int currentTab = VIEW_D_NUM; /*if (!(tabs == null)){ currentTab = tabs.getSelectedIndex(); } */ tabs = new JTabbedPane(); tabs.addChangeListener(new TabChangeListener()); //first, draw the D' picture JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); dPrimeDisplay = new DPrimeDisplay(theData); JScrollPane dPrimeScroller = new JScrollPane(dPrimeDisplay); dPrimeScroller.getViewport().setScrollMode(JViewport.BLIT_SCROLL_MODE); dPrimeScroller.getVerticalScrollBar().setUnitIncrement(60); dPrimeScroller.getHorizontalScrollBar().setUnitIncrement(60); panel.add(dPrimeScroller); tabs.addTab(viewItems[VIEW_D_NUM], panel); viewMenuItems[VIEW_D_NUM].setEnabled(true); //compute and show haps on next tab panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); try { hapDisplay = new HaplotypeDisplay(theData); } catch(HaploViewException e) { JOptionPane.showMessageDialog(window, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } HaplotypeDisplayController hdc = new HaplotypeDisplayController(hapDisplay); hapScroller = new JScrollPane(hapDisplay); hapScroller.getVerticalScrollBar().setUnitIncrement(60); hapScroller.getHorizontalScrollBar().setUnitIncrement(60); panel.add(hapScroller); panel.add(hdc); tabs.addTab(viewItems[VIEW_HAP_NUM], panel); viewMenuItems[VIEW_HAP_NUM].setEnabled(true); //LOD panel /*panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); LODDisplay ld = new LODDisplay(theData); JScrollPane lodScroller = new JScrollPane(ld); panel.add(lodScroller); tabs.addTab(viewItems[VIEW_LOD_NUM], panel); viewMenuItems[VIEW_LOD_NUM].setEnabled(true);*/ //int optionalTabCount = 1; //check data panel if (checkPanel != null){ //optionalTabCount++; //VIEW_CHECK_NUM = optionalTabCount; //viewItems[VIEW_CHECK_NUM] = VIEW_CHECK_PANEL; JPanel metaCheckPanel = new JPanel(); metaCheckPanel.setLayout(new BoxLayout(metaCheckPanel, BoxLayout.Y_AXIS)); JLabel countsLabel = new JLabel("Using " + theData.numSingletons + " singletons and " + theData.numTrios + " trios from " + theData.numPeds + " families."); if (theData.numTrios + theData.numSingletons == 0){ countsLabel.setForeground(Color.red); } countsLabel.setAlignmentX(Component.CENTER_ALIGNMENT); metaCheckPanel.add(countsLabel); metaCheckPanel.add(checkPanel); cdc = new CheckDataController(window); metaCheckPanel.add(cdc); tabs.addTab(viewItems[VIEW_CHECK_NUM], metaCheckPanel); viewMenuItems[VIEW_CHECK_NUM].setEnabled(true); currentTab=VIEW_CHECK_NUM; } //TDT panel if(assocTest > 0) { //optionalTabCount++; //VIEW_TDT_NUM = optionalTabCount; //viewItems[VIEW_TDT_NUM] = VIEW_TDT; tdtPanel = new TDTPanel(theData.chromosomes, assocTest); tabs.addTab(viewItems[VIEW_TDT_NUM], tdtPanel); viewMenuItems[VIEW_TDT_NUM].setEnabled(true); } tabs.setSelectedIndex(currentTab); contents.add(tabs); repaint(); setVisible(true); theData.finished = true; setTitle(TITLE_STRING + " -- " + inputOptions[0]); return null; }
public Object construct(){ dPrimeDisplay=null; theData.infoKnown = false; File markerFile; if (inputOptions[1].equals("")){ markerFile = null; }else{ markerFile = new File(inputOptions[1]); } readMarkers(markerFile, hminfo); theData.generateDPrimeTable(maxCompDist); theData.guessBlocks(BLOX_GABRIEL); //theData.guessBlocks(BLOX_NONE); //for debugging, doesn't call blocks at first colorMenuItems[0].setSelected(true); blockMenuItems[0].setSelected(true); zoomMenuItems[0].setSelected(true); theData.blocksChanged = false; Container contents = getContentPane(); contents.removeAll(); int currentTab = VIEW_D_NUM; /*if (!(tabs == null)){ currentTab = tabs.getSelectedIndex(); } */ tabs = new JTabbedPane(); tabs.addChangeListener(new TabChangeListener()); //first, draw the D' picture JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); dPrimeDisplay = new DPrimeDisplay(theData); JScrollPane dPrimeScroller = new JScrollPane(dPrimeDisplay); dPrimeScroller.getViewport().setScrollMode(JViewport.BLIT_SCROLL_MODE); dPrimeScroller.getVerticalScrollBar().setUnitIncrement(60); dPrimeScroller.getHorizontalScrollBar().setUnitIncrement(60); panel.add(dPrimeScroller); tabs.addTab(viewItems[VIEW_D_NUM], panel); viewMenuItems[VIEW_D_NUM].setEnabled(true); //compute and show haps on next tab panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); try { hapDisplay = new HaplotypeDisplay(theData); } catch(HaploViewException e) { JOptionPane.showMessageDialog(window, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } HaplotypeDisplayController hdc = new HaplotypeDisplayController(hapDisplay); hapScroller = new JScrollPane(hapDisplay); hapScroller.getVerticalScrollBar().setUnitIncrement(60); hapScroller.getHorizontalScrollBar().setUnitIncrement(60); panel.add(hapScroller); panel.add(hdc); tabs.addTab(viewItems[VIEW_HAP_NUM], panel); viewMenuItems[VIEW_HAP_NUM].setEnabled(true); //LOD panel /*panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); LODDisplay ld = new LODDisplay(theData); JScrollPane lodScroller = new JScrollPane(ld); panel.add(lodScroller); tabs.addTab(viewItems[VIEW_LOD_NUM], panel); viewMenuItems[VIEW_LOD_NUM].setEnabled(true);*/ //int optionalTabCount = 1; //check data panel if (checkPanel != null){ //optionalTabCount++; //VIEW_CHECK_NUM = optionalTabCount; //viewItems[VIEW_CHECK_NUM] = VIEW_CHECK_PANEL; JPanel metaCheckPanel = new JPanel(); metaCheckPanel.setLayout(new BoxLayout(metaCheckPanel, BoxLayout.Y_AXIS)); JLabel countsLabel = new JLabel("Using " + theData.numSingletons + " singletons and " + theData.numTrios + " trios from " + theData.numPeds + " families."); if (theData.numTrios + theData.numSingletons == 0){ countsLabel.setForeground(Color.red); } countsLabel.setAlignmentX(Component.CENTER_ALIGNMENT); metaCheckPanel.add(countsLabel); metaCheckPanel.add(checkPanel); cdc = new CheckDataController(window); metaCheckPanel.add(cdc); tabs.addTab(viewItems[VIEW_CHECK_NUM], metaCheckPanel); viewMenuItems[VIEW_CHECK_NUM].setEnabled(true); currentTab=VIEW_CHECK_NUM; } //TDT panel if(assocTest > 0) { //optionalTabCount++; //VIEW_TDT_NUM = optionalTabCount; //viewItems[VIEW_TDT_NUM] = VIEW_TDT; tdtPanel = new TDTPanel(theData.chromosomes, assocTest); tabs.addTab(viewItems[VIEW_TDT_NUM], tdtPanel); viewMenuItems[VIEW_TDT_NUM].setEnabled(true); } tabs.setSelectedIndex(currentTab); contents.add(tabs); repaint(); setVisible(true); theData.finished = true; setTitle(TITLE_STRING + " -- " + inputOptions[0]); return null; }
1,111,128
public Dimension getPreferredSize() { int w = 0; int h = 0; if ( origImage != null ) { if ( xformImage == null ) { buildXformImage(); } w = xformImage.getWidth(); h = xformImage.getHeight(); } return new Dimension( w, h ); }
public Dimension getPreferredSize() { int w = 0; int h = 0; if ( origImage != null ) { if ( xformImage == null ) { buildXformImage(); } w = xformImage.getWidth(); h = xformImage.getHeight(); } return new Dimension( w, h ); }
1,111,129
public Expression createExpression( ExpressionFactory factory, String tagName, String attributeName, String attributeValue) throws Exception { // #### may need to include some namespace URI information in the XPath instance? if (attributeName.equals("select")) { if ( log.isDebugEnabled() ) { log.debug( "Parsing XPath expression: " + attributeValue ); } try { XPath xpath = new Dom4jXPath(attributeValue); return new XPathExpression(xpath); } catch (JaxenException e) { throw new JellyException( "Could not parse XPath expression: \"" + attributeValue + "\" reason: " + e, e ); } } // will use the default expression instead return super.createExpression(factory, tagName, attributeName, attributeValue); }
public Expression createExpression( ExpressionFactory factory, TagScript tagScript, String attributeName, String attributeValue) throws Exception { // #### may need to include some namespace URI information in the XPath instance? if (attributeName.equals("select")) { if ( log.isDebugEnabled() ) { log.debug( "Parsing XPath expression: " + attributeValue ); } try { XPath xpath = new Dom4jXPath(attributeValue); return new XPathExpression(xpath); } catch (JaxenException e) { throw new JellyException( "Could not parse XPath expression: \"" + attributeValue + "\" reason: " + e, e ); } } // will use the default expression instead return super.createExpression(factory, tagName, attributeName, attributeValue); }
1,111,130
public Expression createExpression( ExpressionFactory factory, String tagName, String attributeName, String attributeValue) throws Exception { // #### may need to include some namespace URI information in the XPath instance? if (attributeName.equals("select")) { if ( log.isDebugEnabled() ) { log.debug( "Parsing XPath expression: " + attributeValue ); } try { XPath xpath = new Dom4jXPath(attributeValue); return new XPathExpression(xpath); } catch (JaxenException e) { throw new JellyException( "Could not parse XPath expression: \"" + attributeValue + "\" reason: " + e, e ); } } // will use the default expression instead return super.createExpression(factory, tagName, attributeName, attributeValue); }
public Expression createExpression( ExpressionFactory factory, String tagName, String attributeName, String attributeValue) throws Exception { // #### may need to include some namespace URI information in the XPath instance? if (attributeName.equals("select")) { if ( log.isDebugEnabled() ) { log.debug( "Parsing XPath expression: " + attributeValue ); } try { XPath xpath = new Dom4jXPath(attributeValue); return new XPathExpression(xpath, tagScript); } catch (JaxenException e) { throw new JellyException( "Could not parse XPath expression: \"" + attributeValue + "\" reason: " + e, e ); } } // will use the default expression instead return super.createExpression(factory, tagName, attributeName, attributeValue); }
1,111,131
public Expression createExpression( ExpressionFactory factory, String tagName, String attributeName, String attributeValue) throws Exception { // #### may need to include some namespace URI information in the XPath instance? if (attributeName.equals("select")) { if ( log.isDebugEnabled() ) { log.debug( "Parsing XPath expression: " + attributeValue ); } try { XPath xpath = new Dom4jXPath(attributeValue); return new XPathExpression(xpath); } catch (JaxenException e) { throw new JellyException( "Could not parse XPath expression: \"" + attributeValue + "\" reason: " + e, e ); } } // will use the default expression instead return super.createExpression(factory, tagName, attributeName, attributeValue); }
public Expression createExpression( ExpressionFactory factory, String tagName, String attributeName, String attributeValue) throws Exception { // #### may need to include some namespace URI information in the XPath instance? if (attributeName.equals("select")) { if ( log.isDebugEnabled() ) { log.debug( "Parsing XPath expression: " + attributeValue ); } try { XPath xpath = new Dom4jXPath(attributeValue); return new XPathExpression(xpath); } catch (JaxenException e) { throw new JellyException( "Could not parse XPath expression: \"" + attributeValue + "\" reason: " + e, e ); } } // will use the default expression instead return super.createExpression(factory, tagScript, attributeName, attributeValue); }
1,111,132
public static Vector calcTDT(Vector chromosomes) { Vector results = new Vector(); int numMarkers = Chromosome.getSize(); for(int k=0;k<numMarkers;k++){ results.add(new TDTResult(Chromosome.getMarker(k))); } for(int i=0;i<chromosomes.size()-3;i++){ Chromosome chrom1T = (Chromosome)chromosomes.get(i); i++; Chromosome chrom1U = (Chromosome)chromosomes.get(i); i++; Chromosome chrom2T = (Chromosome)chromosomes.get(i); i++; Chromosome chrom2U = (Chromosome)chromosomes.get(i); //System.out.println("ind1T: " + chrom1T.getPed() + "\t" + chrom1T.getIndividual() ); //System.out.println("ind1U: " + chrom1U.getPed() + "\t" + chrom1U.getIndividual() ); //System.out.println("ind2T: " + chrom2T.getPed() + "\t" + chrom2T.getIndividual() ); //System.out.println("ind2U: " + chrom2U.getPed() + "\t" + chrom2U.getIndividual() ); for(int j=0;j<numMarkers;j++){ byte allele1T = chrom1T.getGenotype(j); byte allele1U = chrom1U.getGenotype(j); byte allele2T = chrom2T.getGenotype(j); byte allele2U = chrom2U.getGenotype(j); TDTResult curRes = (TDTResult)results.get(j); //System.out.println("marker "+ j + ":\t " + allele1T + "\t" + allele1U + "\t" + allele2T + "\t" + allele2U); curRes.tallyInd(allele1T,allele1U); curRes.tallyInd(allele2T,allele2U); } } for(int i=0;i<results.size();i++){ TDTResult tempRes = (TDTResult)results.get(i); int[][] counts = tempRes.counts; //System.out.println( counts[0][0] + "\t" + counts[1][1] + "\t" + counts[0][1] + "\t" + counts[1][0]); } return results; }
public static Vector calcTDT(Vector chromosomes) { Vector results = new Vector(); int numMarkers = Chromosome.getSize(); for(int k=0;k<numMarkers;k++){ results.add(new TDTResult(Chromosome.getMarker(k))); } for(int i=0;i<chromosomes.size()-3;i++){ Chromosome chrom1T = (Chromosome)chromosomes.get(i); i++; Chromosome chrom1U = (Chromosome)chromosomes.get(i); i++; Chromosome chrom2T = (Chromosome)chromosomes.get(i); i++; Chromosome chrom2U = (Chromosome)chromosomes.get(i); //System.out.println("ind1T: " + chrom1T.getPed() + "\t" + chrom1T.getIndividual() ); //System.out.println("ind1U: " + chrom1U.getPed() + "\t" + chrom1U.getIndividual() ); //System.out.println("ind2T: " + chrom2T.getPed() + "\t" + chrom2T.getIndividual() ); //System.out.println("ind2U: " + chrom2U.getPed() + "\t" + chrom2U.getIndividual() ); for(int j=0;j<numMarkers;j++){ byte allele1T = chrom1T.getGenotype(j); byte allele1U = chrom1U.getGenotype(j); byte allele2T = chrom2T.getGenotype(j); byte allele2U = chrom2U.getGenotype(j); TDTResult curRes = (TDTResult)results.get(j); //System.out.println("marker "+ j + ":\t " + allele1T + "\t" + allele1U + "\t" + allele2T + "\t" + allele2U); curRes.tallyInd(allele1T,allele1U); curRes.tallyInd(allele2T,allele2U); } } for(int i=0;i<results.size();i++){ TDTResult tempRes = (TDTResult)results.get(i); int[][] counts = tempRes.counts; //System.out.println( counts[0][0] + "\t" + counts[1][1] + "\t" + counts[0][1] + "\t" + counts[1][0]); } return results; }
1,111,133
public void paintComponent(Graphics g){ DPrimeTable dPrimeTable = theData.dpTable; if (Chromosome.getSize() < 2){ //if there zero or only one valid marker return; } Vector blocks = theData.blocks; Rectangle visRect = getVisibleRect(); //deal with zooming if (chartSize.getWidth() > (3*visRect.width)){ showWM = true; }else{ showWM = false; } if (zoomLevel != 0 || Options.getLDColorScheme() == WMF_SCHEME || Options.getLDColorScheme() == RSQ_SCHEME){ printDPrimeValues = false; } else{ printDPrimeValues = true; } Graphics2D g2 = (Graphics2D) g; Dimension size = getSize(); Dimension pref = getPreferredSize(); g2.setColor(BG_GREY); //if it's a big dataset, resize properly, if it's small make sure to fill whole background if (size.height < pref.height){ g2.fillRect(0,0,pref.width,pref.height); setSize(pref); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); //okay so this dumb if block is to prevent the ugly repainting //bug when loading markers after the data are already being displayed, //results in a little off-centering for small datasets, but not too bad. if (!forExport){ if (!theData.infoKnown){ g2.translate((size.width - pref.width) / 2, (size.height - pref.height) / 2); } else { g2.translate((size.width - pref.width) / 2, 0); } } FontMetrics boxFontMetrics = g2.getFontMetrics(boxFont); int diamondX[] = new int[4]; int diamondY[] = new int[4]; Polygon diamond; double lineSpan = alignedPositions[alignedPositions.length-1] - alignedPositions[0]; long minpos = Chromosome.getMarker(0).getPosition(); long maxpos = Chromosome.getMarker(Chromosome.getSize()-1).getPosition(); double spanpos = maxpos - minpos; //See http://www.hapmap.org/cgi-perl/gbrowse/gbrowse_img //for more info on GBrowse img. int imgHeight = 0; if (Options.isGBrowseShown() && Chromosome.getDataChrom() != null){ g2.drawImage(gBrowseImage,H_BORDER-GBROWSE_MARGIN,V_BORDER,this); imgHeight = gBrowseImage.getHeight(this) + TRACK_GAP; // get height so we can shift everything down } left = H_BORDER; top = V_BORDER + imgHeight; // push the haplotype display down to make room for gbrowse image. if (forExport){ left -= exportStart * boxSize; } FontMetrics metrics; int ascent; g2.setFont(boldMarkerNameFont); metrics = g2.getFontMetrics(); ascent = metrics.getAscent(); //the following values are the bounds on the boxes we want to //display given that the current window is 'visRect' lowX = getBoundaryMarker(visRect.x-clickXShift-(visRect.y +visRect.height-clickYShift)) - 1; highX = getBoundaryMarker(visRect.x + visRect.width); lowY = getBoundaryMarker((visRect.x-clickXShift)+(visRect.y-clickYShift)) - 1; highY = getBoundaryMarker((visRect.x-clickXShift+visRect.width) + (visRect.y-clickYShift+visRect.height)); if (lowX < 0) { lowX = 0; } if (highX > Chromosome.getSize()-1){ highX = Chromosome.getSize()-1; } if (lowY < lowX+1){ lowY = lowX+1; } if (highY > Chromosome.getSize()){ highY = Chromosome.getSize(); } if (forExport){ lowX = exportStart; lowY = exportStart; highX = exportStop; highY = exportStop; } if (theData.trackExists){ //draw the analysis track above where the marker positions will be marked g2.setColor(Color.white); g2.fill(new Rectangle2D.Double(left, top, lineSpan, TRACK_HEIGHT)); g2.setColor(Color.black); g2.drawRect(left,top,(int)lineSpan,TRACK_HEIGHT); //get the data into an easier format double positions[] = new double[theData.analysisPositions.size()]; double values[] = new double[theData.analysisPositions.size()]; for (int x = 0; x < positions.length; x++){ positions[x] = ((Double)theData.analysisPositions.elementAt(x)).doubleValue(); values[x] = ((Double)theData.analysisValues.elementAt(x)).doubleValue(); } g2.setColor(Color.black); double min = Double.MAX_VALUE; double max = -min; for (int x = 0; x < positions.length; x++){ if(values[x] < min){ min = values[x]; } if (values[x] > max){ max = values[x]; } } double range = max-min; //todo: this is kinda hideous for (int x = 0; x < positions.length - 1; x++){ if (positions[x] >= minpos && positions[x+1] <= maxpos){ g2.draw(new Line2D.Double(lineSpan * Math.abs((positions[x] - minpos)/spanpos) + left, top + TRACK_PALETTE + TRACK_BUMPER - (TRACK_PALETTE * Math.abs((values[x] - min)/range)), lineSpan * Math.abs((positions[x+1] - minpos)/spanpos) + left, top + TRACK_PALETTE + TRACK_BUMPER - (TRACK_PALETTE * Math.abs((values[x+1] - min)/range)))); } } top += TRACK_HEIGHT + TRACK_GAP; } if (theData.infoKnown) { Color green = new Color(0, 127, 0); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //// draw the marker locations g2.setStroke(thinnerStroke); g2.setColor(Color.white); g2.fill(new Rectangle2D.Double(left+1, top+1, lineSpan-1, TICK_HEIGHT-1)); g2.setColor(Color.black); g2.draw(new Rectangle2D.Double(left, top, lineSpan, TICK_HEIGHT)); for (int i = 0; i < Chromosome.getSize(); i++){ double pos = (Chromosome.getMarker(i).getPosition() - minpos) / spanpos; double xx = left + lineSpan*pos; // if we're zoomed, use the line color to indicate whether there is extra data available // (since the marker names are not displayed when zoomed) if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setColor(green); //draw tick g2.setStroke(thickerStroke); g2.draw(new Line2D.Double(xx, top, xx, top + TICK_HEIGHT)); if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setStroke(thickerStroke); else g2.setStroke(thinnerStroke); //draw connecting line g2.draw(new Line2D.Double(xx, top + TICK_HEIGHT, left + alignedPositions[i], top+TICK_BOTTOM)); if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setColor(Color.black); } top += TICK_BOTTOM + TICK_HEIGHT; //// draw the marker names if (printMarkerNames){ widestMarkerName = metrics.stringWidth(Chromosome.getMarker(0).getName()); for (int x = 1; x < Chromosome.getSize(); x++) { int thiswide = metrics.stringWidth(Chromosome.getMarker(x).getName()); if (thiswide > widestMarkerName) widestMarkerName = thiswide; } g2.translate(left, top + widestMarkerName); g2.rotate(-Math.PI / 2.0); for (int x = 0; x < Chromosome.getSize(); x++) { if (theData.isInBlock[x]){ g2.setFont(boldMarkerNameFont); }else{ g2.setFont(markerNameFont); } if (Chromosome.getMarker(x).getExtra() != null) g2.setColor(green); g2.drawString(Chromosome.getMarker(x).getName(),(float)TEXT_GAP, (float)alignedPositions[x] + ascent/3); if (Chromosome.getMarker(x).getExtra() != null) g2.setColor(Color.black); } g2.rotate(Math.PI / 2.0); g2.translate(-left, -(top + widestMarkerName)); // move everybody down top += widestMarkerName + TEXT_GAP; } g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } top += blockDispHeight; //// draw the marker numbers if (printMarkerNames){ g2.setFont(markerNumFont); metrics = g2.getFontMetrics(); ascent = metrics.getAscent(); for (int x = 0; x < Chromosome.getSize(); x++) { String mark = String.valueOf(Chromosome.realIndex[x] + 1); g2.drawString(mark, (float)(left + alignedPositions[x] - metrics.stringWidth(mark)/2), (float)(top + ascent)); } top += boxRadius/2; // give a little space between numbers and boxes } //clickxshift and clickyshift are used later to translate from x,y coords //to the pair of markers comparison at those coords if (!(theData.infoKnown)){ clickXShift = left + (size.width-pref.width)/2; clickYShift = top + (size.height - pref.height)/2; } else { clickXShift = left + (size.width-pref.width)/2; clickYShift = top; } // draw table column by column for (int x = lowX; x < highX; x++) { //always draw the fewest possible boxes if (lowY < x+1){ lowY = x+1; } for (int y = lowY; y < highY; y++) { if (dPrimeTable.getLDStats(x,y) == null){ continue; } double d = dPrimeTable.getLDStats(x,y).getDPrime(); //double l = dPrimeTable.getLDStats(x,y).getLOD(); Color boxColor = dPrimeTable.getLDStats(x,y).getColor(); // draw markers above int xx = left + (int)((alignedPositions[x] + alignedPositions[y])/2); int yy = top + (int)((alignedPositions[y] - alignedPositions[x]) / 2); diamondX[0] = xx; diamondY[0] = yy - boxRadius; diamondX[1] = xx + boxRadius; diamondY[1] = yy; diamondX[2] = xx; diamondY[2] = yy + boxRadius; diamondX[3] = xx - boxRadius; diamondY[3] = yy; diamond = new Polygon(diamondX, diamondY, 4); g2.setColor(boxColor); g2.fillPolygon(diamond); if(printDPrimeValues){ g2.setFont(boxFont); ascent = boxFontMetrics.getAscent(); int val = (int) (d * 100); g2.setColor((val < 50) ? Color.gray : Color.black); if (boxColor == Color.darkGray){ g2.setColor(Color.white); } if (val != 100) { String valu = String.valueOf(val); int widf = boxFontMetrics.stringWidth(valu); g.drawString(valu, xx - widf/2, yy + ascent/2); } } } } //highlight blocks g2.setFont(markerNameFont); ascent = g2.getFontMetrics().getAscent(); //g.setColor(new Color(153,255,153)); g2.setColor(Color.black); //g.setColor(new Color(51,153,51)); for (int i = 0; i < blocks.size(); i++){ int[] theBlock = (int[])blocks.elementAt(i); int first = theBlock[0]; int last = theBlock[theBlock.length-1]; //big vee around whole thing g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left + alignedPositions[first] - boxRadius, top, left + (alignedPositions[first] + alignedPositions[last])/2, top + (alignedPositions[last] - alignedPositions[first])/2 + boxRadius)); g2.draw(new Line2D.Double(left + (alignedPositions[first] + alignedPositions[last])/2, top + (alignedPositions[last] - alignedPositions[first])/2 + boxRadius, left + alignedPositions[last] + boxRadius, top)); for (int j = first; j < last; j++){ g2.setStroke(fatStroke); if (theData.isInBlock[j]){ g2.draw(new Line2D.Double(left+alignedPositions[j]-boxSize/2, top-blockDispHeight, left+alignedPositions[j+1]-boxSize/2, top-blockDispHeight)); }else{ g2.draw(new Line2D.Double(left + alignedPositions[j] + boxSize/2, top-blockDispHeight, left+alignedPositions[j+1]-boxSize/2, top-blockDispHeight)); g2.setStroke(dashedFatStroke); g2.draw(new Line2D.Double(left+alignedPositions[j] - boxSize/2, top-blockDispHeight, left+alignedPositions[j] + boxSize/2, top-blockDispHeight)); } } //cap off the end of the block g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left+alignedPositions[last]-boxSize/2, top-blockDispHeight, left+alignedPositions[last]+boxSize/2, top-blockDispHeight)); //lines to connect to block display g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left + alignedPositions[first]-boxSize/2, top-1, left+alignedPositions[first]-boxSize/2, top-blockDispHeight)); g2.draw(new Line2D.Double(left+alignedPositions[last]+boxSize/2, top-1, left+alignedPositions[last]+boxSize/2, top-blockDispHeight)); if (printMarkerNames){ String labelString = new String ("Block " + (i+1)); if (theData.infoKnown){ long blockSize = Chromosome.getMarker(last).getPosition() - Chromosome.getMarker(first).getPosition(); labelString += " (" + blockSize/1000 + " kb)"; } g2.drawString(labelString, (float)(left+alignedPositions[first]-boxSize/2+TEXT_GAP), (float)(top-boxSize/3)); } } g2.setStroke(thickerStroke); if (showWM && !forExport){ //dataset is big enough to require worldmap if (wmMaxWidth == 0){ wmMaxWidth = visRect.width/3; } double scalefactor; scalefactor = (double)(chartSize.width)/wmMaxWidth; double prefBoxSize = boxSize/(scalefactor*((double)wmMaxWidth/(double)(wmMaxWidth))); //stick WM_BD in the middle of the blank space at the top of the worldmap final int WM_BD_GAP = (int)(infoHeight/(scalefactor*2)); final int WM_BD_HEIGHT = 2; CompoundBorder wmBorder = new CompoundBorder(BorderFactory.createRaisedBevelBorder(), BorderFactory.createLoweredBevelBorder()); if (noImage){ //first time through draw a worldmap if dataset is big: worldmap = new BufferedImage((int)(chartSize.width/scalefactor)+wmBorder.getBorderInsets(this).left*2, (int)(chartSize.height/scalefactor)+wmBorder.getBorderInsets(this).top*2, BufferedImage.TYPE_3BYTE_BGR); Graphics gw = worldmap.getGraphics(); Graphics2D gw2 = (Graphics2D)(gw); gw2.setColor(BG_GREY); gw2.fillRect(1,1,worldmap.getWidth()-1,worldmap.getHeight()-1); //make a pretty border gw2.setColor(Color.black); wmBorder.paintBorder(this,gw2,0,0,worldmap.getWidth(),worldmap.getHeight()); wmInteriorRect = wmBorder.getInteriorRectangle(this,0,0,worldmap.getWidth(), worldmap.getHeight()); float[] smallDiamondX = new float[4]; float[] smallDiamondY = new float[4]; GeneralPath gp; for (int x = 0; x < Chromosome.getSize()-1; x++){ for (int y = x+1; y < Chromosome.getSize(); y++){ if (dPrimeTable.getLDStats(x,y) == null){ continue; } double xx = ((alignedPositions[y] + alignedPositions[x])/(scalefactor*2)) + wmBorder.getBorderInsets(this).left; double yy = ((alignedPositions[y] - alignedPositions[x] + infoHeight*2)/(scalefactor*2)) + wmBorder.getBorderInsets(this).top; smallDiamondX[0] = (float)xx; smallDiamondY[0] = (float)(yy - prefBoxSize/2); smallDiamondX[1] = (float)(xx + prefBoxSize/2); smallDiamondY[1] = (float)yy; smallDiamondX[2] = (float)xx; smallDiamondY[2] = (float)(yy + prefBoxSize/2); smallDiamondX[3] = (float)(xx - prefBoxSize/2); smallDiamondY[3] = (float)yy; gp = new GeneralPath(GeneralPath.WIND_EVEN_ODD, smallDiamondX.length); gp.moveTo(smallDiamondX[0],smallDiamondY[0]); for (int i = 1; i < smallDiamondX.length; i++){ gp.lineTo(smallDiamondX[i], smallDiamondY[i]); } gp.closePath(); gw2.setColor(dPrimeTable.getLDStats(x,y).getColor()); gw2.fill(gp); } } noImage = false; } //draw block display in worldmap Graphics gw = worldmap.getGraphics(); Graphics2D gw2 = (Graphics2D)(gw); gw2.setColor(BG_GREY); gw2.fillRect(wmBorder.getBorderInsets(this).left, wmBorder.getBorderInsets(this).top+WM_BD_GAP, wmInteriorRect.width, WM_BD_HEIGHT); gw2.setColor(Color.black); boolean even = true; for (int i = 0; i < blocks.size(); i++){ int first = ((int[])blocks.elementAt(i))[0]; int last = ((int[])blocks.elementAt(i))[((int[])blocks.elementAt(i)).length-1]; int voffset; if (even){ voffset = 0; }else{ voffset = WM_BD_HEIGHT/2; } gw2.fillRect(wmBorder.getBorderInsets(this).left - (int)prefBoxSize/2 + (int)(alignedPositions[first]/scalefactor), wmBorder.getBorderInsets(this).top+voffset+WM_BD_GAP, (int)(prefBoxSize + (alignedPositions[last] - alignedPositions[first])/scalefactor), WM_BD_HEIGHT/2); even = !even; } wmResizeCorner = new Rectangle(visRect.x + worldmap.getWidth() - (worldmap.getWidth()-wmInteriorRect.width)/2, visRect.y + visRect.height - worldmap.getHeight(), (worldmap.getWidth()-wmInteriorRect.width)/2, (worldmap.getHeight() -wmInteriorRect.height)/2); g2.drawImage(worldmap,visRect.x, visRect.y + visRect.height - worldmap.getHeight(), this); wmInteriorRect.x = visRect.x + (worldmap.getWidth() - wmInteriorRect.width)/2; wmInteriorRect.y = visRect.y+visRect.height-worldmap.getHeight() + (worldmap.getHeight() - wmInteriorRect.height)/2; //draw the outline of the viewport g2.setColor(Color.black); double hRatio = wmInteriorRect.getWidth()/pref.getWidth(); double vRatio = wmInteriorRect.getHeight()/pref.getHeight(); int hBump = worldmap.getWidth()-wmInteriorRect.width; int vBump = worldmap.getHeight()-wmInteriorRect.height; //bump a few pixels to avoid drawing on the border g2.drawRect((int)(visRect.x*hRatio)+hBump/2+visRect.x, (int)(visRect.y*vRatio)+vBump/2+(visRect.y + visRect.height - worldmap.getHeight()), (int)(visRect.width*hRatio), (int)(visRect.height*vRatio)); } //see if the user has right-clicked to popup some marker info if(popupDrawRect != null){ //dumb bug where little datasets popup the box in the wrong place int smallDatasetSlopH = 0; int smallDatasetSlopV = 0; if (pref.getHeight() < visRect.height){ smallDatasetSlopV = (int)(visRect.height - pref.getHeight())/2; } if (pref.getWidth() < visRect.width){ smallDatasetSlopH = (int)(visRect.width - pref.getWidth())/2; } g2.setColor(Color.white); g2.fillRect(popupDrawRect.x+1-smallDatasetSlopH, popupDrawRect.y+1-smallDatasetSlopV, popupDrawRect.width-1, popupDrawRect.height-1); g2.setColor(Color.black); g2.drawRect(popupDrawRect.x-smallDatasetSlopH, popupDrawRect.y-smallDatasetSlopV, popupDrawRect.width, popupDrawRect.height); g.setFont(popupFont); for (int x = 0; x < displayStrings.size(); x++){ g.drawString((String)displayStrings.elementAt(x),popupDrawRect.x + popupLeftMargin-smallDatasetSlopH, popupDrawRect.y+((x+1)*metrics.getHeight())-smallDatasetSlopV); } } //see if we're drawing a worldmap resize rect if (resizeWMRect != null){ g2.setColor(Color.black); g2.drawRect(resizeWMRect.x, resizeWMRect.y, resizeWMRect.width, resizeWMRect.height); } //see if we're drawing a block selector rect if (blockRect != null){ g2.setColor(Color.black); g2.setStroke(dashedThinStroke); g2.drawRect(blockRect.x, blockRect.y, blockRect.width, blockRect.height); } }
public void paintComponent(Graphics g){ DPrimeTable dPrimeTable = theData.dpTable; if (Chromosome.getSize() < 2){ //if there zero or only one valid marker return; } Vector blocks = theData.blocks; Rectangle visRect = getVisibleRect(); //deal with zooming if (chartSize.getWidth() > (3*visRect.width)){ showWM = true; }else{ showWM = false; } if (zoomLevel != 0 || Options.getLDColorScheme() == WMF_SCHEME || Options.getLDColorScheme() == RSQ_SCHEME){ printDPrimeValues = false; } else{ printDPrimeValues = true; } Graphics2D g2 = (Graphics2D) g; Dimension size = getSize(); Dimension pref = getPreferredSize(); g2.setColor(BG_GREY); //if it's a big dataset, resize properly, if it's small make sure to fill whole background if (size.height < pref.height){ g2.fillRect(0,0,pref.width,pref.height); setSize(pref); }else{ g2.fillRect(0,0,size.width, size.height); } g2.setColor(Color.black); //okay so this dumb if block is to prevent the ugly repainting //bug when loading markers after the data are already being displayed, //results in a little off-centering for small datasets, but not too bad. if (!forExport){ if (!theData.infoKnown){ g2.translate((size.width - pref.width) / 2, (size.height - pref.height) / 2); } else { g2.translate((size.width - pref.width) / 2, 0); } } FontMetrics boxFontMetrics = g2.getFontMetrics(boxFont); int diamondX[] = new int[4]; int diamondY[] = new int[4]; Polygon diamond; double lineSpan = alignedPositions[alignedPositions.length-1] - alignedPositions[0]; long minpos = Chromosome.getMarker(0).getPosition(); long maxpos = Chromosome.getMarker(Chromosome.getSize()-1).getPosition(); double spanpos = maxpos - minpos; //See http://www.hapmap.org/cgi-perl/gbrowse/gbrowse_img //for more info on GBrowse img. int imgHeight = 0; if (Options.isGBrowseShown() && Chromosome.getDataChrom() != null){ g2.drawImage(gBrowseImage,H_BORDER-GBROWSE_MARGIN,V_BORDER,this); imgHeight = gBrowseImage.getHeight(this) + TRACK_GAP; // get height so we can shift everything down } left = H_BORDER; top = V_BORDER + imgHeight; // push the haplotype display down to make room for gbrowse image. if (forExport){ left -= exportStart * boxSize; } FontMetrics metrics; int ascent; g2.setFont(boldMarkerNameFont); metrics = g2.getFontMetrics(); ascent = metrics.getAscent(); //the following values are the bounds on the boxes we want to //display given that the current window is 'visRect' lowX = getBoundaryMarker(visRect.x-clickXShift-(visRect.y +visRect.height-clickYShift)) - 1; highX = getBoundaryMarker(visRect.x + visRect.width); lowY = getBoundaryMarker((visRect.x-clickXShift)+(visRect.y-clickYShift)) - 1; highY = getBoundaryMarker((visRect.x-clickXShift+visRect.width) + (visRect.y-clickYShift+visRect.height)); if (lowX < 0) { lowX = 0; } if (highX > Chromosome.getSize()-1){ highX = Chromosome.getSize()-1; } if (lowY < lowX+1){ lowY = lowX+1; } if (highY > Chromosome.getSize()){ highY = Chromosome.getSize(); } if (forExport){ lowX = exportStart; lowY = exportStart; highX = exportStop; highY = exportStop+1; } if (theData.trackExists){ //draw the analysis track above where the marker positions will be marked g2.setColor(Color.white); g2.fill(new Rectangle2D.Double(left, top, lineSpan, TRACK_HEIGHT)); g2.setColor(Color.black); g2.drawRect(left,top,(int)lineSpan,TRACK_HEIGHT); //get the data into an easier format double positions[] = new double[theData.analysisPositions.size()]; double values[] = new double[theData.analysisPositions.size()]; for (int x = 0; x < positions.length; x++){ positions[x] = ((Double)theData.analysisPositions.elementAt(x)).doubleValue(); values[x] = ((Double)theData.analysisValues.elementAt(x)).doubleValue(); } g2.setColor(Color.black); double min = Double.MAX_VALUE; double max = -min; for (int x = 0; x < positions.length; x++){ if(values[x] < min){ min = values[x]; } if (values[x] > max){ max = values[x]; } } double range = max-min; //todo: this is kinda hideous for (int x = 0; x < positions.length - 1; x++){ if (positions[x] >= minpos && positions[x+1] <= maxpos){ g2.draw(new Line2D.Double(lineSpan * Math.abs((positions[x] - minpos)/spanpos) + left, top + TRACK_PALETTE + TRACK_BUMPER - (TRACK_PALETTE * Math.abs((values[x] - min)/range)), lineSpan * Math.abs((positions[x+1] - minpos)/spanpos) + left, top + TRACK_PALETTE + TRACK_BUMPER - (TRACK_PALETTE * Math.abs((values[x+1] - min)/range)))); } } top += TRACK_HEIGHT + TRACK_GAP; } if (theData.infoKnown) { Color green = new Color(0, 127, 0); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //// draw the marker locations g2.setStroke(thinnerStroke); g2.setColor(Color.white); g2.fill(new Rectangle2D.Double(left+1, top+1, lineSpan-1, TICK_HEIGHT-1)); g2.setColor(Color.black); g2.draw(new Rectangle2D.Double(left, top, lineSpan, TICK_HEIGHT)); for (int i = 0; i < Chromosome.getSize(); i++){ double pos = (Chromosome.getMarker(i).getPosition() - minpos) / spanpos; double xx = left + lineSpan*pos; // if we're zoomed, use the line color to indicate whether there is extra data available // (since the marker names are not displayed when zoomed) if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setColor(green); //draw tick g2.setStroke(thickerStroke); g2.draw(new Line2D.Double(xx, top, xx, top + TICK_HEIGHT)); if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setStroke(thickerStroke); else g2.setStroke(thinnerStroke); //draw connecting line g2.draw(new Line2D.Double(xx, top + TICK_HEIGHT, left + alignedPositions[i], top+TICK_BOTTOM)); if (Chromosome.getMarker(i).getExtra() != null && zoomLevel != 0) g2.setColor(Color.black); } top += TICK_BOTTOM + TICK_HEIGHT; //// draw the marker names if (printMarkerNames){ widestMarkerName = metrics.stringWidth(Chromosome.getMarker(0).getName()); for (int x = 1; x < Chromosome.getSize(); x++) { int thiswide = metrics.stringWidth(Chromosome.getMarker(x).getName()); if (thiswide > widestMarkerName) widestMarkerName = thiswide; } g2.translate(left, top + widestMarkerName); g2.rotate(-Math.PI / 2.0); for (int x = 0; x < Chromosome.getSize(); x++) { if (theData.isInBlock[x]){ g2.setFont(boldMarkerNameFont); }else{ g2.setFont(markerNameFont); } if (Chromosome.getMarker(x).getExtra() != null) g2.setColor(green); g2.drawString(Chromosome.getMarker(x).getName(),(float)TEXT_GAP, (float)alignedPositions[x] + ascent/3); if (Chromosome.getMarker(x).getExtra() != null) g2.setColor(Color.black); } g2.rotate(Math.PI / 2.0); g2.translate(-left, -(top + widestMarkerName)); // move everybody down top += widestMarkerName + TEXT_GAP; } g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } top += blockDispHeight; //// draw the marker numbers if (printMarkerNames){ g2.setFont(markerNumFont); metrics = g2.getFontMetrics(); ascent = metrics.getAscent(); for (int x = 0; x < Chromosome.getSize(); x++) { String mark = String.valueOf(Chromosome.realIndex[x] + 1); g2.drawString(mark, (float)(left + alignedPositions[x] - metrics.stringWidth(mark)/2), (float)(top + ascent)); } top += boxRadius/2; // give a little space between numbers and boxes } //clickxshift and clickyshift are used later to translate from x,y coords //to the pair of markers comparison at those coords if (!(theData.infoKnown)){ clickXShift = left + (size.width-pref.width)/2; clickYShift = top + (size.height - pref.height)/2; } else { clickXShift = left + (size.width-pref.width)/2; clickYShift = top; } // draw table column by column for (int x = lowX; x < highX; x++) { //always draw the fewest possible boxes if (lowY < x+1){ lowY = x+1; } for (int y = lowY; y < highY; y++) { if (dPrimeTable.getLDStats(x,y) == null){ continue; } double d = dPrimeTable.getLDStats(x,y).getDPrime(); //double l = dPrimeTable.getLDStats(x,y).getLOD(); Color boxColor = dPrimeTable.getLDStats(x,y).getColor(); // draw markers above int xx = left + (int)((alignedPositions[x] + alignedPositions[y])/2); int yy = top + (int)((alignedPositions[y] - alignedPositions[x]) / 2); diamondX[0] = xx; diamondY[0] = yy - boxRadius; diamondX[1] = xx + boxRadius; diamondY[1] = yy; diamondX[2] = xx; diamondY[2] = yy + boxRadius; diamondX[3] = xx - boxRadius; diamondY[3] = yy; diamond = new Polygon(diamondX, diamondY, 4); g2.setColor(boxColor); g2.fillPolygon(diamond); if(printDPrimeValues){ g2.setFont(boxFont); ascent = boxFontMetrics.getAscent(); int val = (int) (d * 100); g2.setColor((val < 50) ? Color.gray : Color.black); if (boxColor == Color.darkGray){ g2.setColor(Color.white); } if (val != 100) { String valu = String.valueOf(val); int widf = boxFontMetrics.stringWidth(valu); g.drawString(valu, xx - widf/2, yy + ascent/2); } } } } //highlight blocks g2.setFont(markerNameFont); ascent = g2.getFontMetrics().getAscent(); //g.setColor(new Color(153,255,153)); g2.setColor(Color.black); //g.setColor(new Color(51,153,51)); for (int i = 0; i < blocks.size(); i++){ int[] theBlock = (int[])blocks.elementAt(i); int first = theBlock[0]; int last = theBlock[theBlock.length-1]; //big vee around whole thing g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left + alignedPositions[first] - boxRadius, top, left + (alignedPositions[first] + alignedPositions[last])/2, top + (alignedPositions[last] - alignedPositions[first])/2 + boxRadius)); g2.draw(new Line2D.Double(left + (alignedPositions[first] + alignedPositions[last])/2, top + (alignedPositions[last] - alignedPositions[first])/2 + boxRadius, left + alignedPositions[last] + boxRadius, top)); for (int j = first; j < last; j++){ g2.setStroke(fatStroke); if (theData.isInBlock[j]){ g2.draw(new Line2D.Double(left+alignedPositions[j]-boxSize/2, top-blockDispHeight, left+alignedPositions[j+1]-boxSize/2, top-blockDispHeight)); }else{ g2.draw(new Line2D.Double(left + alignedPositions[j] + boxSize/2, top-blockDispHeight, left+alignedPositions[j+1]-boxSize/2, top-blockDispHeight)); g2.setStroke(dashedFatStroke); g2.draw(new Line2D.Double(left+alignedPositions[j] - boxSize/2, top-blockDispHeight, left+alignedPositions[j] + boxSize/2, top-blockDispHeight)); } } //cap off the end of the block g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left+alignedPositions[last]-boxSize/2, top-blockDispHeight, left+alignedPositions[last]+boxSize/2, top-blockDispHeight)); //lines to connect to block display g2.setStroke(fatStroke); g2.draw(new Line2D.Double(left + alignedPositions[first]-boxSize/2, top-1, left+alignedPositions[first]-boxSize/2, top-blockDispHeight)); g2.draw(new Line2D.Double(left+alignedPositions[last]+boxSize/2, top-1, left+alignedPositions[last]+boxSize/2, top-blockDispHeight)); if (printMarkerNames){ String labelString = new String ("Block " + (i+1)); if (theData.infoKnown){ long blockSize = Chromosome.getMarker(last).getPosition() - Chromosome.getMarker(first).getPosition(); labelString += " (" + blockSize/1000 + " kb)"; } g2.drawString(labelString, (float)(left+alignedPositions[first]-boxSize/2+TEXT_GAP), (float)(top-boxSize/3)); } } g2.setStroke(thickerStroke); if (showWM && !forExport){ //dataset is big enough to require worldmap if (wmMaxWidth == 0){ wmMaxWidth = visRect.width/3; } double scalefactor; scalefactor = (double)(chartSize.width)/wmMaxWidth; double prefBoxSize = boxSize/(scalefactor*((double)wmMaxWidth/(double)(wmMaxWidth))); //stick WM_BD in the middle of the blank space at the top of the worldmap final int WM_BD_GAP = (int)(infoHeight/(scalefactor*2)); final int WM_BD_HEIGHT = 2; CompoundBorder wmBorder = new CompoundBorder(BorderFactory.createRaisedBevelBorder(), BorderFactory.createLoweredBevelBorder()); if (noImage){ //first time through draw a worldmap if dataset is big: worldmap = new BufferedImage((int)(chartSize.width/scalefactor)+wmBorder.getBorderInsets(this).left*2, (int)(chartSize.height/scalefactor)+wmBorder.getBorderInsets(this).top*2, BufferedImage.TYPE_3BYTE_BGR); Graphics gw = worldmap.getGraphics(); Graphics2D gw2 = (Graphics2D)(gw); gw2.setColor(BG_GREY); gw2.fillRect(1,1,worldmap.getWidth()-1,worldmap.getHeight()-1); //make a pretty border gw2.setColor(Color.black); wmBorder.paintBorder(this,gw2,0,0,worldmap.getWidth(),worldmap.getHeight()); wmInteriorRect = wmBorder.getInteriorRectangle(this,0,0,worldmap.getWidth(), worldmap.getHeight()); float[] smallDiamondX = new float[4]; float[] smallDiamondY = new float[4]; GeneralPath gp; for (int x = 0; x < Chromosome.getSize()-1; x++){ for (int y = x+1; y < Chromosome.getSize(); y++){ if (dPrimeTable.getLDStats(x,y) == null){ continue; } double xx = ((alignedPositions[y] + alignedPositions[x])/(scalefactor*2)) + wmBorder.getBorderInsets(this).left; double yy = ((alignedPositions[y] - alignedPositions[x] + infoHeight*2)/(scalefactor*2)) + wmBorder.getBorderInsets(this).top; smallDiamondX[0] = (float)xx; smallDiamondY[0] = (float)(yy - prefBoxSize/2); smallDiamondX[1] = (float)(xx + prefBoxSize/2); smallDiamondY[1] = (float)yy; smallDiamondX[2] = (float)xx; smallDiamondY[2] = (float)(yy + prefBoxSize/2); smallDiamondX[3] = (float)(xx - prefBoxSize/2); smallDiamondY[3] = (float)yy; gp = new GeneralPath(GeneralPath.WIND_EVEN_ODD, smallDiamondX.length); gp.moveTo(smallDiamondX[0],smallDiamondY[0]); for (int i = 1; i < smallDiamondX.length; i++){ gp.lineTo(smallDiamondX[i], smallDiamondY[i]); } gp.closePath(); gw2.setColor(dPrimeTable.getLDStats(x,y).getColor()); gw2.fill(gp); } } noImage = false; } //draw block display in worldmap Graphics gw = worldmap.getGraphics(); Graphics2D gw2 = (Graphics2D)(gw); gw2.setColor(BG_GREY); gw2.fillRect(wmBorder.getBorderInsets(this).left, wmBorder.getBorderInsets(this).top+WM_BD_GAP, wmInteriorRect.width, WM_BD_HEIGHT); gw2.setColor(Color.black); boolean even = true; for (int i = 0; i < blocks.size(); i++){ int first = ((int[])blocks.elementAt(i))[0]; int last = ((int[])blocks.elementAt(i))[((int[])blocks.elementAt(i)).length-1]; int voffset; if (even){ voffset = 0; }else{ voffset = WM_BD_HEIGHT/2; } gw2.fillRect(wmBorder.getBorderInsets(this).left - (int)prefBoxSize/2 + (int)(alignedPositions[first]/scalefactor), wmBorder.getBorderInsets(this).top+voffset+WM_BD_GAP, (int)(prefBoxSize + (alignedPositions[last] - alignedPositions[first])/scalefactor), WM_BD_HEIGHT/2); even = !even; } wmResizeCorner = new Rectangle(visRect.x + worldmap.getWidth() - (worldmap.getWidth()-wmInteriorRect.width)/2, visRect.y + visRect.height - worldmap.getHeight(), (worldmap.getWidth()-wmInteriorRect.width)/2, (worldmap.getHeight() -wmInteriorRect.height)/2); g2.drawImage(worldmap,visRect.x, visRect.y + visRect.height - worldmap.getHeight(), this); wmInteriorRect.x = visRect.x + (worldmap.getWidth() - wmInteriorRect.width)/2; wmInteriorRect.y = visRect.y+visRect.height-worldmap.getHeight() + (worldmap.getHeight() - wmInteriorRect.height)/2; //draw the outline of the viewport g2.setColor(Color.black); double hRatio = wmInteriorRect.getWidth()/pref.getWidth(); double vRatio = wmInteriorRect.getHeight()/pref.getHeight(); int hBump = worldmap.getWidth()-wmInteriorRect.width; int vBump = worldmap.getHeight()-wmInteriorRect.height; //bump a few pixels to avoid drawing on the border g2.drawRect((int)(visRect.x*hRatio)+hBump/2+visRect.x, (int)(visRect.y*vRatio)+vBump/2+(visRect.y + visRect.height - worldmap.getHeight()), (int)(visRect.width*hRatio), (int)(visRect.height*vRatio)); } //see if the user has right-clicked to popup some marker info if(popupDrawRect != null){ //dumb bug where little datasets popup the box in the wrong place int smallDatasetSlopH = 0; int smallDatasetSlopV = 0; if (pref.getHeight() < visRect.height){ smallDatasetSlopV = (int)(visRect.height - pref.getHeight())/2; } if (pref.getWidth() < visRect.width){ smallDatasetSlopH = (int)(visRect.width - pref.getWidth())/2; } g2.setColor(Color.white); g2.fillRect(popupDrawRect.x+1-smallDatasetSlopH, popupDrawRect.y+1-smallDatasetSlopV, popupDrawRect.width-1, popupDrawRect.height-1); g2.setColor(Color.black); g2.drawRect(popupDrawRect.x-smallDatasetSlopH, popupDrawRect.y-smallDatasetSlopV, popupDrawRect.width, popupDrawRect.height); g.setFont(popupFont); for (int x = 0; x < displayStrings.size(); x++){ g.drawString((String)displayStrings.elementAt(x),popupDrawRect.x + popupLeftMargin-smallDatasetSlopH, popupDrawRect.y+((x+1)*metrics.getHeight())-smallDatasetSlopV); } } //see if we're drawing a worldmap resize rect if (resizeWMRect != null){ g2.setColor(Color.black); g2.drawRect(resizeWMRect.x, resizeWMRect.y, resizeWMRect.width, resizeWMRect.height); } //see if we're drawing a block selector rect if (blockRect != null){ g2.setColor(Color.black); g2.setStroke(dashedThinStroke); g2.drawRect(blockRect.x, blockRect.y, blockRect.width, blockRect.height); } }
1,111,136
private UserManager(File userConfigFile){ try{ lastModified = userConfigFile.lastModified(); Document userConfig = new SAXBuilder().build(userConfigFile); users = loadUsers(userConfig); }catch(JDOMException jdEx){ logger.info("Error reading user info "+USER_CONFIG_FILE_NAME); jdEx.printStackTrace(); } }
private UserManager(File userConfigFile){ try{ Document userConfig = new SAXBuilder().build(userConfigFile); users = loadUsers(userConfig); }catch(JDOMException jdEx){ logger.info("Error reading user info "+USER_CONFIG_FILE_NAME); jdEx.printStackTrace(); } }
1,111,137
public static UserManager getInstance(){ File userConfiguration = new File(USER_CONFIG_FILE_NAME); if(lastModified < userConfiguration.lastModified()){ /* Refresh the cache */ userManager = new UserManager(userConfiguration); } return userManager; }
public static UserManager getInstance(){ File userConfiguration = new File(USER_CONFIG_FILE_NAME); if(lastModified < userConfiguration.lastModified()){ /* Refresh the cache */ userManager = new UserManager(userConfiguration); } return userManager; }
1,111,138
public QueryFulltextCriteria( QueryField field, String text ) { this.field = field; this.text = text; }
public QueryFulltextCriteria( QueryField field ) { this.field = field; this.text = text; }
1,111,140
public QueryFulltextCriteria( QueryField field, String text ) { this.field = field; this.text = text; }
public QueryFulltextCriteria( QueryField field, String text ) { this.field = field; }
1,111,141
public void setupQuery( Criteria crit ) { String sql = "MATCH(" + field.getName() + ") AGAINST('" + text + "')"; System.out.println( sql ); crit.addSql( sql ); System.out.println( "Added" ); }
public void setupQuery( Criteria crit ) { String sql = "MATCH(" + field.getName() + ") AGAINST('" + text + "')"; log.debug( sql ); crit.addSql( sql ); System.out.println( "Added" ); }
1,111,142
public void setupQuery( Criteria crit ) { String sql = "MATCH(" + field.getName() + ") AGAINST('" + text + "')"; System.out.println( sql ); crit.addSql( sql ); System.out.println( "Added" ); }
public void setupQuery( Criteria crit ) { String sql = "MATCH(" + field.getName() + ") AGAINST('" + text + "')"; System.out.println( sql ); crit.addSql( sql ); log.debug( "Added" ); }
1,111,143
public synchronized void addObjects(List list, Point preferredLocation, ArchitectSwingWorker nextProcess) throws ArchitectException { ProgressMonitor pm = new ProgressMonitor(null, "Copying objects to the playpen", "...", 0, 100); AddObjectsTask t = new AddObjectsTask(list, preferredLocation, pm, null); t.setNextProcess(nextProcess); new Thread(t, "Objects-Adder").start(); }
public synchronized void addObjects(List list, Point preferredLocation, ArchitectSwingWorker nextProcess) throws ArchitectException { ProgressMonitor pm = new ProgressMonitor(this, "Copying objects to the playpen", "...", 0, 100); AddObjectsTask t = new AddObjectsTask(list, preferredLocation, pm, null); t.setNextProcess(nextProcess); new Thread(t, "Objects-Adder").start(); }
1,111,144
protected void reset() { if (ignoreReset) { // preserve the objects that are in the Target system when // the connection spec changes logger.debug("Ignoring Reset request for: " + getDataSource()); populated = true; } else { // discard everything and reload (this is generally for source systems) logger.debug("Resetting: " + getDataSource() ); // tear down old connection stuff List old = children; if (old != null && old.size() > 0) { int[] oldIndices = new int[old.size()]; for (int i = 0, n = old.size(); i < n; i++) { oldIndices[i] = i; } fireDbChildrenRemoved(oldIndices, old); } children = new ArrayList(); populated = false; } // reset connection in either case if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } connection = null; }
protected void reset() { if (playPenDatabase) { // preserve the objects that are in the Target system when // the connection spec changes logger.debug("Ignoring Reset request for: " + getDataSource()); populated = true; } else { // discard everything and reload (this is generally for source systems) logger.debug("Resetting: " + getDataSource() ); // tear down old connection stuff List old = children; if (old != null && old.size() > 0) { int[] oldIndices = new int[old.size()]; for (int i = 0, n = old.size(); i < n; i++) { oldIndices[i] = i; } fireDbChildrenRemoved(oldIndices, old); } children = new ArrayList(); populated = false; } // reset connection in either case if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } connection = null; }
1,111,145
public void mousePressed(MouseEvent evt) { evt.getComponent().requestFocus(); // make sure it was a left click? if ((evt.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) != 0) { TablePane tp = (TablePane) evt.getSource(); // dragging try { PlayPen pp = (PlayPen) tp.getPlayPen(); int clickCol = tp.pointToColumnIndex(evt.getPoint()); logger.debug("MP: clickCol="+clickCol+",columnsSize="+tp.model.getColumns().size()); if ( (evt.getModifiersEx() & (InputEvent.SHIFT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK)) == 0) { // 1. unconditionally de-select everything if this table is unselected // 2. if the table was selected, de-select everything if the click was not on the // column header of the table if (!tp.isSelected() || (clickCol > COLUMN_INDEX_TITLE && clickCol < tp.model.getColumns().size()) ) { pp.selectNone(); } } // re-select the table pane (fire new selection event when appropriate) tp.setSelected(true); // de-select columns if shift and ctrl were not pressed if ( (evt.getModifiersEx() & (InputEvent.SHIFT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK)) == 0) { tp.selectNone(); } // select current column unconditionally if (clickCol < tp.model.getColumns().size()) { tp.selectColumn(clickCol); } // handle drag if (clickCol == COLUMN_INDEX_TITLE) { Iterator it = getPlayPen().getSelectedTables().iterator(); logger.debug("event point: " + evt.getPoint()); logger.debug("zoomed event point: " + getPlayPen().zoomPoint(evt.getPoint())); while (it.hasNext()) { // create FloatingTableListener for each selected item TablePane t3 = (TablePane)it.next(); logger.debug("(" + t3.getModel().getTableName() + ") zoomed selected table point: " + t3.getLocationOnScreen()); logger.debug("(" + t3.getModel().getTableName() + ") unzoomed selected table point: " + getPlayPen().unzoomPoint(t3.getLocationOnScreen())); /* the floating table listener expects zoomed handles which are relative to the location of the table column which was clicked on. */ Point clickedColumn = tp.getLocationOnScreen(); Point otherTable = t3.getLocationOnScreen(); Point handle = getPlayPen().zoomPoint(new Point(evt.getPoint())); logger.debug("(" + t3.getModel().getTableName() + ") translation x=" + (otherTable.getX() - clickedColumn.getX()) + ",y=" + (otherTable.getY() - clickedColumn.getY())); handle.translate((int)(clickedColumn.getX() - otherTable.getX()), (int) (clickedColumn.getY() - otherTable.getY())); new PlayPen.FloatingTableListener(getPlayPen(), t3, handle); } } } catch (ArchitectException e) { logger.error("Exception converting point to column", e); } } maybeShowPopup(evt); }
public void mousePressed(MouseEvent evt) { evt.getComponent().requestFocus(); // make sure it was a left click? if ((evt.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) != 0) { TablePane tp = (TablePane) evt.getSource(); // dragging try { PlayPen pp = (PlayPen) tp.getPlayPen(); int clickCol = tp.pointToColumnIndex(evt.getPoint()); logger.debug("MP: clickCol="+clickCol+",columnsSize="+tp.model.getColumns().size()); if ( (evt.getModifiersEx() & (InputEvent.SHIFT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK)) == 0) { // 1. unconditionally de-select everything if this table is unselected // 2. if the table was selected, de-select everything if the click was not on the // column header of the table if (!tp.isSelected() || (clickCol > COLUMN_INDEX_TITLE && clickCol < tp.model.getColumns().size()) ) { pp.selectNone(); } } // re-select the table pane (fire new selection event when appropriate) tp.setSelected(true); // de-select columns if shift and ctrl were not pressed if ( (evt.getModifiersEx() & (InputEvent.SHIFT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK)) == 0) { tp.selectNone(); } // select current column unconditionally if (clickCol < tp.model.getColumns().size()) { tp.selectColumn(clickCol); } // handle drag if (clickCol == COLUMN_INDEX_TITLE && !ArchitectFrame.getMainInstance().createRelationshipIsActive()) { Iterator it = getPlayPen().getSelectedTables().iterator(); logger.debug("event point: " + evt.getPoint()); logger.debug("zoomed event point: " + getPlayPen().zoomPoint(evt.getPoint())); while (it.hasNext()) { // create FloatingTableListener for each selected item TablePane t3 = (TablePane)it.next(); logger.debug("(" + t3.getModel().getTableName() + ") zoomed selected table point: " + t3.getLocationOnScreen()); logger.debug("(" + t3.getModel().getTableName() + ") unzoomed selected table point: " + getPlayPen().unzoomPoint(t3.getLocationOnScreen())); /* the floating table listener expects zoomed handles which are relative to the location of the table column which was clicked on. */ Point clickedColumn = tp.getLocationOnScreen(); Point otherTable = t3.getLocationOnScreen(); Point handle = getPlayPen().zoomPoint(new Point(evt.getPoint())); logger.debug("(" + t3.getModel().getTableName() + ") translation x=" + (otherTable.getX() - clickedColumn.getX()) + ",y=" + (otherTable.getY() - clickedColumn.getY())); handle.translate((int)(clickedColumn.getX() - otherTable.getX()), (int) (clickedColumn.getY() - otherTable.getY())); new PlayPen.FloatingTableListener(getPlayPen(), t3, handle); } } } catch (ArchitectException e) { logger.error("Exception converting point to column", e); } } maybeShowPopup(evt); }
1,111,146
protected ActionForward processActionPerform(HttpServletRequest request, HttpServletResponse response, Action action, ActionForm form, ActionMapping mapping) throws IOException, ServletException{ final String requestPath = mapping.getPath(); logger.info("Start Request Path:" + requestPath); ActionForward resultForward = null; try{ /* execute the action */ resultForward = action.execute(mapping, form, request, response); }catch (Exception e){ logger.log(Level.INFO, "Exception on Request: " + requestPath, e); /* process exception */ resultForward = processException(request, response, e, form, mapping); }finally{ String resultForwardPath = (resultForward == null) ? "none" : resultForward.getPath(); if(resultForwardPath == null){ /* the path attribute of resultForward was null */ resultForwardPath = "none"; } logger.info("End Request:" + requestPath + " Forward:" + resultForwardPath); } /* handle debug mode*/ resultForward = handleDebugMode(request, response, resultForward); return resultForward; }
protected ActionForward processActionPerform(HttpServletRequest request, HttpServletResponse response, Action action, ActionForm form, ActionMapping mapping) throws IOException, ServletException{ final String requestPath = mapping.getPath(); logger.fine("Start Request Path:" + requestPath); ActionForward resultForward = null; try{ /* execute the action */ resultForward = action.execute(mapping, form, request, response); }catch (Exception e){ logger.log(Level.INFO, "Exception on Request: " + requestPath, e); /* process exception */ resultForward = processException(request, response, e, form, mapping); }finally{ String resultForwardPath = (resultForward == null) ? "none" : resultForward.getPath(); if(resultForwardPath == null){ /* the path attribute of resultForward was null */ resultForwardPath = "none"; } logger.info("End Request:" + requestPath + " Forward:" + resultForwardPath); } /* handle debug mode*/ resultForward = handleDebugMode(request, response, resultForward); return resultForward; }
1,111,147
protected ActionForward processActionPerform(HttpServletRequest request, HttpServletResponse response, Action action, ActionForm form, ActionMapping mapping) throws IOException, ServletException{ final String requestPath = mapping.getPath(); logger.info("Start Request Path:" + requestPath); ActionForward resultForward = null; try{ /* execute the action */ resultForward = action.execute(mapping, form, request, response); }catch (Exception e){ logger.log(Level.INFO, "Exception on Request: " + requestPath, e); /* process exception */ resultForward = processException(request, response, e, form, mapping); }finally{ String resultForwardPath = (resultForward == null) ? "none" : resultForward.getPath(); if(resultForwardPath == null){ /* the path attribute of resultForward was null */ resultForwardPath = "none"; } logger.info("End Request:" + requestPath + " Forward:" + resultForwardPath); } /* handle debug mode*/ resultForward = handleDebugMode(request, response, resultForward); return resultForward; }
protected ActionForward processActionPerform(HttpServletRequest request, HttpServletResponse response, Action action, ActionForm form, ActionMapping mapping) throws IOException, ServletException{ final String requestPath = mapping.getPath(); logger.info("Start Request Path:" + requestPath); ActionForward resultForward = null; try{ /* execute the action */ resultForward = ensureLoggedIn(request, response, mapping); if(resultForward == null){ resultForward = action.execute(mapping, form, request, response); } }catch (Exception e){ logger.log(Level.INFO, "Exception on Request: " + requestPath, e); /* process exception */ resultForward = processException(request, response, e, form, mapping); }finally{ String resultForwardPath = (resultForward == null) ? "none" : resultForward.getPath(); if(resultForwardPath == null){ /* the path attribute of resultForward was null */ resultForwardPath = "none"; } logger.info("End Request:" + requestPath + " Forward:" + resultForwardPath); } /* handle debug mode*/ resultForward = handleDebugMode(request, response, resultForward); return resultForward; }
1,111,148
protected ActionForward processActionPerform(HttpServletRequest request, HttpServletResponse response, Action action, ActionForm form, ActionMapping mapping) throws IOException, ServletException{ final String requestPath = mapping.getPath(); logger.info("Start Request Path:" + requestPath); ActionForward resultForward = null; try{ /* execute the action */ resultForward = action.execute(mapping, form, request, response); }catch (Exception e){ logger.log(Level.INFO, "Exception on Request: " + requestPath, e); /* process exception */ resultForward = processException(request, response, e, form, mapping); }finally{ String resultForwardPath = (resultForward == null) ? "none" : resultForward.getPath(); if(resultForwardPath == null){ /* the path attribute of resultForward was null */ resultForwardPath = "none"; } logger.info("End Request:" + requestPath + " Forward:" + resultForwardPath); } /* handle debug mode*/ resultForward = handleDebugMode(request, response, resultForward); return resultForward; }
protected ActionForward processActionPerform(HttpServletRequest request, HttpServletResponse response, Action action, ActionForm form, ActionMapping mapping) throws IOException, ServletException{ final String requestPath = mapping.getPath(); logger.info("Start Request Path:" + requestPath); ActionForward resultForward = null; try{ /* execute the action */ resultForward = action.execute(mapping, form, request, response); }catch (Exception e){ logger.log(Level.FINE, "Exception on Request: " + requestPath, e); /* process exception */ resultForward = processException(request, response, e, form, mapping); }finally{ String resultForwardPath = (resultForward == null) ? "none" : resultForward.getPath(); if(resultForwardPath == null){ /* the path attribute of resultForward was null */ resultForwardPath = "none"; } logger.info("End Request:" + requestPath + " Forward:" + resultForwardPath); } /* handle debug mode*/ resultForward = handleDebugMode(request, response, resultForward); return resultForward; }
1,111,149
protected ActionForward processActionPerform(HttpServletRequest request, HttpServletResponse response, Action action, ActionForm form, ActionMapping mapping) throws IOException, ServletException{ final String requestPath = mapping.getPath(); logger.info("Start Request Path:" + requestPath); ActionForward resultForward = null; try{ /* execute the action */ resultForward = action.execute(mapping, form, request, response); }catch (Exception e){ logger.log(Level.INFO, "Exception on Request: " + requestPath, e); /* process exception */ resultForward = processException(request, response, e, form, mapping); }finally{ String resultForwardPath = (resultForward == null) ? "none" : resultForward.getPath(); if(resultForwardPath == null){ /* the path attribute of resultForward was null */ resultForwardPath = "none"; } logger.info("End Request:" + requestPath + " Forward:" + resultForwardPath); } /* handle debug mode*/ resultForward = handleDebugMode(request, response, resultForward); return resultForward; }
protected ActionForward processActionPerform(HttpServletRequest request, HttpServletResponse response, Action action, ActionForm form, ActionMapping mapping) throws IOException, ServletException{ final String requestPath = mapping.getPath(); logger.info("Start Request Path:" + requestPath); ActionForward resultForward = null; try{ /* execute the action */ resultForward = action.execute(mapping, form, request, response); }catch (Exception e){ logger.log(Level.INFO, "Exception on Request: " + requestPath, e); /* process exception */ resultForward = processException(request, response, e, form, mapping); }finally{ String resultForwardPath = (resultForward == null) ? "none" : resultForward.getPath(); if(resultForwardPath == null){ /* the path attribute of resultForward was null */ resultForwardPath = "none"; } logger.fine("End Request:" + requestPath + " Forward:" + resultForwardPath); } /* handle debug mode*/ resultForward = handleDebugMode(request, response, resultForward); return resultForward; }
1,111,150
public void actionPerformed(ActionEvent evt) { dbcsPanel.applyChanges(); DBConnectionSpec dbcs = dbcsPanel.getDbcs(); ASUtils.LabelValueBean connLvb = ASUtils.lvb(dbcs.getDisplayName(), dbcs); connectionsBox.addItem(connLvb); connectionsBox.setSelectedItem(connLvb); ArchitectFrame.getMainInstance().getUserSettings().getConnections().add(dbcs); d.setVisible(false); }
public void actionPerformed(ActionEvent evt) { dbcsPanel.applyChanges(); DBConnectionSpec dbcs = dbcsPanel.getDbcs(); ASUtils.LabelValueBean connLvb = ASUtils.lvb(dbcs.getDisplayName(), dbcs); connectionsBox.addItem(connLvb); connectionsBox.setSelectedItem(connLvb); ArchitectFrame.getMainInstance().getUserSettings().getConnections().add(dbcs); d.setVisible(false); }
1,111,152
public PLExportPanel() { setLayout(new GridLayout(1,2)); ArchitectFrame af = ArchitectFrame.getMainInstance(); SwingUIProject project = af.getProject(); projName = new String(project.getName()); newConnButton= new JButton("New"); newConnButton.addActionListener(new NewConnectionListener()); String plIniPath = af.getUserSettings().getETLUserSettings().getPlDotIniPath(); List plConnectionSpecs = new ArrayList(); try { if (plIniPath != null) { plConnectionSpecs = PLUtils.parsePlDotIni(plIniPath); } else { JOptionPane.showMessageDialog (this, "Warning: You have not set the PL.INI file location." +"\nThe list of PL Connections will be empty."); } } catch (FileNotFoundException ie) { JOptionPane.showMessageDialog (this, "PL database config file not found in specified path:\n" +plIniPath+"\nThe list of PL Connections will be empty."); } catch (IOException ie){ JOptionPane.showMessageDialog(this, "Error reading PL.ini file "+plIniPath +"\nThe list of PL Connections will be empty."); } connections = new Vector(); connections.add(ASUtils.lvb("(Select Architect Connection)", null)); Iterator it = af.getUserSettings().getConnections().iterator(); while (it.hasNext()) { DBConnectionSpec spec = (DBConnectionSpec) it.next(); connections.add(ASUtils.lvb(spec.getDisplayName(), spec)); } connectionsBox = new JComboBox(connections); plodbc = new Vector(); plodbc.add(ASUtils.lvb("(Select PL ODBC Connection)", null)); it = plConnectionSpecs.iterator(); while (it.hasNext()) { PLConnectionSpec plcon = (PLConnectionSpec) it.next(); plodbc.add(ASUtils.lvb(plcon.getLogical(), plcon)); } plOdbcTargetRepositoryBox = new JComboBox(plodbc); plOdbcTargetRepositoryBox.addActionListener(new OdbcTargetRepositoryListener()); runPLEngine = new JCheckBox(); runPLEngine.setEnabled(false); JPanel jdbcPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); jdbcPanel.add(connectionsBox); jdbcPanel.add(newConnButton); JComponent[] jdbcFields = new JComponent[] {jdbcPanel, plRepOwner = new JTextField(), plFolderName = new JTextField(), plJobId = new JTextField(), plJobDescription = new JTextField(), plJobComment = new JTextField(), plOutputTableOwner = new JTextField()}; String[] jdbcLabels = new String[] {"Architect Connection Name", "PL Repository Owner", "PL Folder Name", "PL Job Id", "PL Job Description", "PL Job Comment", "Target Schema Owner"}; char[] jdbcMnemonics = new char[] {'t', 'r', 'f', 'i', 'd', 'c', 'o'}; int[] jdbcWidths = new int[] {18, 18, 18, 18, 18, 18, 18, 18,10}; String[] jdbcTips = new String[] {"Target database and PL repository", "Owner of PL Repository", "The folder name for transactions", "The Job unique Id", "The Job Description", "Comment about the Job", "Owner (Schema) for output transaction tables"}; TextPanel jdbcForm = new TextPanel(jdbcFields, jdbcLabels, jdbcMnemonics, jdbcWidths, jdbcTips); JComponent[] engineFields = new JComponent[] {plOdbcTargetRepositoryBox, plUserName = new JTextField(), plPassword = new JPasswordField(), runPLEngine}; String[] engineLabels = new String[] {"PL.INI Logical Database Name", "PL User Name", "PL Password", "Run Engine"}; char[] engineMnemonics = new char[] {'l', 'u', 'p', 'e'}; int[] engineWidths = new int[] {18, 18, 18, 10}; String[] engineTips = new String[] {"ODBC Source Name connection for PL", "PowerLoader User Name", "PowerLoader Password", "Run PL Engine immediately?"}; TextPanel engineForm = new TextPanel(engineFields, engineLabels, engineMnemonics, engineWidths, engineTips); add(jdbcForm); add(engineForm); }
public PLExportPanel() { setLayout(new GridLayout(1,2)); ArchitectFrame af = ArchitectFrame.getMainInstance(); SwingUIProject project = af.getProject(); projName = new String(project.getName()); newConnButton= new JButton("New"); newConnButton.addActionListener(new NewConnectionListener()); String plIniPath = af.getUserSettings().getETLUserSettings().getPlDotIniPath(); List plConnectionSpecs = new ArrayList(); try { if (plIniPath != null) { plConnectionSpecs = PLUtils.parsePlDotIni(plIniPath); } else { JOptionPane.showMessageDialog (this, "Warning: You have not set the PL.INI file location." +"\nThe list of PL Connections will be empty."); } } catch (FileNotFoundException ie) { JOptionPane.showMessageDialog (this, "PL database config file not found in specified path:\n" +plIniPath+"\nThe list of PL Connections will be empty."); } catch (IOException ie){ JOptionPane.showMessageDialog(this, "Error reading PL.ini file "+plIniPath +"\nThe list of PL Connections will be empty."); } connections = new Vector(); connections.add(ASUtils.lvb("(Select Architect Connection)", null)); Iterator it = af.getUserSettings().getConnections().iterator(); while (it.hasNext()) { DBConnectionSpec spec = (DBConnectionSpec) it.next(); connections.add(ASUtils.lvb(spec.getDisplayName(), spec)); } connectionsBox = new JComboBox(connections); plodbc = new Vector(); plodbc.add(ASUtils.lvb("(Select PL ODBC Connection)", null)); it = plConnectionSpecs.iterator(); while (it.hasNext()) { PLConnectionSpec plcon = (PLConnectionSpec) it.next(); plodbc.add(ASUtils.lvb(plcon.getLogical(), plcon)); } plOdbcTargetRepositoryBox = new JComboBox(plodbc); plOdbcTargetRepositoryBox.addActionListener(new OdbcTargetRepositoryListener()); runPLEngine = new JCheckBox(); runPLEngine.setEnabled(false); JPanel jdbcPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); jdbcPanel.add(connectionsBox); jdbcPanel.add(newConnButton); JComponent[] jdbcFields = new JComponent[] {jdbcPanel, plRepOwner = new JTextField(), plFolderName = new JTextField(), plJobId = new JTextField(), plJobDescription = new JTextField(), plJobComment = new JTextField(), plOutputTableOwner = new JTextField()}; String[] jdbcLabels = new String[] {"Architect Connection Name", "PL Repository Owner", "PL Folder Name", "PL Job Id", "PL Job Description", "PL Job Comment", "Target Schema Owner"}; char[] jdbcMnemonics = new char[] {'t', 'r', 'f', 'i', 'd', 'c', 'o'}; int[] jdbcWidths = new int[] {18, 18, 18, 18, 18, 18, 18, 18,10}; String[] jdbcTips = new String[] {"Target database and PL repository", "Owner of PL Repository", "The folder name for transactions", "The Job unique Id", "The Job Description", "Comment about the Job", "Owner (Schema) for output transaction tables"}; TextPanel jdbcForm = new TextPanel(jdbcFields, jdbcLabels, jdbcMnemonics, jdbcWidths, jdbcTips); JComponent[] engineFields = new JComponent[] {plOdbcTargetRepositoryBox, plUserName = new JTextField(), plPassword = new JPasswordField(), runPLEngine}; String[] engineLabels = new String[] {"PL.INI Logical Database Name", "PL User Name", "PL Password", "Run Engine"}; char[] engineMnemonics = new char[] {'l', 'u', 'p', 'e'}; int[] engineWidths = new int[] {18, 18, 18, 10}; String[] engineTips = new String[] {"ODBC Source Name connection for PL", "PowerLoader User Name", "PowerLoader Password", "Run PL Engine immediately?"}; TextPanel engineForm = new TextPanel(engineFields, engineLabels, engineMnemonics, engineWidths, engineTips); add(jdbcForm); add(engineForm); }
1,111,155
public PLExportPanel() { setLayout(new GridLayout(1,2)); ArchitectFrame af = ArchitectFrame.getMainInstance(); SwingUIProject project = af.getProject(); projName = new String(project.getName()); newConnButton= new JButton("New"); newConnButton.addActionListener(new NewConnectionListener()); String plIniPath = af.getUserSettings().getETLUserSettings().getPlDotIniPath(); List plConnectionSpecs = new ArrayList(); try { if (plIniPath != null) { plConnectionSpecs = PLUtils.parsePlDotIni(plIniPath); } else { JOptionPane.showMessageDialog (this, "Warning: You have not set the PL.INI file location." +"\nThe list of PL Connections will be empty."); } } catch (FileNotFoundException ie) { JOptionPane.showMessageDialog (this, "PL database config file not found in specified path:\n" +plIniPath+"\nThe list of PL Connections will be empty."); } catch (IOException ie){ JOptionPane.showMessageDialog(this, "Error reading PL.ini file "+plIniPath +"\nThe list of PL Connections will be empty."); } connections = new Vector(); connections.add(ASUtils.lvb("(Select Architect Connection)", null)); Iterator it = af.getUserSettings().getConnections().iterator(); while (it.hasNext()) { DBConnectionSpec spec = (DBConnectionSpec) it.next(); connections.add(ASUtils.lvb(spec.getDisplayName(), spec)); } connectionsBox = new JComboBox(connections); plodbc = new Vector(); plodbc.add(ASUtils.lvb("(Select PL ODBC Connection)", null)); it = plConnectionSpecs.iterator(); while (it.hasNext()) { PLConnectionSpec plcon = (PLConnectionSpec) it.next(); plodbc.add(ASUtils.lvb(plcon.getLogical(), plcon)); } plOdbcTargetRepositoryBox = new JComboBox(plodbc); plOdbcTargetRepositoryBox.addActionListener(new OdbcTargetRepositoryListener()); runPLEngine = new JCheckBox(); runPLEngine.setEnabled(false); JPanel jdbcPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); jdbcPanel.add(connectionsBox); jdbcPanel.add(newConnButton); JComponent[] jdbcFields = new JComponent[] {jdbcPanel, plRepOwner = new JTextField(), plFolderName = new JTextField(), plJobId = new JTextField(), plJobDescription = new JTextField(), plJobComment = new JTextField(), plOutputTableOwner = new JTextField()}; String[] jdbcLabels = new String[] {"Architect Connection Name", "PL Repository Owner", "PL Folder Name", "PL Job Id", "PL Job Description", "PL Job Comment", "Target Schema Owner"}; char[] jdbcMnemonics = new char[] {'t', 'r', 'f', 'i', 'd', 'c', 'o'}; int[] jdbcWidths = new int[] {18, 18, 18, 18, 18, 18, 18, 18,10}; String[] jdbcTips = new String[] {"Target database and PL repository", "Owner of PL Repository", "The folder name for transactions", "The Job unique Id", "The Job Description", "Comment about the Job", "Owner (Schema) for output transaction tables"}; TextPanel jdbcForm = new TextPanel(jdbcFields, jdbcLabels, jdbcMnemonics, jdbcWidths, jdbcTips); JComponent[] engineFields = new JComponent[] {plOdbcTargetRepositoryBox, plUserName = new JTextField(), plPassword = new JPasswordField(), runPLEngine}; String[] engineLabels = new String[] {"PL.INI Logical Database Name", "PL User Name", "PL Password", "Run Engine"}; char[] engineMnemonics = new char[] {'l', 'u', 'p', 'e'}; int[] engineWidths = new int[] {18, 18, 18, 10}; String[] engineTips = new String[] {"ODBC Source Name connection for PL", "PowerLoader User Name", "PowerLoader Password", "Run PL Engine immediately?"}; TextPanel engineForm = new TextPanel(engineFields, engineLabels, engineMnemonics, engineWidths, engineTips); add(jdbcForm); add(engineForm); }
public PLExportPanel() { setLayout(new GridLayout(1,2)); ArchitectFrame af = ArchitectFrame.getMainInstance(); SwingUIProject project = af.getProject(); projName = new String(project.getName()); newConnButton= new JButton("New"); newConnButton.addActionListener(new NewConnectionListener()); String plIniPath = af.getUserSettings().getETLUserSettings().getPlDotIniPath(); List plConnectionSpecs = new ArrayList(); try { if (plIniPath != null) { plConnectionSpecs = PLUtils.parsePlDotIni(plIniPath); } else { JOptionPane.showMessageDialog (this, "Warning: You have not set the PL.INI file location." +"\nThe list of PL Connections will be empty."); } } catch (FileNotFoundException ie) { JOptionPane.showMessageDialog (this, "PL database config file not found in specified path:\n" +plIniPath+"\nThe list of PL Connections will be empty."); } catch (IOException ie){ JOptionPane.showMessageDialog(this, "Error reading PL.ini file "+plIniPath +"\nThe list of PL Connections will be empty."); } connections = new Vector(); connections.add(ASUtils.lvb("(Select Architect Connection)", null)); Iterator it = af.getUserSettings().getConnections().iterator(); while (it.hasNext()) { DBConnectionSpec spec = (DBConnectionSpec) it.next(); connections.add(ASUtils.lvb(spec.getDisplayName(), spec)); } connectionsBox = new JComboBox(connections); plodbc = new Vector(); plodbc.add(ASUtils.lvb("(Select PL ODBC Connection)", null)); it = plConnectionSpecs.iterator(); while (it.hasNext()) { PLConnectionSpec plcon = (PLConnectionSpec) it.next(); plodbc.add(ASUtils.lvb(plcon.getLogical(), plcon)); } plOdbcTargetRepositoryBox = new JComboBox(plodbc); plOdbcTargetRepositoryBox.addActionListener(new OdbcTargetRepositoryListener()); runPLEngine = new JCheckBox(); runPLEngine.setEnabled(false); JPanel jdbcPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); jdbcPanel.add(connectionsBox); jdbcPanel.add(newConnButton); JComponent[] jdbcFields = new JComponent[] {jdbcPanel, plRepOwner = new JTextField(), plFolderName = new JTextField(), plJobId = new JTextField(), plJobDescription = new JTextField(), plJobComment = new JTextField(), plOutputTableOwner = new JTextField()}; String[] jdbcLabels = new String[] {"Architect Connection Name", "PL Repository Owner", "PL Folder Name", "PL Job Id", "PL Job Description", "PL Job Comment", "Target Schema Owner"}; char[] jdbcMnemonics = new char[] {'t', 'r', 'f', 'i', 'd', 'c', 'o'}; int[] jdbcWidths = new int[] {18, 18, 18, 18, 18, 18, 18, 18,10}; String[] jdbcTips = new String[] {"Target database and PL repository", "Owner of PL Repository", "The folder name for transactions", "The Job unique Id", "The Job Description", "Comment about the Job", "Owner (Schema) for output transaction tables"}; TextPanel jdbcForm = new TextPanel(jdbcFields, jdbcLabels, jdbcMnemonics, jdbcWidths, jdbcTips); JComponent[] engineFields = new JComponent[] {plOdbcTargetRepositoryBox, plUserName = new JTextField(), plPassword = new JPasswordField(), runPLEngine}; String[] engineLabels = new String[] {"PL.INI Logical Database Name", "PL User Name", "PL Password", "Run Engine"}; char[] engineMnemonics = new char[] {'l', 'u', 'p', 'e'}; int[] engineWidths = new int[] {18, 18, 18, 10}; String[] engineTips = new String[] {"ODBC Source Name connection for PL", "PowerLoader User Name", "PowerLoader Password", "Run PL Engine immediately?"}; TextPanel engineForm = new TextPanel(engineFields, engineLabels, engineMnemonics, engineWidths, engineTips); add(jdbcForm); add(engineForm); }
1,111,156
public void stateChanged(ChangeEvent e) { viewMenuItems[tabs.getSelectedIndex()].setSelected(true); if (checkPanel.changed){ window.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); JTable table = checkPanel.getTable(); boolean[] markerResults = new boolean[table.getRowCount()]; for (int i = 0; i < table.getRowCount(); i++){ markerResults[i] = ((Boolean)table.getValueAt(i,7)).booleanValue(); } int count = 0; for (int i = 0; i < Chromosome.getSize(); i++){ if (markerResults[i]){ count++; } } Chromosome.realIndex = new int[count]; int k = 0; for (int i =0; i < Chromosome.getSize(); i++){ if (markerResults[i]){ Chromosome.realIndex[k] = i; k++; } } dPrimeDisplay.dPrimeTable = theData.getFilteredTable(theData.dPrimeTable); theData.guessBlocks(currentBlockDef); dPrimeDisplay.refreshBlocks(theData.blocks); //hack-y way to refresh the image dPrimeDisplay.setVisible(false); dPrimeDisplay.setVisible(true); hapDisplay.theData = theData; try{ hapDisplay.getHaps(); }catch(HaploViewException hv){ JOptionPane.showMessageDialog(window, hv.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); checkPanel.changed=false; } }
public void stateChanged(ChangeEvent e) { viewMenuItems[tabs.getSelectedIndex()].setSelected(true); if (checkPanel != null && checkPanel.changed){ window.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); JTable table = checkPanel.getTable(); boolean[] markerResults = new boolean[table.getRowCount()]; for (int i = 0; i < table.getRowCount(); i++){ markerResults[i] = ((Boolean)table.getValueAt(i,7)).booleanValue(); } int count = 0; for (int i = 0; i < Chromosome.getSize(); i++){ if (markerResults[i]){ count++; } } Chromosome.realIndex = new int[count]; int k = 0; for (int i =0; i < Chromosome.getSize(); i++){ if (markerResults[i]){ Chromosome.realIndex[k] = i; k++; } } dPrimeDisplay.dPrimeTable = theData.getFilteredTable(theData.dPrimeTable); theData.guessBlocks(currentBlockDef); dPrimeDisplay.refreshBlocks(theData.blocks); //hack-y way to refresh the image dPrimeDisplay.setVisible(false); dPrimeDisplay.setVisible(true); hapDisplay.theData = theData; try{ hapDisplay.getHaps(); }catch(HaploViewException hv){ JOptionPane.showMessageDialog(window, hv.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); checkPanel.changed=false; } }
1,111,159
public ActionForward execute(WebContext context, ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception { MBeanQueryForm queryForm = (MBeanQueryForm)actionForm; final String queryObjectName = queryForm.getObjectName(); ServerConnection serverConnection = context.getServerConnection(); // TODO: change to use queryNames Set mbeans = serverConnection.queryObjects(new ObjectName(queryObjectName)); Map domainToObjectNameListMap = new TreeMap(); ObjectNameTuple tuple = new ObjectNameTuple(); for(Iterator it=mbeans.iterator(); it.hasNext();){ ObjectInstance oi = (ObjectInstance)it.next(); tuple.setObjectName(oi.getObjectName()); String domain = tuple.getDomain(); String name = tuple.getName(); List objectNameList = (List)domainToObjectNameListMap.get(domain); if(objectNameList == null){ objectNameList = new LinkedList(); domainToObjectNameListMap.put(domain, objectNameList); } objectNameList.add(name); } request.setAttribute("domainToObjectNameListMap", domainToObjectNameListMap); return mapping.findForward(Forwards.SUCCESS); }
public ActionForward execute(WebContext context, ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception { MBeanQueryForm queryForm = (MBeanQueryForm)actionForm; final String queryObjectName = queryForm.getObjectName(); ServerConnection serverConnection = context.getServerConnection(); // TODO: change to use queryNames Set mbeans = serverConnection.queryObjects(new ObjectName(queryObjectName)); Map domainToObjectNameListMap = new TreeMap(); ObjectNameTuple tuple = new ObjectNameTuple(); for(Iterator it=mbeans.iterator(); it.hasNext();){ ObjectInstance oi = (ObjectInstance)it.next(); tuple.setObjectName(oi.getObjectName()); String domain = tuple.getDomain(); String name = tuple.getName(); Set objectNameList = (Set)domainToObjectNameListMap.get(domain); if(objectNameList == null){ objectNameList = new LinkedList(); domainToObjectNameListMap.put(domain, objectNameList); } objectNameList.add(name); } request.setAttribute("domainToObjectNameListMap", domainToObjectNameListMap); return mapping.findForward(Forwards.SUCCESS); }
1,111,160
public ActionForward execute(WebContext context, ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception { MBeanQueryForm queryForm = (MBeanQueryForm)actionForm; final String queryObjectName = queryForm.getObjectName(); ServerConnection serverConnection = context.getServerConnection(); // TODO: change to use queryNames Set mbeans = serverConnection.queryObjects(new ObjectName(queryObjectName)); Map domainToObjectNameListMap = new TreeMap(); ObjectNameTuple tuple = new ObjectNameTuple(); for(Iterator it=mbeans.iterator(); it.hasNext();){ ObjectInstance oi = (ObjectInstance)it.next(); tuple.setObjectName(oi.getObjectName()); String domain = tuple.getDomain(); String name = tuple.getName(); List objectNameList = (List)domainToObjectNameListMap.get(domain); if(objectNameList == null){ objectNameList = new LinkedList(); domainToObjectNameListMap.put(domain, objectNameList); } objectNameList.add(name); } request.setAttribute("domainToObjectNameListMap", domainToObjectNameListMap); return mapping.findForward(Forwards.SUCCESS); }
public ActionForward execute(WebContext context, ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception { MBeanQueryForm queryForm = (MBeanQueryForm)actionForm; final String queryObjectName = queryForm.getObjectName(); ServerConnection serverConnection = context.getServerConnection(); // TODO: change to use queryNames Set mbeans = serverConnection.queryObjects(new ObjectName(queryObjectName)); Map domainToObjectNameListMap = new TreeMap(); ObjectNameTuple tuple = new ObjectNameTuple(); for(Iterator it=mbeans.iterator(); it.hasNext();){ ObjectInstance oi = (ObjectInstance)it.next(); tuple.setObjectName(oi.getObjectName()); String domain = tuple.getDomain(); String name = tuple.getName(); List objectNameList = (List)domainToObjectNameListMap.get(domain); if(objectNameList == null){ objectNameList = new TreeSet(); domainToObjectNameListMap.put(domain, objectNameList); } objectNameList.add(name); } request.setAttribute("domainToObjectNameListMap", domainToObjectNameListMap); return mapping.findForward(Forwards.SUCCESS); }
1,111,161
protected void init() throws ArchitectException { int accelMask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); UserSettings us; // must be done right away, because a static // initializer in this class effects BeanUtils // behaviour which the XML Digester relies // upon heavily //TypeMap.getInstance(); contentPane = (JComponent)getContentPane(); try { ConfigFile cf = ConfigFile.getDefaultInstance(); us = cf.read(); architectSession.setUserSettings(us); sprefs = architectSession.getUserSettings().getSwingSettings(); } catch (IOException e) { throw new ArchitectException("prefs.read", e); } while (us.getPlDotIni() == null) { String message; String[] options = new String[] {"Browse", "Create"}; if (us.getPlDotIniPath() == null) { message = "location is not set"; } else if (new File(us.getPlDotIniPath()).isFile()) { message = "file \n\n\""+us.getPlDotIniPath()+"\"\n\n could not be read"; } else { message = "file \n\n\""+us.getPlDotIniPath()+"\"\n\n does not exist"; } int choice = JOptionPane.showOptionDialog(null, "The Architect keeps its list of database connections" + "\nin a file called PL.INI. Your PL.INI "+message+"." + "\n\nYou can browse for an existing PL.INI file on your system" + "\nor allow the Architect to create a new one in your home directory." + "\n\nHint: If you are a Power*Loader Suite user, you should browse for" + "\nan existing PL.INI in your Power*Loader installation directory.", "Missing PL.INI", 0, JOptionPane.INFORMATION_MESSAGE, null, options, null); File newPlIniFile; if (choice == 0) { JFileChooser fc = new JFileChooser(); fc.setFileFilter(ASUtils.INI_FILE_FILTER); fc.setDialogTitle("Locate your PL.INI file"); int fcChoice = fc.showOpenDialog(null); if (fcChoice == JFileChooser.APPROVE_OPTION) { newPlIniFile = fc.getSelectedFile(); } else { newPlIniFile = null; } } else { newPlIniFile = new File(System.getProperty("user.home"), "pl.ini"); } if (newPlIniFile != null) try { newPlIniFile.createNewFile(); us.setPlDotIniPath(newPlIniFile.getPath()); } catch (IOException e1) { logger.error("Caught IO exception while creating empty PL.INI at \"" +newPlIniFile.getPath()+"\"", e1); JOptionPane.showMessageDialog(null, "Failed to create file \""+newPlIniFile.getPath()+"\":\n"+e1.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } } // Create actions aboutAction = new AboutAction(); newProjectAction = new AbstractAction("New Project", ASUtils.createJLFIcon("general/New","New Project",sprefs.getInt(SwingUserSettings.ICON_SIZE, 24))) { public void actionPerformed(ActionEvent e) { if (promptForUnsavedModifications()) { try { closeProject(getProject()); setProject(new SwingUIProject("New Project")); logger.debug("Glass pane is "+getGlassPane()); getGlassPane().setVisible(true); } catch (Exception ex) { JOptionPane.showMessageDialog(ArchitectFrame.this, "Can't create new project: "+ex.getMessage()); logger.error("Got exception while creating new project", ex); } } } }; newProjectAction.putValue(AbstractAction.SHORT_DESCRIPTION, "New"); newProjectAction.putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_N, accelMask)); openProjectAction = new AbstractAction("Open Project...", ASUtils.createJLFIcon("general/Open", "Open Project", sprefs.getInt(SwingUserSettings.ICON_SIZE, 24))) { public void actionPerformed(ActionEvent e) { if (promptForUnsavedModifications()) { JFileChooser chooser = new JFileChooser(); chooser.addChoosableFileFilter(ASUtils.ARCHITECT_FILE_FILTER); int returnVal = chooser.showOpenDialog(ArchitectFrame.this); if (returnVal == JFileChooser.APPROVE_OPTION) { final File file = chooser.getSelectedFile(); new Thread() { public void run() { InputStream in = null; try { closeProject(getProject()); SwingUIProject project = new SwingUIProject("Loading..."); project.setFile(file); in = new BufferedInputStream (new ProgressMonitorInputStream (ArchitectFrame.this, "Reading " + file.getName(), new FileInputStream(file))); project.load(in); setProject(project); } catch (Exception ex) { JOptionPane.showMessageDialog (ArchitectFrame.this, "Can't open project: "+ex.getMessage()); logger.error("Got exception while opening project", ex); } finally { try { if (in != null) { in.close(); } } catch (IOException ie) { logger.error("got exception while closing project file", ie); } } } }.start(); } } } }; openProjectAction.putValue(AbstractAction.SHORT_DESCRIPTION, "Open"); openProjectAction.putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_O, accelMask)); saveProjectAction = new AbstractAction("Save Project", ASUtils.createJLFIcon("general/Save", "Save Project", sprefs.getInt(SwingUserSettings.ICON_SIZE, 24))) { public void actionPerformed(ActionEvent e) { saveOrSaveAs(false, true); } }; saveProjectAction.putValue(AbstractAction.SHORT_DESCRIPTION, "Save"); saveProjectAction.putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_S, accelMask)); saveProjectAsAction = new AbstractAction("Save Project As...", ASUtils.createJLFIcon("general/SaveAs", "Save Project As...", sprefs.getInt(SwingUserSettings.ICON_SIZE, 24))) { public void actionPerformed(ActionEvent e) { saveOrSaveAs(true, true); } }; saveProjectAsAction.putValue(AbstractAction.SHORT_DESCRIPTION, "Save As"); prefAction = new PreferencesAction(); projectSettingsAction = new ProjectSettingsAction(); projectSettingsAction.putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_COMMA, accelMask)); printAction = new PrintAction(); printAction.putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_P, accelMask)); zoomInAction = new ZoomAction(ZOOM_STEP); zoomOutAction = new ZoomAction(ZOOM_STEP * -1.0); zoomNormalAction = new AbstractAction("Reset Zoom", ASUtils.createJLFIcon("general/Zoom", "Reset Zoom", sprefs.getInt(SwingUserSettings.ICON_SIZE, 24))) { public void actionPerformed(ActionEvent e) { playpen.setZoom(1.0); } }; zoomNormalAction.putValue(AbstractAction.SHORT_DESCRIPTION, "Reset Zoom"); undoAction = new UndoAction(); redoAction = new RedoAction(); autoLayoutAction = new AutoLayoutAction(); autoLayout = new FruchtermanReingoldForceLayout(); autoLayoutAction.setLayout(autoLayout); exportDDLAction = new ExportDDLAction(); compareDMAction = new CompareDMAction(); exportPLTransAction = new ExportPLTransAction(); quickStartAction = new QuickStartAction(); deleteSelectedAction = new DeleteSelectedAction(); createIdentifyingRelationshipAction = new CreateRelationshipAction(true); createNonIdentifyingRelationshipAction = new CreateRelationshipAction(false); editRelationshipAction = new EditRelationshipAction(); createTableAction = new CreateTableAction(); editColumnAction = new EditColumnAction(); insertColumnAction = new InsertColumnAction(); editTableAction = new EditTableAction(); searchReplaceAction = new SearchReplaceAction(); searchReplaceAction.putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_F, accelMask)); menuBar = new JMenuBar(); //Settingup JMenu fileMenu = new JMenu("File"); fileMenu.setMnemonic('f'); fileMenu.add(new JMenuItem(newProjectAction)); fileMenu.add(new JMenuItem(openProjectAction)); fileMenu.add(new JMenuItem(saveProjectAction)); fileMenu.add(new JMenuItem(saveProjectAsAction)); fileMenu.add(new JMenuItem(printAction)); fileMenu.add(new JMenuItem(prefAction)); fileMenu.add(new JMenuItem(projectSettingsAction)); fileMenu.add(new JMenuItem(saveSettingsAction)); fileMenu.add(new JMenuItem(exitAction)); menuBar.add(fileMenu); JMenu editMenu = new JMenu("Edit"); editMenu.setMnemonic('e'); editMenu.add(undoAction); editMenu.add(redoAction); editMenu.addSeparator(); editMenu.add(new JMenuItem(searchReplaceAction)); menuBar.add(editMenu); // the connections menu is set up when a new project is created (because it depends on the current DBTree) connectionsMenu = new JMenu("Connections"); connectionsMenu.setMnemonic('c'); menuBar.add(connectionsMenu); JMenu etlMenu = new JMenu("ETL"); etlMenu.setMnemonic('l'); JMenu etlSubmenuOne = new JMenu("Power*Loader"); etlSubmenuOne.add(new JMenuItem(exportPLTransAction)); etlSubmenuOne.add(new JMenuItem("PL Transaction File Export")); etlSubmenuOne.add(new JMenuItem("Run Power*Loader")); etlSubmenuOne.add(new JMenuItem(quickStartAction)); etlMenu.add(etlSubmenuOne); menuBar.add(etlMenu); JMenu toolsMenu = new JMenu("Tools"); toolsMenu.setMnemonic('t'); toolsMenu.add(new JMenuItem(exportDDLAction)); toolsMenu.add(new JMenuItem(compareDMAction)); menuBar.add(toolsMenu); JMenu helpMenu = new JMenu("Help"); helpMenu.setMnemonic('h'); helpMenu.add(new JMenuItem(aboutAction)); menuBar.add(helpMenu); setJMenuBar(menuBar); projectBar = new JToolBar(JToolBar.HORIZONTAL); ppBar = new JToolBar(JToolBar.VERTICAL); projectBar.add(newProjectAction); projectBar.add(openProjectAction); projectBar.add(saveProjectAction); projectBar.addSeparator(); projectBar.add(printAction); projectBar.addSeparator(); projectBar.add(undoAction); projectBar.add(redoAction); projectBar.addSeparator(); projectBar.add(exportDDLAction); projectBar.addSeparator(); projectBar.add(compareDMAction); projectBar.addSeparator(); projectBar.add(autoLayoutAction); JButton tempButton = null; // shared actions need to report where they are coming from ppBar.add(zoomInAction); ppBar.add(zoomOutAction); ppBar.add(zoomNormalAction); ppBar.addSeparator(); tempButton = ppBar.add(deleteSelectedAction); tempButton.setActionCommand(ArchitectSwingConstants.ACTION_COMMAND_SRC_PLAYPEN); ppBar.addSeparator(); tempButton = ppBar.add(createTableAction); tempButton.setActionCommand(ArchitectSwingConstants.ACTION_COMMAND_SRC_PLAYPEN); ppBar.addSeparator(); tempButton = ppBar.add(insertColumnAction); tempButton.setActionCommand(ArchitectSwingConstants.ACTION_COMMAND_SRC_PLAYPEN); tempButton = ppBar.add(editColumnAction); tempButton.setActionCommand(ArchitectSwingConstants.ACTION_COMMAND_SRC_PLAYPEN); ppBar.addSeparator(); ppBar.add(createNonIdentifyingRelationshipAction); ppBar.add(createIdentifyingRelationshipAction); tempButton = ppBar.add(editRelationshipAction); tempButton.setActionCommand(ArchitectSwingConstants.ACTION_COMMAND_SRC_PLAYPEN); Container projectBarPane = getContentPane(); projectBarPane.setLayout(new BorderLayout()); projectBarPane.add(projectBar, BorderLayout.NORTH); JPanel cp = new JPanel(new BorderLayout()); cp.add(ppBar, BorderLayout.EAST); projectBarPane.add(cp, BorderLayout.CENTER); splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); cp.add(splitPane, BorderLayout.CENTER); logger.debug("Added splitpane to content pane"); splitPane.setDividerLocation (sprefs.getInt(SwingUserSettings.DIVIDER_LOCATION, 150)); //dbTree.getPreferredSize().width)); Rectangle bounds = new Rectangle(); bounds.x = sprefs.getInt(SwingUserSettings.MAIN_FRAME_X, 40); bounds.y = sprefs.getInt(SwingUserSettings.MAIN_FRAME_Y, 40); bounds.width = sprefs.getInt(SwingUserSettings.MAIN_FRAME_WIDTH, 600); bounds.height = sprefs.getInt(SwingUserSettings.MAIN_FRAME_HEIGHT, 440); setBounds(bounds); addWindowListener(afWindowListener = new ArchitectFrameWindowListener()); setProject(new SwingUIProject("New Project")); }
protected void init() throws ArchitectException { int accelMask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); UserSettings us; // must be done right away, because a static // initializer in this class effects BeanUtils // behaviour which the XML Digester relies // upon heavily //TypeMap.getInstance(); contentPane = (JComponent)getContentPane(); try { ConfigFile cf = ConfigFile.getDefaultInstance(); us = cf.read(); architectSession.setUserSettings(us); sprefs = architectSession.getUserSettings().getSwingSettings(); } catch (IOException e) { throw new ArchitectException("prefs.read", e); } while (us.getPlDotIni() == null) { String message; String[] options = new String[] {"Browse", "Create"}; if (us.getPlDotIniPath() == null) { message = "location is not set"; } else if (new File(us.getPlDotIniPath()).isFile()) { message = "file \n\n\""+us.getPlDotIniPath()+"\"\n\n could not be read"; } else { message = "file \n\n\""+us.getPlDotIniPath()+"\"\n\n does not exist"; } int choice = JOptionPane.showOptionDialog(null, "The Architect keeps its list of database connections" + "\nin a file called PL.INI. Your PL.INI "+message+"." + "\n\nYou can browse for an existing PL.INI file on your system" + "\nor allow the Architect to create a new one in your home directory." + "\n\nHint: If you are a Power*Loader Suite user, you should browse for" + "\nan existing PL.INI in your Power*Loader installation directory.", "Missing PL.INI", 0, JOptionPane.INFORMATION_MESSAGE, null, options, null); File newPlIniFile; if (choice == 0) { JFileChooser fc = new JFileChooser(); fc.setFileFilter(ASUtils.INI_FILE_FILTER); fc.setDialogTitle("Locate your PL.INI file"); int fcChoice = fc.showOpenDialog(null); if (fcChoice == JFileChooser.APPROVE_OPTION) { newPlIniFile = fc.getSelectedFile(); } else { newPlIniFile = null; } } else { newPlIniFile = new File(System.getProperty("user.home"), "pl.ini"); } if (newPlIniFile != null) try { newPlIniFile.createNewFile(); us.setPlDotIniPath(newPlIniFile.getPath()); } catch (IOException e1) { logger.error("Caught IO exception while creating empty PL.INI at \"" +newPlIniFile.getPath()+"\"", e1); JOptionPane.showMessageDialog(null, "Failed to create file \""+newPlIniFile.getPath()+"\":\n"+e1.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } } // Create actions aboutAction = new AboutAction(); newProjectAction = new AbstractAction("New Project", ASUtils.createJLFIcon("general/New","New Project",sprefs.getInt(SwingUserSettings.ICON_SIZE, 24))) { public void actionPerformed(ActionEvent e) { if (promptForUnsavedModifications()) { try { closeProject(getProject()); setProject(new SwingUIProject("New Project")); logger.debug("Glass pane is "+getGlassPane()); getGlassPane().setVisible(true); } catch (Exception ex) { JOptionPane.showMessageDialog(ArchitectFrame.this, "Can't create new project: "+ex.getMessage()); logger.error("Got exception while creating new project", ex); } } } }; newProjectAction.putValue(AbstractAction.SHORT_DESCRIPTION, "New"); newProjectAction.putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_N, accelMask)); openProjectAction = new AbstractAction("Open Project...", ASUtils.createJLFIcon("general/Open", "Open Project", sprefs.getInt(SwingUserSettings.ICON_SIZE, 24))) { public void actionPerformed(ActionEvent e) { if (promptForUnsavedModifications()) { JFileChooser chooser = new JFileChooser(); chooser.addChoosableFileFilter(ASUtils.ARCHITECT_FILE_FILTER); int returnVal = chooser.showOpenDialog(ArchitectFrame.this); if (returnVal == JFileChooser.APPROVE_OPTION) { final File file = chooser.getSelectedFile(); new Thread() { public void run() { InputStream in = null; try { closeProject(getProject()); SwingUIProject project = new SwingUIProject("Loading..."); project.setFile(file); in = new BufferedInputStream (new ProgressMonitorInputStream (ArchitectFrame.this, "Reading " + file.getName(), new FileInputStream(file))); project.load(in); setProject(project); } catch (Exception ex) { JOptionPane.showMessageDialog (ArchitectFrame.this, "Can't open project: "+ex.getMessage()); logger.error("Got exception while opening project", ex); } finally { try { if (in != null) { in.close(); } } catch (IOException ie) { logger.error("got exception while closing project file", ie); } } } }.start(); } } } }; openProjectAction.putValue(AbstractAction.SHORT_DESCRIPTION, "Open"); openProjectAction.putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_O, accelMask)); saveProjectAction = new AbstractAction("Save Project", ASUtils.createJLFIcon("general/Save", "Save Project", sprefs.getInt(SwingUserSettings.ICON_SIZE, 24))) { public void actionPerformed(ActionEvent e) { saveOrSaveAs(false, true); } }; saveProjectAction.putValue(AbstractAction.SHORT_DESCRIPTION, "Save"); saveProjectAction.putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_S, accelMask)); saveProjectAsAction = new AbstractAction("Save Project As...", ASUtils.createJLFIcon("general/SaveAs", "Save Project As...", sprefs.getInt(SwingUserSettings.ICON_SIZE, 24))) { public void actionPerformed(ActionEvent e) { saveOrSaveAs(true, true); } }; saveProjectAsAction.putValue(AbstractAction.SHORT_DESCRIPTION, "Save As"); prefAction = new PreferencesAction(); projectSettingsAction = new ProjectSettingsAction(); projectSettingsAction.putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_COMMA, accelMask)); printAction = new PrintAction(); printAction.putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_P, accelMask)); zoomInAction = new ZoomAction(ZOOM_STEP); zoomOutAction = new ZoomAction(ZOOM_STEP * -1.0); zoomNormalAction = new AbstractAction("Reset Zoom", ASUtils.createJLFIcon("general/Zoom", "Reset Zoom", sprefs.getInt(SwingUserSettings.ICON_SIZE, 24))) { public void actionPerformed(ActionEvent e) { playpen.setZoom(1.0); } }; zoomNormalAction.putValue(AbstractAction.SHORT_DESCRIPTION, "Reset Zoom"); undoAction = new UndoAction(); redoAction = new RedoAction(); autoLayoutAction = new AutoLayoutAction(); autoLayout = new FruchtermanReingoldForceLayout(); autoLayoutAction.setLayout(autoLayout); exportDDLAction = new ExportDDLAction(); compareDMAction = new CompareDMAction(); exportPLTransAction = new ExportPLTransAction(); quickStartAction = new QuickStartAction(); deleteSelectedAction = new DeleteSelectedAction(); createIdentifyingRelationshipAction = new CreateRelationshipAction(true); createNonIdentifyingRelationshipAction = new CreateRelationshipAction(false); editRelationshipAction = new EditRelationshipAction(); createTableAction = new CreateTableAction(); editColumnAction = new EditColumnAction(); insertColumnAction = new InsertColumnAction(); editTableAction = new EditTableAction(); searchReplaceAction = new SearchReplaceAction(); searchReplaceAction.putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_F, accelMask)); menuBar = new JMenuBar(); //Settingup JMenu fileMenu = new JMenu("File"); fileMenu.setMnemonic('f'); fileMenu.add(new JMenuItem(newProjectAction)); fileMenu.add(new JMenuItem(openProjectAction)); fileMenu.add(new JMenuItem(saveProjectAction)); fileMenu.add(new JMenuItem(saveProjectAsAction)); fileMenu.add(new JMenuItem(printAction)); fileMenu.add(new JMenuItem(prefAction)); fileMenu.add(new JMenuItem(projectSettingsAction)); fileMenu.add(new JMenuItem(saveSettingsAction)); fileMenu.add(new JMenuItem(exitAction)); menuBar.add(fileMenu); JMenu editMenu = new JMenu("Edit"); editMenu.setMnemonic('e'); editMenu.add(undoAction); editMenu.add(redoAction); editMenu.addSeparator(); editMenu.add(new JMenuItem(searchReplaceAction)); menuBar.add(editMenu); // the connections menu is set up when a new project is created (because it depends on the current DBTree) connectionsMenu = new JMenu("Connections"); connectionsMenu.setMnemonic('c'); menuBar.add(connectionsMenu); JMenu etlMenu = new JMenu("ETL"); etlMenu.setMnemonic('l'); JMenu etlSubmenuOne = new JMenu("Power*Loader"); etlSubmenuOne.add(new JMenuItem(exportPLTransAction)); etlSubmenuOne.add(new JMenuItem("PL Transaction File Export")); etlSubmenuOne.add(new JMenuItem("Run Power*Loader")); etlSubmenuOne.add(new JMenuItem(quickStartAction)); etlMenu.add(etlSubmenuOne); menuBar.add(etlMenu); JMenu toolsMenu = new JMenu("Tools"); toolsMenu.setMnemonic('t'); toolsMenu.add(new JMenuItem(exportDDLAction)); toolsMenu.add(new JMenuItem(compareDMAction)); menuBar.add(toolsMenu); JMenu helpMenu = new JMenu("Help"); helpMenu.setMnemonic('h'); helpMenu.add(new JMenuItem(aboutAction)); menuBar.add(helpMenu); setJMenuBar(menuBar); projectBar = new JToolBar(JToolBar.HORIZONTAL); ppBar = new JToolBar(JToolBar.VERTICAL); projectBar.add(newProjectAction); projectBar.add(openProjectAction); projectBar.add(saveProjectAction); projectBar.addSeparator(); projectBar.add(printAction); projectBar.addSeparator(); projectBar.add(undoAction); projectBar.add(redoAction); projectBar.addSeparator(); projectBar.add(exportDDLAction); projectBar.addSeparator(); projectBar.add(compareDMAction); projectBar.addSeparator(); projectBar.add(autoLayoutAction); JButton tempButton = null; // shared actions need to report where they are coming from ppBar.add(zoomInAction); ppBar.add(zoomOutAction); ppBar.add(zoomNormalAction); ppBar.addSeparator(); tempButton = ppBar.add(deleteSelectedAction); tempButton.setActionCommand(ArchitectSwingConstants.ACTION_COMMAND_SRC_PLAYPEN); ppBar.addSeparator(); tempButton = ppBar.add(createTableAction); tempButton.setActionCommand(ArchitectSwingConstants.ACTION_COMMAND_SRC_PLAYPEN); ppBar.addSeparator(); tempButton = ppBar.add(insertColumnAction); tempButton.setActionCommand(ArchitectSwingConstants.ACTION_COMMAND_SRC_PLAYPEN); tempButton = ppBar.add(editColumnAction); tempButton.setActionCommand(ArchitectSwingConstants.ACTION_COMMAND_SRC_PLAYPEN); ppBar.addSeparator(); ppBar.add(createNonIdentifyingRelationshipAction); ppBar.add(createIdentifyingRelationshipAction); tempButton = ppBar.add(editRelationshipAction); tempButton.setActionCommand(ArchitectSwingConstants.ACTION_COMMAND_SRC_PLAYPEN); Container projectBarPane = getContentPane(); projectBarPane.setLayout(new BorderLayout()); projectBarPane.add(projectBar, BorderLayout.NORTH); JPanel cp = new JPanel(new BorderLayout()); cp.add(ppBar, BorderLayout.EAST); projectBarPane.add(cp, BorderLayout.CENTER); splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); cp.add(splitPane, BorderLayout.CENTER); logger.debug("Added splitpane to content pane"); splitPane.setDividerLocation (sprefs.getInt(SwingUserSettings.DIVIDER_LOCATION, 150)); //dbTree.getPreferredSize().width)); Rectangle bounds = new Rectangle(); bounds.x = sprefs.getInt(SwingUserSettings.MAIN_FRAME_X, 40); bounds.y = sprefs.getInt(SwingUserSettings.MAIN_FRAME_Y, 40); bounds.width = sprefs.getInt(SwingUserSettings.MAIN_FRAME_WIDTH, 600); bounds.height = sprefs.getInt(SwingUserSettings.MAIN_FRAME_HEIGHT, 440); setBounds(bounds); addWindowListener(afWindowListener = new ArchitectFrameWindowListener()); setProject(new SwingUIProject("New Project")); }
1,111,162
public void actionPerformed(ActionEvent e) { if (promptForUnsavedModifications()) { JFileChooser chooser = new JFileChooser(); chooser.addChoosableFileFilter(ASUtils.ARCHITECT_FILE_FILTER); int returnVal = chooser.showOpenDialog(ArchitectFrame.this); if (returnVal == JFileChooser.APPROVE_OPTION) { final File file = chooser.getSelectedFile(); new Thread() { public void run() { InputStream in = null; try { closeProject(getProject()); SwingUIProject project = new SwingUIProject("Loading..."); project.setFile(file); in = new BufferedInputStream (new ProgressMonitorInputStream (ArchitectFrame.this, "Reading " + file.getName(), new FileInputStream(file))); project.load(in); setProject(project); } catch (Exception ex) { JOptionPane.showMessageDialog (ArchitectFrame.this, "Can't open project: "+ex.getMessage()); logger.error("Got exception while opening project", ex); } finally { try { if (in != null) { in.close(); } } catch (IOException ie) { logger.error("got exception while closing project file", ie); } } } }.start(); } } }
public void actionPerformed(ActionEvent e) { if (promptForUnsavedModifications()) { JFileChooser chooser = new JFileChooser(); chooser.addChoosableFileFilter(ASUtils.ARCHITECT_FILE_FILTER); int returnVal = chooser.showOpenDialog(ArchitectFrame.this); if (returnVal == JFileChooser.APPROVE_OPTION) { final File file = chooser.getSelectedFile(); new Thread() { public void run() { InputStream in = null; try { closeProject(getProject()); SwingUIProject project = new SwingUIProject("Loading..."); project.setFile(file); in = new BufferedInputStream (new ProgressMonitorInputStream (ArchitectFrame.this, "Reading " + file.getName(), new FileInputStream(file))); project.load(in); setProject(project); } catch (Exception ex) { JOptionPane.showMessageDialog (ArchitectFrame.this, "Can't open project: "+ex.getMessage()); logger.error("Got exception while opening project", ex); } finally { try { if (in != null) { in.close(); } } catch (IOException ie) { logger.error("got exception while closing project file", ie); } } } }.start(); } } }
1,111,163