bugged
stringlengths 6
599k
| fixed
stringlengths 10
599k
| __index_level_0__
int64 0
1.13M
|
|---|---|---|
public void actionPerformed(ActionEvent evt) { dbcs = new DBConnectionSpec(); dbcsPanel.applyChanges(dbcs); historyBox.addItem(ASUtils.lvb(dbcs.getDisplayName(), dbcs)); d.setVisible(false); }
|
public void actionPerformed(ActionEvent evt) { dbcs = new DBConnectionSpec(); dbcsPanel.applyChanges(dbcs); historyBox.addItem(ASUtils.lvb(dbcs.getDisplayName(), dbcs)); d.setVisible(false); }
| 1,108,717
|
public Tag getTag() { return tag; }
|
public Tag getTag() throws Exception { Tag tag = (Tag) tagHolder.get(); if ( tag == null ) { tag = createTag(); if ( tag != null ) { configureTag(tag); tagHolder.set(tag); } } return tag; }
| 1,108,718
|
public static TagScript newInstance(Tag tag) { if (tag instanceof DynaTag) { return new DynaTagScript((DynaTag) tag); } return new BeanTagScript(tag); }
|
public static TagScript newInstance(Tag tag) { if (tag instanceof DynaTag) { return new DynaTagScript((DynaTag) tag); } return new BeanTagScript(tag); }
| 1,108,719
|
public static TagScript newInstance(Tag tag) { if (tag instanceof DynaTag) { return new DynaTagScript((DynaTag) tag); } return new BeanTagScript(tag); }
|
public static TagScript newInstance(Tag tag) { if (tag instanceof DynaTag) { return new DynaTagScript((DynaTag) tag); } return new BeanTagScript(factory); }
| 1,108,720
|
public String toString() { return super.toString() + "[tag=" + tag + "]"; }
|
public String toString() { return super.toString() + "[tag=" + elementName + ";at=" + lineNumber + ":" + columnNumber + "]"; }
| 1,108,722
|
public BeanTagScript(Tag tag) { super(tag); }
|
public BeanTagScript(Tag tag) { super(tag); }
| 1,108,723
|
public void doTag(final XMLOutput output) throws Exception { getGoal(getName()).addPreGoalCallback( new PreGoalCallback() { public void firePreGoal(Goal goal) throws Exception { // lets run the body log.debug( "Running pre goal: " + getName() ); getBody().run( context, output); } } ); }
|
public void doTag(final XMLOutput output) throws Exception { getGoal(getName()).addPreGoalCallback( new PreGoalCallback() { public void firePreGoal(Goal goal) throws Exception { // lets run the body log.debug( "Running pre goal: " + getName() ); invokeBody( output); } } ); }
| 1,108,724
|
public void firePreGoal(Goal goal) throws Exception { // lets run the body log.debug( "Running pre goal: " + getName() ); getBody().run( context, output); }
|
public void firePreGoal(Goal goal) throws Exception { // lets run the body log.debug( "Running pre goal: " + getName() ); invokeBody( output); }
| 1,108,725
|
public DPrimeTable(int numMarkers){ theTable = new PairwiseLinkage[numMarkers][]; sample = new PairwiseLinkage[1]; }
|
public DPrimeTable(int numMarkers){ theTable = new PairwiseLinkage[numMarkers][]; }
| 1,108,727
|
public void addMarker(Vector marker, int pos){ theTable[pos] = (PairwiseLinkage[]) marker.toArray(sample); }
|
public void addMarker(Vector marker, int pos){ theTable[pos] = (PairwiseLinkage[]) marker.toArray(new PairwiseLinkage[0]); }
| 1,108,728
|
SNP(String n, long p, double m, byte a1, byte a2, String e){ name = n; position = p; MAF = m; major = a1; minor = a2; extra = e; }
|
SNP(String n, long p, double m, byte a1, byte a2){ name = n; position = p; MAF = m; major = a1; minor = a2; extra = e; }
| 1,108,729
|
SNP(String n, long p, double m, byte a1, byte a2, String e){ name = n; position = p; MAF = m; major = a1; minor = a2; extra = e; }
|
SNP(String n, long p, double m, byte a1, byte a2, String e){ name = n; position = p; MAF = m; major = a1; minor = a2; }
| 1,108,730
|
public String getPValue() { double pval = 0; pval= MathUtil.gammq(.5,.5*this.chiSqVal); DecimalFormat df; //java truly sucks for simply restricting the number of sigfigs but still //using scientific notation when appropriate if (pval < 0.0001){ df = new DecimalFormat("0.0000E0"); }else{ df = new DecimalFormat(); df.setMaximumFractionDigits(4); } String formattedNumber = df.format(pval, new StringBuffer(), new FieldPosition(NumberFormat.INTEGER_FIELD)).toString(); return formattedNumber; }
|
public String getPValue() { double pval = 0; pval= MathUtil.gammq(.5,.5*this.chiSqVal); DecimalFormat df; //java truly sucks for simply restricting the number of sigfigs but still //using scientific notation when appropriate if (pval < 0.0001){ df = new DecimalFormat("0.0000E0", new DecimalFormatSymbols(Locale.US)); }else{ df = new DecimalFormat(); df.setMaximumFractionDigits(4); } String formattedNumber = df.format(pval, new StringBuffer(), new FieldPosition(NumberFormat.INTEGER_FIELD)).toString(); return formattedNumber; }
| 1,108,731
|
public String getPValue() { double pval = 0; pval= MathUtil.gammq(.5,.5*this.chiSqVal); DecimalFormat df; //java truly sucks for simply restricting the number of sigfigs but still //using scientific notation when appropriate if (pval < 0.0001){ df = new DecimalFormat("0.0000E0"); }else{ df = new DecimalFormat(); df.setMaximumFractionDigits(4); } String formattedNumber = df.format(pval, new StringBuffer(), new FieldPosition(NumberFormat.INTEGER_FIELD)).toString(); return formattedNumber; }
|
public String getPValue() { double pval = 0; pval= MathUtil.gammq(.5,.5*this.chiSqVal); DecimalFormat df; //java truly sucks for simply restricting the number of sigfigs but still //using scientific notation when appropriate if (pval < 0.0001){ df = new DecimalFormat("0.0000E0"); }else{ df = new DecimalFormat(); df.setMaximumFractionDigits(4); } String formattedNumber = df.format(pval, new StringBuffer(), new FieldPosition(NumberFormat.INTEGER_FIELD)).toString(); return formattedNumber; }
| 1,108,732
|
protected void createThumbnail( VolumeBase volume ) { log.debug( "Creating thumbnail for " + uid ); ODMGXAWrapper txw = new ODMGXAWrapper(); txw.lock( this, Transaction.WRITE ); // Maximum size of the thumbnail int maxThumbWidth = 100; int maxThumbHeight = 100; checkCropBounds(); /* Determine the minimum size for the instance used for thumbnail creation to get decent image quality. The cropped portion of the image must be roughly the same resolution as the intended thumbnail. */ double cropWidth = cropMaxX - cropMinX; cropWidth = ( cropWidth > 0.000001 ) ? cropWidth : 1.0; double cropHeight = cropMaxY - cropMinY; cropHeight = ( cropHeight > 0.000001 ) ? cropHeight : 1.0; int minInstanceWidth = (int)(((double)maxThumbWidth)/cropWidth); int minInstanceHeight = (int)(((double)maxThumbHeight)/cropHeight); int minInstanceSide = Math.max( minInstanceWidth, minInstanceHeight ); // Find the original image to use as a staring point ImageInstance original = null; for ( int n = 0; n < instances.size(); n++ ) { ImageInstance instance = (ImageInstance) instances.get( n ); if ( instance.getInstanceType() == ImageInstance.INSTANCE_TYPE_ORIGINAL ) { original = instance; txw.lock( original, Transaction.READ ); break; } } if ( original == null || original.getImageFile() == null || !original.getImageFile().exists() ) { // If there are uncorrupted instances, no thumbnail can be created log.warn( "Error - no original image was found!!!" ); txw.commit(); return; } log.debug( "Found original, reading it..." ); /* We try to ensure that the thumbnail is actually from the original image by comparing aspect ratio of it to original. This is not a perfect check but it will usually catch the most typical errors (like having a the original rotated by RAW conversion SW but still the original EXIF thumbnail. */ double origAspect = this.getAspect( original.getWidth(), original.getHeight(), 1.0 ); double aspectAccuracy = 0.01; // First, check if there is a thumbnail in image header BufferedImage origImage = readExifThumbnail( original.getImageFile() ); if ( origImage == null || !isOkForThumbCreation( origImage.getWidth(), origImage.getHeight(), minInstanceWidth, minInstanceHeight, origAspect, aspectAccuracy ) ) { // Read the image try { Iterator readers = ImageIO.getImageReadersByFormatName( "jpg" ); if ( readers.hasNext() ) { ImageReader reader = (ImageReader)readers.next(); log.debug( "Creating stream" ); ImageInputStream iis = ImageIO.createImageInputStream( original.getImageFile() ); reader.setInput( iis, false, false ); int numThumbs = 0; try { int numImages = reader.getNumImages( true ); numThumbs = reader.getNumThumbnails(0); } catch (IOException ex) { ex.printStackTrace(); } if ( numThumbs > 0 && isOkForThumbCreation( reader.getThumbnailWidth( 0, 0 ), reader.getThumbnailHeight( 0, 0 ) , minInstanceWidth, minInstanceHeight, origAspect, aspectAccuracy ) ) { // There is a thumbanil that is big enough - use it log.debug( "Original has thumbnail, size " + reader.getThumbnailWidth( 0, 0 ) + " x " + reader.getThumbnailHeight( 0, 0 ) ); origImage = reader.readThumbnail( 0, 0 ); log.debug( "Read thumbnail" ); } else { log.debug( "No thumbnail in original" ); ImageReadParam param = reader.getDefaultReadParam(); // Find the maximum subsampling rate we can still use for creating // a quality thumbnail int subsampling = 1; int minDim = Math.min( reader.getWidth( 0 ),reader.getHeight( 0 ) ); while ( 2 * minInstanceSide * subsampling < minDim ) { subsampling *= 2; } param.setSourceSubsampling( subsampling, subsampling, 0, 0 ); origImage = reader.read( 0, param ); log.debug( "Read original" ); } iis.close(); } } catch ( IOException e ) { log.warn( "Error reading image: " + e.getMessage() ); txw.abort(); return; } } log.debug( "Done, finding name" ); // Find where to store the file in the target volume File thumbnailFile = volume.getInstanceName( this, "jpg" ); log.debug( "name = " + thumbnailFile.getName() ); // Shrink the image to desired state and save it // Find first the correct transformation for doing this int origWidth = origImage.getWidth(); int origHeight = origImage.getHeight(); AffineTransform xform = org.photovault.image.ImageXform.getRotateXform( prefRotation -original.getRotated(), origWidth, origHeight ); ParameterBlockJAI rotParams = new ParameterBlockJAI( "affine" ); rotParams.addSource( origImage ); rotParams.setParameter( "transform", xform ); rotParams.setParameter( "interpolation", Interpolation.getInstance( Interpolation.INTERP_NEAREST ) ); RenderedOp rotatedImage = JAI.create( "affine", rotParams ); ParameterBlockJAI cropParams = new ParameterBlockJAI( "crop" ); cropParams.addSource( rotatedImage ); float cropX = (float)( Math.rint( rotatedImage.getMinX() + cropMinX * rotatedImage.getWidth() ) ); float cropY = (float)( Math.rint( rotatedImage.getMinY() + cropMinY * rotatedImage.getHeight())); float cropW = (float)( Math.rint((cropWidth) * rotatedImage.getWidth() ) ); float cropH = (float) ( Math.rint((cropHeight) * rotatedImage.getHeight() )); cropParams.setParameter( "x", cropX ); cropParams.setParameter( "y", cropY ); cropParams.setParameter( "width", cropW ); cropParams.setParameter( "height", cropH ); RenderedOp cropped = JAI.create("crop", cropParams, null); // Translate the image so that it begins in origo ParameterBlockJAI pbXlate = new ParameterBlockJAI( "translate" ); pbXlate.addSource( cropped ); pbXlate.setParameter( "xTrans", (float) (-cropped.getMinX() ) ); pbXlate.setParameter( "yTrans", (float) (-cropped.getMinY() ) ); RenderedOp xformImage = JAI.create( "translate", pbXlate ); // Finally, scale this to thumbnail AffineTransform thumbScale = org.photovault.image.ImageXform.getFittingXform( maxThumbWidth, maxThumbHeight, 0, xformImage.getWidth(), xformImage.getHeight() ); ParameterBlockJAI thumbScaleParams = new ParameterBlockJAI( "affine" ); thumbScaleParams.addSource( xformImage ); thumbScaleParams.setParameter( "transform", thumbScale ); thumbScaleParams.setParameter( "interpolation", Interpolation.getInstance( Interpolation.INTERP_NEAREST ) ); PlanarImage thumbImage = JAI.create( "affine", thumbScaleParams ); // Save it FileOutputStream out = null; try { out = new FileOutputStream(thumbnailFile.getAbsolutePath()); } catch(IOException e) { log.error( "Error writing thumbnail: " + e.getMessage() ); txw.abort(); return; } JPEGEncodeParam encodeParam = new JPEGEncodeParam(); ImageEncoder encoder = ImageCodec.createImageEncoder("JPEG", out, encodeParam); try { encoder.encode( thumbImage ); out.close(); // origImage.dispose(); thumbImage.dispose(); } catch (IOException e) { log.error( "Error writing thumbnail: " + e.getMessage() ); txw.abort(); return; } // add the created instance to this persistent object ImageInstance thumbInstance = addInstance( volume, thumbnailFile, ImageInstance.INSTANCE_TYPE_THUMBNAIL ); thumbInstance.setRotated( prefRotation -original.getRotated() ); thumbInstance.setCropBounds( getCropBounds() ); log.debug( "Loading thumbnail..." ); thumbnail = Thumbnail.createThumbnail( this, thumbnailFile ); oldThumbnail = null; log.debug( "Thumbnail loaded" ); txw.commit(); }
|
protected void createThumbnail( VolumeBase volume ) { log.debug( "Creating thumbnail for " + uid ); ODMGXAWrapper txw = new ODMGXAWrapper(); txw.lock( this, Transaction.WRITE ); // Maximum size of the thumbnail int maxThumbWidth = 100; int maxThumbHeight = 100; checkCropBounds(); /* Determine the minimum size for the instance used for thumbnail creation to get decent image quality. The cropped portion of the image must be roughly the same resolution as the intended thumbnail. */ double cropWidth = cropMaxX - cropMinX; cropWidth = ( cropWidth > 0.000001 ) ? cropWidth : 1.0; double cropHeight = cropMaxY - cropMinY; cropHeight = ( cropHeight > 0.000001 ) ? cropHeight : 1.0; int minInstanceWidth = (int)(((double)maxThumbWidth)/cropWidth); int minInstanceHeight = (int)(((double)maxThumbHeight)/cropHeight); int minInstanceSide = Math.max( minInstanceWidth, minInstanceHeight ); // Find the original image to use as a staring point ImageInstance original = null; for ( int n = 0; n < instances.size(); n++ ) { ImageInstance instance = (ImageInstance) instances.get( n ); if ( instance.getInstanceType() == ImageInstance.INSTANCE_TYPE_ORIGINAL ) { original = instance; txw.lock( original, Transaction.READ ); break; } } if ( original == null || original.getImageFile() == null || !original.getImageFile().exists() ) { // If there are uncorrupted instances, no thumbnail can be created log.warn( "Error - no original image was found!!!" ); txw.commit(); return; } log.debug( "Found original, reading it..." ); /* We try to ensure that the thumbnail is actually from the original image by comparing aspect ratio of it to original. This is not a perfect check but it will usually catch the most typical errors (like having a the original rotated by RAW conversion SW but still the original EXIF thumbnail. */ double origAspect = this.getAspect( original.getWidth(), original.getHeight(), 1.0 ); double aspectAccuracy = 0.01; // First, check if there is a thumbnail in image header BufferedImage origImage = readExifThumbnail( original.getImageFile() ); if ( origImage == null || !isOkForThumbCreation( origImage.getWidth(), origImage.getHeight(), minInstanceWidth, minInstanceHeight, origAspect, aspectAccuracy ) ) { // Read the image try { File imageFile = original.getImageFile(); String fname = imageFile.getName(); int lastDotPos = fname.lastIndexOf( "." ); if ( lastDotPos <= 0 || lastDotPos >= fname.length()-1 ) { throw new IOException( "Cannot determine file type extension of " + imageFile.getAbsolutePath() ); } String suffix = fname.substring( lastDotPos+1 ); Iterator readers = ImageIO.getImageReadersBySuffix( suffix ); if ( !readers.hasNext() ) { throw new IOException( "Unknown image file extension " + suffix + "\nwhile reading " + imageFile.getAbsolutePath() ); } if ( readers.hasNext() ) { ImageReader reader = (ImageReader)readers.next(); log.debug( "Creating stream" ); ImageInputStream iis = ImageIO.createImageInputStream( original.getImageFile() ); reader.setInput( iis, false, false ); int numThumbs = 0; try { int numImages = reader.getNumImages( true ); numThumbs = reader.getNumThumbnails(0); } catch (IOException ex) { ex.printStackTrace(); } if ( numThumbs > 0 && isOkForThumbCreation( reader.getThumbnailWidth( 0, 0 ), reader.getThumbnailHeight( 0, 0 ) , minInstanceWidth, minInstanceHeight, origAspect, aspectAccuracy ) ) { // There is a thumbanil that is big enough - use it log.debug( "Original has thumbnail, size " + reader.getThumbnailWidth( 0, 0 ) + " x " + reader.getThumbnailHeight( 0, 0 ) ); origImage = reader.readThumbnail( 0, 0 ); log.debug( "Read thumbnail" ); } else { log.debug( "No thumbnail in original" ); ImageReadParam param = reader.getDefaultReadParam(); // Find the maximum subsampling rate we can still use for creating // a quality thumbnail int subsampling = 1; int minDim = Math.min( reader.getWidth( 0 ),reader.getHeight( 0 ) ); while ( 2 * minInstanceSide * subsampling < minDim ) { subsampling *= 2; } param.setSourceSubsampling( subsampling, subsampling, 0, 0 ); origImage = reader.read( 0, param ); log.debug( "Read original" ); } iis.close(); } } catch ( IOException e ) { log.warn( "Error reading image: " + e.getMessage() ); txw.abort(); return; } } log.debug( "Done, finding name" ); // Find where to store the file in the target volume File thumbnailFile = volume.getInstanceName( this, "jpg" ); log.debug( "name = " + thumbnailFile.getName() ); // Shrink the image to desired state and save it // Find first the correct transformation for doing this int origWidth = origImage.getWidth(); int origHeight = origImage.getHeight(); AffineTransform xform = org.photovault.image.ImageXform.getRotateXform( prefRotation -original.getRotated(), origWidth, origHeight ); ParameterBlockJAI rotParams = new ParameterBlockJAI( "affine" ); rotParams.addSource( origImage ); rotParams.setParameter( "transform", xform ); rotParams.setParameter( "interpolation", Interpolation.getInstance( Interpolation.INTERP_NEAREST ) ); RenderedOp rotatedImage = JAI.create( "affine", rotParams ); ParameterBlockJAI cropParams = new ParameterBlockJAI( "crop" ); cropParams.addSource( rotatedImage ); float cropX = (float)( Math.rint( rotatedImage.getMinX() + cropMinX * rotatedImage.getWidth() ) ); float cropY = (float)( Math.rint( rotatedImage.getMinY() + cropMinY * rotatedImage.getHeight())); float cropW = (float)( Math.rint((cropWidth) * rotatedImage.getWidth() ) ); float cropH = (float) ( Math.rint((cropHeight) * rotatedImage.getHeight() )); cropParams.setParameter( "x", cropX ); cropParams.setParameter( "y", cropY ); cropParams.setParameter( "width", cropW ); cropParams.setParameter( "height", cropH ); RenderedOp cropped = JAI.create("crop", cropParams, null); // Translate the image so that it begins in origo ParameterBlockJAI pbXlate = new ParameterBlockJAI( "translate" ); pbXlate.addSource( cropped ); pbXlate.setParameter( "xTrans", (float) (-cropped.getMinX() ) ); pbXlate.setParameter( "yTrans", (float) (-cropped.getMinY() ) ); RenderedOp xformImage = JAI.create( "translate", pbXlate ); // Finally, scale this to thumbnail AffineTransform thumbScale = org.photovault.image.ImageXform.getFittingXform( maxThumbWidth, maxThumbHeight, 0, xformImage.getWidth(), xformImage.getHeight() ); ParameterBlockJAI thumbScaleParams = new ParameterBlockJAI( "affine" ); thumbScaleParams.addSource( xformImage ); thumbScaleParams.setParameter( "transform", thumbScale ); thumbScaleParams.setParameter( "interpolation", Interpolation.getInstance( Interpolation.INTERP_NEAREST ) ); PlanarImage thumbImage = JAI.create( "affine", thumbScaleParams ); // Save it FileOutputStream out = null; try { out = new FileOutputStream(thumbnailFile.getAbsolutePath()); } catch(IOException e) { log.error( "Error writing thumbnail: " + e.getMessage() ); txw.abort(); return; } JPEGEncodeParam encodeParam = new JPEGEncodeParam(); ImageEncoder encoder = ImageCodec.createImageEncoder("JPEG", out, encodeParam); try { encoder.encode( thumbImage ); out.close(); // origImage.dispose(); thumbImage.dispose(); } catch (IOException e) { log.error( "Error writing thumbnail: " + e.getMessage() ); txw.abort(); return; } // add the created instance to this persistent object ImageInstance thumbInstance = addInstance( volume, thumbnailFile, ImageInstance.INSTANCE_TYPE_THUMBNAIL ); thumbInstance.setRotated( prefRotation -original.getRotated() ); thumbInstance.setCropBounds( getCropBounds() ); log.debug( "Loading thumbnail..." ); thumbnail = Thumbnail.createThumbnail( this, thumbnailFile ); oldThumbnail = null; log.debug( "Thumbnail loaded" ); txw.commit(); }
| 1,108,733
|
protected void createThumbnail( VolumeBase volume ) { log.debug( "Creating thumbnail for " + uid ); ODMGXAWrapper txw = new ODMGXAWrapper(); txw.lock( this, Transaction.WRITE ); // Maximum size of the thumbnail int maxThumbWidth = 100; int maxThumbHeight = 100; checkCropBounds(); /* Determine the minimum size for the instance used for thumbnail creation to get decent image quality. The cropped portion of the image must be roughly the same resolution as the intended thumbnail. */ double cropWidth = cropMaxX - cropMinX; cropWidth = ( cropWidth > 0.000001 ) ? cropWidth : 1.0; double cropHeight = cropMaxY - cropMinY; cropHeight = ( cropHeight > 0.000001 ) ? cropHeight : 1.0; int minInstanceWidth = (int)(((double)maxThumbWidth)/cropWidth); int minInstanceHeight = (int)(((double)maxThumbHeight)/cropHeight); int minInstanceSide = Math.max( minInstanceWidth, minInstanceHeight ); // Find the original image to use as a staring point ImageInstance original = null; for ( int n = 0; n < instances.size(); n++ ) { ImageInstance instance = (ImageInstance) instances.get( n ); if ( instance.getInstanceType() == ImageInstance.INSTANCE_TYPE_ORIGINAL ) { original = instance; txw.lock( original, Transaction.READ ); break; } } if ( original == null || original.getImageFile() == null || !original.getImageFile().exists() ) { // If there are uncorrupted instances, no thumbnail can be created log.warn( "Error - no original image was found!!!" ); txw.commit(); return; } log.debug( "Found original, reading it..." ); /* We try to ensure that the thumbnail is actually from the original image by comparing aspect ratio of it to original. This is not a perfect check but it will usually catch the most typical errors (like having a the original rotated by RAW conversion SW but still the original EXIF thumbnail. */ double origAspect = this.getAspect( original.getWidth(), original.getHeight(), 1.0 ); double aspectAccuracy = 0.01; // First, check if there is a thumbnail in image header BufferedImage origImage = readExifThumbnail( original.getImageFile() ); if ( origImage == null || !isOkForThumbCreation( origImage.getWidth(), origImage.getHeight(), minInstanceWidth, minInstanceHeight, origAspect, aspectAccuracy ) ) { // Read the image try { Iterator readers = ImageIO.getImageReadersByFormatName( "jpg" ); if ( readers.hasNext() ) { ImageReader reader = (ImageReader)readers.next(); log.debug( "Creating stream" ); ImageInputStream iis = ImageIO.createImageInputStream( original.getImageFile() ); reader.setInput( iis, false, false ); int numThumbs = 0; try { int numImages = reader.getNumImages( true ); numThumbs = reader.getNumThumbnails(0); } catch (IOException ex) { ex.printStackTrace(); } if ( numThumbs > 0 && isOkForThumbCreation( reader.getThumbnailWidth( 0, 0 ), reader.getThumbnailHeight( 0, 0 ) , minInstanceWidth, minInstanceHeight, origAspect, aspectAccuracy ) ) { // There is a thumbanil that is big enough - use it log.debug( "Original has thumbnail, size " + reader.getThumbnailWidth( 0, 0 ) + " x " + reader.getThumbnailHeight( 0, 0 ) ); origImage = reader.readThumbnail( 0, 0 ); log.debug( "Read thumbnail" ); } else { log.debug( "No thumbnail in original" ); ImageReadParam param = reader.getDefaultReadParam(); // Find the maximum subsampling rate we can still use for creating // a quality thumbnail int subsampling = 1; int minDim = Math.min( reader.getWidth( 0 ),reader.getHeight( 0 ) ); while ( 2 * minInstanceSide * subsampling < minDim ) { subsampling *= 2; } param.setSourceSubsampling( subsampling, subsampling, 0, 0 ); origImage = reader.read( 0, param ); log.debug( "Read original" ); } iis.close(); } } catch ( IOException e ) { log.warn( "Error reading image: " + e.getMessage() ); txw.abort(); return; } } log.debug( "Done, finding name" ); // Find where to store the file in the target volume File thumbnailFile = volume.getInstanceName( this, "jpg" ); log.debug( "name = " + thumbnailFile.getName() ); // Shrink the image to desired state and save it // Find first the correct transformation for doing this int origWidth = origImage.getWidth(); int origHeight = origImage.getHeight(); AffineTransform xform = org.photovault.image.ImageXform.getRotateXform( prefRotation -original.getRotated(), origWidth, origHeight ); ParameterBlockJAI rotParams = new ParameterBlockJAI( "affine" ); rotParams.addSource( origImage ); rotParams.setParameter( "transform", xform ); rotParams.setParameter( "interpolation", Interpolation.getInstance( Interpolation.INTERP_NEAREST ) ); RenderedOp rotatedImage = JAI.create( "affine", rotParams ); ParameterBlockJAI cropParams = new ParameterBlockJAI( "crop" ); cropParams.addSource( rotatedImage ); float cropX = (float)( Math.rint( rotatedImage.getMinX() + cropMinX * rotatedImage.getWidth() ) ); float cropY = (float)( Math.rint( rotatedImage.getMinY() + cropMinY * rotatedImage.getHeight())); float cropW = (float)( Math.rint((cropWidth) * rotatedImage.getWidth() ) ); float cropH = (float) ( Math.rint((cropHeight) * rotatedImage.getHeight() )); cropParams.setParameter( "x", cropX ); cropParams.setParameter( "y", cropY ); cropParams.setParameter( "width", cropW ); cropParams.setParameter( "height", cropH ); RenderedOp cropped = JAI.create("crop", cropParams, null); // Translate the image so that it begins in origo ParameterBlockJAI pbXlate = new ParameterBlockJAI( "translate" ); pbXlate.addSource( cropped ); pbXlate.setParameter( "xTrans", (float) (-cropped.getMinX() ) ); pbXlate.setParameter( "yTrans", (float) (-cropped.getMinY() ) ); RenderedOp xformImage = JAI.create( "translate", pbXlate ); // Finally, scale this to thumbnail AffineTransform thumbScale = org.photovault.image.ImageXform.getFittingXform( maxThumbWidth, maxThumbHeight, 0, xformImage.getWidth(), xformImage.getHeight() ); ParameterBlockJAI thumbScaleParams = new ParameterBlockJAI( "affine" ); thumbScaleParams.addSource( xformImage ); thumbScaleParams.setParameter( "transform", thumbScale ); thumbScaleParams.setParameter( "interpolation", Interpolation.getInstance( Interpolation.INTERP_NEAREST ) ); PlanarImage thumbImage = JAI.create( "affine", thumbScaleParams ); // Save it FileOutputStream out = null; try { out = new FileOutputStream(thumbnailFile.getAbsolutePath()); } catch(IOException e) { log.error( "Error writing thumbnail: " + e.getMessage() ); txw.abort(); return; } JPEGEncodeParam encodeParam = new JPEGEncodeParam(); ImageEncoder encoder = ImageCodec.createImageEncoder("JPEG", out, encodeParam); try { encoder.encode( thumbImage ); out.close(); // origImage.dispose(); thumbImage.dispose(); } catch (IOException e) { log.error( "Error writing thumbnail: " + e.getMessage() ); txw.abort(); return; } // add the created instance to this persistent object ImageInstance thumbInstance = addInstance( volume, thumbnailFile, ImageInstance.INSTANCE_TYPE_THUMBNAIL ); thumbInstance.setRotated( prefRotation -original.getRotated() ); thumbInstance.setCropBounds( getCropBounds() ); log.debug( "Loading thumbnail..." ); thumbnail = Thumbnail.createThumbnail( this, thumbnailFile ); oldThumbnail = null; log.debug( "Thumbnail loaded" ); txw.commit(); }
|
protected void createThumbnail( VolumeBase volume ) { log.debug( "Creating thumbnail for " + uid ); ODMGXAWrapper txw = new ODMGXAWrapper(); txw.lock( this, Transaction.WRITE ); // Maximum size of the thumbnail int maxThumbWidth = 100; int maxThumbHeight = 100; checkCropBounds(); /* Determine the minimum size for the instance used for thumbnail creation to get decent image quality. The cropped portion of the image must be roughly the same resolution as the intended thumbnail. */ double cropWidth = cropMaxX - cropMinX; cropWidth = ( cropWidth > 0.000001 ) ? cropWidth : 1.0; double cropHeight = cropMaxY - cropMinY; cropHeight = ( cropHeight > 0.000001 ) ? cropHeight : 1.0; int minInstanceWidth = (int)(((double)maxThumbWidth)/cropWidth); int minInstanceHeight = (int)(((double)maxThumbHeight)/cropHeight); int minInstanceSide = Math.max( minInstanceWidth, minInstanceHeight ); // Find the original image to use as a staring point ImageInstance original = null; for ( int n = 0; n < instances.size(); n++ ) { ImageInstance instance = (ImageInstance) instances.get( n ); if ( instance.getInstanceType() == ImageInstance.INSTANCE_TYPE_ORIGINAL ) { original = instance; txw.lock( original, Transaction.READ ); break; } } if ( original == null || original.getImageFile() == null || !original.getImageFile().exists() ) { // If there are uncorrupted instances, no thumbnail can be created log.warn( "Error - no original image was found!!!" ); txw.commit(); return; } log.debug( "Found original, reading it..." ); /* We try to ensure that the thumbnail is actually from the original image by comparing aspect ratio of it to original. This is not a perfect check but it will usually catch the most typical errors (like having a the original rotated by RAW conversion SW but still the original EXIF thumbnail. */ double origAspect = this.getAspect( original.getWidth(), original.getHeight(), 1.0 ); double aspectAccuracy = 0.01; // First, check if there is a thumbnail in image header BufferedImage origImage = readExifThumbnail( original.getImageFile() ); if ( origImage == null || !isOkForThumbCreation( origImage.getWidth(), origImage.getHeight(), minInstanceWidth, minInstanceHeight, origAspect, aspectAccuracy ) ) { // Read the image try { Iterator readers = ImageIO.getImageReadersByFormatName( "jpg" ); if ( readers.hasNext() ) { ImageReader reader = (ImageReader)readers.next(); log.debug( "Creating stream" ); ImageInputStream iis = ImageIO.createImageInputStream( original.getImageFile() ); reader.setInput( iis, false, false ); int numThumbs = 0; try { int numImages = reader.getNumImages( true ); numThumbs = reader.getNumThumbnails(0); } catch (IOException ex) { ex.printStackTrace(); } if ( numThumbs > 0 && isOkForThumbCreation( reader.getThumbnailWidth( 0, 0 ), reader.getThumbnailHeight( 0, 0 ) , minInstanceWidth, minInstanceHeight, origAspect, aspectAccuracy ) ) { // There is a thumbanil that is big enough - use it log.debug( "Original has thumbnail, size " + reader.getThumbnailWidth( 0, 0 ) + " x " + reader.getThumbnailHeight( 0, 0 ) ); origImage = reader.readThumbnail( 0, 0 ); log.debug( "Read thumbnail" ); } else { log.debug( "No thumbnail in original" ); ImageReadParam param = reader.getDefaultReadParam(); // Find the maximum subsampling rate we can still use for creating // a quality thumbnail int subsampling = 1; int minDim = Math.min( reader.getWidth( 0 ),reader.getHeight( 0 ) ); while ( 2 * minInstanceSide * subsampling < minDim ) { subsampling *= 2; } param.setSourceSubsampling( subsampling, subsampling, 0, 0 ); origImage = reader.read( 0, param ); log.debug( "Read original" ); } iis.close(); } } catch ( IOException e ) { log.warn( "Error reading image: " + e.getMessage() ); txw.abort(); return; } } log.debug( "Done, finding name" ); // Find where to store the file in the target volume File thumbnailFile = volume.getInstanceName( this, "jpg" ); log.debug( "name = " + thumbnailFile.getName() ); // Shrink the image to desired state and save it // Find first the correct transformation for doing this int origWidth = origImage.getWidth(); int origHeight = origImage.getHeight(); AffineTransform xform = org.photovault.image.ImageXform.getRotateXform( prefRotation -original.getRotated(), origWidth, origHeight ); ParameterBlockJAI rotParams = new ParameterBlockJAI( "affine" ); rotParams.addSource( origImage ); rotParams.setParameter( "transform", xform ); rotParams.setParameter( "interpolation", Interpolation.getInstance( Interpolation.INTERP_NEAREST ) ); RenderedOp rotatedImage = JAI.create( "affine", rotParams ); ParameterBlockJAI cropParams = new ParameterBlockJAI( "crop" ); cropParams.addSource( rotatedImage ); float cropX = (float)( Math.rint( rotatedImage.getMinX() + cropMinX * rotatedImage.getWidth() ) ); float cropY = (float)( Math.rint( rotatedImage.getMinY() + cropMinY * rotatedImage.getHeight())); float cropW = (float)( Math.rint((cropWidth) * rotatedImage.getWidth() ) ); float cropH = (float) ( Math.rint((cropHeight) * rotatedImage.getHeight() )); cropParams.setParameter( "x", cropX ); cropParams.setParameter( "y", cropY ); cropParams.setParameter( "width", cropW ); cropParams.setParameter( "height", cropH ); RenderedOp cropped = JAI.create("crop", cropParams, null); // Translate the image so that it begins in origo ParameterBlockJAI pbXlate = new ParameterBlockJAI( "translate" ); pbXlate.addSource( cropped ); pbXlate.setParameter( "xTrans", (float) (-cropped.getMinX() ) ); pbXlate.setParameter( "yTrans", (float) (-cropped.getMinY() ) ); RenderedOp xformImage = JAI.create( "translate", pbXlate ); // Finally, scale this to thumbnail AffineTransform thumbScale = org.photovault.image.ImageXform.getFittingXform( maxThumbWidth, maxThumbHeight, 0, xformImage.getWidth(), xformImage.getHeight() ); ParameterBlockJAI thumbScaleParams = new ParameterBlockJAI( "affine" ); thumbScaleParams.addSource( xformImage ); thumbScaleParams.setParameter( "transform", thumbScale ); thumbScaleParams.setParameter( "interpolation", Interpolation.getInstance( Interpolation.INTERP_NEAREST ) ); PlanarImage thumbImage = JAI.create( "affine", thumbScaleParams ); // Save it FileOutputStream out = null; try { out = new FileOutputStream(thumbnailFile.getAbsolutePath()); } catch(IOException e) { log.error( "Error writing thumbnail: " + e.getMessage() ); txw.abort(); return; } JPEGEncodeParam encodeParam = new JPEGEncodeParam(); ImageEncoder encoder = ImageCodec.createImageEncoder("JPEG", out, encodeParam); try { encoder.encode( thumbImage ); out.close(); // origImage.dispose(); thumbImage.dispose(); } catch (IOException e) { log.error( "Error writing thumbnail: " + e.getMessage() ); txw.abort(); return; } // add the created instance to this persistent object ImageInstance thumbInstance = addInstance( volume, thumbnailFile, ImageInstance.INSTANCE_TYPE_THUMBNAIL ); thumbInstance.setRotated( prefRotation -original.getRotated() ); thumbInstance.setCropBounds( getCropBounds() ); log.debug( "Loading thumbnail..." ); thumbnail = Thumbnail.createThumbnail( this, thumbnailFile ); oldThumbnail = null; log.debug( "Thumbnail loaded" ); txw.commit(); }
| 1,108,734
|
protected void createThumbnail( VolumeBase volume ) { log.debug( "Creating thumbnail for " + uid ); ODMGXAWrapper txw = new ODMGXAWrapper(); txw.lock( this, Transaction.WRITE ); // Maximum size of the thumbnail int maxThumbWidth = 100; int maxThumbHeight = 100; checkCropBounds(); /* Determine the minimum size for the instance used for thumbnail creation to get decent image quality. The cropped portion of the image must be roughly the same resolution as the intended thumbnail. */ double cropWidth = cropMaxX - cropMinX; cropWidth = ( cropWidth > 0.000001 ) ? cropWidth : 1.0; double cropHeight = cropMaxY - cropMinY; cropHeight = ( cropHeight > 0.000001 ) ? cropHeight : 1.0; int minInstanceWidth = (int)(((double)maxThumbWidth)/cropWidth); int minInstanceHeight = (int)(((double)maxThumbHeight)/cropHeight); int minInstanceSide = Math.max( minInstanceWidth, minInstanceHeight ); // Find the original image to use as a staring point ImageInstance original = null; for ( int n = 0; n < instances.size(); n++ ) { ImageInstance instance = (ImageInstance) instances.get( n ); if ( instance.getInstanceType() == ImageInstance.INSTANCE_TYPE_ORIGINAL ) { original = instance; txw.lock( original, Transaction.READ ); break; } } if ( original == null || original.getImageFile() == null || !original.getImageFile().exists() ) { // If there are uncorrupted instances, no thumbnail can be created log.warn( "Error - no original image was found!!!" ); txw.commit(); return; } log.debug( "Found original, reading it..." ); /* We try to ensure that the thumbnail is actually from the original image by comparing aspect ratio of it to original. This is not a perfect check but it will usually catch the most typical errors (like having a the original rotated by RAW conversion SW but still the original EXIF thumbnail. */ double origAspect = this.getAspect( original.getWidth(), original.getHeight(), 1.0 ); double aspectAccuracy = 0.01; // First, check if there is a thumbnail in image header BufferedImage origImage = readExifThumbnail( original.getImageFile() ); if ( origImage == null || !isOkForThumbCreation( origImage.getWidth(), origImage.getHeight(), minInstanceWidth, minInstanceHeight, origAspect, aspectAccuracy ) ) { // Read the image try { Iterator readers = ImageIO.getImageReadersByFormatName( "jpg" ); if ( readers.hasNext() ) { ImageReader reader = (ImageReader)readers.next(); log.debug( "Creating stream" ); ImageInputStream iis = ImageIO.createImageInputStream( original.getImageFile() ); reader.setInput( iis, false, false ); int numThumbs = 0; try { int numImages = reader.getNumImages( true ); numThumbs = reader.getNumThumbnails(0); } catch (IOException ex) { ex.printStackTrace(); } if ( numThumbs > 0 && isOkForThumbCreation( reader.getThumbnailWidth( 0, 0 ), reader.getThumbnailHeight( 0, 0 ) , minInstanceWidth, minInstanceHeight, origAspect, aspectAccuracy ) ) { // There is a thumbanil that is big enough - use it log.debug( "Original has thumbnail, size " + reader.getThumbnailWidth( 0, 0 ) + " x " + reader.getThumbnailHeight( 0, 0 ) ); origImage = reader.readThumbnail( 0, 0 ); log.debug( "Read thumbnail" ); } else { log.debug( "No thumbnail in original" ); ImageReadParam param = reader.getDefaultReadParam(); // Find the maximum subsampling rate we can still use for creating // a quality thumbnail int subsampling = 1; int minDim = Math.min( reader.getWidth( 0 ),reader.getHeight( 0 ) ); while ( 2 * minInstanceSide * subsampling < minDim ) { subsampling *= 2; } param.setSourceSubsampling( subsampling, subsampling, 0, 0 ); origImage = reader.read( 0, param ); log.debug( "Read original" ); } iis.close(); } } catch ( IOException e ) { log.warn( "Error reading image: " + e.getMessage() ); txw.abort(); return; } } log.debug( "Done, finding name" ); // Find where to store the file in the target volume File thumbnailFile = volume.getInstanceName( this, "jpg" ); log.debug( "name = " + thumbnailFile.getName() ); // Shrink the image to desired state and save it // Find first the correct transformation for doing this int origWidth = origImage.getWidth(); int origHeight = origImage.getHeight(); AffineTransform xform = org.photovault.image.ImageXform.getRotateXform( prefRotation -original.getRotated(), origWidth, origHeight ); ParameterBlockJAI rotParams = new ParameterBlockJAI( "affine" ); rotParams.addSource( origImage ); rotParams.setParameter( "transform", xform ); rotParams.setParameter( "interpolation", Interpolation.getInstance( Interpolation.INTERP_NEAREST ) ); RenderedOp rotatedImage = JAI.create( "affine", rotParams ); ParameterBlockJAI cropParams = new ParameterBlockJAI( "crop" ); cropParams.addSource( rotatedImage ); float cropX = (float)( Math.rint( rotatedImage.getMinX() + cropMinX * rotatedImage.getWidth() ) ); float cropY = (float)( Math.rint( rotatedImage.getMinY() + cropMinY * rotatedImage.getHeight())); float cropW = (float)( Math.rint((cropWidth) * rotatedImage.getWidth() ) ); float cropH = (float) ( Math.rint((cropHeight) * rotatedImage.getHeight() )); cropParams.setParameter( "x", cropX ); cropParams.setParameter( "y", cropY ); cropParams.setParameter( "width", cropW ); cropParams.setParameter( "height", cropH ); RenderedOp cropped = JAI.create("crop", cropParams, null); // Translate the image so that it begins in origo ParameterBlockJAI pbXlate = new ParameterBlockJAI( "translate" ); pbXlate.addSource( cropped ); pbXlate.setParameter( "xTrans", (float) (-cropped.getMinX() ) ); pbXlate.setParameter( "yTrans", (float) (-cropped.getMinY() ) ); RenderedOp xformImage = JAI.create( "translate", pbXlate ); // Finally, scale this to thumbnail AffineTransform thumbScale = org.photovault.image.ImageXform.getFittingXform( maxThumbWidth, maxThumbHeight, 0, xformImage.getWidth(), xformImage.getHeight() ); ParameterBlockJAI thumbScaleParams = new ParameterBlockJAI( "affine" ); thumbScaleParams.addSource( xformImage ); thumbScaleParams.setParameter( "transform", thumbScale ); thumbScaleParams.setParameter( "interpolation", Interpolation.getInstance( Interpolation.INTERP_NEAREST ) ); PlanarImage thumbImage = JAI.create( "affine", thumbScaleParams ); // Save it FileOutputStream out = null; try { out = new FileOutputStream(thumbnailFile.getAbsolutePath()); } catch(IOException e) { log.error( "Error writing thumbnail: " + e.getMessage() ); txw.abort(); return; } JPEGEncodeParam encodeParam = new JPEGEncodeParam(); ImageEncoder encoder = ImageCodec.createImageEncoder("JPEG", out, encodeParam); try { encoder.encode( thumbImage ); out.close(); // origImage.dispose(); thumbImage.dispose(); } catch (IOException e) { log.error( "Error writing thumbnail: " + e.getMessage() ); txw.abort(); return; } // add the created instance to this persistent object ImageInstance thumbInstance = addInstance( volume, thumbnailFile, ImageInstance.INSTANCE_TYPE_THUMBNAIL ); thumbInstance.setRotated( prefRotation -original.getRotated() ); thumbInstance.setCropBounds( getCropBounds() ); log.debug( "Loading thumbnail..." ); thumbnail = Thumbnail.createThumbnail( this, thumbnailFile ); oldThumbnail = null; log.debug( "Thumbnail loaded" ); txw.commit(); }
|
protected void createThumbnail( VolumeBase volume ) { log.debug( "Creating thumbnail for " + uid ); ODMGXAWrapper txw = new ODMGXAWrapper(); txw.lock( this, Transaction.WRITE ); // Maximum size of the thumbnail int maxThumbWidth = 100; int maxThumbHeight = 100; checkCropBounds(); /* Determine the minimum size for the instance used for thumbnail creation to get decent image quality. The cropped portion of the image must be roughly the same resolution as the intended thumbnail. */ double cropWidth = cropMaxX - cropMinX; cropWidth = ( cropWidth > 0.000001 ) ? cropWidth : 1.0; double cropHeight = cropMaxY - cropMinY; cropHeight = ( cropHeight > 0.000001 ) ? cropHeight : 1.0; int minInstanceWidth = (int)(((double)maxThumbWidth)/cropWidth); int minInstanceHeight = (int)(((double)maxThumbHeight)/cropHeight); int minInstanceSide = Math.max( minInstanceWidth, minInstanceHeight ); // Find the original image to use as a staring point ImageInstance original = null; for ( int n = 0; n < instances.size(); n++ ) { ImageInstance instance = (ImageInstance) instances.get( n ); if ( instance.getInstanceType() == ImageInstance.INSTANCE_TYPE_ORIGINAL ) { original = instance; txw.lock( original, Transaction.READ ); break; } } if ( original == null || original.getImageFile() == null || !original.getImageFile().exists() ) { // If there are uncorrupted instances, no thumbnail can be created log.warn( "Error - no original image was found!!!" ); txw.commit(); return; } log.debug( "Found original, reading it..." ); /* We try to ensure that the thumbnail is actually from the original image by comparing aspect ratio of it to original. This is not a perfect check but it will usually catch the most typical errors (like having a the original rotated by RAW conversion SW but still the original EXIF thumbnail. */ double origAspect = this.getAspect( original.getWidth(), original.getHeight(), 1.0 ); double aspectAccuracy = 0.01; // First, check if there is a thumbnail in image header BufferedImage origImage = readExifThumbnail( original.getImageFile() ); if ( origImage == null || !isOkForThumbCreation( origImage.getWidth(), origImage.getHeight(), minInstanceWidth, minInstanceHeight, origAspect, aspectAccuracy ) ) { // Read the image try { Iterator readers = ImageIO.getImageReadersByFormatName( "jpg" ); if ( readers.hasNext() ) { ImageReader reader = (ImageReader)readers.next(); log.debug( "Creating stream" ); ImageInputStream iis = ImageIO.createImageInputStream( original.getImageFile() ); reader.setInput( iis, false, false ); int numThumbs = 0; try { int numImages = reader.getNumImages( true ); numThumbs = reader.getNumThumbnails(0); } catch (IOException ex) { ex.printStackTrace(); } if ( numThumbs > 0 && isOkForThumbCreation( reader.getThumbnailWidth( 0, 0 ), reader.getThumbnailHeight( 0, 0 ) , minInstanceWidth, minInstanceHeight, origAspect, aspectAccuracy ) ) { // There is a thumbanil that is big enough - use it log.debug( "Original has thumbnail, size " + reader.getThumbnailWidth( 0, 0 ) + " x " + reader.getThumbnailHeight( 0, 0 ) ); origImage = reader.readThumbnail( 0, 0 ); log.debug( "Read thumbnail" ); } else { log.debug( "No thumbnail in original" ); ImageReadParam param = reader.getDefaultReadParam(); // Find the maximum subsampling rate we can still use for creating // a quality thumbnail int subsampling = 1; int minDim = Math.min( reader.getWidth( 0 ),reader.getHeight( 0 ) ); while ( 2 * minInstanceSide * subsampling < minDim ) { subsampling *= 2; } param.setSourceSubsampling( subsampling, subsampling, 0, 0 ); origImage = reader.read( 0, param ); log.debug( "Read original" ); } iis.close(); } } catch ( IOException e ) { log.warn( "Error reading image: " + e.getMessage() ); txw.abort(); return; } } log.debug( "Done, finding name" ); // Find where to store the file in the target volume File thumbnailFile = volume.getInstanceName( this, "jpg" ); log.debug( "name = " + thumbnailFile.getName() ); // Shrink the image to desired state and save it // Find first the correct transformation for doing this int origWidth = origImage.getWidth(); int origHeight = origImage.getHeight(); AffineTransform xform = org.photovault.image.ImageXform.getRotateXform( prefRotation -original.getRotated(), origWidth, origHeight ); ParameterBlockJAI rotParams = new ParameterBlockJAI( "affine" ); rotParams.addSource( origImage ); rotParams.setParameter( "transform", xform ); rotParams.setParameter( "interpolation", Interpolation.getInstance( Interpolation.INTERP_NEAREST ) ); RenderedOp rotatedImage = JAI.create( "affine", rotParams ); ParameterBlockJAI cropParams = new ParameterBlockJAI( "crop" ); cropParams.addSource( rotatedImage ); float cropX = (float)( Math.rint( rotatedImage.getMinX() + cropMinX * rotatedImage.getWidth() ) ); float cropY = (float)( Math.rint( rotatedImage.getMinY() + cropMinY * rotatedImage.getHeight())); float cropW = (float)( Math.rint((cropWidth) * rotatedImage.getWidth() ) ); float cropH = (float) ( Math.rint((cropHeight) * rotatedImage.getHeight() )); cropParams.setParameter( "x", cropX ); cropParams.setParameter( "y", cropY ); cropParams.setParameter( "width", cropW ); cropParams.setParameter( "height", cropH ); RenderedOp cropped = JAI.create("crop", cropParams, null); // Translate the image so that it begins in origo ParameterBlockJAI pbXlate = new ParameterBlockJAI( "translate" ); pbXlate.addSource( cropped ); pbXlate.setParameter( "xTrans", (float) (-cropped.getMinX() ) ); pbXlate.setParameter( "yTrans", (float) (-cropped.getMinY() ) ); RenderedOp xformImage = JAI.create( "translate", pbXlate ); // Finally, scale this to thumbnail AffineTransform thumbScale = org.photovault.image.ImageXform.getFittingXform( maxThumbWidth, maxThumbHeight, 0, xformImage.getWidth(), xformImage.getHeight() ); ParameterBlockJAI thumbScaleParams = new ParameterBlockJAI( "affine" ); thumbScaleParams.addSource( xformImage ); thumbScaleParams.setParameter( "transform", thumbScale ); thumbScaleParams.setParameter( "interpolation", Interpolation.getInstance( Interpolation.INTERP_NEAREST ) ); PlanarImage thumbImage = JAI.create( "affine", thumbScaleParams ); // Save it FileOutputStream out = null; try { out = new FileOutputStream(thumbnailFile.getAbsolutePath()); } catch(IOException e) { log.error( "Error writing thumbnail: " + e.getMessage() ); txw.abort(); return; } JPEGEncodeParam encodeParam = new JPEGEncodeParam(); ImageEncoder encoder = ImageCodec.createImageEncoder("JPEG", out, encodeParam); try { encoder.encode( thumbImage ); out.close(); // origImage.dispose(); thumbImage.dispose(); } catch (IOException e) { log.error( "Error writing thumbnail: " + e.getMessage() ); txw.abort(); return; } // add the created instance to this persistent object ImageInstance thumbInstance = addInstance( volume, thumbnailFile, ImageInstance.INSTANCE_TYPE_THUMBNAIL ); thumbInstance.setRotated( prefRotation -original.getRotated() ); thumbInstance.setCropBounds( getCropBounds() ); log.debug( "Loading thumbnail..." ); thumbnail = Thumbnail.createThumbnail( this, thumbnailFile ); oldThumbnail = null; log.debug( "Thumbnail loaded" ); txw.commit(); }
| 1,108,735
|
void updateFromFileMetadata( File f ) { ExifDirectory exif = null; try { Metadata metadata = JpegMetadataReader.readMetadata(f); if ( metadata.containsDirectory( ExifDirectory.class ) ) { try { exif = (ExifDirectory) metadata.getDirectory( ExifDirectory.class ); } catch ( MetadataException e ) { } } else { // No known directory was found no reason to continue return; } } catch (FileNotFoundException e) { // If error, just return - this is just an additional 'nice-if-succesful' operation. // If there is no metadata this will happen... return; } // Shooting date try { java.util.Date origDate = exif.getDate( exif.TAG_DATETIME_ORIGINAL ); setShootTime( origDate ); log.debug( "TAG_DATETIME_ORIGINAL: " + origDate.toString() ); } catch ( MetadataException e ) { log.info( "Error reading origDate: " + e.getMessage() ); } // Exposure try { double fstop = exif.getDouble( exif.TAG_FNUMBER ); log.debug( "TAG_FNUMBER: " + fstop ); setFStop( fstop ); } catch ( MetadataException e ) { log.info( "Error reading origDate: " + e.getMessage() ); } try { double sspeed = exif.getDouble( exif.TAG_EXPOSURE_TIME ); setShutterSpeed( sspeed ); log.debug( "TAG_EXPOSURE_TIME: " + sspeed ); } catch ( MetadataException e ) { log.info( "Error reading origDate: " + e.getMessage() ); } try { double flen = exif.getDouble( exif.TAG_FOCAL_LENGTH ); setFocalLength( flen ); } catch ( MetadataException e ) { log.info( "Error reading origDate: " + e.getMessage() ); } try { int filmSpeed = exif.getInt( exif.TAG_ISO_EQUIVALENT ); setFilmSpeed( filmSpeed ); } catch ( MetadataException e ) { log.info( "Error reading origDate: " + e.getMessage() ); } // Camera name. Put here both camera manufacturer and model String maker = exif.getString( exif.TAG_MAKE ); String model = exif.getString( exif.TAG_MODEL ); StringBuffer cameraBuf = new StringBuffer( maker ); cameraBuf.append( " "). append( model ); String camera = cameraBuf.toString(); if ( cameraBuf.length() > CAMERA_LENGTH ) { camera = cameraBuf.substring( 0, CAMERA_LENGTH ); } setCamera( camera ); }
|
void updateFromFileMetadata( File f ) { ExifDirectory exif = null; try { Metadata metadata = JpegMetadataReader.readMetadata(f); if ( metadata.containsDirectory( ExifDirectory.class ) ) { try { exif = (ExifDirectory) metadata.getDirectory( ExifDirectory.class ); } catch ( MetadataException e ) { } } else { // No known directory was found no reason to continue return; } } catch (FileNotFoundException e) { // If error, just return - this is just an additional 'nice-if-succesful' operation. // If there is no metadata this will happen... return; } // Shooting date try { java.util.Date origDate = exif.getDate( exif.TAG_DATETIME_ORIGINAL ); setShootTime( origDate ); log.debug( "TAG_DATETIME_ORIGINAL: " + origDate.toString() ); } catch ( MetadataException e ) { log.info( "Error reading origDate: " + e.getMessage() ); } // Exposure try { double fstop = exif.getDouble( exif.TAG_FNUMBER ); log.debug( "TAG_FNUMBER: " + fstop ); setFStop( fstop ); } catch ( MetadataException e ) { log.info( "Error reading origDate: " + e.getMessage() ); } try { double sspeed = exif.getDouble( exif.TAG_EXPOSURE_TIME ); setShutterSpeed( sspeed ); log.debug( "TAG_EXPOSURE_TIME: " + sspeed ); } catch ( MetadataException e ) { log.info( "Error reading origDate: " + e.getMessage() ); } try { double flen = exif.getDouble( exif.TAG_FOCAL_LENGTH ); setFocalLength( flen ); } catch ( MetadataException e ) { log.info( "Error reading origDate: " + e.getMessage() ); } try { int filmSpeed = exif.getInt( exif.TAG_ISO_EQUIVALENT ); setFilmSpeed( filmSpeed ); } catch ( MetadataException e ) { log.info( "Error reading origDate: " + e.getMessage() ); } // Camera name. Put here both camera manufacturer and model String maker = exif.getString( exif.TAG_MAKE ); String model = exif.getString( exif.TAG_MODEL ); StringBuffer cameraBuf = new StringBuffer( maker ); cameraBuf.append( " "). append( model ); String camera = cameraBuf.toString(); if ( cameraBuf.length() > CAMERA_LENGTH ) { camera = cameraBuf.substring( 0, CAMERA_LENGTH ); } setCamera( camera ); }
| 1,108,736
|
public void remove(PlayPenComponent c) { int j = children.indexOf(c); if ( j >= 0 ) remove(j); }
|
public void remove(PlayPenComponent c) { int j = children.indexOf(c); if ( j >= 0 ) remove(j); }
| 1,108,738
|
public void actionPerformed(ActionEvent evt) { List selection = pp.getSelectedItems(); if (selection.size() < 1) { JOptionPane.showMessageDialog(pp, "Select a relationship (by clicking on it) and try again."); } else if (selection.size() > 1) { JOptionPane.showMessageDialog(pp, "You have selected multiple items, but you can only edit one at a time."); } else if (selection.get(0) instanceof Relationship) { Relationship r = (Relationship) selection.get(0); final JDialog d = new JDialog(ArchitectFrame.getMainInstance(), "Relationship Properties"); JPanel cp = new JPanel(new BorderLayout(12,12)); cp.setBorder(BorderFactory.createEmptyBorder(12,12,12,12)); final RelationshipEditPanel editPanel = new RelationshipEditPanel(); editPanel.setRelationship(r.getModel()); cp.add(editPanel, BorderLayout.CENTER); JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); JButton okButton = new JButton("Ok"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { editPanel.applyChanges(); d.setVisible(false); } }); buttonPanel.add(okButton); JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { editPanel.discardChanges(); d.setVisible(false); } }); buttonPanel.add(cancelButton); cp.add(buttonPanel, BorderLayout.SOUTH); d.setContentPane(cp); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); } else { JOptionPane.showMessageDialog(pp, "The selected item type is not recognised"); } }
|
public void actionPerformed(ActionEvent evt) { List selection = pp.getSelectedItems(); if (selection.size() < 1) { JOptionPane.showMessageDialog(pp, "Select a relationship (by clicking on it) and try again."); } else if (selection.size() > 1) { JOptionPane.showMessageDialog(pp, "You have selected multiple items, but you can only edit one at a time."); } else if (selection.get(0) instanceof Relationship) { Relationship r = (Relationship) selection.get(0); final JDialog d = new JDialog(ArchitectFrame.getMainInstance(), "Relationship Properties"); JPanel cp = new JPanel(new BorderLayout(12,12)); cp.setBorder(BorderFactory.createEmptyBorder(12,12,12,12)); final RelationshipEditPanel editPanel = new RelationshipEditPanel(); editPanel.setRelationship(r.getModel()); cp.add(editPanel, BorderLayout.CENTER); JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); JButton okButton = new JButton("Ok"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { editPanel.applyChanges(); d.setVisible(false); } }); buttonPanel.add(okButton); JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { editPanel.discardChanges(); d.setVisible(false); } }); buttonPanel.add(cancelButton); cp.add(buttonPanel, BorderLayout.SOUTH); d.setContentPane(cp); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); } else { JOptionPane.showMessageDialog(pp, "The selected item type is not recognised"); } }
| 1,108,739
|
public void actionPerformed(ActionEvent evt) { List selection = pp.getSelectedItems(); if (selection.size() < 1) { JOptionPane.showMessageDialog(pp, "Select a relationship (by clicking on it) and try again."); } else if (selection.size() > 1) { JOptionPane.showMessageDialog(pp, "You have selected multiple items, but you can only edit one at a time."); } else if (selection.get(0) instanceof Relationship) { Relationship r = (Relationship) selection.get(0); final JDialog d = new JDialog(ArchitectFrame.getMainInstance(), "Relationship Properties"); JPanel cp = new JPanel(new BorderLayout(12,12)); cp.setBorder(BorderFactory.createEmptyBorder(12,12,12,12)); final RelationshipEditPanel editPanel = new RelationshipEditPanel(); editPanel.setRelationship(r.getModel()); cp.add(editPanel, BorderLayout.CENTER); JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); JButton okButton = new JButton("Ok"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { editPanel.applyChanges(); d.setVisible(false); } }); buttonPanel.add(okButton); JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { editPanel.discardChanges(); d.setVisible(false); } }); buttonPanel.add(cancelButton); cp.add(buttonPanel, BorderLayout.SOUTH); d.setContentPane(cp); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); } else { JOptionPane.showMessageDialog(pp, "The selected item type is not recognised"); } }
|
public void actionPerformed(ActionEvent evt) { List selection = pp.getSelectedItems(); if (selection.size() < 1) { JOptionPane.showMessageDialog(pp, "Select a relationship (by clicking on it) and try again."); } else if (selection.size() > 1) { JOptionPane.showMessageDialog(pp, "You have selected multiple items, but you can only edit one at a time."); } else if (selection.get(0) instanceof Relationship) { Relationship r = (Relationship) selection.get(0); final JDialog d = new JDialog(ArchitectFrame.getMainInstance(), "Relationship Properties"); JPanel cp = new JPanel(new BorderLayout(12,12)); cp.setBorder(BorderFactory.createEmptyBorder(12,12,12,12)); final RelationshipEditPanel editPanel = new RelationshipEditPanel(); editPanel.setRelationship(r.getModel()); cp.add(editPanel, BorderLayout.CENTER); JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); JButton okButton = new JButton("Ok"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { editPanel.applyChanges(); d.setVisible(false); } }); buttonPanel.add(okButton); JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { editPanel.discardChanges(); d.setVisible(false); } }); buttonPanel.add(cancelButton); cp.add(buttonPanel, BorderLayout.SOUTH); d.setContentPane(cp); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); d.setVisible(true); } else { JOptionPane.showMessageDialog(pp, "The selected item type is not recognised"); } }
| 1,108,740
|
public String getToolTipText(MouseEvent e) { String text = null; Point ep = e.getPoint(); // event's point in playpen in screen coords Point sp = owner.unzoomPoint(ep); PlayPenComponent c = getComponentAt(sp); if (c != null) { text = c.getToolTipText(); } logger.debug("Checking for tooltip component at "+e.getPoint()+" is "+c+". tooltipText is "+text); return text; }
|
public String getToolTipText(MouseEvent e) { String text = null; Point ep = e.getPoint(); // event's point in playpen in screen coords Point sp = owner.unzoomPoint(ep); PlayPenComponent c = getComponentAt(sp); if (c != null) { text = c.getToolTipText(); } logger.debug("Checking for tooltip component at "+e.getPoint()+" is "+c+". tooltipText is "+text); return text; }
| 1,108,741
|
public void setName(String argName){ put(PL_LOGICAL, argName); }
|
public void setName(String argName){ putImpl(PL_LOGICAL, argName, "name"); }
| 1,108,742
|
public void mousePressed (MouseEvent e) { Rectangle blockselector = new Rectangle(clickXShift-boxRadius,clickYShift - boxRadius, (Chromosome.getFilteredSize()*boxSize), boxSize); //if users right clicks & holds, pop up the info if ((e.getModifiers() & InputEvent.BUTTON3_MASK) == InputEvent.BUTTON3_MASK){ Graphics g = getGraphics(); g.setFont(boxFont); FontMetrics metrics = g.getFontMetrics(); PairwiseLinkage[][] dPrimeTable = theData.filteredDPrimeTable; final int clickX = e.getX(); final int clickY = e.getY(); double dboxX = (double)(clickX - clickXShift - (clickY-clickYShift))/boxSize; double dboxY = (double)(clickX - clickXShift + (clickY-clickYShift))/boxSize; final int boxX, boxY; if (dboxX < 0){ boxX = (int)(dboxX - 0.5); } else{ boxX = (int)(dboxX + 0.5); } if (dboxY < 0){ boxY = (int)(dboxY - 0.5); }else{ boxY = (int)(dboxY + 0.5); } if ((boxX >= lowX && boxX <= highX) && (boxY > boxX && boxY < highY) && !(worldmapRect.contains(clickX,clickY))){ if (dPrimeTable[boxX][boxY] != null){ displayStrings = new String[5]; if (theData.infoKnown){ displayStrings[0] = new String ("(" +Chromosome.getFilteredMarker(boxX).getName() + ", " + Chromosome.getFilteredMarker(boxY).getName() + ")"); }else{ displayStrings[0] = new String("(" + (Chromosome.realIndex[boxX]+1) + ", " + (Chromosome.realIndex[boxY]+1) + ")"); } displayStrings[1] = new String ("D': " + dPrimeTable[boxX][boxY].getDPrime()); displayStrings[2] = new String ("LOD: " + dPrimeTable[boxX][boxY].getLOD()); displayStrings[3] = new String ("r^2: " + dPrimeTable[boxX][boxY].getRSquared()); displayStrings[4] = new String ("D' conf. bounds: " + dPrimeTable[boxX][boxY].getConfidenceLow() + "-" + dPrimeTable[boxX][boxY].getConfidenceHigh()); popupExists = true; } } else if (blockselector.contains(clickX, clickY)){ int marker = (int)(0.5 + (double)((clickX - clickXShift))/boxSize); displayStrings = new String[2]; if (theData.infoKnown){ displayStrings[0] = new String (Chromosome.getFilteredMarker(marker).getName()); }else{ displayStrings[0] = new String("Marker " + (Chromosome.realIndex[marker]+1)); } displayStrings[1] = new String ("MAF: " + Chromosome.getFilteredMarker(marker).getMAF()); popupExists = true; } if (popupExists){ int strlen = 0; for (int x = 0; x < displayStrings.length; x++){ if (strlen < metrics.stringWidth(displayStrings[x])){ strlen = metrics.stringWidth(displayStrings[x]); } } //edge shifts prevent window from popping up partially offscreen int visRightBound = (int)(getVisibleRect().getWidth() + getVisibleRect().getX()); int visBotBound = (int)(getVisibleRect().getHeight() + getVisibleRect().getY()); int rightEdgeShift = 0; if (clickX + strlen + popupLeftMargin +5 > visRightBound){ rightEdgeShift = clickX + strlen + popupLeftMargin + 10 - visRightBound; } int botEdgeShift = 0; if (clickY + 5*metrics.getHeight()+10 > visBotBound){ botEdgeShift = clickY + 5*metrics.getHeight()+15 - visBotBound; } int smallDataVertSlop = 0; if (getPreferredSize().getWidth() < getVisibleRect().width){ smallDataVertSlop = (int)(getVisibleRect().height - getPreferredSize().getHeight())/2; } popupDrawRect = new Rectangle(clickX-rightEdgeShift, clickY-botEdgeShift+smallDataVertSlop, strlen+popupLeftMargin+5, displayStrings.length*metrics.getHeight()+10); repaint(); } }else if ((e.getModifiers() & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK){ int x = e.getX(); int y = e.getY(); if (blockselector.contains(x,y)){ setCursor(Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR)); blockStartX = x; } } }
|
public void mousePressed (MouseEvent e) { Rectangle blockselector = new Rectangle(clickXShift-boxRadius,clickYShift - boxRadius, (Chromosome.getFilteredSize()*boxSize), boxSize); //if users right clicks & holds, pop up the info if ((e.getModifiers() & InputEvent.BUTTON3_MASK) == InputEvent.BUTTON3_MASK){ Graphics g = getGraphics(); g.setFont(boxFont); FontMetrics metrics = g.getFontMetrics(); PairwiseLinkage[][] dPrimeTable = theData.filteredDPrimeTable; final int clickX = e.getX(); final int clickY = e.getY(); double dboxX = (double)(clickX - clickXShift - (clickY-clickYShift))/boxSize; double dboxY = (double)(clickX - clickXShift + (clickY-clickYShift))/boxSize; final int boxX, boxY; if (dboxX < 0){ boxX = (int)(dboxX - 0.5); } else{ boxX = (int)(dboxX + 0.5); } if (dboxY < 0){ boxY = (int)(dboxY - 0.5); }else{ boxY = (int)(dboxY + 0.5); } if ((boxX >= lowX && boxX <= highX) && (boxY > boxX && boxY < highY) && !(worldmapRect.contains(clickX,clickY))){ if (dPrimeTable[boxX][boxY] != null){ displayStrings = new String[5]; if (theData.infoKnown){ displayStrings[0] = new String ("(" +Chromosome.getFilteredMarker(boxX).getName() + ", " + Chromosome.getFilteredMarker(boxY).getName() + ")"); }else{ displayStrings[0] = new String("(" + (Chromosome.realIndex[boxX]+1) + ", " + (Chromosome.realIndex[boxY]+1) + ")"); } displayStrings[1] = new String ("D': " + dPrimeTable[boxX][boxY].getDPrime()); displayStrings[2] = new String ("LOD: " + dPrimeTable[boxX][boxY].getLOD()); displayStrings[3] = new String ("r^2: " + dPrimeTable[boxX][boxY].getRSquared()); displayStrings[4] = new String ("D' conf. bounds: " + dPrimeTable[boxX][boxY].getConfidenceLow() + "-" + dPrimeTable[boxX][boxY].getConfidenceHigh()); popupExists = true; } } else if (blockselector.contains(clickX, clickY)){ int marker = (int)(0.5 + (double)((clickX - clickXShift))/boxSize); displayStrings = new String[2]; if (theData.infoKnown){ displayStrings[0] = new String (Chromosome.getFilteredMarker(marker).getName()); }else{ displayStrings[0] = new String("Marker " + (Chromosome.realIndex[marker]+1)); } displayStrings[1] = new String ("MAF: " + Chromosome.getFilteredMarker(marker).getMAF()); popupExists = true; } if (popupExists){ int strlen = 0; for (int x = 0; x < displayStrings.length; x++){ if (strlen < metrics.stringWidth(displayStrings[x])){ strlen = metrics.stringWidth(displayStrings[x]); } } //edge shifts prevent window from popping up partially offscreen int visRightBound = (int)(getVisibleRect().getWidth() + getVisibleRect().getX()); int visBotBound = (int)(getVisibleRect().getHeight() + getVisibleRect().getY()); int rightEdgeShift = 0; if (clickX + strlen + popupLeftMargin +5 > visRightBound){ rightEdgeShift = clickX + strlen + popupLeftMargin + 10 - visRightBound; } int botEdgeShift = 0; if (clickY + 5*metrics.getHeight()+10 > visBotBound){ botEdgeShift = clickY + 5*metrics.getHeight()+15 - visBotBound; } int smallDataVertSlop = 0; if (getPreferredSize().getWidth() < getVisibleRect().width && theData.infoKnown){ smallDataVertSlop = (int)(getVisibleRect().height - getPreferredSize().getHeight())/2; } popupDrawRect = new Rectangle(clickX-rightEdgeShift, clickY-botEdgeShift+smallDataVertSlop, strlen+popupLeftMargin+5, displayStrings.length*metrics.getHeight()+10); repaint(); } }else if ((e.getModifiers() & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK){ int x = e.getX(); int y = e.getY(); if (blockselector.contains(x,y)){ setCursor(Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR)); blockStartX = x; } } }
| 1,108,743
|
public ActionForward execute(WebContext context, ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception { ApplicationForm appForm = (ApplicationForm)actionForm; ApplicationConfigManager.deleteApplication(appForm.getApplicationId()); UserActivityLogger.getInstance().logActivity( context.getUser().getUsername(), "Deleted application with ID "+appForm.getApplicationId()); return mapping.findForward(Forwards.SUCCESS); }
|
public ActionForward execute(WebContext context, ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception { ApplicationForm appForm = (ApplicationForm)actionForm; ApplicationConfig config=ApplicationConfigManager.deleteApplication (appForm.getApplicationId()); UserActivityLogger.getInstance().logActivity( context.getUser().getUsername(), "Deleted application with ID "+appForm.getApplicationId()); return mapping.findForward(Forwards.SUCCESS); }
| 1,108,744
|
public ActionForward execute(WebContext context, ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception { ApplicationForm appForm = (ApplicationForm)actionForm; ApplicationConfigManager.deleteApplication(appForm.getApplicationId()); UserActivityLogger.getInstance().logActivity( context.getUser().getUsername(), "Deleted application with ID "+appForm.getApplicationId()); return mapping.findForward(Forwards.SUCCESS); }
|
public ActionForward execute(WebContext context, ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception { ApplicationForm appForm = (ApplicationForm)actionForm; ApplicationConfigManager.deleteApplication(appForm.getApplicationId()); UserActivityLogger.getInstance().logActivity( context.getUser().getUsername(), "Deleted application "+"\""+config.getName()+"\""); return mapping.findForward(Forwards.SUCCESS); }
| 1,108,745
|
private User buildUser(ActionForm form){ UserForm userForm = (UserForm)form; List<Role> roles = new ArrayList<Role>(1); roles.add(new Role(userForm.getRole())); User user = new User(userForm.getUsername(), Crypto.hash(userForm.getPassword()), roles, userForm.getStatus(), 0); return user; }
|
private User buildUser(ActionForm form){ UserForm userForm = (UserForm)form; List<Role> roles = new ArrayList<Role>(1); String[] rolesString = userForm.getRole(); for(int ctr=0; ctr < rolesString.length; ctr++){ roles.add(new Role(rolesString[ctr])); } User user = new User(userForm.getUsername(), Crypto.hash(userForm.getPassword()), roles, userForm.getStatus(), 0); return user; }
| 1,108,746
|
public static void checkAccess(ServiceContext context, String aclName) throws UnAuthorizedAccessException { checkAccess(context, aclName, null); }
|
public static void checkAccess(ServiceContext context, String aclName, String targetName) throws UnAuthorizedAccessException { checkAccess(context, aclName, null); }
| 1,108,747
|
public static void checkAccess(ServiceContext context, String aclName) throws UnAuthorizedAccessException { checkAccess(context, aclName, null); }
|
public static void checkAccess(ServiceContext context, String aclName) throws UnAuthorizedAccessException { if(!canAccess(context, aclName, targetName)){ throw new UnAuthorizedAccessException("Insufficient Privileges"); } }
| 1,108,748
|
public ActionForward execute(WebContext context, ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) { ApplicationConfig config = context.getApplicationConfig(); ApplicationForm appForm = (ApplicationForm)actionForm; ModuleConfig moduleConfig = ModuleRegistry.getModule(config.getType()); MetaApplicationConfig metaAppConfig = moduleConfig.getMetaApplicationConfig(); /* populate the form */ appForm.setApplicationId(config.getApplicationId()); appForm.setName(config.getName()); appForm.setType(config.getType()); if(metaAppConfig.isDisplayHost()) appForm.setHost(config.getHost()); if(metaAppConfig.isDisplayPort()) appForm.setPort(String.valueOf(config.getPort())); if(metaAppConfig.isDisplayUsername()) appForm.setUsername(config.getUsername()); if(metaAppConfig.isDisplayPassword() && config.getPassword() != null) appForm.setPassword(ApplicationForm.FORM_PASSWORD); request.setAttribute(RequestAttributes.META_APP_CONFIG, metaAppConfig); return mapping.findForward(Forwards.SUCCESS); }
|
public ActionForward execute(WebContext context, ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) { ApplicationConfig config = context.getApplicationConfig(); ApplicationForm appForm = (ApplicationForm)actionForm; ModuleConfig moduleConfig = ModuleRegistry.getModule(config.getType()); MetaApplicationConfig metaAppConfig = moduleConfig.getMetaApplicationConfig(); /* populate the form */ appForm.setApplicationId(config.getApplicationId()); appForm.setName(config.getName()); appForm.setType(config.getType()); if(metaAppConfig.isDisplayHost()) appForm.setHost(config.getHost()); if(metaAppConfig.isDisplayPort()) appForm.setPort(String.valueOf(config.getPort())); if(metaAppConfig.isDisplayUsername()) appForm.setUsername(config.getUsername()); if(metaAppConfig.isDisplayPassword() && config.getPassword() != null && config.getPassword().length()>0) appForm.setPassword(ApplicationForm.FORM_PASSWORD); request.setAttribute(RequestAttributes.META_APP_CONFIG, metaAppConfig); return mapping.findForward(Forwards.SUCCESS); }
| 1,108,749
|
protected Object newInstance(Class theClass, Map attributes, XMLOutput output) throws Exception { Object parentObject = getParentObject(); if (parentObject != null) { // now lets try call the create method... Class parentClass = parentObject.getClass(); Method method = findCreateMethod(parentClass); if (method != null) { try { return method.invoke(parentObject, EMPTY_ARGS); } catch (Exception e) { throw new JellyException( "failed to invoke method: " + method + " on bean: " + parentObject + " reason: " + e, e ); } } } else { throw new JellyException( "The " + getTagName() + " tag must be nested within a tag which maps to a bean property" ); } return null; }
|
protected Object newInstance(Class theClass, Map attributes, XMLOutput output) throws Exception { Object parentObject = getParentObject(); if (parentObject != null) { // now lets try call the create method... Class parentClass = parentObject.getClass(); Method method = findCreateMethod(parentClass); if (method != null) { try { return method.invoke(parentObject, EMPTY_ARGS); } catch (Exception e) { throw new JellyException( "failed to invoke method: " + method + " on bean: " + parentObject + " reason: " + e, e ); } } } else { throw new JellyException( "The " + getTagName() + " tag must be nested within a tag which maps to a bean property" ); } return null; }
| 1,108,751
|
public void setUp() { try { volumeRoot = File.createTempFile( "photovaultVolumeTest", "" ); volumeRoot.delete(); volumeRoot.mkdir(); extvolRoot = File.createTempFile( "photovaultVolumeTestExt", "" ); extvolRoot.delete(); extvolRoot.mkdir(); } catch (IOException ex) { ex.printStackTrace(); } volume = new Volume( "testVolume", volumeRoot.getAbsolutePath() ); extVol = new ExternalVolume( "extVolume", extvolRoot.getAbsolutePath() ); PhotovaultSettings settings = PhotovaultSettings.getSettings(); PVDatabase curDb = settings.getCurrentDatabase(); curDb.addVolume( extVol ); }
|
public void setUp() { try { volumeRoot = File.createTempFile( "photovaultVolumeTest", "" ); volumeRoot.delete(); volumeRoot.mkdir(); extvolRoot = File.createTempFile( "photovaultVolumeTestExt", "" ); extvolRoot.delete(); extvolRoot.mkdir(); } catch (IOException ex) { ex.printStackTrace(); } volume = new Volume( "testVolume", volumeRoot.getAbsolutePath() ); extVol = new ExternalVolume( "extVolume", extvolRoot.getAbsolutePath() ); PhotovaultSettings settings = PhotovaultSettings.getSettings(); PVDatabase curDb = settings.getCurrentDatabase(); try { curDb.addVolume( extVol ); } catch (PhotovaultException ex) { ex.printStackTrace(); } }
| 1,108,752
|
public void doTag(XMLOutput output) throws Exception { // evaluate body as it may contain a <destination> or message tag getBody().run(context, output); Message message = getMessage(); if ( message == null ) { throw new JellyException( "No message specified. Either specify a 'message' attribute or use a nested <jms:message> tag" ); } Destination destination = getDestination(); if ( destination == null ) { throw new JellyException( "No destination specified. Either specify a 'destination' attribute or use a nested <jms:destination> tag" ); } getConnection().send( destination, message ); }
|
public void doTag(XMLOutput output) throws Exception { // evaluate body as it may contain a <destination> or message tag invokeBody(output); Message message = getMessage(); if ( message == null ) { throw new JellyException( "No message specified. Either specify a 'message' attribute or use a nested <jms:message> tag" ); } Destination destination = getDestination(); if ( destination == null ) { throw new JellyException( "No destination specified. Either specify a 'destination' attribute or use a nested <jms:destination> tag" ); } getConnection().send( destination, message ); }
| 1,108,753
|
public Object getValueAt(Object node, int column) { HaplotypeAssociationNode n = (HaplotypeAssociationNode) node; switch (column){ case 0: return n.getName(); case 1: return n.getFreq(); case 2: return n.getRatios(); case 3: return n.getChiSq(); case 4: return n.getPVal(); } return null; }
|
public Object getValueAt(Object node, int column) { HaplotypeAssociationNode n = (HaplotypeAssociationNode) node; switch (column){ case 0: return n.getName(); case 1: return n.getFreq(); case 2: if(this.countsOrRatios == SHOW_COUNTS) { return n.getCounts(); } else if(this.countsOrRatios == SHOW_RATIOS) { return n.getRatios(); } case 3: return n.getChiSq(); case 4: return n.getPVal(); } return null; }
| 1,108,754
|
private double hwCalculate(int obsAA, int obsAB, int obsBB) throws PedFileException{ //Calculates exact two-sided hardy-weinberg p-value. Parameters //are number of genotypes, number of rare alleles observed and //number of heterozygotes observed. // // (c) 2003 Jan Wigginton, Goncalo Abecasis int diplotypes = obsAA + obsAB + obsBB; int rare = (obsAA*2) + obsAB; int hets = obsAB; //make sure "rare" allele is really the rare allele if (rare > diplotypes){ rare = 2*diplotypes-rare; } //make sure numbers aren't screwy if (hets > rare){ throw new PedFileException("HW test: " + hets + "heterozygotes but only " + rare + "rare alleles."); } double[] tailProbs = new double[rare+1]; for (int z = 0; z < tailProbs.length; z++){ tailProbs[z] = 0; } //start at midpoint int mid = rare * (2 * diplotypes - rare) / (2 * diplotypes); //check to ensure that midpoint and rare alleles have same parity if (((rare & 1) ^ (mid & 1)) != 0){ mid++; } int het = mid; int hom_r = (rare - mid) / 2; int hom_c = diplotypes - het - hom_r; //Calculate probability for each possible observed heterozygote //count up to a scaling constant, to avoid underflow and overflow tailProbs[mid] = 1.0; double sum = tailProbs[mid]; for (het = mid; het > 1; het -=2){ tailProbs[het-2] = (tailProbs[het] * het * (het-1.0))/(4.0*(hom_r + 1.0) * (hom_c + 1.0)); sum += tailProbs[het-2]; //2 fewer hets for next iteration -> add one rare and one common homozygote hom_r++; hom_c++; } het = mid; hom_r = (rare - mid) / 2; hom_c = diplotypes - het - hom_r; for (het = mid; het <= rare - 2; het += 2){ tailProbs[het+2] = (tailProbs[het] * 4.0 * hom_r * hom_c) / ((het+2.0)*(het+1.0)); sum += tailProbs[het+2]; //2 more hets for next iteration -> subtract one rare and one common homozygote hom_r--; hom_c--; } for (int z = 0; z < tailProbs.length; z++){ tailProbs[z] /= sum; } double top = tailProbs[hets]; for (int i = hets+1; i <= rare; i++){ top += tailProbs[i]; } double otherSide = tailProbs[hets]; for (int i = hets-1; i >= 0; i--){ otherSide += tailProbs[i]; } if (top > 0.5 && otherSide > 0.5){ return 1.0; }else{ if (top < otherSide){ return top * 2; }else{ return otherSide * 2; } } }
|
private double hwCalculate(int obsAA, int obsAB, int obsBB) throws PedFileException{ //Calculates exact two-sided hardy-weinberg p-value. Parameters //are number of genotypes, number of rare alleles observed and //number of heterozygotes observed. // // (c) 2003 Jan Wigginton, Goncalo Abecasis int diplotypes = obsAA + obsAB + obsBB; int rare = (obsAA*2) + obsAB; int hets = obsAB; //make sure "rare" allele is really the rare allele if (rare > diplotypes){ rare = 2*diplotypes-rare; } //make sure numbers aren't screwy if (hets > rare){ throw new PedFileException("HW test: " + hets + "heterozygotes but only " + rare + "rare alleles."); } double[] tailProbs = new double[rare+1]; for (int z = 0; z < tailProbs.length; z++){ tailProbs[z] = 0; } //start at midpoint int mid = (int)((double)rare * (double)(2 * diplotypes - rare) / (double)(2 * diplotypes)); //check to ensure that midpoint and rare alleles have same parity if (((rare & 1) ^ (mid & 1)) != 0){ mid++; } int het = mid; int hom_r = (rare - mid) / 2; int hom_c = diplotypes - het - hom_r; //Calculate probability for each possible observed heterozygote //count up to a scaling constant, to avoid underflow and overflow tailProbs[mid] = 1.0; double sum = tailProbs[mid]; for (het = mid; het > 1; het -=2){ tailProbs[het-2] = (tailProbs[het] * het * (het-1.0))/(4.0*(hom_r + 1.0) * (hom_c + 1.0)); sum += tailProbs[het-2]; //2 fewer hets for next iteration -> add one rare and one common homozygote hom_r++; hom_c++; } het = mid; hom_r = (rare - mid) / 2; hom_c = diplotypes - het - hom_r; for (het = mid; het <= rare - 2; het += 2){ tailProbs[het+2] = (tailProbs[het] * 4.0 * hom_r * hom_c) / ((het+2.0)*(het+1.0)); sum += tailProbs[het+2]; //2 more hets for next iteration -> subtract one rare and one common homozygote hom_r--; hom_c--; } for (int z = 0; z < tailProbs.length; z++){ tailProbs[z] /= sum; } double top = tailProbs[hets]; for (int i = hets+1; i <= rare; i++){ top += tailProbs[i]; } double otherSide = tailProbs[hets]; for (int i = hets-1; i >= 0; i--){ otherSide += tailProbs[i]; } if (top > 0.5 && otherSide > 0.5){ return 1.0; }else{ if (top < otherSide){ return top * 2; }else{ return otherSide * 2; } } }
| 1,108,755
|
public Expression createExpression(final String text) throws Exception {/* org.apache.commons.jexl.Expression expr = org.apache.commons.jexl.ExpressionFactory.createExpression(text); if ( isSupportAntVariables() ) { expr.addPostResolver(new FlatResolver()); } return new JexlExpression( expr );*/ final Expression jexlExpression = new JexlExpression( org.apache.commons.jexl.ExpressionFactory.createExpression(text) ); if ( isSupportAntVariables() && isValidAntVariableName(text) ) { ExpressionSupport expr = new ExpressionSupport() { public Object evaluate(JellyContext context) { Object answer = jexlExpression.evaluate(context); if ( answer == null ) { answer = context.getVariable(text); } return answer; } }; return expr; } return jexlExpression; }
|
public Expression createExpression(final String text) throws Exception {/* org.apache.commons.jexl.Expression expr = org.apache.commons.jexl.ExpressionFactory.createExpression(text); if ( isSupportAntVariables() ) { expr.addPostResolver(new FlatResolver()); } return new JexlExpression( expr );*/ final Expression jexlExpression = new JexlExpression( org.apache.commons.jexl.ExpressionFactory.createExpression(text) ); if ( isSupportAntVariables() && isValidAntVariableName(text) ) { ExpressionSupport expr = new ExpressionSupport() { public Object evaluate(JellyContext context) { Object answer = jexlExpression.evaluate(context); if ( answer == null ) { answer = context.getVariable(text); } return answer; } }; return expr; } return jexlExpression; }
| 1,108,756
|
public static void fitColumnWidth(JTable table, int colIndex) { fitColumnWidth(table, colIndex, -1); }
|
public static void fitColumnWidth(JTable table, int colIndex) { fitColumnWidth(table, colIndex, -1); }
| 1,108,757
|
public static void fitColumnWidths(JTable table, int maxColumnWidth) { table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); for (int colIndex = 0; colIndex < table.getColumnCount(); colIndex++) { fitColumnWidth(table, colIndex, maxColumnWidth); } }
|
public static void fitColumnWidths(JTable table, int maxColumnWidth, int padding) { table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); for (int colIndex = 0; colIndex < table.getColumnCount(); colIndex++) { fitColumnWidth(table, colIndex, maxColumnWidth); } }
| 1,108,758
|
public static void fitColumnWidths(JTable table, int maxColumnWidth) { table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); for (int colIndex = 0; colIndex < table.getColumnCount(); colIndex++) { fitColumnWidth(table, colIndex, maxColumnWidth); } }
|
public static void fitColumnWidths(JTable table, int maxColumnWidth) { table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); for (int colIndex = 0; colIndex < table.getColumnCount(); colIndex++) { fitColumnWidth(table, colIndex, maxColumnWidth, padding); } }
| 1,108,759
|
public void run(JellyContext context, XMLOutput output) throws Exception { if ( firstRun ) { firstRun = false; // lets see if we have a dynamic tag tag = findDynamicTag(context, (StaticTag) tag); } 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); } runTag(output); }
|
public void run(JellyContext context, XMLOutput output) throws Exception { if ( firstRun ) { firstRun = false; // lets see if we have a dynamic tag tag = findDynamicTag(context, (StaticTag) tag); } try { tag.setContext(context); DynaTag dynaTag = (DynaTag) tag; 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); } 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); } runTag(output); }
| 1,108,760
|
public void run(JellyContext context, XMLOutput output) throws Exception { if ( firstRun ) { firstRun = false; // lets see if we have a dynamic tag tag = findDynamicTag(context, (StaticTag) tag); } 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); } runTag(output); }
|
public void run(JellyContext context, XMLOutput output) throws Exception { if ( firstRun ) { firstRun = false; // lets see if we have a dynamic tag tag = findDynamicTag(context, (StaticTag) tag); } 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); } runTag(output); }
| 1,108,761
|
public void run(JellyContext context, XMLOutput output) throws Exception { if ( firstRun ) { firstRun = false; // lets see if we have a dynamic tag tag = findDynamicTag(context, (StaticTag) tag); } 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); } runTag(output); }
|
public void run(JellyContext context, XMLOutput output) throws Exception { if ( firstRun ) { firstRun = false; // lets see if we have a dynamic tag tag = findDynamicTag(context, (StaticTag) tag); } 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); } catch (Exception e) { handleException(e); } }
| 1,108,762
|
public Tag createTag(String name) throws Exception { Object value = templates.get(name); if ( value instanceof Script ) { Script template = (Script) value; return new DynamicTag(template); } else if ( value instanceof DynaTag ) { return (DynaTag) value; } return null; }
|
public Tag createTag(String name) throws Exception { Object value = templates.get(name); if ( value instanceof Script ) { Script template = (Script) value; return new DynamicTag(template); } else if ( value instanceof DynaTag ) { return (DynaTag) value; } return null; }
| 1,108,763
|
public void run(JellyContext context, XMLOutput output) throws Exception { try { Tag tag = getTag(); if ( tag == null ) { return; } tag.setContext(context); if ( tag instanceof DynaTag ) { 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); } } else { // treat the tag as a bean DynaBean dynaBean = new ConvertingWrapDynaBean( tag ); 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); dynaBean.set(name, value); } } tag.doTag(output); } catch (JellyException e) { handleException(e); } catch (Exception e) { handleException(e); } finally { if ( ! context.isCacheTags() ) { clearTag(); } } }
|
public void run(JellyContext context, XMLOutput output) throws Exception { try { Tag tag = getTag(); if ( tag == null ) { return; } tag.setContext(context); if ( tag instanceof DynaTag ) { 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); } } else { // treat the tag as a bean DynaBean dynaBean = new ConvertingWrapDynaBean( tag ); 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); dynaBean.set(name, value); } } tag.doTag(output); } catch (JellyException e) { handleException(e); } catch (Exception e) { handleException(e); } finally { if ( ! context.isCacheTags() ) { clearTag(); } } }
| 1,108,764
|
public void drop(DropTargetDropEvent dtde) { Transferable t = dtde.getTransferable(); PlayPen c = (PlayPen) dtde.getDropTargetContext().getComponent(); DataFlavor importFlavor = bestImportFlavor(c, t.getTransferDataFlavors()); if (importFlavor == null) { dtde.rejectDrop(); } else { try { Object someData = t.getTransferData(importFlavor); logger.debug("MyJTreeTransferHandler.importData: got object of type "+someData.getClass().getName()); if (someData instanceof SQLTable) { dtde.acceptDrop(DnDConstants.ACTION_COPY); c.addTable((SQLTable) someData, dtde.getLocation()); dtde.dropComplete(true); return; } else if (someData instanceof SQLSchema) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLSchema sourceSchema = (SQLSchema) someData; c.addSchema(sourceSchema, dtde.getLocation()); dtde.dropComplete(true); return; } else if (someData instanceof SQLCatalog) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLCatalog sourceCatalog = (SQLCatalog) someData; Iterator cit = sourceCatalog.getChildren().iterator(); if (sourceCatalog.isSchemaContainer()) { while (cit.hasNext()) { SQLSchema sourceSchema = (SQLSchema) cit.next(); c.addSchema(sourceSchema, dtde.getLocation()); } } else { while (cit.hasNext()) { SQLTable sourceTable = (SQLTable) cit.next(); c.addTable(sourceTable, dtde.getLocation()); } } dtde.dropComplete(true); return; } else if (someData instanceof SQLColumn) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLColumn column = (SQLColumn) someData; JLabel colName = new JLabel(column.getColumnName()); colName.setSize(colName.getPreferredSize()); c.add(colName, dtde.getLocation()); logger.debug("Added "+column.getColumnName()+" to playpen (temporary, only for testing)"); colName.revalidate(); dtde.dropComplete(true); return; } else if (someData instanceof SQLObject[]) { // needs work (should use addSchema()) dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLObject[] objects = (SQLObject[]) someData; for (int i = 0; i < objects.length; i++) { if (objects[i] instanceof SQLTable) { TablePane tp = new TablePane((SQLTable) objects[i]); c.add(tp, dtde.getLocation()); tp.revalidate(); } } dtde.dropComplete(true); return; } else { dtde.rejectDrop(); } } catch (UnsupportedFlavorException ufe) { ufe.printStackTrace(); dtde.rejectDrop(); } catch (IOException ioe) { ioe.printStackTrace(); dtde.rejectDrop(); } catch (InvalidDnDOperationException ex) { ex.printStackTrace(); dtde.rejectDrop(); } catch (ArchitectException ex) { ex.printStackTrace(); dtde.rejectDrop(); } } }
|
public void drop(DropTargetDropEvent dtde) { Transferable t = dtde.getTransferable(); PlayPen c = (PlayPen) dtde.getDropTargetContext().getComponent(); DataFlavor importFlavor = bestImportFlavor(c, t.getTransferDataFlavors()); if (importFlavor == null) { dtde.rejectDrop(); } else { try { Object someData = t.getTransferData(importFlavor); logger.debug("MyJTreeTransferHandler.importData: got object of type "+someData.getClass().getName()); if (someData instanceof SQLTable) { dtde.acceptDrop(DnDConstants.ACTION_COPY); c.addTable((SQLTable) someData, dtde.getLocation()); dtde.dropComplete(true); return; } else if (someData instanceof SQLSchema) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLSchema sourceSchema = (SQLSchema) someData; c.addSchema(sourceSchema, dtde.getLocation()); dtde.dropComplete(true); return; } else if (someData instanceof SQLCatalog) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLCatalog sourceCatalog = (SQLCatalog) someData; Iterator cit = sourceCatalog.getChildren().iterator(); if (sourceCatalog.isSchemaContainer()) { while (cit.hasNext()) { SQLSchema sourceSchema = (SQLSchema) cit.next(); c.addSchema(sourceSchema, dtde.getLocation()); } } else { while (cit.hasNext()) { SQLTable sourceTable = (SQLTable) cit.next(); c.addTable(sourceTable, dtde.getLocation()); } } dtde.dropComplete(true); return; } else if (someData instanceof SQLColumn) { dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLColumn column = (SQLColumn) someData; JLabel colName = new JLabel(column.getColumnName()); colName.setSize(colName.getPreferredSize()); c.add(colName, dtde.getLocation()); logger.debug("Added "+column.getColumnName()+" to playpen (temporary, only for testing)"); colName.revalidate(); dtde.dropComplete(true); return; } else if (someData instanceof SQLObject[]) { // needs work (should use addSchema()) dtde.acceptDrop(DnDConstants.ACTION_COPY); SQLObject[] objects = (SQLObject[]) someData; for (int i = 0; i < objects.length; i++) { if (objects[i] instanceof SQLTable) { TablePane tp = new TablePane((SQLTable) objects[i]); c.add(tp, dtde.getLocation()); tp.revalidate(); } } dtde.dropComplete(true); return; } else { dtde.rejectDrop(); } } catch (UnsupportedFlavorException ufe) { ufe.printStackTrace(); dtde.rejectDrop(); } catch (IOException ioe) { ioe.printStackTrace(); dtde.rejectDrop(); } catch (InvalidDnDOperationException ex) { ex.printStackTrace(); dtde.rejectDrop(); } catch (ArchitectException ex) { ex.printStackTrace(); dtde.rejectDrop(); } } }
| 1,108,765
|
public void setContext(JellyContext context) { this.context = context; }
|
public void setContext(JellyContext context) throws Exception { this.context = context; }
| 1,108,766
|
public TDTPanel(PedFile pf) throws PedFileException{ if (Options.getAssocTest() == 1){ result = TDT.calcTrioTDT(pf); }else{ result = TDT.calcCCTDT(pf); } tableColumnNames.add("#"); tableColumnNames.add("Name"); if (Options.getAssocTest() == 1){ tableColumnNames.add("Overtransmitted"); tableColumnNames.add("T:U"); }else{ tableColumnNames.add("Major Alleles"); tableColumnNames.add("Case, Control Ratios"); } tableColumnNames.add("Chi Squared"); tableColumnNames.add("p value"); refreshTable(); }
|
public TDTPanel(PedFile pf) throws PedFileException{ if (Options.getAssocTest() == ASSOC_TRIO){ result = TDT.calcTrioTDT(pf); }else{ result = TDT.calcCCTDT(pf); } tableColumnNames.add("#"); tableColumnNames.add("Name"); if (Options.getAssocTest() == ASSOC_TRIO){ tableColumnNames.add("Overtransmitted"); tableColumnNames.add("T:U"); }else{ tableColumnNames.add("Major Alleles"); tableColumnNames.add("Case, Control Ratios"); } tableColumnNames.add("Chi Squared"); tableColumnNames.add("p value"); refreshTable(); }
| 1,108,767
|
public void refreshTable(){ this.removeAll(); Vector tableData = new Vector(); int numRes = Chromosome.getSize(); for (int i = 0; i < numRes; i++){ Vector tempVect = new Vector(); TDTResult currentResult = (TDTResult)result.get(Chromosome.realIndex[i]); tempVect.add(new Integer(Chromosome.realIndex[i]+1)); tempVect.add(currentResult.getName()); tempVect.add(currentResult.getOverTransmittedAllele(Options.getAssocTest())); tempVect.add(currentResult.getTURatio(Options.getAssocTest())); tempVect.add(new Double(currentResult.getChiSq(Options.getAssocTest()))); tempVect.add(currentResult.getPValue()); tableData.add(tempVect.clone()); } TDTTableModel tm = new TDTTableModel(tableColumnNames, tableData); table = new JTable(tm); table.getColumnModel().getColumn(0).setPreferredWidth(50); table.getColumnModel().getColumn(1).setPreferredWidth(100); if (Options.getAssocTest() != 1){ table.getColumnModel().getColumn(3).setPreferredWidth(160); } table.getColumnModel().getColumn(2).setPreferredWidth(100); JScrollPane tableScroller = new JScrollPane(table); add(tableScroller); }
|
public void refreshTable(){ this.removeAll(); Vector tableData = new Vector(); int numRes = Chromosome.getSize(); for (int i = 0; i < numRes; i++){ Vector tempVect = new Vector(); TDTResult currentResult = (TDTResult)result.get(Chromosome.realIndex[i]); tempVect.add(new Integer(Chromosome.realIndex[i]+1)); tempVect.add(currentResult.getName()); tempVect.add(currentResult.getOverTransmittedAllele(Options.getAssocTest())); tempVect.add(currentResult.getTURatio(Options.getAssocTest())); tempVect.add(new Double(currentResult.getChiSq(Options.getAssocTest()))); tempVect.add(currentResult.getPValue()); tableData.add(tempVect.clone()); } TDTTableModel tm = new TDTTableModel(tableColumnNames, tableData); table = new JTable(tm); table.getColumnModel().getColumn(0).setPreferredWidth(50); table.getColumnModel().getColumn(1).setPreferredWidth(100); if (Options.getAssocTest() != ASSOC_TRIO){ table.getColumnModel().getColumn(3).setPreferredWidth(160); } table.getColumnModel().getColumn(2).setPreferredWidth(100); JScrollPane tableScroller = new JScrollPane(table); add(tableScroller); }
| 1,108,768
|
public Result analyze(Filter<S> filter, List<OrderedProperty<S>> orderings) { if (!filter.isBound()) { // Strictly speaking, this is not required, but it detects the // mistake of not properly calling initialFilterValues. throw new IllegalArgumentException("Filter must be bound"); } List<IndexedQueryAnalyzer<S>.Result> subResults = splitIntoSubResults(filter, orderings); if (subResults.size() < 1) { // Total ordering not required. return new Result(subResults); } boolean canMutateOrderings = false; // If any orderings have an unspecified direction, switch to ASCENDING // or DESCENDING, depending on which is more popular. Then build new // sub-results. for (int pos = 0; pos < orderings.size(); pos++) { OrderedProperty<S> ordering = orderings.get(pos); if (ordering.getDirection() != Direction.UNSPECIFIED) { continue; } // Find out which direction is most popular for this property. Tally tally = new Tally(ordering.getChainedProperty()); for (IndexedQueryAnalyzer<S>.Result result : subResults) { tally.increment(findHandledDirection(result, ordering)); } if (!canMutateOrderings) { orderings = new ArrayList<OrderedProperty<S>>(orderings); canMutateOrderings = true; } orderings.set(pos, ordering.direction(tally.getBestDirection())); // Re-calc with specified direction. Only do one property at a time // since one simple change might alter the query plan. subResults = splitIntoSubResults(filter, orderings); if (subResults.size() < 1) { // Total ordering no longer required. return new Result(subResults); } } // Gather all the keys available. As ordering properties touch key // properties, they are removed from all key sets. When a key set size // reaches zero, total ordering has been achieved. List<Set<ChainedProperty<S>>> keys = getKeys(); // Check if current ordering is total. for (OrderedProperty<S> ordering : orderings) { ChainedProperty<S> property = ordering.getChainedProperty(); if (pruneKeys(keys, property)) { // Found a key which is fully covered, indicating total ordering. return new Result(subResults); } } // Create a super key which contains all the properties required for // total ordering. The goal here is to append these properties to the // ordering in a fashion that takes advantage of each index's natural // ordering. This in turn should cause any sort operation to operate // over smaller groups. Smaller groups means smaller sort buffers. // Smaller sort buffers makes a merge sort happy. // Super key could be stored simply in a set, but a map makes it // convenient for tracking tallies. Map<ChainedProperty<S>, Tally> superKey = new LinkedHashMap<ChainedProperty<S>, Tally>(); for (Set<ChainedProperty<S>> key : keys) { for (ChainedProperty<S> property : key) { superKey.put(property, new Tally(property)); } } // Prepare to augment orderings to ensure a total ordering. if (!canMutateOrderings) { orderings = new ArrayList<OrderedProperty<S>>(orderings); canMutateOrderings = true; } // Keep looping until total ordering achieved. while (true) { // For each ordering score, find the next free property. If // property is in the super key increment a tally associated with // property direction. Choose the property with the best tally and // augment the orderings with it and create new sub-results. // Remove the property from the super key and the key set. If any // key is now fully covered, a total ordering has been achieved. for (IndexedQueryAnalyzer<S>.Result result : subResults) { OrderingScore<S> score = result.getCompositeScore().getOrderingScore(); List<OrderedProperty<S>> free = score.getFreeOrderings(); if (free.size() > 0) { OrderedProperty<S> prop = free.get(0); ChainedProperty<S> chainedProp = prop.getChainedProperty(); Tally tally = superKey.get(chainedProp); if (tally != null) { tally.increment(prop.getDirection()); } } } Tally best = bestTally(superKey.values()); ChainedProperty<S> bestProperty = best.getProperty(); // Now augment the orderings and create new sub-results. orderings.add(OrderedProperty.get(bestProperty, best.getBestDirection())); subResults = splitIntoSubResults(filter, orderings); if (subResults.size() < 1) { // Total ordering no longer required. break; } // Remove property from super key and key set... superKey.remove(bestProperty); if (superKey.size() == 0) { break; } if (pruneKeys(keys, bestProperty)) { break; } // Clear the tallies for the next run. for (Tally tally : superKey.values()) { tally.clear(); } } return new Result(subResults); }
|
public Result analyze(Filter<S> filter, List<OrderedProperty<S>> orderings) { if (!filter.isBound()) { // Strictly speaking, this is not required, but it detects the // mistake of not properly calling initialFilterValues. throw new IllegalArgumentException("Filter must be bound"); } List<IndexedQueryAnalyzer<S>.Result> subResults = splitIntoSubResults(filter, orderings); if (subResults.size() <= 1) { // Total ordering not required. return new Result(subResults); } boolean canMutateOrderings = false; // If any orderings have an unspecified direction, switch to ASCENDING // or DESCENDING, depending on which is more popular. Then build new // sub-results. for (int pos = 0; pos < orderings.size(); pos++) { OrderedProperty<S> ordering = orderings.get(pos); if (ordering.getDirection() != Direction.UNSPECIFIED) { continue; } // Find out which direction is most popular for this property. Tally tally = new Tally(ordering.getChainedProperty()); for (IndexedQueryAnalyzer<S>.Result result : subResults) { tally.increment(findHandledDirection(result, ordering)); } if (!canMutateOrderings) { orderings = new ArrayList<OrderedProperty<S>>(orderings); canMutateOrderings = true; } orderings.set(pos, ordering.direction(tally.getBestDirection())); // Re-calc with specified direction. Only do one property at a time // since one simple change might alter the query plan. subResults = splitIntoSubResults(filter, orderings); if (subResults.size() <= 1) { // Total ordering no longer required. return new Result(subResults); } } // Gather all the keys available. As ordering properties touch key // properties, they are removed from all key sets. When a key set size // reaches zero, total ordering has been achieved. List<Set<ChainedProperty<S>>> keys = getKeys(); // Check if current ordering is total. for (OrderedProperty<S> ordering : orderings) { ChainedProperty<S> property = ordering.getChainedProperty(); if (pruneKeys(keys, property)) { // Found a key which is fully covered, indicating total ordering. return new Result(subResults); } } // Create a super key which contains all the properties required for // total ordering. The goal here is to append these properties to the // ordering in a fashion that takes advantage of each index's natural // ordering. This in turn should cause any sort operation to operate // over smaller groups. Smaller groups means smaller sort buffers. // Smaller sort buffers makes a merge sort happy. // Super key could be stored simply in a set, but a map makes it // convenient for tracking tallies. Map<ChainedProperty<S>, Tally> superKey = new LinkedHashMap<ChainedProperty<S>, Tally>(); for (Set<ChainedProperty<S>> key : keys) { for (ChainedProperty<S> property : key) { superKey.put(property, new Tally(property)); } } // Prepare to augment orderings to ensure a total ordering. if (!canMutateOrderings) { orderings = new ArrayList<OrderedProperty<S>>(orderings); canMutateOrderings = true; } // Keep looping until total ordering achieved. while (true) { // For each ordering score, find the next free property. If // property is in the super key increment a tally associated with // property direction. Choose the property with the best tally and // augment the orderings with it and create new sub-results. // Remove the property from the super key and the key set. If any // key is now fully covered, a total ordering has been achieved. for (IndexedQueryAnalyzer<S>.Result result : subResults) { OrderingScore<S> score = result.getCompositeScore().getOrderingScore(); List<OrderedProperty<S>> free = score.getFreeOrderings(); if (free.size() > 0) { OrderedProperty<S> prop = free.get(0); ChainedProperty<S> chainedProp = prop.getChainedProperty(); Tally tally = superKey.get(chainedProp); if (tally != null) { tally.increment(prop.getDirection()); } } } Tally best = bestTally(superKey.values()); ChainedProperty<S> bestProperty = best.getProperty(); // Now augment the orderings and create new sub-results. orderings.add(OrderedProperty.get(bestProperty, best.getBestDirection())); subResults = splitIntoSubResults(filter, orderings); if (subResults.size() <= 1) { // Total ordering no longer required. break; } // Remove property from super key and key set... superKey.remove(bestProperty); if (superKey.size() == 0) { break; } if (pruneKeys(keys, bestProperty)) { break; } // Clear the tallies for the next run. for (Tally tally : superKey.values()) { tally.clear(); } } return new Result(subResults); }
| 1,108,769
|
public void actionPerformed(ActionEvent evt) { logger.debug("delete action detected!"); logger.debug("ACTION COMMAND: " + evt.getActionCommand()); if (evt.getActionCommand().equals(ArchitectSwingConstants.ACTION_COMMAND_SRC_PLAYPEN)) { logger.debug("delete action came from playpen"); List items = pp.getSelectedItems(); if (items.size() < 1) { JOptionPane.showMessageDialog(pp, "No items to delete!"); } if (items.size() > 1) { // count how many relationships and tables there are int tCount = pp.getSelectedTables().size(); int rCount = pp.getSelectedRelationShips().size(); int decision = JOptionPane.showConfirmDialog(pp, "Are you sure you want to delete these " +tCount+" tables and "+rCount+" relationships?", "Multiple Delete", JOptionPane.YES_NO_OPTION); if (decision == JOptionPane.NO_OPTION) { return; } } else { // single selection, so we might be deleting columns boolean deletingColumns = false; Selectable item = (Selectable) items.get(0); if (item instanceof TablePane) { // make a list of columns to delete TablePane tp = (TablePane) item; List<SQLColumn> selectedColumns = null; try { selectedColumns = tp.getSelectedColumns(); if (selectedColumns.size() > 0) { // don't fall through into Table/Relationship delete logic deletingColumns = true; } } catch (ArchitectException ae) { JOptionPane.showMessageDialog(pp, ae.getMessage()); return; } try { pp.startCompoundEdit("Starting multi-select"); // now, delete the columns Iterator it2 = selectedColumns.iterator(); while (it2.hasNext()) { SQLColumn sc = (SQLColumn) it2.next(); try { tp.getModel().removeColumn(sc); } catch (LockedColumnException ex) { int decision = JOptionPane.showConfirmDialog(pp, "Could not delete the column " + sc.getName() + " because it is part of\n" + "the relationship \""+ex.getLockingRelationship()+"\".\n\n" + "Continue deleting remaining selected columns?", "Column is Locked", JOptionPane.YES_NO_OPTION); if (decision == JOptionPane.NO_OPTION) { return; } } catch (ArchitectException e) { logger.error("Unexpected exception encountered when attempting to delete column '"+ sc+"' of table '"+sc.getParentTable()+"'"); ASUtils.showExceptionDialog(pp, "Encountered a Problem Deleting the column", e); } } } finally { pp.endCompoundEdit("Ending multi-select"); } } if (deletingColumns) { // we tried to delete 1 or more columns, so don't try to delete the table return; } } pp.startCompoundEdit("Starting multi-select"); try { // items.size() > 0, user has OK'ed the delete Iterator it = items.iterator(); while (it.hasNext()) { Selectable item = (Selectable) it.next(); logger.debug("next item for delete is: " + item.getClass().getName()); if (item instanceof TablePane) { TablePane tp = (TablePane) item; tp.setSelected(false); pp.getDatabase().removeChild(tp.getModel()); if (logger.isDebugEnabled()) { logger.debug("removing element from tableNames set: " + tp.getModel().getName()); logger.debug("before delete: " + pp.getTablePanes().toArray()); } pp.getTablePanes().remove(tp.getModel().getName().toLowerCase()); if (logger.isDebugEnabled()) { logger.debug("after delete: " + pp.getTablePanes().toArray()); } } else if (item instanceof Relationship) { Relationship r = (Relationship) item; logger.debug("trying to delete relationship " + r); r.setSelected(false); SQLRelationship sr = r.getModel(); sr.getPkTable().removeExportedKey(sr); } else { JOptionPane.showMessageDialog((JComponent) item, "The selected item type is not recognised"); } } } finally { pp.endCompoundEdit("Ending multi-select"); } } else if (evt.getActionCommand().equals(ArchitectSwingConstants.ACTION_COMMAND_SRC_DBTREE)) { logger.debug("delete action came from dbtree"); TreePath [] selections = dbt.getSelectionPaths(); if (selections.length > 1) { int decision = JOptionPane.showConfirmDialog(dbt, "Are you sure you want to delete the " +selections.length+" selected items?", "Multiple Delete", JOptionPane.YES_NO_OPTION); if (decision == JOptionPane.NO_OPTION) { return; } } pp.startCompoundEdit("Starting multi-select"); try { // FIXME: parts of the following code look like they were cut'n'pasted from above... PURE EVIL! Iterator it = Arrays.asList(selections).iterator(); while (it.hasNext()) { TreePath tp = (TreePath) it.next(); SQLObject so = (SQLObject) tp.getLastPathComponent(); if (so instanceof SQLTable) { SQLTable st = (SQLTable) so; pp.getDatabase().removeChild(st); pp.getTablePanes().remove(st.getName().toLowerCase()); } else if (so instanceof SQLColumn) { SQLColumn sc = (SQLColumn)so; SQLTable st = sc.getParentTable(); try { st.removeColumn(sc); } catch (LockedColumnException ex) { int decision = JOptionPane.showConfirmDialog(dbt, "Could not delete the column " + sc.getName() + " because it is part of a relationship key. Continue" + " deleting of other selected items?", "Column is Locked", JOptionPane.YES_NO_OPTION); if (decision == JOptionPane.NO_OPTION) { return; } } catch (ArchitectException e) { logger.error("Unexpected exception encountered when attempting to delete column '"+ sc+"' of table '"+sc.getParentTable()+"'"); ASUtils.showExceptionDialog(pp, "Encountered a Problem Deleting the column", e); } } else if (so instanceof SQLRelationship) { SQLRelationship sr = (SQLRelationship) so; sr.getPkTable().removeExportedKey(sr); sr.getFkTable().removeImportedKey(sr); } else { JOptionPane.showMessageDialog(dbt, "The selected SQLObject type is not recognised: " + so.getClass().getName()); } } } finally { pp.endCompoundEdit("Ending multi-select"); } } else { logger.debug("delete action came from unknown source, so we do nothing."); // unknown action command source, do nothing } }
|
public void actionPerformed(ActionEvent evt) { logger.debug("delete action detected!"); logger.debug("ACTION COMMAND: " + evt.getActionCommand()); if (evt.getActionCommand().equals(ArchitectSwingConstants.ACTION_COMMAND_SRC_PLAYPEN)) { logger.debug("delete action came from playpen"); List items = pp.getSelectedItems(); if (items.size() < 1) { JOptionPane.showMessageDialog(pp, "No items to delete!"); } if (items.size() > 1) { // count how many relationships and tables there are int tCount = pp.getSelectedTables().size(); int rCount = pp.getSelectedRelationShips().size(); int decision = JOptionPane.showConfirmDialog(pp, "Are you sure you want to delete these " +tCount+" tables and "+rCount+" relationships?", "Multiple Delete", JOptionPane.YES_NO_OPTION); if (decision != JOptionPane.YES_OPTION ) { return; } } else { // single selection, so we might be deleting columns boolean deletingColumns = false; Selectable item = (Selectable) items.get(0); if (item instanceof TablePane) { // make a list of columns to delete TablePane tp = (TablePane) item; List<SQLColumn> selectedColumns = null; try { selectedColumns = tp.getSelectedColumns(); if (selectedColumns.size() > 0) { // don't fall through into Table/Relationship delete logic deletingColumns = true; } } catch (ArchitectException ae) { JOptionPane.showMessageDialog(pp, ae.getMessage()); return; } try { pp.startCompoundEdit("Starting multi-select"); // now, delete the columns Iterator it2 = selectedColumns.iterator(); while (it2.hasNext()) { SQLColumn sc = (SQLColumn) it2.next(); try { tp.getModel().removeColumn(sc); } catch (LockedColumnException ex) { int decision = JOptionPane.showConfirmDialog(pp, "Could not delete the column " + sc.getName() + " because it is part of\n" + "the relationship \""+ex.getLockingRelationship()+"\".\n\n" + "Continue deleting remaining selected columns?", "Column is Locked", JOptionPane.YES_NO_OPTION); if (decision != JOptionPane.YES_OPTION ) { return; } } catch (ArchitectException e) { logger.error("Unexpected exception encountered when attempting to delete column '"+ sc+"' of table '"+sc.getParentTable()+"'"); ASUtils.showExceptionDialog(pp, "Encountered a Problem Deleting the column", e); } } } finally { pp.endCompoundEdit("Ending multi-select"); } } if (deletingColumns) { // we tried to delete 1 or more columns, so don't try to delete the table return; } } pp.startCompoundEdit("Starting multi-select"); try { // items.size() > 0, user has OK'ed the delete Iterator it = items.iterator(); while (it.hasNext()) { Selectable item = (Selectable) it.next(); logger.debug("next item for delete is: " + item.getClass().getName()); if (item instanceof TablePane) { TablePane tp = (TablePane) item; tp.setSelected(false); pp.getDatabase().removeChild(tp.getModel()); if (logger.isDebugEnabled()) { logger.debug("removing element from tableNames set: " + tp.getModel().getName()); logger.debug("before delete: " + pp.getTablePanes().toArray()); } pp.getTablePanes().remove(tp.getModel().getName().toLowerCase()); if (logger.isDebugEnabled()) { logger.debug("after delete: " + pp.getTablePanes().toArray()); } } else if (item instanceof Relationship) { Relationship r = (Relationship) item; logger.debug("trying to delete relationship " + r); r.setSelected(false); SQLRelationship sr = r.getModel(); sr.getPkTable().removeExportedKey(sr); } else { JOptionPane.showMessageDialog((JComponent) item, "The selected item type is not recognised"); } } } finally { pp.endCompoundEdit("Ending multi-select"); } } else if (evt.getActionCommand().equals(ArchitectSwingConstants.ACTION_COMMAND_SRC_DBTREE)) { logger.debug("delete action came from dbtree"); TreePath [] selections = dbt.getSelectionPaths(); if (selections.length > 1) { int decision = JOptionPane.showConfirmDialog(dbt, "Are you sure you want to delete the " +selections.length+" selected items?", "Multiple Delete", JOptionPane.YES_NO_OPTION); if (decision != JOptionPane.YES_OPTION ) { return; } } pp.startCompoundEdit("Starting multi-select"); try { // FIXME: parts of the following code look like they were cut'n'pasted from above... PURE EVIL! Iterator it = Arrays.asList(selections).iterator(); while (it.hasNext()) { TreePath tp = (TreePath) it.next(); SQLObject so = (SQLObject) tp.getLastPathComponent(); if (so instanceof SQLTable) { SQLTable st = (SQLTable) so; pp.getDatabase().removeChild(st); pp.getTablePanes().remove(st.getName().toLowerCase()); } else if (so instanceof SQLColumn) { SQLColumn sc = (SQLColumn)so; SQLTable st = sc.getParentTable(); try { st.removeColumn(sc); } catch (LockedColumnException ex) { int decision = JOptionPane.showConfirmDialog(dbt, "Could not delete the column " + sc.getName() + " because it is part of a relationship key. Continue" + " deleting of other selected items?", "Column is Locked", JOptionPane.YES_NO_OPTION); if (decision != JOptionPane.YES_OPTION ) { return; } } catch (ArchitectException e) { logger.error("Unexpected exception encountered when attempting to delete column '"+ sc+"' of table '"+sc.getParentTable()+"'"); ASUtils.showExceptionDialog(pp, "Encountered a Problem Deleting the column", e); } } else if (so instanceof SQLRelationship) { SQLRelationship sr = (SQLRelationship) so; sr.getPkTable().removeExportedKey(sr); sr.getFkTable().removeImportedKey(sr); } else { JOptionPane.showMessageDialog(dbt, "The selected SQLObject type is not recognised: " + so.getClass().getName()); } } } finally { pp.endCompoundEdit("Ending multi-select"); } } else { logger.debug("delete action came from unknown source, so we do nothing."); // unknown action command source, do nothing } }
| 1,108,770
|
protected void registerWidgetTag(String name, Class widgetClass) { registerWidgetTag(name, widgetClass, SWT.DEFAULT); }
|
protected void registerWidgetTag(String name, Class widgetClass) { registerWidgetTag(name, widgetClass, SWT.NULL); }
| 1,108,771
|
public ActionForward execute(WebContext context, ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception { Subject subject = context.getSubject(); final String userName = context.getUser().getName(); if(subject != null){ LoginContext loginContext = new LoginContext(AuthConstants.AUTH_CONFIG_INDEX, subject, new LoginCallbackHandler()); loginContext.logout(); context.removeSubject(); } UserActivityLogger.getInstance().logActivity(userName, userName+" logged out successfully"); return mapping.findForward(Forwards.SUCCESS); }
|
public ActionForward execute(WebContext context, ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception { Subject subject = context.getSubject(); if(subject != null){ LoginContext loginContext = new LoginContext(AuthConstants.AUTH_CONFIG_INDEX, subject, new LoginCallbackHandler()); loginContext.logout(); context.removeSubject(); } UserActivityLogger.getInstance().logActivity(userName, userName+" logged out successfully"); return mapping.findForward(Forwards.SUCCESS); }
| 1,108,772
|
public ActionForward execute(WebContext context, ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception { Subject subject = context.getSubject(); final String userName = context.getUser().getName(); if(subject != null){ LoginContext loginContext = new LoginContext(AuthConstants.AUTH_CONFIG_INDEX, subject, new LoginCallbackHandler()); loginContext.logout(); context.removeSubject(); } UserActivityLogger.getInstance().logActivity(userName, userName+" logged out successfully"); return mapping.findForward(Forwards.SUCCESS); }
|
public ActionForward execute(WebContext context, ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception { Subject subject = context.getSubject(); final String userName = context.getUser().getName(); if(subject != null){ LoginContext loginContext = new LoginContext(AuthConstants.AUTH_CONFIG_INDEX, subject, new LoginCallbackHandler()); loginContext.logout(); context.removeSubject(); } UserActivityLogger.getInstance().logActivity(userName, userName+" logged out successfully"); return mapping.findForward(Forwards.SUCCESS); }
| 1,108,773
|
private void argHandler(String[] args){ argHandlerMessages = new Vector(); int maxDistance = -1; //this means that user didn't specify any output type if it doesn't get changed below blockOutputType = -1; double hapThresh = -1; double minimumMAF=-1; double spacingThresh = -1; double minimumGenoPercent = -1; double hwCutoff = -1; double missingCutoff = -1; int maxMendel = -1; boolean assocTDT = false; boolean assocCC = false; permutationCount = 0; tagging = Tagger.NONE; maxNumTags = Tagger.DEFAULT_MAXNUMTAGS; findTags = true; double cutHighCI = -1; double cutLowCI = -1; double mafThresh = -1; double recHighCI = -1; double informFrac = -1; double fourGameteCutoff = -1; double spineDP = -1; for(int i =0; i < args.length; i++) { if(args[i].equalsIgnoreCase("-help") || args[i].equalsIgnoreCase("-h")) { System.out.println(HELP_OUTPUT); System.exit(0); } else if(args[i].equalsIgnoreCase("-n") || args[i].equalsIgnoreCase("-nogui")) { nogui = true; } else if(args[i].equalsIgnoreCase("-p") || args[i].equalsIgnoreCase("-pedfile")) { i++; if( i>=args.length || (args[i].charAt(0) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(pedFileName != null){ argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last pedfile listed will be used"); } pedFileName = args[i]; } } else if (args[i].equalsIgnoreCase("-pcloadletter")){ die("PC LOADLETTER?! What the fuck does that mean?!"); } else if (args[i].equalsIgnoreCase("-skipcheck") || args[i].equalsIgnoreCase("--skipcheck")){ skipCheck = true; } else if (args[i].equalsIgnoreCase("-excludeMarkers")){ i++; if(i>=args.length || (args[i].charAt(0) == '-')){ die("-excludeMarkers requires a list of markers"); } else { StringTokenizer str = new StringTokenizer(args[i],","); try { StringBuffer sb = new StringBuffer(); if (!quietMode) sb.append("Excluding markers: "); while(str.hasMoreTokens()) { String token = str.nextToken(); if(token.indexOf("..") != -1) { int lastIndex = token.indexOf(".."); int rangeStart = Integer.parseInt(token.substring(0,lastIndex)); int rangeEnd = Integer.parseInt(token.substring(lastIndex+2,token.length())); for(int j=rangeStart;j<=rangeEnd;j++) { if (!quietMode) sb.append(j+" "); excludedMarkers.add(new Integer(j)); } } else { if (!quietMode) sb.append(token+" "); excludedMarkers.add(new Integer(token)); } } if (!quietMode) argHandlerMessages.add(sb.toString()); } catch(NumberFormatException nfe) { die("-excludeMarkers argument should be of the format: 1,3,5..8,12"); } } } else if(args[i].equalsIgnoreCase("-ha") || args[i].equalsIgnoreCase("-l") || args[i].equalsIgnoreCase("-haps")) { i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(hapsFileName != null){ argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last haps file listed will be used"); } hapsFileName = args[i]; } } else if(args[i].equalsIgnoreCase("-i") || args[i].equalsIgnoreCase("-info")) { i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(infoFileName != null){ argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last info file listed will be used"); } infoFileName = args[i]; } } else if (args[i].equalsIgnoreCase("-a") || args[i].equalsIgnoreCase("-hapmap")){ i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(hapmapFileName != null){ argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last hapmap file listed will be used"); } hapmapFileName = args[i]; } } else if (args[i].equalsIgnoreCase("-phasedhmpdata")){ i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(phasedhmpdataFileName != null){ argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last phased hapmap data file listed will be used"); } phasedhmpdataFileName = args[i]; } } else if (args[i].equalsIgnoreCase("-phasedhmpsample")){ i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(phasedhmpsampleFileName != null){ argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last phased hapmap sample file listed will be used"); } phasedhmpsampleFileName = args[i]; } } else if (args[i].equalsIgnoreCase("-phasedhmplegend")){ i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(phasedhmplegendFileName != null){ argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last phased hapmap legend file listed will be used"); } phasedhmplegendFileName = args[i]; } } else if (args[i].equalsIgnoreCase("-phasedhapmapdl")){ phasedhapmapDownload = true; } else if (args[i].equalsIgnoreCase("-plink")){ i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(plinkFileName != null){ argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last PLINK file listed will be used"); } plinkFileName = args[i]; } } else if (args[i].equalsIgnoreCase("-map")){ i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(plinkFileName != null){ argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last map file listed will be used"); } mapFileName = args[i]; } } else if(args[i].equalsIgnoreCase("-k") || args[i].equalsIgnoreCase("-blocks")) { i++; if (!(i>=args.length) && !((args[i].charAt(0)) == '-')){ blockFileName = args[i]; blockOutputType = BLOX_CUSTOM; }else{ die(args[i-1] + " requires a filename"); } } else if (args[i].equalsIgnoreCase("-png")){ outputPNG = true; } else if (args[i].equalsIgnoreCase("-smallpng") || args[i].equalsIgnoreCase("-compressedPNG")){ outputCompressedPNG = true; } else if (args[i].equalsIgnoreCase("-track")){ i++; if (!(i>=args.length) && !((args[i].charAt(0)) == '-')){ trackFileName = args[i]; }else{ die("-track requires a filename"); } } else if(args[i].equalsIgnoreCase("-o") || args[i].equalsIgnoreCase("-output") || args[i].equalsIgnoreCase("-blockoutput")) { i++; if(!(i>=args.length) && !((args[i].charAt(0)) == '-')){ if(blockOutputType != -1){ die("Only one block output type argument is allowed."); } if(args[i].equalsIgnoreCase("SFS") || args[i].equalsIgnoreCase("GAB")){ blockOutputType = BLOX_GABRIEL; } else if(args[i].equalsIgnoreCase("GAM")){ blockOutputType = BLOX_4GAM; } else if(args[i].equalsIgnoreCase("MJD") || args[i].equalsIgnoreCase("SPI")){ blockOutputType = BLOX_SPINE; } else if(args[i].equalsIgnoreCase("ALL")) { blockOutputType = BLOX_ALL; } } else { //defaults to SFS output blockOutputType = BLOX_GABRIEL; i--; } } else if(args[i].equalsIgnoreCase("-d") || args[i].equalsIgnoreCase("--dprime") || args[i].equalsIgnoreCase("-dprime")) { outputDprime = true; } else if (args[i].equalsIgnoreCase("-c") || args[i].equalsIgnoreCase("-check")){ outputCheck = true; } else if (args[i].equalsIgnoreCase("-indcheck")){ individualCheck = true; } else if (args[i].equalsIgnoreCase("-mendel")){ mendel = true; } else if (args[i].equalsIgnoreCase("-malehets")){ malehets = true; } else if(args[i].equalsIgnoreCase("-m") || args[i].equalsIgnoreCase("-maxdistance")) { i++; maxDistance = getIntegerArg(args,i); } else if(args[i].equalsIgnoreCase("-b") || args[i].equalsIgnoreCase("-batch")) { //batch mode i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(batchFileName != null){ argHandlerMessages.add("multiple " + args[i-1] + " arguments found. only last batch file listed will be used"); } batchFileName = args[i]; } } else if(args[i].equalsIgnoreCase("-hapthresh")) { i++; hapThresh = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-spacing")) { i++; spacingThresh = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-minMAF")) { i++; minimumMAF = getDoubleArg(args,i,0,0.5); } else if(args[i].equalsIgnoreCase("-minGeno") || args[i].equalsIgnoreCase("-minGenoPercent")) { i++; minimumGenoPercent = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-hwcutoff")) { i++; hwCutoff = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-maxMendel") ) { i++; maxMendel = getIntegerArg(args,i); } else if(args[i].equalsIgnoreCase("-missingcutoff")) { i++; missingCutoff = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-assoctdt")) { assocTDT = true; } else if(args[i].equalsIgnoreCase("-assoccc")) { assocCC = true; } else if(args[i].equalsIgnoreCase("-randomcc")){ assocCC = true; randomizeAffection = true; } else if(args[i].equalsIgnoreCase("-ldcolorscheme")) { i++; if(!(i>=args.length) && !((args[i].charAt(0)) == '-')){ if(args[i].equalsIgnoreCase("default")){ Options.setLDColorScheme(STD_SCHEME); } else if(args[i].equalsIgnoreCase("RSQ")){ Options.setLDColorScheme(RSQ_SCHEME); } else if(args[i].equalsIgnoreCase("DPALT") ){ Options.setLDColorScheme(WMF_SCHEME); } else if(args[i].equalsIgnoreCase("GAB")) { Options.setLDColorScheme(GAB_SCHEME); } else if(args[i].equalsIgnoreCase("GAM")) { Options.setLDColorScheme(GAM_SCHEME); } else if(args[i].equalsIgnoreCase("GOLD")) { Options.setLDColorScheme(GOLD_SCHEME); } } else { //defaults to STD color scheme Options.setLDColorScheme(STD_SCHEME); i--; } } else if(args[i].equalsIgnoreCase("-blockCutHighCI")) { i++; cutHighCI = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-blockCutLowCI")) { i++; cutLowCI = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-blockMafThresh")) { i++; mafThresh = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-blockRecHighCI")) { i++; recHighCI = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-blockInformFrac")) { i++; informFrac = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-block4GamCut")) { i++; fourGameteCutoff = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-blockSpineDP")) { i++; spineDP = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-permtests")) { i++; doPermutationTest = true; permutationCount = getIntegerArg(args,i); } else if(args[i].equalsIgnoreCase("-customassoc")) { i++; if (!(i>=args.length) && !((args[i].charAt(0)) == '-')){ customAssocTestsFileName = args[i]; }else{ die(args[i-1] + " requires a filename"); } } else if(args[i].equalsIgnoreCase("-aggressiveTagging")) { tagging = Tagger.AGGRESSIVE_TRIPLE; } else if (args[i].equalsIgnoreCase("-pairwiseTagging")){ tagging = Tagger.PAIRWISE_ONLY; } else if (args[i].equalsIgnoreCase("-printalltags")){ Options.setPrintAllTags(true); } else if(args[i].equalsIgnoreCase("-maxNumTags")){ i++; maxNumTags = getIntegerArg(args,i); } else if(args[i].equalsIgnoreCase("-tagrSqCutoff")) { i++; tagRSquaredCutOff = getDoubleArg(args,i,0,1); } else if (args[i].equalsIgnoreCase("-dontaddtags")){ findTags = false; } else if(args[i].equalsIgnoreCase("-tagLODCutoff")) { i++; Options.setTaggerLODCutoff(getDoubleArg(args,i,0,100000)); } else if(args[i].equalsIgnoreCase("-includeTags")) { i++; if(i>=args.length || args[i].charAt(0) == '-') { die(args[i-1] + " requires a list of marker names."); } StringTokenizer str = new StringTokenizer(args[i],","); forceIncludeTags = new Vector(); while(str.hasMoreTokens()) { forceIncludeTags.add(str.nextToken()); } } else if (args[i].equalsIgnoreCase("-includeTagsFile")) { i++; if(!(i>=args.length) && !(args[i].charAt(0) == '-')) { forceIncludeFileName =args[i]; }else { die(args[i-1] + " requires a filename"); } } else if(args[i].equalsIgnoreCase("-excludeTags")) { i++; if(i>=args.length || args[i].charAt(0) == '-') { die("-excludeTags requires a list of marker names."); } StringTokenizer str = new StringTokenizer(args[i],","); forceExcludeTags = new Vector(); while(str.hasMoreTokens()) { forceExcludeTags.add(str.nextToken()); } } else if (args[i].equalsIgnoreCase("-excludeTagsFile")) { i++; if(!(i>=args.length) && !(args[i].charAt(0) == '-')) { forceExcludeFileName =args[i]; }else { die(args[i-1] + " requires a filename"); } } else if (args[i].equalsIgnoreCase("-captureAlleles")){ i++; if(!(i>=args.length) && !(args[i].charAt(0) == '-')) { captureAllelesFileName =args[i]; }else { die(args[i-1] + " requires a filename"); } } else if (args[i].equalsIgnoreCase("-designScores")){ i++; if(!(i>=args.length) && !(args[i].charAt(0) == '-')) { designScoresFileName =args[i]; }else { die(args[i-1] + " requires a filename"); } } else if (args[i].equalsIgnoreCase("-mintagdistance")){ i++; minTagDistance = args[i]; } else if(args[i].equalsIgnoreCase("-chromosome") || args[i].equalsIgnoreCase("-chr")) { i++; if(!(i>=args.length) && !(args[i].charAt(0) == '-')) { chromosomeArg =args[i]; }else { die(args[i-1] + " requires a chromosome name"); } if(!(chromosomeArg.equalsIgnoreCase("x"))){ try{ if (Integer.parseInt(chromosomeArg) > 22){ die("-chromosome requires a chromsome name of 1-22 or X"); } }catch(NumberFormatException nfe){ die("-chromosome requires a chromsome name of 1-22 or X"); } } } else if(args[i].equalsIgnoreCase("-population")){ i++; if(!(i>=args.length) && !(args[i].charAt(0)== '-')) { populationArg = args[i]; }else { die(args[i-1] + "requires a population name"); } } else if(args[i].equalsIgnoreCase("-startpos")){ i++; startPos = args[i]; } else if(args[i].equalsIgnoreCase("-endPos")){ i++; endPos = args[i]; } else if(args[i].equalsIgnoreCase("-q") || args[i].equalsIgnoreCase("-quiet")) { quietMode = true; } else if(args[i].equalsIgnoreCase("-gzip")){ Options.setGzip(true); } else { die("invalid parameter specified: " + args[i]); } } int countOptions = 0; if(pedFileName != null) { countOptions++; } if(hapsFileName != null) { countOptions++; } if(hapmapFileName != null) { countOptions++; } if(phasedhmpdataFileName != null) { countOptions++; if(phasedhmpsampleFileName == null){ die("You must specify a sample file for phased hapmap input."); }else if(phasedhmplegendFileName == null){ die("You must specify a legend file for phased hapmap input."); } } if(phasedhapmapDownload) { countOptions++; } if(plinkFileName != null){ countOptions++; if(mapFileName == null){ die("You must specify a map file for plink format input."); } } if(batchFileName != null) { countOptions++; } if(countOptions > 1) { die("Only one genotype input file may be specified on the command line."); } else if(countOptions == 0 && nogui) { die("You must specify a genotype input file."); } //mess with vars, set defaults, etc if(skipCheck && !quietMode) { argHandlerMessages.add("Skipping genotype file check"); } if(maxDistance == -1){ maxDistance = MAXDIST_DEFAULT; }else{ if (!quietMode) argHandlerMessages.add("Max LD comparison distance = " +maxDistance + "kb"); } Options.setMaxDistance(maxDistance); if(hapThresh != -1) { Options.setHaplotypeDisplayThreshold(hapThresh); if (!quietMode) argHandlerMessages.add("Haplotype display threshold = " + hapThresh); } if(minimumMAF != -1) { CheckData.mafCut = minimumMAF; if (!quietMode) argHandlerMessages.add("Minimum MAF = " + minimumMAF); } if(minimumGenoPercent != -1) { CheckData.failedGenoCut = (int)(minimumGenoPercent*100); if (!quietMode) argHandlerMessages.add("Minimum SNP genotype % = " + minimumGenoPercent); } if(hwCutoff != -1) { CheckData.hwCut = hwCutoff; if (!quietMode) argHandlerMessages.add("Hardy Weinberg equilibrium p-value cutoff = " + hwCutoff); } if(maxMendel != -1) { CheckData.numMendErrCut = maxMendel; if (!quietMode) argHandlerMessages.add("Maximum number of Mendel errors = "+maxMendel); } if(spacingThresh != -1) { Options.setSpacingThreshold(spacingThresh); if (!quietMode) argHandlerMessages.add("LD display spacing value = "+spacingThresh); } if(missingCutoff != -1) { Options.setMissingThreshold(missingCutoff); if (!quietMode) argHandlerMessages.add("Maximum amount of missing data allowed per individual = "+missingCutoff); } if(cutHighCI != -1) { FindBlocks.cutHighCI = cutHighCI; } if(cutLowCI != -1) { FindBlocks.cutLowCI = cutLowCI; } if(mafThresh != -1) { FindBlocks.mafThresh = mafThresh; } if(recHighCI != -1) { FindBlocks.recHighCI = recHighCI; } if(informFrac != -1) { FindBlocks.informFrac = informFrac; } if(fourGameteCutoff != -1) { FindBlocks.fourGameteCutoff = fourGameteCutoff; } if(spineDP != -1) { FindBlocks.spineDP = spineDP; } if(assocTDT) { Options.setAssocTest(ASSOC_TRIO); }else if(assocCC) { Options.setAssocTest(ASSOC_CC); } if (Options.getAssocTest() != ASSOC_NONE && infoFileName == null && hapmapFileName == null) { die("A marker info file must be specified when performing association tests."); } if(doPermutationTest) { if(!assocCC && !assocTDT) { die("An association test type must be specified for permutation tests to be performed."); } } if(customAssocTestsFileName != null) { if(!assocCC && !assocTDT) { die("An association test type must be specified when using a custom association test file."); } if(infoFileName == null) { die("A marker info file must be specified when using a custom association test file."); } } if(tagging != Tagger.NONE) { if(infoFileName == null && hapmapFileName == null && batchFileName == null && phasedhmpdataFileName == null && !phasedhapmapDownload) { die("A marker info file must be specified when tagging."); } if(forceExcludeTags == null) { forceExcludeTags = new Vector(); } else if (forceExcludeFileName != null) { die("-excludeTags and -excludeTagsFile cannot both be used"); } if(forceExcludeFileName != null) { File excludeFile = new File(forceExcludeFileName); forceExcludeTags = new Vector(); try { BufferedReader br = new BufferedReader(new FileReader(excludeFile)); String line; while((line = br.readLine()) != null) { if(line.length() > 0 && line.charAt(0) != '#'){ forceExcludeTags.add(line); } } }catch(IOException ioe) { die("An error occured while reading the file specified by -excludeTagsFile."); } } if(forceIncludeTags == null ) { forceIncludeTags = new Vector(); } else if (forceIncludeFileName != null) { die("-includeTags and -includeTagsFile cannot both be used"); } if(forceIncludeFileName != null) { File includeFile = new File(forceIncludeFileName); forceIncludeTags = new Vector(); try { BufferedReader br = new BufferedReader(new FileReader(includeFile)); String line; while((line = br.readLine()) != null) { if(line.length() > 0 && line.charAt(0) != '#'){ forceIncludeTags.add(line); } } }catch(IOException ioe) { die("An error occured while reading the file specified by -includeTagsFile."); } } if (captureAllelesFileName != null) { File captureFile = new File(captureAllelesFileName); captureAlleleTags = new Vector(); try { BufferedReader br = new BufferedReader(new FileReader(captureFile)); String line; while((line = br.readLine()) != null) { if(line.length() > 0 && line.charAt(0) != '#'){ line = line.trim(); captureAlleleTags.add(line); } } }catch(IOException ioe) { die("An error occured while reading the file specified by -captureAlleles."); } } if (designScoresFileName != null) { File designFile = new File(designScoresFileName); designScores = new Hashtable(1,1); try { BufferedReader br = new BufferedReader(new FileReader(designFile)); String line; while((line = br.readLine()) != null) { if(line.length() > 0 && line.charAt(0) != '#'){ StringTokenizer st = new StringTokenizer(line); String marker = st.nextToken(); Double score = new Double(st.nextToken()); designScores.put(marker,score); } } }catch(IOException ioe) { die("An error occured while reading the file specified by -captureAlleles."); } } if (minTagDistance != null) { try{ if (Integer.parseInt(minTagDistance) < 0){ die("minimum tag distance cannot be negative"); } }catch(NumberFormatException nfe){ die("minimum tag distance must be a positive integer"); } Options.setTaggerMinDistance(Integer.parseInt(minTagDistance)); } //check that there isn't any overlap between include/exclude lists Vector tempInclude = (Vector) forceIncludeTags.clone(); tempInclude.retainAll(forceExcludeTags); if(tempInclude.size() > 0) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < tempInclude.size(); i++) { String s = (String) tempInclude.elementAt(i); sb.append(s).append(","); } die("The following markers appear in both the include and exclude lists: " + sb.toString()); } if(tagRSquaredCutOff != -1) { Options.setTaggerRsqCutoff(tagRSquaredCutOff); } } else if(forceExcludeTags != null || forceIncludeTags != null || tagRSquaredCutOff != -1) { die("-tagrSqCutoff, -excludeTags, -excludeTagsFile, -includeTags and -includeTagsFile cannot be used without a tagging option"); } if(chromosomeArg != null && hapmapFileName != null) { argHandlerMessages.add("-chromosome flag ignored when loading hapmap file"); chromosomeArg = null; } if(chromosomeArg != null) { Chromosome.setDataChrom("chr" + chromosomeArg); } if (phasedhapmapDownload){ if (chromosomeArg == null){ die("-phasedhapmapdl requires a chromosome specification"); }else if (!(populationArg.equalsIgnoreCase("CEU") || populationArg.equalsIgnoreCase("YRI") || populationArg.equalsIgnoreCase("HCB") || populationArg.equalsIgnoreCase("JPT"))){ die("-phasedhapmapdl requires a population specification of CEU, YRI, HCB, or JPT"); } if (Integer.parseInt(chromosomeArg) < 1 && Integer.parseInt(chromosomeArg) > 22){ if (!(chromosomeArg.equalsIgnoreCase("x"))){ die("chromsome specification must be betweeen 1 and 22 or X"); } } try{ if (Integer.parseInt(startPos) > Integer.parseInt(endPos)){ die("end position must be greater then start position"); } }catch(NumberFormatException nfe){ die("start and end positions must be integer values"); } } }
|
private void argHandler(String[] args){ argHandlerMessages = new Vector(); int maxDistance = -1; //this means that user didn't specify any output type if it doesn't get changed below blockOutputType = -1; double hapThresh = -1; double minimumMAF=-1; double spacingThresh = -1; double minimumGenoPercent = -1; double hwCutoff = -1; double missingCutoff = -1; int maxMendel = -1; boolean assocTDT = false; boolean assocCC = false; permutationCount = 0; tagging = Tagger.NONE; maxNumTags = Tagger.DEFAULT_MAXNUMTAGS; findTags = true; double cutHighCI = -1; double cutLowCI = -1; double mafThresh = -1; double recHighCI = -1; double informFrac = -1; double fourGameteCutoff = -1; double spineDP = -1; for(int i =0; i < args.length; i++) { if(args[i].equalsIgnoreCase("-help") || args[i].equalsIgnoreCase("-h")) { System.out.println(HELP_OUTPUT); System.exit(0); } else if(args[i].equalsIgnoreCase("-n") || args[i].equalsIgnoreCase("-nogui")) { nogui = true; } else if(args[i].equalsIgnoreCase("-p") || args[i].equalsIgnoreCase("-pedfile")) { i++; if( i>=args.length || (args[i].charAt(0) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(pedFileName != null){ argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last pedfile listed will be used"); } pedFileName = args[i]; } } else if (args[i].equalsIgnoreCase("-pcloadletter")){ die("PC LOADLETTER?! What the fuck does that mean?!"); } else if (args[i].equalsIgnoreCase("-skipcheck") || args[i].equalsIgnoreCase("--skipcheck")){ skipCheck = true; } else if (args[i].equalsIgnoreCase("-excludeMarkers")){ i++; if(i>=args.length || (args[i].charAt(0) == '-')){ die("-excludeMarkers requires a list of markers"); } else { StringTokenizer str = new StringTokenizer(args[i],","); try { StringBuffer sb = new StringBuffer(); if (!quietMode) sb.append("Excluding markers: "); while(str.hasMoreTokens()) { String token = str.nextToken(); if(token.indexOf("..") != -1) { int lastIndex = token.indexOf(".."); int rangeStart = Integer.parseInt(token.substring(0,lastIndex)); int rangeEnd = Integer.parseInt(token.substring(lastIndex+2,token.length())); for(int j=rangeStart;j<=rangeEnd;j++) { if (!quietMode) sb.append(j+" "); excludedMarkers.add(new Integer(j)); } } else { if (!quietMode) sb.append(token+" "); excludedMarkers.add(new Integer(token)); } } if (!quietMode) argHandlerMessages.add(sb.toString()); } catch(NumberFormatException nfe) { die("-excludeMarkers argument should be of the format: 1,3,5..8,12"); } } } else if(args[i].equalsIgnoreCase("-ha") || args[i].equalsIgnoreCase("-l") || args[i].equalsIgnoreCase("-haps")) { i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(hapsFileName != null){ argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last haps file listed will be used"); } hapsFileName = args[i]; } } else if(args[i].equalsIgnoreCase("-i") || args[i].equalsIgnoreCase("-info")) { i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(infoFileName != null){ argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last info file listed will be used"); } infoFileName = args[i]; } } else if (args[i].equalsIgnoreCase("-a") || args[i].equalsIgnoreCase("-hapmap")){ i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(hapmapFileName != null){ argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last hapmap file listed will be used"); } hapmapFileName = args[i]; } } else if (args[i].equalsIgnoreCase("-phasedhmpdata")){ i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(phasedhmpdataFileName != null){ argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last phased hapmap data file listed will be used"); } phasedhmpdataFileName = args[i]; } } else if (args[i].equalsIgnoreCase("-phasedhmpsample")){ i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(phasedhmpsampleFileName != null){ argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last phased hapmap sample file listed will be used"); } phasedhmpsampleFileName = args[i]; } } else if (args[i].equalsIgnoreCase("-phasedhmplegend")){ i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(phasedhmplegendFileName != null){ argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last phased hapmap legend file listed will be used"); } phasedhmplegendFileName = args[i]; } } else if (args[i].equalsIgnoreCase("-phasedhapmapdl")){ phasedhapmapDownload = true; } else if (args[i].equalsIgnoreCase("-plink")){ i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(plinkFileName != null){ argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last PLINK file listed will be used"); } plinkFileName = args[i]; } } else if (args[i].equalsIgnoreCase("-map")){ i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(plinkFileName != null){ argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last map file listed will be used"); } mapFileName = args[i]; } } else if(args[i].equalsIgnoreCase("-k") || args[i].equalsIgnoreCase("-blocks")) { i++; if (!(i>=args.length) && !((args[i].charAt(0)) == '-')){ blockFileName = args[i]; blockOutputType = BLOX_CUSTOM; }else{ die(args[i-1] + " requires a filename"); } } else if (args[i].equalsIgnoreCase("-png")){ outputPNG = true; } else if (args[i].equalsIgnoreCase("-smallpng") || args[i].equalsIgnoreCase("-compressedPNG")){ outputCompressedPNG = true; } else if (args[i].equalsIgnoreCase("-track")){ i++; if (!(i>=args.length) && !((args[i].charAt(0)) == '-')){ trackFileName = args[i]; }else{ die("-track requires a filename"); } } else if(args[i].equalsIgnoreCase("-o") || args[i].equalsIgnoreCase("-output") || args[i].equalsIgnoreCase("-blockoutput")) { i++; if(!(i>=args.length) && !((args[i].charAt(0)) == '-')){ if(blockOutputType != -1){ die("Only one block output type argument is allowed."); } if(args[i].equalsIgnoreCase("SFS") || args[i].equalsIgnoreCase("GAB")){ blockOutputType = BLOX_GABRIEL; } else if(args[i].equalsIgnoreCase("GAM")){ blockOutputType = BLOX_4GAM; } else if(args[i].equalsIgnoreCase("MJD") || args[i].equalsIgnoreCase("SPI")){ blockOutputType = BLOX_SPINE; } else if(args[i].equalsIgnoreCase("ALL")) { blockOutputType = BLOX_ALL; } } else { //defaults to SFS output blockOutputType = BLOX_GABRIEL; i--; } } else if(args[i].equalsIgnoreCase("-d") || args[i].equalsIgnoreCase("--dprime") || args[i].equalsIgnoreCase("-dprime")) { outputDprime = true; } else if (args[i].equalsIgnoreCase("-c") || args[i].equalsIgnoreCase("-check")){ outputCheck = true; } else if (args[i].equalsIgnoreCase("-indcheck")){ individualCheck = true; } else if (args[i].equalsIgnoreCase("-mendel")){ mendel = true; } else if (args[i].equalsIgnoreCase("-malehets")){ malehets = true; } else if(args[i].equalsIgnoreCase("-m") || args[i].equalsIgnoreCase("-maxdistance")) { i++; maxDistance = getIntegerArg(args,i); } else if(args[i].equalsIgnoreCase("-b") || args[i].equalsIgnoreCase("-batch")) { //batch mode i++; if(i>=args.length || ((args[i].charAt(0)) == '-')){ die(args[i-1] + " requires a filename"); } else{ if(batchFileName != null){ argHandlerMessages.add("multiple " + args[i-1] + " arguments found. only last batch file listed will be used"); } batchFileName = args[i]; } } else if(args[i].equalsIgnoreCase("-hapthresh")) { i++; hapThresh = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-spacing")) { i++; spacingThresh = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-minMAF")) { i++; minimumMAF = getDoubleArg(args,i,0,0.5); } else if(args[i].equalsIgnoreCase("-minGeno") || args[i].equalsIgnoreCase("-minGenoPercent")) { i++; minimumGenoPercent = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-hwcutoff")) { i++; hwCutoff = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-maxMendel") ) { i++; maxMendel = getIntegerArg(args,i); } else if(args[i].equalsIgnoreCase("-missingcutoff")) { i++; missingCutoff = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-assoctdt")) { assocTDT = true; } else if(args[i].equalsIgnoreCase("-assoccc")) { assocCC = true; } else if(args[i].equalsIgnoreCase("-randomcc")){ assocCC = true; randomizeAffection = true; } else if(args[i].equalsIgnoreCase("-ldcolorscheme")) { i++; if(!(i>=args.length) && !((args[i].charAt(0)) == '-')){ if(args[i].equalsIgnoreCase("default")){ Options.setLDColorScheme(STD_SCHEME); } else if(args[i].equalsIgnoreCase("RSQ")){ Options.setLDColorScheme(RSQ_SCHEME); } else if(args[i].equalsIgnoreCase("DPALT") ){ Options.setLDColorScheme(WMF_SCHEME); } else if(args[i].equalsIgnoreCase("GAB")) { Options.setLDColorScheme(GAB_SCHEME); } else if(args[i].equalsIgnoreCase("GAM")) { Options.setLDColorScheme(GAM_SCHEME); } else if(args[i].equalsIgnoreCase("GOLD")) { Options.setLDColorScheme(GOLD_SCHEME); } } else { //defaults to STD color scheme Options.setLDColorScheme(STD_SCHEME); i--; } } else if(args[i].equalsIgnoreCase("-blockCutHighCI")) { i++; cutHighCI = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-blockCutLowCI")) { i++; cutLowCI = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-blockMafThresh")) { i++; mafThresh = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-blockRecHighCI")) { i++; recHighCI = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-blockInformFrac")) { i++; informFrac = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-block4GamCut")) { i++; fourGameteCutoff = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-blockSpineDP")) { i++; spineDP = getDoubleArg(args,i,0,1); } else if(args[i].equalsIgnoreCase("-permtests")) { i++; doPermutationTest = true; permutationCount = getIntegerArg(args,i); } else if(args[i].equalsIgnoreCase("-customassoc")) { i++; if (!(i>=args.length) && !((args[i].charAt(0)) == '-')){ customAssocTestsFileName = args[i]; }else{ die(args[i-1] + " requires a filename"); } } else if(args[i].equalsIgnoreCase("-aggressiveTagging")) { tagging = Tagger.AGGRESSIVE_TRIPLE; } else if (args[i].equalsIgnoreCase("-pairwiseTagging")){ tagging = Tagger.PAIRWISE_ONLY; } else if (args[i].equalsIgnoreCase("-printalltags")){ Options.setPrintAllTags(true); } else if(args[i].equalsIgnoreCase("-maxNumTags")){ i++; maxNumTags = getIntegerArg(args,i); } else if(args[i].equalsIgnoreCase("-tagrSqCutoff")) { i++; tagRSquaredCutOff = getDoubleArg(args,i,0,1); } else if (args[i].equalsIgnoreCase("-dontaddtags")){ findTags = false; } else if(args[i].equalsIgnoreCase("-tagLODCutoff")) { i++; Options.setTaggerLODCutoff(getDoubleArg(args,i,0,100000)); } else if(args[i].equalsIgnoreCase("-includeTags")) { i++; if(i>=args.length || args[i].charAt(0) == '-') { die(args[i-1] + " requires a list of marker names."); } StringTokenizer str = new StringTokenizer(args[i],","); forceIncludeTags = new Vector(); while(str.hasMoreTokens()) { forceIncludeTags.add(str.nextToken()); } } else if (args[i].equalsIgnoreCase("-includeTagsFile")) { i++; if(!(i>=args.length) && !(args[i].charAt(0) == '-')) { forceIncludeFileName =args[i]; }else { die(args[i-1] + " requires a filename"); } } else if(args[i].equalsIgnoreCase("-excludeTags")) { i++; if(i>=args.length || args[i].charAt(0) == '-') { die("-excludeTags requires a list of marker names."); } StringTokenizer str = new StringTokenizer(args[i],","); forceExcludeTags = new Vector(); while(str.hasMoreTokens()) { forceExcludeTags.add(str.nextToken()); } } else if (args[i].equalsIgnoreCase("-excludeTagsFile")) { i++; if(!(i>=args.length) && !(args[i].charAt(0) == '-')) { forceExcludeFileName =args[i]; }else { die(args[i-1] + " requires a filename"); } } else if (args[i].equalsIgnoreCase("-captureAlleles")){ i++; if(!(i>=args.length) && !(args[i].charAt(0) == '-')) { captureAllelesFileName =args[i]; }else { die(args[i-1] + " requires a filename"); } } else if (args[i].equalsIgnoreCase("-designScores")){ i++; if(!(i>=args.length) && !(args[i].charAt(0) == '-')) { designScoresFileName =args[i]; }else { die(args[i-1] + " requires a filename"); } } else if (args[i].equalsIgnoreCase("-mintagdistance")){ i++; minTagDistance = args[i]; } else if(args[i].equalsIgnoreCase("-chromosome") || args[i].equalsIgnoreCase("-chr")) { i++; if(!(i>=args.length) && !(args[i].charAt(0) == '-')) { chromosomeArg =args[i]; }else { die(args[i-1] + " requires a chromosome name"); } if(!(chromosomeArg.equalsIgnoreCase("x"))){ try{ if (Integer.parseInt(chromosomeArg) > 22){ die("-chromosome requires a chromsome name of 1-22 or X"); } }catch(NumberFormatException nfe){ die("-chromosome requires a chromsome name of 1-22 or X"); } } } else if(args[i].equalsIgnoreCase("-population")){ i++; if(!(i>=args.length) && !(args[i].charAt(0)== '-')) { populationArg = args[i]; }else { die(args[i-1] + "requires a population name"); } } else if(args[i].equalsIgnoreCase("-startpos")){ i++; startPos = args[i]; } else if(args[i].equalsIgnoreCase("-endPos")){ i++; endPos = args[i]; } else if(args[i].equalsIgnoreCase("-q") || args[i].equalsIgnoreCase("-quiet")) { quietMode = true; } else if(args[i].equalsIgnoreCase("-gzip")){ Options.setGzip(true); } else { die("invalid parameter specified: " + args[i]); } } int countOptions = 0; if(pedFileName != null) { countOptions++; } if(hapsFileName != null) { countOptions++; } if(hapmapFileName != null) { countOptions++; } if(phasedhmpdataFileName != null) { countOptions++; if(phasedhmpsampleFileName == null){ die("You must specify a sample file for phased hapmap input."); }else if(phasedhmplegendFileName == null){ die("You must specify a legend file for phased hapmap input."); } } if(phasedhapmapDownload) { countOptions++; } if(plinkFileName != null){ countOptions++; if(mapFileName == null){ die("You must specify a map file for plink format input."); } } if(batchFileName != null) { countOptions++; } if(countOptions > 1) { die("Only one genotype input file may be specified on the command line."); } else if(countOptions == 0 && nogui) { die("You must specify a genotype input file."); } //mess with vars, set defaults, etc if(skipCheck && !quietMode) { argHandlerMessages.add("Skipping genotype file check"); } if(maxDistance == -1){ maxDistance = MAXDIST_DEFAULT; }else{ if (!quietMode) argHandlerMessages.add("Max LD comparison distance = " +maxDistance + "kb"); } Options.setMaxDistance(maxDistance); if(hapThresh != -1) { Options.setHaplotypeDisplayThreshold(hapThresh); if (!quietMode) argHandlerMessages.add("Haplotype display threshold = " + hapThresh); } if(minimumMAF != -1) { CheckData.mafCut = minimumMAF; if (!quietMode) argHandlerMessages.add("Minimum MAF = " + minimumMAF); } if(minimumGenoPercent != -1) { CheckData.failedGenoCut = (int)(minimumGenoPercent*100); if (!quietMode) argHandlerMessages.add("Minimum SNP genotype % = " + minimumGenoPercent); } if(hwCutoff != -1) { CheckData.hwCut = hwCutoff; if (!quietMode) argHandlerMessages.add("Hardy Weinberg equilibrium p-value cutoff = " + hwCutoff); } if(maxMendel != -1) { CheckData.numMendErrCut = maxMendel; if (!quietMode) argHandlerMessages.add("Maximum number of Mendel errors = "+maxMendel); } if(spacingThresh != -1) { Options.setSpacingThreshold(spacingThresh); if (!quietMode) argHandlerMessages.add("LD display spacing value = "+spacingThresh); } if(missingCutoff != -1) { Options.setMissingThreshold(missingCutoff); if (!quietMode) argHandlerMessages.add("Maximum amount of missing data allowed per individual = "+missingCutoff); } if(cutHighCI != -1) { FindBlocks.cutHighCI = cutHighCI; } if(cutLowCI != -1) { FindBlocks.cutLowCI = cutLowCI; } if(mafThresh != -1) { FindBlocks.mafThresh = mafThresh; } if(recHighCI != -1) { FindBlocks.recHighCI = recHighCI; } if(informFrac != -1) { FindBlocks.informFrac = informFrac; } if(fourGameteCutoff != -1) { FindBlocks.fourGameteCutoff = fourGameteCutoff; } if(spineDP != -1) { FindBlocks.spineDP = spineDP; } if(assocTDT) { Options.setAssocTest(ASSOC_TRIO); }else if(assocCC) { Options.setAssocTest(ASSOC_CC); } if (Options.getAssocTest() != ASSOC_NONE && infoFileName == null && hapmapFileName == null) { die("A marker info file must be specified when performing association tests."); } if(doPermutationTest) { if(!assocCC && !assocTDT) { die("An association test type must be specified for permutation tests to be performed."); } } if(customAssocTestsFileName != null) { if(!assocCC && !assocTDT) { die("An association test type must be specified when using a custom association test file."); } if(infoFileName == null) { die("A marker info file must be specified when using a custom association test file."); } } if(tagging != Tagger.NONE) { if(infoFileName == null && hapmapFileName == null && batchFileName == null && phasedhmpdataFileName == null && !phasedhapmapDownload) { die("A marker info file must be specified when tagging."); } if(forceExcludeTags == null) { forceExcludeTags = new Vector(); } else if (forceExcludeFileName != null) { die("-excludeTags and -excludeTagsFile cannot both be used"); } if(forceExcludeFileName != null) { File excludeFile = new File(forceExcludeFileName); forceExcludeTags = new Vector(); try { BufferedReader br = new BufferedReader(new FileReader(excludeFile)); String line; while((line = br.readLine()) != null) { if(line.length() > 0 && line.charAt(0) != '#'){ forceExcludeTags.add(line); } } }catch(IOException ioe) { die("An error occured while reading the file specified by -excludeTagsFile."); } } if(forceIncludeTags == null ) { forceIncludeTags = new Vector(); } else if (forceIncludeFileName != null) { die("-includeTags and -includeTagsFile cannot both be used"); } if(forceIncludeFileName != null) { File includeFile = new File(forceIncludeFileName); forceIncludeTags = new Vector(); try { BufferedReader br = new BufferedReader(new FileReader(includeFile)); String line; while((line = br.readLine()) != null) { if(line.length() > 0 && line.charAt(0) != '#'){ forceIncludeTags.add(line); } } }catch(IOException ioe) { die("An error occured while reading the file specified by -includeTagsFile."); } } if (captureAllelesFileName != null) { File captureFile = new File(captureAllelesFileName); captureAlleleTags = new Vector(); try { BufferedReader br = new BufferedReader(new FileReader(captureFile)); String line; while((line = br.readLine()) != null) { if(line.length() > 0 && line.charAt(0) != '#'){ line = line.trim(); captureAlleleTags.add(line); } } }catch(IOException ioe) { die("An error occured while reading the file specified by -captureAlleles."); } } if (designScoresFileName != null) { File designFile = new File(designScoresFileName); designScores = new Hashtable(1,1); try { BufferedReader br = new BufferedReader(new FileReader(designFile)); String line; while((line = br.readLine()) != null) { if(line.length() > 0 && line.charAt(0) != '#'){ StringTokenizer st = new StringTokenizer(line); String marker = st.nextToken(); Double score = new Double(st.nextToken()); designScores.put(marker,score); } } }catch(IOException ioe) { die("An error occured while reading the file specified by -captureAlleles."); } } if (minTagDistance != null) { try{ if (Integer.parseInt(minTagDistance) < 0){ die("minimum tag distance cannot be negative"); } }catch(NumberFormatException nfe){ die("minimum tag distance must be a positive integer"); } Options.setTaggerMinDistance(Integer.parseInt(minTagDistance)); } //check that there isn't any overlap between include/exclude lists Vector tempInclude = (Vector) forceIncludeTags.clone(); tempInclude.retainAll(forceExcludeTags); if(tempInclude.size() > 0) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < tempInclude.size(); i++) { String s = (String) tempInclude.elementAt(i); sb.append(s).append(","); } die("The following markers appear in both the include and exclude lists: " + sb.toString()); } if(tagRSquaredCutOff != -1) { Options.setTaggerRsqCutoff(tagRSquaredCutOff); } } else if(forceExcludeTags != null || forceIncludeTags != null || tagRSquaredCutOff != -1) { die("-tagrSqCutoff, -excludeTags, -excludeTagsFile, -includeTags and -includeTagsFile cannot be used without a tagging option"); } if(chromosomeArg != null && hapmapFileName != null) { argHandlerMessages.add("-chromosome flag ignored when loading hapmap file"); chromosomeArg = null; } if(chromosomeArg != null) { Chromosome.setDataChrom("chr" + chromosomeArg); } if (phasedhapmapDownload){ if (chromosomeArg == null){ die("-phasedhapmapdl requires a chromosome specification"); }else if (!(populationArg.equalsIgnoreCase("CEU") || populationArg.equalsIgnoreCase("YRI") || populationArg.equalsIgnoreCase("HCB") || populationArg.equalsIgnoreCase("JPT"))){ die("-phasedhapmapdl requires a population specification of CEU, YRI, HCB, or JPT"); } if (Integer.parseInt(chromosomeArg) < 1 && Integer.parseInt(chromosomeArg) > 22){ if (!(chromosomeArg.equalsIgnoreCase("x"))){ die("chromsome specification must be betweeen 1 and 22 or X"); } } try{ if (Integer.parseInt(startPos) > Integer.parseInt(endPos)){ die("end position must be greater then start position"); } }catch(NumberFormatException nfe){ die("start and end positions must be integer values"); } } }
| 1,108,775
|
public FolderNodeEditor( FolderTreePane treePane ) { super(); this.treePane = treePane; setLayout( new BoxLayout(this, BoxLayout.X_AXIS) ); check = new JCheckBox(); check.setBackground( Color.WHITE ); check.addActionListener( this ); name = new JLabel(); icon = new JLabel(); add( icon ); add( check ); add( name ); this.setBackground( Color.WHITE ); closedIcon = getIcon( "folder_icon.png"); expandedIcon = getIcon( "folder_expanded_icon.png" ); DefaultTreeCellRenderer dr = new DefaultTreeCellRenderer(); name.setFont( dr.getFont() ); selectedBkg = dr.getBackgroundSelectionColor(); nonSelectedBkg = dr.getBackgroundNonSelectionColor(); }
|
public FolderNodeEditor( FolderTreePane treePane ) { super(); this.treePane = treePane; setLayout( new BoxLayout(this, BoxLayout.X_AXIS) ); check = new ThreeStateCheckBox(); check.setBackground( Color.WHITE ); check.addActionListener( this ); name = new JLabel(); icon = new JLabel(); add( icon ); add( check ); add( name ); this.setBackground( Color.WHITE ); closedIcon = getIcon( "folder_icon.png"); expandedIcon = getIcon( "folder_expanded_icon.png" ); DefaultTreeCellRenderer dr = new DefaultTreeCellRenderer(); name.setFont( dr.getFont() ); selectedBkg = dr.getBackgroundSelectionColor(); nonSelectedBkg = dr.getBackgroundNonSelectionColor(); }
| 1,108,776
|
public Component getTreeCellEditorComponent(JTree jTree, Object object, boolean isSelected, boolean isExpanded, boolean isLeaf, int i) { node = (FolderNode) object; icon.setIcon( isExpanded ? expandedIcon : closedIcon ); PhotoFolder f = node.getFolder(); name.setText( f.getName() ); name.setBackground( isSelected ? selectedBkg : nonSelectedBkg ); check.setSelected( node.containsPhotos() ); return this; }
|
public Component getTreeCellEditorComponent(JTree jTree, Object object, boolean isSelected, boolean isExpanded, boolean isLeaf, int row ) { node = (FolderNode) object; icon.setIcon( isExpanded ? expandedIcon : closedIcon ); PhotoFolder f = node.getFolder(); name.setText( f.getName() ); name.setBackground( isSelected ? selectedBkg : nonSelectedBkg ); check.setSelected( node.containsPhotos() ); return this; }
| 1,108,778
|
public Component getTreeCellEditorComponent(JTree jTree, Object object, boolean isSelected, boolean isExpanded, boolean isLeaf, int i) { node = (FolderNode) object; icon.setIcon( isExpanded ? expandedIcon : closedIcon ); PhotoFolder f = node.getFolder(); name.setText( f.getName() ); name.setBackground( isSelected ? selectedBkg : nonSelectedBkg ); check.setSelected( node.containsPhotos() ); return this; }
|
public Component getTreeCellEditorComponent(JTree jTree, Object object, boolean isSelected, boolean isExpanded, boolean isLeaf, int i) { node = (FolderNode) object; icon.setIcon( isExpanded ? expandedIcon : closedIcon ); PhotoFolder f = node.getFolder(); name.setText( f.getName() ); name.setBackground( isSelected ? selectedBkg : nonSelectedBkg ); check.setSelected( node.containsPhotos() ); return this; }
| 1,108,779
|
public Component getTreeCellRendererComponent(JTree jTree, Object object, boolean isSelected, boolean isExpanded, boolean isLeaf, int row, boolean hasFocus) { if (object instanceof FolderNode) { node = (FolderNode) object; icon.setIcon( isExpanded ? expandedIcon : closedIcon ); PhotoFolder f = node.getFolder(); name.setText( f.getName() ); name.setBackground( isSelected ? selectedBkg : nonSelectedBkg ); check.setSelected( node.containsPhotos() ); } return this; }
|
public Component getTreeCellRendererComponent(JTree jTree, Object object, boolean isSelected, boolean isExpanded, boolean isLeaf, int row, boolean hasFocus) { if (object instanceof FolderNode) { node = (FolderNode) object; icon.setIcon( isExpanded ? expandedIcon : closedIcon ); PhotoFolder f = node.getFolder(); name.setText( f.getName() ); name.setBackground( isSelected ? selectedBkg : nonSelectedBkg ); check.setSelected( node.containsPhotos() ); } return this; }
| 1,108,780
|
public void run() { synchronized ( this ) { while ( true ) { try { System.out.println( "Waiting..." ); wait(); System.out.println( "Waited..." ); if ( photo != null ) { System.out.println( "Creating thumbnail..." ); Thumbnail thumb = photo.getThumbnail(); System.out.println( "Done!" ); final PhotoInfo lastPhoto = photo; photo = null; SwingUtilities.invokeLater( new Runnable() { public void run() { view.thumbnailCreated( lastPhoto ); } }); } } catch ( InterruptedException e ) {} } } }
|
public void run() { synchronized ( this ) { while ( true ) { try { log.debug( "Waiting..." ); wait(); System.out.println( "Waited..." ); if ( photo != null ) { System.out.println( "Creating thumbnail..." ); Thumbnail thumb = photo.getThumbnail(); System.out.println( "Done!" ); final PhotoInfo lastPhoto = photo; photo = null; SwingUtilities.invokeLater( new Runnable() { public void run() { view.thumbnailCreated( lastPhoto ); } }); } } catch ( InterruptedException e ) {} } } }
| 1,108,782
|
public void run() { synchronized ( this ) { while ( true ) { try { System.out.println( "Waiting..." ); wait(); System.out.println( "Waited..." ); if ( photo != null ) { System.out.println( "Creating thumbnail..." ); Thumbnail thumb = photo.getThumbnail(); System.out.println( "Done!" ); final PhotoInfo lastPhoto = photo; photo = null; SwingUtilities.invokeLater( new Runnable() { public void run() { view.thumbnailCreated( lastPhoto ); } }); } } catch ( InterruptedException e ) {} } } }
|
public void run() { synchronized ( this ) { while ( true ) { try { System.out.println( "Waiting..." ); wait(); log.debug( "Waited..." ); if ( photo != null ) { System.out.println( "Creating thumbnail..." ); Thumbnail thumb = photo.getThumbnail(); System.out.println( "Done!" ); final PhotoInfo lastPhoto = photo; photo = null; SwingUtilities.invokeLater( new Runnable() { public void run() { view.thumbnailCreated( lastPhoto ); } }); } } catch ( InterruptedException e ) {} } } }
| 1,108,783
|
public void run() { synchronized ( this ) { while ( true ) { try { System.out.println( "Waiting..." ); wait(); System.out.println( "Waited..." ); if ( photo != null ) { System.out.println( "Creating thumbnail..." ); Thumbnail thumb = photo.getThumbnail(); System.out.println( "Done!" ); final PhotoInfo lastPhoto = photo; photo = null; SwingUtilities.invokeLater( new Runnable() { public void run() { view.thumbnailCreated( lastPhoto ); } }); } } catch ( InterruptedException e ) {} } } }
|
public void run() { synchronized ( this ) { while ( true ) { try { System.out.println( "Waiting..." ); wait(); System.out.println( "Waited..." ); if ( photo != null ) { log.debug( "Creating thumbnail for " + photo.getUid() ); Thumbnail thumb = photo.getThumbnail(); System.out.println( "Done!" ); final PhotoInfo lastPhoto = photo; photo = null; SwingUtilities.invokeLater( new Runnable() { public void run() { view.thumbnailCreated( lastPhoto ); } }); } } catch ( InterruptedException e ) {} } } }
| 1,108,784
|
public void run() { synchronized ( this ) { while ( true ) { try { System.out.println( "Waiting..." ); wait(); System.out.println( "Waited..." ); if ( photo != null ) { System.out.println( "Creating thumbnail..." ); Thumbnail thumb = photo.getThumbnail(); System.out.println( "Done!" ); final PhotoInfo lastPhoto = photo; photo = null; SwingUtilities.invokeLater( new Runnable() { public void run() { view.thumbnailCreated( lastPhoto ); } }); } } catch ( InterruptedException e ) {} } } }
|
public void run() { synchronized ( this ) { while ( true ) { try { System.out.println( "Waiting..." ); wait(); System.out.println( "Waited..." ); if ( photo != null ) { System.out.println( "Creating thumbnail..." ); Thumbnail thumb = photo.getThumbnail(); log.debug( "Done!" ); final PhotoInfo lastPhoto = photo; photo = null; SwingUtilities.invokeLater( new Runnable() { public void run() { view.thumbnailCreated( lastPhoto ); } }); } } catch ( InterruptedException e ) {} } } }
| 1,108,785
|
public DBCSPanel() { setupContents(); }
|
public DBCSPanel() { setLayout(new BorderLayout()); dbDriverField = new JComboBox(getDriverClasses()); dbDriverField.insertItemAt("", 0); dbNameField = new JTextField(); JComponent[] fields = new JComponent[] {dbNameField, dbDriverField, dbUrlField = new JTextField(), dbUserField = new JTextField(), dbPassField = new JPasswordField()}; String[] labels = new String[] {"Connection Name", "JDBC Driver", "JDBC URL", "Username", "Password"}; char[] mnemonics = new char[] {'n', 'd', 'u', 'r', 'p'}; int[] widths = new int[] {30, 30, 40, 20, 20}; String[] tips = new String[] {"The name of this database", "The class name of the JDBC Driver", "Vendor-specific JDBC URL", "Username for this database", "Password for this database"}; dbDriverField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String t = getTemplateForDriver(dbDriverField.getSelectedItem().toString()); if (t == null) t = "jdbc:"; dbUrlField.setText(t); } }); form = new TextPanel(fields, labels, mnemonics, widths, tips); add(form, BorderLayout.CENTER); }
| 1,108,788
|
public void actionPerformed(ActionEvent e) { int i = dbNameField.getSelectedIndex(); if (!itemChanging && i >= 0) { logger.debug("Changing to index "+i+" of "+dbcsHistory); applyChanges(); setDbcs((DBConnectionSpec) dbcsHistory.get(i)); } else if (i == -1) { String newName = (String) dbNameField.getEditor().getItem(); i = dbcsHistory.indexOf(dbcs); dbNameHistory.set(i, newName); logger.debug("Set name at index "+i+" to "+newName); } }
|
public void actionPerformed(ActionEvent e) { int i = dbNameField.getSelectedIndex(); if (!itemChanging && i >= 0) { logger.debug("Changing to index "+i+" of "+dbcsHistory); applyChanges(); setDbcs((DBConnectionSpec) dbcsHistory.get(i)); } else if (i == -1) { String newName = (String) dbNameField.getEditor().getItem(); i = dbcsHistory.indexOf(dbcs); dbNameHistory.set(i, newName); logger.debug("Set name at index "+i+" to "+newName); } }
| 1,108,789
|
public void applyChanges() { int oldIndex = dbcsHistory.indexOf(dbcs); String name = (String) dbNameField.getItemAt(oldIndex); logger.debug("Changing name of DBCS at index "+oldIndex+" to "+name); dbcs.setName(name); dbcs.setDisplayName(name); dbcs.setDriverClass(dbDriverField.getSelectedItem().toString()); dbcs.setUrl(dbUrlField.getText()); dbcs.setUser(dbUserField.getText()); dbcs.setPass(new String(dbPassField.getPassword())); // completely defeats the purpose for JPasswordField.getText() being deprecated, but we're saving passwords to the config file so it hardly matters. }
|
public void applyChanges() { int oldIndex = dbcsHistory.indexOf(dbcs); String name = (String) dbNameField.getItemAt(oldIndex); logger.debug("Changing name of DBCS at index "+oldIndex+" to "+name); dbcs.setName(name); dbcs.setDisplayName(name); dbcs.setDriverClass(dbDriverField.getSelectedItem().toString()); dbcs.setUrl(dbUrlField.getText()); dbcs.setUser(dbUserField.getText()); dbcs.setPass(new String(dbPassField.getPassword())); // completely defeats the purpose for JPasswordField.getText() being deprecated, but we're saving passwords to the config file so it hardly matters. }
| 1,108,790
|
public void setDbcs(DBConnectionSpec dbcs) { try { itemChanging = true; int index = dbcsHistory.indexOf(dbcs); if (index < 0) { logger.debug("Adding NEW dbcs to history list: "+dbcs); dbcsHistory.add(dbcs); dbNameField.addItem(dbcs.getDisplayName()); index = dbcsHistory.size() - 1; } dbNameField.setSelectedIndex(index); dbDriverField.removeItemAt(0); if (dbcs.getDriverClass() != null) { dbDriverField.insertItemAt(dbcs.getDriverClass(), 0); } else { dbDriverField.insertItemAt("", 0); } dbDriverField.setSelectedIndex(0); dbUrlField.setText(dbcs.getUrl()); dbUserField.setText(dbcs.getUser()); dbPassField.setText(dbcs.getPass()); this.dbcs = dbcs; } finally { itemChanging = false; } }
|
public void setDbcs(DBConnectionSpec dbcs) { try { itemChanging = true; int index = dbcsHistory.indexOf(dbcs); if (index < 0) { logger.debug("Adding NEW dbcs to history list: "+dbcs); dbcsHistory.add(dbcs); dbNameField.addItem(dbcs.getDisplayName()); index = dbcsHistory.size() - 1; } dbNameField.setSelectedIndex(index); dbDriverField.removeItemAt(0); if (dbcs.getDriverClass() != null) { dbDriverField.insertItemAt(dbcs.getDriverClass(), 0); } else { dbDriverField.insertItemAt("", 0); } dbDriverField.setSelectedIndex(0); dbUrlField.setText(dbcs.getUrl()); dbUserField.setText(dbcs.getUser()); dbPassField.setText(dbcs.getPass()); this.dbcs = dbcs; } finally { itemChanging = false; } }
| 1,108,791
|
public Vector<Transaction> getTransactions(Date startDate, Date endDate){ Vector<Transaction> transactions = getTransactions(); Vector<Transaction> v = new Vector<Transaction>(); for (Transaction t : transactions) { if (t.getDate().after(startDate) && t.getDate().before(endDate)){ v.add(t); } } return v; }
|
public Vector<Transaction> getTransactions(Date startDate, Date endDate){ Vector<Transaction> transactions = getTransactions(); Vector<Transaction> v = new Vector<Transaction>(); for (Transaction t : transactions) { if (t.getDate().after(startDate) && t.getDate().before(endDate)){ v.add(t); } } return v; }
| 1,108,793
|
public void save(ProgressMonitor pm) throws IOException, ArchitectException { // write to temp file and then rename (this preserves old project file // when there's problems) if (file.exists() && !file.canWrite()) { // write problems with architect file will muck up the save process throw new ArchitectException("problem saving project -- " + "cannot write to architect file: " + file.getAbsolutePath()); } File backupFile = new File (file.getParent(), file.getName()+"~"); // Several places we would check dir perms, but MS-Windows stupidly doesn't let use the // "directory write" attribute for directory writing (but instead overloads // it to mean 'this is a special directory'. File tempFile = null; tempFile = new File (file.getParent(),"tmp___" + file.getName()); try { // If creating this temp file fails, feed the user back a more explanatory message out = new PrintWriter(new BufferedWriter(new FileWriter(tempFile))); } catch (IOException e) { throw new ArchitectException("Unable to create output file for save operation, data NOT saved.\n" + e, e); } objectIdMap = new HashMap(); dbcsIdMap = new HashMap(); indent = 0; progress = 0; boolean saveOk = false; // use this to determine if save process worked this.pm = pm; if (pm != null) { int pmMax = 0; pm.setMinimum(0); if (savingEntireSource) { pmMax = ArchitectUtils.countTablesSnapshot((SQLObject) sourceDatabases.getModel().getRoot()); } else { pmMax = ArchitectUtils.countTables((SQLObject) sourceDatabases.getModel().getRoot()); } logger.error("Setting progress monitor maximum to "+pmMax); pm.setMaximum(pmMax); pm.setProgress(progress); pm.setMillisToDecideToPopup(0); } saveOk = save(out); // Does ALL the actual I/O out = null; if (pm != null) pm.close(); pm = null; // Do the rename dance. // This is a REALLY bad place for failure (especially if we've made the user wait several hours to save // a large project), so we MUST check failures from renameto (both places!) if (saveOk) { boolean fstatus = false; fstatus = backupFile.delete(); logger.debug("deleting backup~ file: " + fstatus); // If this is a brand new project, the old file does not yet exist, no point trying to rename it. // But if it already existed, renaming current to backup must succeed, or we give up. if (file.exists()) { fstatus = file.renameTo(backupFile); logger.debug("rename current file to backupFile: " + fstatus); if (!fstatus) { throw new ArchitectException(( "Could not rename current file to backup\nProject saved in " + tempFile + ": " + file + " still contains old project")); } } fstatus = tempFile.renameTo(file); if (!fstatus) { throw new ArchitectException(( "Could not rename temp file to current\nProject saved in " + tempFile + ": " + file + " still contains old project")); } logger.debug("rename tempFile to current file: " + fstatus); } }
|
public void save(ProgressMonitor pm) throws IOException, ArchitectException { // write to temp file and then rename (this preserves old project file // when there's problems) if (file.exists() && !file.canWrite()) { // write problems with architect file will muck up the save process throw new ArchitectException("problem saving project -- " + "cannot write to architect file: " + file.getAbsolutePath()); } File backupFile = new File (file.getParent(), file.getName()+"~"); // Several places we would check dir perms, but MS-Windows stupidly doesn't let use the // "directory write" attribute for directory writing (but instead overloads // it to mean 'this is a special directory'. File tempFile = null; tempFile = new File (file.getParent(),"tmp___" + file.getName()); try { // If creating this temp file fails, feed the user back a more explanatory message out = new PrintWriter(tempFile,encoding); } catch (IOException e) { throw new ArchitectException("Unable to create output file for save operation, data NOT saved.\n" + e, e); } objectIdMap = new HashMap(); dbcsIdMap = new HashMap(); indent = 0; progress = 0; boolean saveOk = false; // use this to determine if save process worked this.pm = pm; if (pm != null) { int pmMax = 0; pm.setMinimum(0); if (savingEntireSource) { pmMax = ArchitectUtils.countTablesSnapshot((SQLObject) sourceDatabases.getModel().getRoot()); } else { pmMax = ArchitectUtils.countTables((SQLObject) sourceDatabases.getModel().getRoot()); } logger.error("Setting progress monitor maximum to "+pmMax); pm.setMaximum(pmMax); pm.setProgress(progress); pm.setMillisToDecideToPopup(0); } saveOk = save(out); // Does ALL the actual I/O out = null; if (pm != null) pm.close(); pm = null; // Do the rename dance. // This is a REALLY bad place for failure (especially if we've made the user wait several hours to save // a large project), so we MUST check failures from renameto (both places!) if (saveOk) { boolean fstatus = false; fstatus = backupFile.delete(); logger.debug("deleting backup~ file: " + fstatus); // If this is a brand new project, the old file does not yet exist, no point trying to rename it. // But if it already existed, renaming current to backup must succeed, or we give up. if (file.exists()) { fstatus = file.renameTo(backupFile); logger.debug("rename current file to backupFile: " + fstatus); if (!fstatus) { throw new ArchitectException(( "Could not rename current file to backup\nProject saved in " + tempFile + ": " + file + " still contains old project")); } } fstatus = tempFile.renameTo(file); if (!fstatus) { throw new ArchitectException(( "Could not rename temp file to current\nProject saved in " + tempFile + ": " + file + " still contains old project")); } logger.debug("rename tempFile to current file: " + fstatus); } }
| 1,108,796
|
public void save(ProgressMonitor pm) throws IOException, ArchitectException { // write to temp file and then rename (this preserves old project file // when there's problems) if (file.exists() && !file.canWrite()) { // write problems with architect file will muck up the save process throw new ArchitectException("problem saving project -- " + "cannot write to architect file: " + file.getAbsolutePath()); } File backupFile = new File (file.getParent(), file.getName()+"~"); // Several places we would check dir perms, but MS-Windows stupidly doesn't let use the // "directory write" attribute for directory writing (but instead overloads // it to mean 'this is a special directory'. File tempFile = null; tempFile = new File (file.getParent(),"tmp___" + file.getName()); try { // If creating this temp file fails, feed the user back a more explanatory message out = new PrintWriter(new BufferedWriter(new FileWriter(tempFile))); } catch (IOException e) { throw new ArchitectException("Unable to create output file for save operation, data NOT saved.\n" + e, e); } objectIdMap = new HashMap(); dbcsIdMap = new HashMap(); indent = 0; progress = 0; boolean saveOk = false; // use this to determine if save process worked this.pm = pm; if (pm != null) { int pmMax = 0; pm.setMinimum(0); if (savingEntireSource) { pmMax = ArchitectUtils.countTablesSnapshot((SQLObject) sourceDatabases.getModel().getRoot()); } else { pmMax = ArchitectUtils.countTables((SQLObject) sourceDatabases.getModel().getRoot()); } logger.error("Setting progress monitor maximum to "+pmMax); pm.setMaximum(pmMax); pm.setProgress(progress); pm.setMillisToDecideToPopup(0); } saveOk = save(out); // Does ALL the actual I/O out = null; if (pm != null) pm.close(); pm = null; // Do the rename dance. // This is a REALLY bad place for failure (especially if we've made the user wait several hours to save // a large project), so we MUST check failures from renameto (both places!) if (saveOk) { boolean fstatus = false; fstatus = backupFile.delete(); logger.debug("deleting backup~ file: " + fstatus); // If this is a brand new project, the old file does not yet exist, no point trying to rename it. // But if it already existed, renaming current to backup must succeed, or we give up. if (file.exists()) { fstatus = file.renameTo(backupFile); logger.debug("rename current file to backupFile: " + fstatus); if (!fstatus) { throw new ArchitectException(( "Could not rename current file to backup\nProject saved in " + tempFile + ": " + file + " still contains old project")); } } fstatus = tempFile.renameTo(file); if (!fstatus) { throw new ArchitectException(( "Could not rename temp file to current\nProject saved in " + tempFile + ": " + file + " still contains old project")); } logger.debug("rename tempFile to current file: " + fstatus); } }
|
public void save(ProgressMonitor pm) throws IOException, ArchitectException { // write to temp file and then rename (this preserves old project file // when there's problems) if (file.exists() && !file.canWrite()) { // write problems with architect file will muck up the save process throw new ArchitectException("problem saving project -- " + "cannot write to architect file: " + file.getAbsolutePath()); } File backupFile = new File (file.getParent(), file.getName()+"~"); // Several places we would check dir perms, but MS-Windows stupidly doesn't let use the // "directory write" attribute for directory writing (but instead overloads // it to mean 'this is a special directory'. File tempFile = null; tempFile = new File (file.getParent(),"tmp___" + file.getName()); try { // If creating this temp file fails, feed the user back a more explanatory message out = new PrintWriter(new BufferedWriter(new FileWriter(tempFile))); } catch (IOException e) { throw new ArchitectException("Unable to create output file for save operation, data NOT saved.\n" + e, e); } objectIdMap = new HashMap(); dbcsIdMap = new HashMap(); indent = 0; progress = 0; boolean saveOk = false; // use this to determine if save process worked this.pm = pm; if (pm != null) { int pmMax = 0; pm.setMinimum(0); if (savingEntireSource) { pmMax = ArchitectUtils.countTablesSnapshot((SQLObject) sourceDatabases.getModel().getRoot()); } else { pmMax = ArchitectUtils.countTables((SQLObject) sourceDatabases.getModel().getRoot()); } logger.error("Setting progress monitor maximum to "+pmMax); pm.setMaximum(pmMax); pm.setProgress(progress); pm.setMillisToDecideToPopup(0); } saveOk = save(out,encoding); // Does ALL the actual I/O out = null; if (pm != null) pm.close(); pm = null; // Do the rename dance. // This is a REALLY bad place for failure (especially if we've made the user wait several hours to save // a large project), so we MUST check failures from renameto (both places!) if (saveOk) { boolean fstatus = false; fstatus = backupFile.delete(); logger.debug("deleting backup~ file: " + fstatus); // If this is a brand new project, the old file does not yet exist, no point trying to rename it. // But if it already existed, renaming current to backup must succeed, or we give up. if (file.exists()) { fstatus = file.renameTo(backupFile); logger.debug("rename current file to backupFile: " + fstatus); if (!fstatus) { throw new ArchitectException(( "Could not rename current file to backup\nProject saved in " + tempFile + ": " + file + " still contains old project")); } } fstatus = tempFile.renameTo(file); if (!fstatus) { throw new ArchitectException(( "Could not rename temp file to current\nProject saved in " + tempFile + ": " + file + " still contains old project")); } logger.debug("rename tempFile to current file: " + fstatus); } }
| 1,108,797
|
private void createDatabase() { // Ask for the admin password PVDatabase db = new PVDatabase(); String user = ""; String passwd = ""; if ( dbServerBtn.isSelected() ) { AdminLoginDlg loginDlg = new AdminLoginDlg( this, true ); if ( loginDlg.showDialog() == AdminLoginDlg.LOGIN_DLG_OK ) { user = loginDlg.getUsername(); passwd = loginDlg.getPasswd(); } db.setDbName( dbNameFld.getText() ); db.setDbHost( dbHostFld.getText() ); db.setName( nameFld.getText() ); Volume vol = new Volume( "defaultVolume", volumeDirFld.getText() ); db.addVolume( vol ); } else { // Creating an embedded database db.setName( nameFld.getText() ); db.setInstanceType( PVDatabase.TYPE_EMBEDDED ); db.setEmbeddedDirectory( new File( volumeDirFld.getText() ) ); } db.createDatabase( user, passwd ); PhotovaultSettings settings = PhotovaultSettings.getSettings(); settings.addDatabase( db ); settings.saveConfig(); JOptionPane.showMessageDialog( this, "Database " + nameFld.getText() + " created succesfully", "Database created", JOptionPane.INFORMATION_MESSAGE ); }
|
private void createDatabase() { // Ask for the admin password PVDatabase db = new PVDatabase(); String user = ""; String passwd = ""; if ( dbServerBtn.isSelected() ) { AdminLoginDlg loginDlg = new AdminLoginDlg( this, true ); if ( loginDlg.showDialog() == AdminLoginDlg.LOGIN_DLG_OK ) { user = loginDlg.getUsername(); passwd = loginDlg.getPasswd(); } db.setDbName( dbNameFld.getText() ); db.setDbHost( dbHostFld.getText() ); db.setName( nameFld.getText() ); Volume vol = new Volume( "defaultVolume", volumeDirFld.getText() ); db.addVolume( vol ); } else { // Creating an embedded database db.setName( nameFld.getText() ); db.setInstanceType( PVDatabase.TYPE_EMBEDDED ); db.setEmbeddedDirectory( new File( volumeDirFld.getText() ) ); } db.createDatabase( user, passwd ); PhotovaultSettings settings = PhotovaultSettings.getSettings(); settings.addDatabase( db ); settings.saveConfig(); JOptionPane.showMessageDialog( this, "Database " + nameFld.getText() + " created successfully", "Database created", JOptionPane.INFORMATION_MESSAGE ); }
| 1,108,798
|
protected void init() throws ArchitectException { int accelMask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); prefs = PrefsUtils.getUserPrefsNode(architectSession); 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(getArchitectSession()); 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 { prefs.putInt(SwingUserSettings.DIVIDER_LOCATION, splitPane.getDividerLocation()); closeProject(getProject()); setProject(new SwingUIProject("New Project")); logger.debug("Glass pane is "+getGlassPane()); } 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)); final RecentMenu recent = new RecentMenu(this) { @Override public void loadFile(String fileName) throws IOException { openFile(fileName); } }; openProjectAction = new OpenProjectAction(recent); JMenuItem clearItem = new JMenuItem("Clear Recent Files"); clearItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { recent.clear(); } }); 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"); zoomAllAction = new AbstractAction("Zoom to fit", ASUtils.createJLFIcon("general/Zoom", "Reset Zoom", sprefs.getInt(SwingUserSettings.ICON_SIZE, 24))) { public void actionPerformed(ActionEvent e) { Rectangle rect = null; if ( playpen != null ) { for (int i = 0; i < playpen.getContentPane().getComponentCount(); i++) { PlayPenComponent ppc = playpen.getContentPane().getComponent(i); if ( i == 0 ) { rect = new Rectangle(ppc.getLocation(),ppc.getSize()); } else { rect.add(ppc.getBounds()); } } } double zoom = playpen.getViewportSize().getHeight()/rect.height; double zoom1 = playpen.getViewportSize().getWidth()/rect.width; if ( zoom1 < zoom ) zoom = zoom1; zoom *= 0.95; playpen.setZoom(zoom); playpen.scrollRectToVisible(playpen.unzoomRect(rect)); } }; zoomAllAction.putValue(AbstractAction.SHORT_DESCRIPTION, "View All"); 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)); selectAllAction = new SelectAllAction(); selectAllAction.putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_A, accelMask)); menuBar = new JMenuBar(); //Settingup JMenu fileMenu = new JMenu("File"); fileMenu.setMnemonic('f'); fileMenu.add(newProjectAction); fileMenu.add(openProjectAction); fileMenu.add(recent); fileMenu.add(clearItem); fileMenu.addSeparator(); fileMenu.add(saveProjectAction); fileMenu.add(saveProjectAsAction); fileMenu.add(printAction); fileMenu.addSeparator(); fileMenu.add(prefAction); fileMenu.add(projectSettingsAction); fileMenu.add(saveSettingsAction); fileMenu.addSeparator(); fileMenu.add(exitAction); menuBar.add(fileMenu); JMenu editMenu = new JMenu("Edit"); editMenu.setMnemonic('e'); editMenu.add(undoAction); editMenu.add(redoAction); editMenu.addSeparator(); editMenu.add(selectAllAction); editMenu.addSeparator(); editMenu.add(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(exportPLTransAction); etlSubmenuOne.add(new JMenuItem("PL Transaction File Export")); etlSubmenuOne.add(new JMenuItem("Run Power*Loader")); etlSubmenuOne.add(quickStartAction); etlMenu.add(etlSubmenuOne); menuBar.add(etlMenu); JMenu toolsMenu = new JMenu("Tools"); toolsMenu.setMnemonic('t'); toolsMenu.add(exportDDLAction); toolsMenu.add(compareDMAction); menuBar.add(toolsMenu); JMenu helpMenu = new JMenu("Help"); helpMenu.setMnemonic('h'); helpMenu.add(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.add(compareDMAction); projectBar.addSeparator(); projectBar.add(autoLayoutAction); projectBar.setToolTipText("Project Toolbar"); projectBar.setName("Project Toolbar"); JButton tempButton = null; // shared actions need to report where they are coming from ppBar.setToolTipText("PlayPen Toolbar"); ppBar.setName("PlayPen ToolBar"); ppBar.add(zoomInAction); ppBar.add(zoomOutAction); ppBar.add(zoomNormalAction); ppBar.add(zoomAllAction); 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(prefs.getInt(SwingUserSettings.DIVIDER_LOCATION,150)); Rectangle bounds = new Rectangle(); bounds.x = prefs.getInt(SwingUserSettings.MAIN_FRAME_X, 40); bounds.y = prefs.getInt(SwingUserSettings.MAIN_FRAME_Y, 40); bounds.width = prefs.getInt(SwingUserSettings.MAIN_FRAME_WIDTH, 600); bounds.height = prefs.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(); prefs = PrefsUtils.getUserPrefsNode(architectSession); 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(getArchitectSession()); 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 { prefs.putInt(SwingUserSettings.DIVIDER_LOCATION, splitPane.getDividerLocation()); closeProject(getProject()); setProject(new SwingUIProject("New Project")); logger.debug("Glass pane is "+getGlassPane()); } 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)); final RecentMenu recent = new RecentMenu(this) { @Override public void loadFile(String fileName) throws IOException { openFile(fileName); } }; openProjectAction = new OpenProjectAction(recent); JMenuItem clearItem = new JMenuItem("Clear Recent Files"); clearItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { recent.clear(); } }); 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"); zoomAllAction = new AbstractAction("Zoom to fit", ASUtils.createJLFIcon("general/Zoom", "Reset Zoom", sprefs.getInt(SwingUserSettings.ICON_SIZE, 24))) { public void actionPerformed(ActionEvent e) { Rectangle rect = null; if ( playpen != null ) { for (int i = 0; i < playpen.getContentPane().getComponentCount(); i++) { PlayPenComponent ppc = playpen.getContentPane().getComponent(i); if ( rect == null ) { rect = new Rectangle(ppc.getLocation(),ppc.getSize()); } else { rect.add(ppc.getBounds()); } } } double zoom = playpen.getViewportSize().getHeight()/rect.height; double zoom1 = playpen.getViewportSize().getWidth()/rect.width; if ( zoom1 < zoom ) zoom = zoom1; zoom *= 0.95; playpen.setZoom(zoom); playpen.scrollRectToVisible(playpen.unzoomRect(rect)); } }; zoomAllAction.putValue(AbstractAction.SHORT_DESCRIPTION, "View All"); 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)); selectAllAction = new SelectAllAction(); selectAllAction.putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_A, accelMask)); menuBar = new JMenuBar(); //Settingup JMenu fileMenu = new JMenu("File"); fileMenu.setMnemonic('f'); fileMenu.add(newProjectAction); fileMenu.add(openProjectAction); fileMenu.add(recent); fileMenu.add(clearItem); fileMenu.addSeparator(); fileMenu.add(saveProjectAction); fileMenu.add(saveProjectAsAction); fileMenu.add(printAction); fileMenu.addSeparator(); fileMenu.add(prefAction); fileMenu.add(projectSettingsAction); fileMenu.add(saveSettingsAction); fileMenu.addSeparator(); fileMenu.add(exitAction); menuBar.add(fileMenu); JMenu editMenu = new JMenu("Edit"); editMenu.setMnemonic('e'); editMenu.add(undoAction); editMenu.add(redoAction); editMenu.addSeparator(); editMenu.add(selectAllAction); editMenu.addSeparator(); editMenu.add(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(exportPLTransAction); etlSubmenuOne.add(new JMenuItem("PL Transaction File Export")); etlSubmenuOne.add(new JMenuItem("Run Power*Loader")); etlSubmenuOne.add(quickStartAction); etlMenu.add(etlSubmenuOne); menuBar.add(etlMenu); JMenu toolsMenu = new JMenu("Tools"); toolsMenu.setMnemonic('t'); toolsMenu.add(exportDDLAction); toolsMenu.add(compareDMAction); menuBar.add(toolsMenu); JMenu helpMenu = new JMenu("Help"); helpMenu.setMnemonic('h'); helpMenu.add(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.add(compareDMAction); projectBar.addSeparator(); projectBar.add(autoLayoutAction); projectBar.setToolTipText("Project Toolbar"); projectBar.setName("Project Toolbar"); JButton tempButton = null; // shared actions need to report where they are coming from ppBar.setToolTipText("PlayPen Toolbar"); ppBar.setName("PlayPen ToolBar"); ppBar.add(zoomInAction); ppBar.add(zoomOutAction); ppBar.add(zoomNormalAction); ppBar.add(zoomAllAction); 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(prefs.getInt(SwingUserSettings.DIVIDER_LOCATION,150)); Rectangle bounds = new Rectangle(); bounds.x = prefs.getInt(SwingUserSettings.MAIN_FRAME_X, 40); bounds.y = prefs.getInt(SwingUserSettings.MAIN_FRAME_Y, 40); bounds.width = prefs.getInt(SwingUserSettings.MAIN_FRAME_WIDTH, 600); bounds.height = prefs.getInt(SwingUserSettings.MAIN_FRAME_HEIGHT, 440); setBounds(bounds); addWindowListener(afWindowListener = new ArchitectFrameWindowListener()); setProject(new SwingUIProject("New Project")); }
| 1,108,800
|
protected void init() throws ArchitectException { int accelMask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); prefs = PrefsUtils.getUserPrefsNode(architectSession); 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(getArchitectSession()); 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 { prefs.putInt(SwingUserSettings.DIVIDER_LOCATION, splitPane.getDividerLocation()); closeProject(getProject()); setProject(new SwingUIProject("New Project")); logger.debug("Glass pane is "+getGlassPane()); } 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)); final RecentMenu recent = new RecentMenu(this) { @Override public void loadFile(String fileName) throws IOException { openFile(fileName); } }; openProjectAction = new OpenProjectAction(recent); JMenuItem clearItem = new JMenuItem("Clear Recent Files"); clearItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { recent.clear(); } }); 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"); zoomAllAction = new AbstractAction("Zoom to fit", ASUtils.createJLFIcon("general/Zoom", "Reset Zoom", sprefs.getInt(SwingUserSettings.ICON_SIZE, 24))) { public void actionPerformed(ActionEvent e) { Rectangle rect = null; if ( playpen != null ) { for (int i = 0; i < playpen.getContentPane().getComponentCount(); i++) { PlayPenComponent ppc = playpen.getContentPane().getComponent(i); if ( i == 0 ) { rect = new Rectangle(ppc.getLocation(),ppc.getSize()); } else { rect.add(ppc.getBounds()); } } } double zoom = playpen.getViewportSize().getHeight()/rect.height; double zoom1 = playpen.getViewportSize().getWidth()/rect.width; if ( zoom1 < zoom ) zoom = zoom1; zoom *= 0.95; playpen.setZoom(zoom); playpen.scrollRectToVisible(playpen.unzoomRect(rect)); } }; zoomAllAction.putValue(AbstractAction.SHORT_DESCRIPTION, "View All"); 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)); selectAllAction = new SelectAllAction(); selectAllAction.putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_A, accelMask)); menuBar = new JMenuBar(); //Settingup JMenu fileMenu = new JMenu("File"); fileMenu.setMnemonic('f'); fileMenu.add(newProjectAction); fileMenu.add(openProjectAction); fileMenu.add(recent); fileMenu.add(clearItem); fileMenu.addSeparator(); fileMenu.add(saveProjectAction); fileMenu.add(saveProjectAsAction); fileMenu.add(printAction); fileMenu.addSeparator(); fileMenu.add(prefAction); fileMenu.add(projectSettingsAction); fileMenu.add(saveSettingsAction); fileMenu.addSeparator(); fileMenu.add(exitAction); menuBar.add(fileMenu); JMenu editMenu = new JMenu("Edit"); editMenu.setMnemonic('e'); editMenu.add(undoAction); editMenu.add(redoAction); editMenu.addSeparator(); editMenu.add(selectAllAction); editMenu.addSeparator(); editMenu.add(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(exportPLTransAction); etlSubmenuOne.add(new JMenuItem("PL Transaction File Export")); etlSubmenuOne.add(new JMenuItem("Run Power*Loader")); etlSubmenuOne.add(quickStartAction); etlMenu.add(etlSubmenuOne); menuBar.add(etlMenu); JMenu toolsMenu = new JMenu("Tools"); toolsMenu.setMnemonic('t'); toolsMenu.add(exportDDLAction); toolsMenu.add(compareDMAction); menuBar.add(toolsMenu); JMenu helpMenu = new JMenu("Help"); helpMenu.setMnemonic('h'); helpMenu.add(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.add(compareDMAction); projectBar.addSeparator(); projectBar.add(autoLayoutAction); projectBar.setToolTipText("Project Toolbar"); projectBar.setName("Project Toolbar"); JButton tempButton = null; // shared actions need to report where they are coming from ppBar.setToolTipText("PlayPen Toolbar"); ppBar.setName("PlayPen ToolBar"); ppBar.add(zoomInAction); ppBar.add(zoomOutAction); ppBar.add(zoomNormalAction); ppBar.add(zoomAllAction); 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(prefs.getInt(SwingUserSettings.DIVIDER_LOCATION,150)); Rectangle bounds = new Rectangle(); bounds.x = prefs.getInt(SwingUserSettings.MAIN_FRAME_X, 40); bounds.y = prefs.getInt(SwingUserSettings.MAIN_FRAME_Y, 40); bounds.width = prefs.getInt(SwingUserSettings.MAIN_FRAME_WIDTH, 600); bounds.height = prefs.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(); prefs = PrefsUtils.getUserPrefsNode(architectSession); 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(getArchitectSession()); 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 { prefs.putInt(SwingUserSettings.DIVIDER_LOCATION, splitPane.getDividerLocation()); closeProject(getProject()); setProject(new SwingUIProject("New Project")); logger.debug("Glass pane is "+getGlassPane()); } 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)); final RecentMenu recent = new RecentMenu(this) { @Override public void loadFile(String fileName) throws IOException { openFile(fileName); } }; openProjectAction = new OpenProjectAction(recent); JMenuItem clearItem = new JMenuItem("Clear Recent Files"); clearItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { recent.clear(); } }); 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"); zoomAllAction = new AbstractAction("Zoom to fit", ASUtils.createJLFIcon("general/Zoom", "Reset Zoom", sprefs.getInt(SwingUserSettings.ICON_SIZE, 24))) { public void actionPerformed(ActionEvent e) { Rectangle rect = null; if ( playpen != null ) { for (int i = 0; i < playpen.getContentPane().getComponentCount(); i++) { PlayPenComponent ppc = playpen.getContentPane().getComponent(i); if ( i == 0 ) { rect = new Rectangle(ppc.getLocation(),ppc.getSize()); } else { rect.add(ppc.getBounds()); } } } double zoom = playpen.getViewportSize().getHeight()/rect.height; double zoom1 = playpen.getViewportSize().getWidth()/rect.width; if ( zoom1 < zoom ) zoom = zoom1; zoom *= 0.95; playpen.setZoom(zoom); playpen.scrollRectToVisible(playpen.unzoomRect(rect)); } }; zoomAllAction.putValue(AbstractAction.SHORT_DESCRIPTION, "View All"); 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)); selectAllAction = new SelectAllAction(); selectAllAction.putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_A, accelMask)); menuBar = new JMenuBar(); //Settingup JMenu fileMenu = new JMenu("File"); fileMenu.setMnemonic('f'); fileMenu.add(newProjectAction); fileMenu.add(openProjectAction); fileMenu.add(recent); fileMenu.add(clearItem); fileMenu.addSeparator(); fileMenu.add(saveProjectAction); fileMenu.add(saveProjectAsAction); fileMenu.add(printAction); fileMenu.addSeparator(); fileMenu.add(prefAction); fileMenu.add(projectSettingsAction); fileMenu.add(saveSettingsAction); fileMenu.addSeparator(); fileMenu.add(exitAction); menuBar.add(fileMenu); JMenu editMenu = new JMenu("Edit"); editMenu.setMnemonic('e'); editMenu.add(undoAction); editMenu.add(redoAction); editMenu.addSeparator(); editMenu.add(selectAllAction); editMenu.addSeparator(); editMenu.add(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(exportPLTransAction); etlSubmenuOne.add(new JMenuItem("PL Transaction File Export")); etlSubmenuOne.add(new JMenuItem("Run Power*Loader")); etlSubmenuOne.add(quickStartAction); etlMenu.add(etlSubmenuOne); menuBar.add(etlMenu); JMenu toolsMenu = new JMenu("Tools"); toolsMenu.setMnemonic('t'); toolsMenu.add(exportDDLAction); toolsMenu.add(compareDMAction); menuBar.add(toolsMenu); JMenu helpMenu = new JMenu("Help"); helpMenu.setMnemonic('h'); helpMenu.add(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.add(compareDMAction); projectBar.addSeparator(); projectBar.add(autoLayoutAction); projectBar.setToolTipText("Project Toolbar"); projectBar.setName("Project Toolbar"); JButton tempButton = null; // shared actions need to report where they are coming from ppBar.setToolTipText("PlayPen Toolbar"); ppBar.setName("PlayPen ToolBar"); ppBar.add(zoomInAction); ppBar.add(zoomOutAction); ppBar.add(zoomNormalAction); ppBar.add(zoomAllAction); 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(prefs.getInt(SwingUserSettings.DIVIDER_LOCATION,150)); Rectangle bounds = new Rectangle(); bounds.x = prefs.getInt(SwingUserSettings.MAIN_FRAME_X, 40); bounds.y = prefs.getInt(SwingUserSettings.MAIN_FRAME_Y, 40); bounds.width = prefs.getInt(SwingUserSettings.MAIN_FRAME_WIDTH, 600); bounds.height = prefs.getInt(SwingUserSettings.MAIN_FRAME_HEIGHT, 440); setBounds(bounds); addWindowListener(afWindowListener = new ArchitectFrameWindowListener()); setProject(new SwingUIProject("New Project")); }
| 1,108,801
|
protected void init() throws ArchitectException { int accelMask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); prefs = PrefsUtils.getUserPrefsNode(architectSession); 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(getArchitectSession()); 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 { prefs.putInt(SwingUserSettings.DIVIDER_LOCATION, splitPane.getDividerLocation()); closeProject(getProject()); setProject(new SwingUIProject("New Project")); logger.debug("Glass pane is "+getGlassPane()); } 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)); final RecentMenu recent = new RecentMenu(this) { @Override public void loadFile(String fileName) throws IOException { openFile(fileName); } }; openProjectAction = new OpenProjectAction(recent); JMenuItem clearItem = new JMenuItem("Clear Recent Files"); clearItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { recent.clear(); } }); 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"); zoomAllAction = new AbstractAction("Zoom to fit", ASUtils.createJLFIcon("general/Zoom", "Reset Zoom", sprefs.getInt(SwingUserSettings.ICON_SIZE, 24))) { public void actionPerformed(ActionEvent e) { Rectangle rect = null; if ( playpen != null ) { for (int i = 0; i < playpen.getContentPane().getComponentCount(); i++) { PlayPenComponent ppc = playpen.getContentPane().getComponent(i); if ( i == 0 ) { rect = new Rectangle(ppc.getLocation(),ppc.getSize()); } else { rect.add(ppc.getBounds()); } } } double zoom = playpen.getViewportSize().getHeight()/rect.height; double zoom1 = playpen.getViewportSize().getWidth()/rect.width; if ( zoom1 < zoom ) zoom = zoom1; zoom *= 0.95; playpen.setZoom(zoom); playpen.scrollRectToVisible(playpen.unzoomRect(rect)); } }; zoomAllAction.putValue(AbstractAction.SHORT_DESCRIPTION, "View All"); 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)); selectAllAction = new SelectAllAction(); selectAllAction.putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_A, accelMask)); menuBar = new JMenuBar(); //Settingup JMenu fileMenu = new JMenu("File"); fileMenu.setMnemonic('f'); fileMenu.add(newProjectAction); fileMenu.add(openProjectAction); fileMenu.add(recent); fileMenu.add(clearItem); fileMenu.addSeparator(); fileMenu.add(saveProjectAction); fileMenu.add(saveProjectAsAction); fileMenu.add(printAction); fileMenu.addSeparator(); fileMenu.add(prefAction); fileMenu.add(projectSettingsAction); fileMenu.add(saveSettingsAction); fileMenu.addSeparator(); fileMenu.add(exitAction); menuBar.add(fileMenu); JMenu editMenu = new JMenu("Edit"); editMenu.setMnemonic('e'); editMenu.add(undoAction); editMenu.add(redoAction); editMenu.addSeparator(); editMenu.add(selectAllAction); editMenu.addSeparator(); editMenu.add(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(exportPLTransAction); etlSubmenuOne.add(new JMenuItem("PL Transaction File Export")); etlSubmenuOne.add(new JMenuItem("Run Power*Loader")); etlSubmenuOne.add(quickStartAction); etlMenu.add(etlSubmenuOne); menuBar.add(etlMenu); JMenu toolsMenu = new JMenu("Tools"); toolsMenu.setMnemonic('t'); toolsMenu.add(exportDDLAction); toolsMenu.add(compareDMAction); menuBar.add(toolsMenu); JMenu helpMenu = new JMenu("Help"); helpMenu.setMnemonic('h'); helpMenu.add(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.add(compareDMAction); projectBar.addSeparator(); projectBar.add(autoLayoutAction); projectBar.setToolTipText("Project Toolbar"); projectBar.setName("Project Toolbar"); JButton tempButton = null; // shared actions need to report where they are coming from ppBar.setToolTipText("PlayPen Toolbar"); ppBar.setName("PlayPen ToolBar"); ppBar.add(zoomInAction); ppBar.add(zoomOutAction); ppBar.add(zoomNormalAction); ppBar.add(zoomAllAction); 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(prefs.getInt(SwingUserSettings.DIVIDER_LOCATION,150)); Rectangle bounds = new Rectangle(); bounds.x = prefs.getInt(SwingUserSettings.MAIN_FRAME_X, 40); bounds.y = prefs.getInt(SwingUserSettings.MAIN_FRAME_Y, 40); bounds.width = prefs.getInt(SwingUserSettings.MAIN_FRAME_WIDTH, 600); bounds.height = prefs.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(); prefs = PrefsUtils.getUserPrefsNode(architectSession); 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(getArchitectSession()); 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 { prefs.putInt(SwingUserSettings.DIVIDER_LOCATION, splitPane.getDividerLocation()); closeProject(getProject()); setProject(new SwingUIProject("New Project")); logger.debug("Glass pane is "+getGlassPane()); } 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)); final RecentMenu recent = new RecentMenu(this) { @Override public void loadFile(String fileName) throws IOException { openFile(fileName); } }; openProjectAction = new OpenProjectAction(recent); JMenuItem clearItem = new JMenuItem("Clear Recent Files"); clearItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { recent.clear(); } }); 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"); zoomAllAction = new AbstractAction("Zoom to fit", ASUtils.createJLFIcon("general/Zoom", "Reset Zoom", sprefs.getInt(SwingUserSettings.ICON_SIZE, 24))) { public void actionPerformed(ActionEvent e) { Rectangle rect = null; if ( playpen != null ) { for (int i = 0; i < playpen.getContentPane().getComponentCount(); i++) { PlayPenComponent ppc = playpen.getContentPane().getComponent(i); if ( i == 0 ) { rect = new Rectangle(ppc.getLocation(),ppc.getSize()); } else { rect.add(ppc.getBounds()); } } } double zoom = playpen.getViewportSize().getHeight()/rect.height; double zoom1 = playpen.getViewportSize().getWidth()/rect.width; if ( zoom1 < zoom ) zoom = zoom1; zoom *= 0.95; playpen.setZoom(zoom); playpen.scrollRectToVisible(playpen.zoomRect(rect)); } }; zoomAllAction.putValue(AbstractAction.SHORT_DESCRIPTION, "View All"); 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)); selectAllAction = new SelectAllAction(); selectAllAction.putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_A, accelMask)); menuBar = new JMenuBar(); //Settingup JMenu fileMenu = new JMenu("File"); fileMenu.setMnemonic('f'); fileMenu.add(newProjectAction); fileMenu.add(openProjectAction); fileMenu.add(recent); fileMenu.add(clearItem); fileMenu.addSeparator(); fileMenu.add(saveProjectAction); fileMenu.add(saveProjectAsAction); fileMenu.add(printAction); fileMenu.addSeparator(); fileMenu.add(prefAction); fileMenu.add(projectSettingsAction); fileMenu.add(saveSettingsAction); fileMenu.addSeparator(); fileMenu.add(exitAction); menuBar.add(fileMenu); JMenu editMenu = new JMenu("Edit"); editMenu.setMnemonic('e'); editMenu.add(undoAction); editMenu.add(redoAction); editMenu.addSeparator(); editMenu.add(selectAllAction); editMenu.addSeparator(); editMenu.add(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(exportPLTransAction); etlSubmenuOne.add(new JMenuItem("PL Transaction File Export")); etlSubmenuOne.add(new JMenuItem("Run Power*Loader")); etlSubmenuOne.add(quickStartAction); etlMenu.add(etlSubmenuOne); menuBar.add(etlMenu); JMenu toolsMenu = new JMenu("Tools"); toolsMenu.setMnemonic('t'); toolsMenu.add(exportDDLAction); toolsMenu.add(compareDMAction); menuBar.add(toolsMenu); JMenu helpMenu = new JMenu("Help"); helpMenu.setMnemonic('h'); helpMenu.add(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.add(compareDMAction); projectBar.addSeparator(); projectBar.add(autoLayoutAction); projectBar.setToolTipText("Project Toolbar"); projectBar.setName("Project Toolbar"); JButton tempButton = null; // shared actions need to report where they are coming from ppBar.setToolTipText("PlayPen Toolbar"); ppBar.setName("PlayPen ToolBar"); ppBar.add(zoomInAction); ppBar.add(zoomOutAction); ppBar.add(zoomNormalAction); ppBar.add(zoomAllAction); 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(prefs.getInt(SwingUserSettings.DIVIDER_LOCATION,150)); Rectangle bounds = new Rectangle(); bounds.x = prefs.getInt(SwingUserSettings.MAIN_FRAME_X, 40); bounds.y = prefs.getInt(SwingUserSettings.MAIN_FRAME_Y, 40); bounds.width = prefs.getInt(SwingUserSettings.MAIN_FRAME_WIDTH, 600); bounds.height = prefs.getInt(SwingUserSettings.MAIN_FRAME_HEIGHT, 440); setBounds(bounds); addWindowListener(afWindowListener = new ArchitectFrameWindowListener()); setProject(new SwingUIProject("New Project")); }
| 1,108,802
|
protected void init() throws ArchitectException { int accelMask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); prefs = PrefsUtils.getUserPrefsNode(architectSession); 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(getArchitectSession()); 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 { prefs.putInt(SwingUserSettings.DIVIDER_LOCATION, splitPane.getDividerLocation()); closeProject(getProject()); setProject(new SwingUIProject("New Project")); logger.debug("Glass pane is "+getGlassPane()); } 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)); final RecentMenu recent = new RecentMenu(this) { @Override public void loadFile(String fileName) throws IOException { openFile(fileName); } }; openProjectAction = new OpenProjectAction(recent); JMenuItem clearItem = new JMenuItem("Clear Recent Files"); clearItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { recent.clear(); } }); 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"); zoomAllAction = new AbstractAction("Zoom to fit", ASUtils.createJLFIcon("general/Zoom", "Reset Zoom", sprefs.getInt(SwingUserSettings.ICON_SIZE, 24))) { public void actionPerformed(ActionEvent e) { Rectangle rect = null; if ( playpen != null ) { for (int i = 0; i < playpen.getContentPane().getComponentCount(); i++) { PlayPenComponent ppc = playpen.getContentPane().getComponent(i); if ( i == 0 ) { rect = new Rectangle(ppc.getLocation(),ppc.getSize()); } else { rect.add(ppc.getBounds()); } } } double zoom = playpen.getViewportSize().getHeight()/rect.height; double zoom1 = playpen.getViewportSize().getWidth()/rect.width; if ( zoom1 < zoom ) zoom = zoom1; zoom *= 0.95; playpen.setZoom(zoom); playpen.scrollRectToVisible(playpen.unzoomRect(rect)); } }; zoomAllAction.putValue(AbstractAction.SHORT_DESCRIPTION, "View All"); 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)); selectAllAction = new SelectAllAction(); selectAllAction.putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_A, accelMask)); menuBar = new JMenuBar(); //Settingup JMenu fileMenu = new JMenu("File"); fileMenu.setMnemonic('f'); fileMenu.add(newProjectAction); fileMenu.add(openProjectAction); fileMenu.add(recent); fileMenu.add(clearItem); fileMenu.addSeparator(); fileMenu.add(saveProjectAction); fileMenu.add(saveProjectAsAction); fileMenu.add(printAction); fileMenu.addSeparator(); fileMenu.add(prefAction); fileMenu.add(projectSettingsAction); fileMenu.add(saveSettingsAction); fileMenu.addSeparator(); fileMenu.add(exitAction); menuBar.add(fileMenu); JMenu editMenu = new JMenu("Edit"); editMenu.setMnemonic('e'); editMenu.add(undoAction); editMenu.add(redoAction); editMenu.addSeparator(); editMenu.add(selectAllAction); editMenu.addSeparator(); editMenu.add(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(exportPLTransAction); etlSubmenuOne.add(new JMenuItem("PL Transaction File Export")); etlSubmenuOne.add(new JMenuItem("Run Power*Loader")); etlSubmenuOne.add(quickStartAction); etlMenu.add(etlSubmenuOne); menuBar.add(etlMenu); JMenu toolsMenu = new JMenu("Tools"); toolsMenu.setMnemonic('t'); toolsMenu.add(exportDDLAction); toolsMenu.add(compareDMAction); menuBar.add(toolsMenu); JMenu helpMenu = new JMenu("Help"); helpMenu.setMnemonic('h'); helpMenu.add(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.add(compareDMAction); projectBar.addSeparator(); projectBar.add(autoLayoutAction); projectBar.setToolTipText("Project Toolbar"); projectBar.setName("Project Toolbar"); JButton tempButton = null; // shared actions need to report where they are coming from ppBar.setToolTipText("PlayPen Toolbar"); ppBar.setName("PlayPen ToolBar"); ppBar.add(zoomInAction); ppBar.add(zoomOutAction); ppBar.add(zoomNormalAction); ppBar.add(zoomAllAction); 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(prefs.getInt(SwingUserSettings.DIVIDER_LOCATION,150)); Rectangle bounds = new Rectangle(); bounds.x = prefs.getInt(SwingUserSettings.MAIN_FRAME_X, 40); bounds.y = prefs.getInt(SwingUserSettings.MAIN_FRAME_Y, 40); bounds.width = prefs.getInt(SwingUserSettings.MAIN_FRAME_WIDTH, 600); bounds.height = prefs.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(); prefs = PrefsUtils.getUserPrefsNode(architectSession); 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(getArchitectSession()); 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 { prefs.putInt(SwingUserSettings.DIVIDER_LOCATION, splitPane.getDividerLocation()); closeProject(getProject()); setProject(new SwingUIProject("New Project")); logger.debug("Glass pane is "+getGlassPane()); } 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)); final RecentMenu recent = new RecentMenu(this) { @Override public void loadFile(String fileName) throws IOException { openFile(fileName); } }; openProjectAction = new OpenProjectAction(recent); JMenuItem clearItem = new JMenuItem("Clear Recent Files"); clearItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { recent.clear(); } }); 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"); zoomAllAction = new AbstractAction("Zoom to fit", ASUtils.createJLFIcon("general/Zoom", "Reset Zoom", sprefs.getInt(SwingUserSettings.ICON_SIZE, 24))) { public void actionPerformed(ActionEvent e) { Rectangle rect = null; if ( playpen != null ) { for (int i = 0; i < playpen.getContentPane().getComponentCount(); i++) { PlayPenComponent ppc = playpen.getContentPane().getComponent(i); if ( i == 0 ) { rect = new Rectangle(ppc.getLocation(),ppc.getSize()); } else { rect.add(ppc.getBounds()); } } } double zoom = playpen.getViewportSize().getHeight()/rect.height; double zoom1 = playpen.getViewportSize().getWidth()/rect.width; if ( zoom1 < zoom ) zoom = zoom1; zoom *= 0.95; playpen.setZoom(zoom); playpen.scrollRectToVisible(playpen.unzoomRect(rect)); } }; zoomAllAction.putValue(AbstractAction.SHORT_DESCRIPTION, "Zoom to fit"); 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)); selectAllAction = new SelectAllAction(); selectAllAction.putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_A, accelMask)); menuBar = new JMenuBar(); //Settingup JMenu fileMenu = new JMenu("File"); fileMenu.setMnemonic('f'); fileMenu.add(newProjectAction); fileMenu.add(openProjectAction); fileMenu.add(recent); fileMenu.add(clearItem); fileMenu.addSeparator(); fileMenu.add(saveProjectAction); fileMenu.add(saveProjectAsAction); fileMenu.add(printAction); fileMenu.addSeparator(); fileMenu.add(prefAction); fileMenu.add(projectSettingsAction); fileMenu.add(saveSettingsAction); fileMenu.addSeparator(); fileMenu.add(exitAction); menuBar.add(fileMenu); JMenu editMenu = new JMenu("Edit"); editMenu.setMnemonic('e'); editMenu.add(undoAction); editMenu.add(redoAction); editMenu.addSeparator(); editMenu.add(selectAllAction); editMenu.addSeparator(); editMenu.add(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(exportPLTransAction); etlSubmenuOne.add(new JMenuItem("PL Transaction File Export")); etlSubmenuOne.add(new JMenuItem("Run Power*Loader")); etlSubmenuOne.add(quickStartAction); etlMenu.add(etlSubmenuOne); menuBar.add(etlMenu); JMenu toolsMenu = new JMenu("Tools"); toolsMenu.setMnemonic('t'); toolsMenu.add(exportDDLAction); toolsMenu.add(compareDMAction); menuBar.add(toolsMenu); JMenu helpMenu = new JMenu("Help"); helpMenu.setMnemonic('h'); helpMenu.add(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.add(compareDMAction); projectBar.addSeparator(); projectBar.add(autoLayoutAction); projectBar.setToolTipText("Project Toolbar"); projectBar.setName("Project Toolbar"); JButton tempButton = null; // shared actions need to report where they are coming from ppBar.setToolTipText("PlayPen Toolbar"); ppBar.setName("PlayPen ToolBar"); ppBar.add(zoomInAction); ppBar.add(zoomOutAction); ppBar.add(zoomNormalAction); ppBar.add(zoomAllAction); 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(prefs.getInt(SwingUserSettings.DIVIDER_LOCATION,150)); Rectangle bounds = new Rectangle(); bounds.x = prefs.getInt(SwingUserSettings.MAIN_FRAME_X, 40); bounds.y = prefs.getInt(SwingUserSettings.MAIN_FRAME_Y, 40); bounds.width = prefs.getInt(SwingUserSettings.MAIN_FRAME_WIDTH, 600); bounds.height = prefs.getInt(SwingUserSettings.MAIN_FRAME_HEIGHT, 440); setBounds(bounds); addWindowListener(afWindowListener = new ArchitectFrameWindowListener()); setProject(new SwingUIProject("New Project")); }
| 1,108,803
|
public void actionPerformed(ActionEvent e) { Rectangle rect = null; if ( playpen != null ) { for (int i = 0; i < playpen.getContentPane().getComponentCount(); i++) { PlayPenComponent ppc = playpen.getContentPane().getComponent(i); if ( i == 0 ) { rect = new Rectangle(ppc.getLocation(),ppc.getSize()); } else { rect.add(ppc.getBounds()); } } } double zoom = playpen.getViewportSize().getHeight()/rect.height; double zoom1 = playpen.getViewportSize().getWidth()/rect.width; if ( zoom1 < zoom ) zoom = zoom1; zoom *= 0.95; playpen.setZoom(zoom); playpen.scrollRectToVisible(playpen.unzoomRect(rect)); }
|
public void actionPerformed(ActionEvent e) { Rectangle rect = null; if ( playpen != null ) { for (int i = 0; i < playpen.getContentPane().getComponentCount(); i++) { PlayPenComponent ppc = playpen.getContentPane().getComponent(i); if ( rect == null ) { rect = new Rectangle(ppc.getLocation(),ppc.getSize()); } else { rect.add(ppc.getBounds()); } } } double zoom = playpen.getViewportSize().getHeight()/rect.height; double zoom1 = playpen.getViewportSize().getWidth()/rect.width; if ( zoom1 < zoom ) zoom = zoom1; zoom *= 0.95; playpen.setZoom(zoom); playpen.scrollRectToVisible(playpen.unzoomRect(rect)); }
| 1,108,804
|
public void actionPerformed(ActionEvent e) { Rectangle rect = null; if ( playpen != null ) { for (int i = 0; i < playpen.getContentPane().getComponentCount(); i++) { PlayPenComponent ppc = playpen.getContentPane().getComponent(i); if ( i == 0 ) { rect = new Rectangle(ppc.getLocation(),ppc.getSize()); } else { rect.add(ppc.getBounds()); } } } double zoom = playpen.getViewportSize().getHeight()/rect.height; double zoom1 = playpen.getViewportSize().getWidth()/rect.width; if ( zoom1 < zoom ) zoom = zoom1; zoom *= 0.95; playpen.setZoom(zoom); playpen.scrollRectToVisible(playpen.unzoomRect(rect)); }
|
public void actionPerformed(ActionEvent e) { Rectangle rect = null; if ( playpen != null ) { for (int i = 0; i < playpen.getContentPane().getComponentCount(); i++) { PlayPenComponent ppc = playpen.getContentPane().getComponent(i); if ( i == 0 ) { rect = new Rectangle(ppc.getLocation(),ppc.getSize()); } else { rect.add(ppc.getBounds()); } } } double zoom = playpen.getViewportSize().getHeight()/rect.height; double zoom1 = playpen.getViewportSize().getWidth()/rect.width; if ( zoom1 < zoom ) zoom = zoom1; zoom *= 0.95; playpen.setZoom(zoom); playpen.scrollRectToVisible(playpen.unzoomRect(rect)); }
| 1,108,805
|
public void actionPerformed(ActionEvent e) { Rectangle rect = null; if ( playpen != null ) { for (int i = 0; i < playpen.getContentPane().getComponentCount(); i++) { PlayPenComponent ppc = playpen.getContentPane().getComponent(i); if ( i == 0 ) { rect = new Rectangle(ppc.getLocation(),ppc.getSize()); } else { rect.add(ppc.getBounds()); } } } double zoom = playpen.getViewportSize().getHeight()/rect.height; double zoom1 = playpen.getViewportSize().getWidth()/rect.width; if ( zoom1 < zoom ) zoom = zoom1; zoom *= 0.95; playpen.setZoom(zoom); playpen.scrollRectToVisible(playpen.unzoomRect(rect)); }
|
public void actionPerformed(ActionEvent e) { Rectangle rect = null; if ( playpen != null ) { for (int i = 0; i < playpen.getContentPane().getComponentCount(); i++) { PlayPenComponent ppc = playpen.getContentPane().getComponent(i); if ( i == 0 ) { rect = new Rectangle(ppc.getLocation(),ppc.getSize()); } else { rect.add(ppc.getBounds()); } } } double zoom = playpen.getViewportSize().getHeight()/rect.height; double zoom1 = playpen.getViewportSize().getWidth()/rect.width; if ( zoom1 < zoom ) zoom = zoom1; zoom *= 0.95; playpen.setZoom(zoom); playpen.scrollRectToVisible(playpen.zoomRect(rect)); }
| 1,108,806
|
public void addDatabase( PVDatabase db ) { databases.put( db.getName(), db ); }
|
public void addDatabase( PVDatabase db ) throws PhotovaultException { if ( databases.containsKey( db.getName() ) ) { throw new PhotovaultException( "Database " + db.getDbName() + " already exists!" ); } databases.put( db.getName(), db ); }
| 1,108,807
|
private static ConnectorRegistry create(ApplicationConfig config) throws Exception { Map paramValues = config.getParamValues(); String appId = config.getApplicationId(); String connectorId = (String) paramValues.get("connectorId"); File file1 = new File(CoreUtils.getConnectorDir() + File.separatorChar + connectorId); URL[] urls = new URL[]{file1.toURL()}; ClassLoader cl = ClassLoaderRepository.getClassLoader(urls, true); //URLClassLoader cl = new URLClassLoader(urls, // ConnectorMBeanRegistry.class.getClassLoader()); Registry.MODELER_MANIFEST = MBEANS_DESCRIPTOR; URL res = cl.getResource(MBEANS_DESCRIPTOR); logger.log(Level.INFO, "Application ID : " + appId); logger.log(Level.INFO, "Connector Archive: " + file1.getAbsoluteFile()); logger.log(Level.INFO, "MBean Descriptor : " + res.toString()); //Thread.currentThread().setContextClassLoader(cl); //Registry.setUseContextClassLoader(true); ConnectorRegistry registry = new ConnectorRegistry(); registry.loadMetadata(cl); String[] mbeans = registry.findManagedBeans(); MBeanServer server = MBeanServerFactory.newMBeanServer(DOMAIN_CONNECTOR); String objName = ":appId=" + appId + ",appType=connector,appName=" + config.getName()+ ",connectorType=" + connectorId; for (int i = 0; i < mbeans.length; i++) { ManagedBean managed = registry.findManagedBean(mbeans[i]); String clsName = managed.getType(); String domain = managed.getDomain(); if (domain == null) { domain = DOMAIN_CONNECTOR; } Class cls = Class.forName(clsName, true, cl); Object objMBean = null; // Use the factory method when it is defined. Method[] methods = cls.getMethods(); for (Method method : methods) { if (method.getName().equals(FACTORY_METHOD) && Modifier.isStatic(method.getModifiers())) { objMBean = method.invoke(null); logger.log(Level.INFO, "Create MBean using factory method."); break; } } if (objMBean == null) { objMBean = cls.newInstance(); } // Call the initialize method if the MBean extends ConnectorSupport class if (cls.getSuperclass().getName().equals(CLASS_CONNECTOR_SUPPORT)) { Method method = cls.getMethod("initialize", new Class[] {Map.class}); Map props = config.getParamValues(); method.invoke(objMBean, new Object[] {props}); } ModelMBean mm = managed.createMBean(objMBean); String beanObjName = domain + objName + ",name=" + mbeans[i]; server.registerMBean(mm, new ObjectName(beanObjName)); } registry.setMBeanServer(server); entries.put(appId, registry); return registry; }
|
private static ConnectorRegistry create(ApplicationConfig config) throws Exception { Map paramValues = config.getParamValues(); String appId = config.getApplicationId(); String connectorId = (String) paramValues.get("connectorId"); File file1 = new File(CoreUtils.getConnectorDir() + File.separatorChar + connectorId); URL[] urls = new URL[]{file1.toURL()}; ClassLoader cl = ClassLoaderRepository.getClassLoader(urls, true); //URLClassLoader cl = new URLClassLoader(urls, // ConnectorMBeanRegistry.class.getClassLoader()); Registry.MODELER_MANIFEST = MBEANS_DESCRIPTOR; URL res = cl.getResource(MBEANS_DESCRIPTOR); logger.log(Level.INFO, "Application ID : " + appId); logger.log(Level.INFO, "Connector Archive: " + file1.getAbsoluteFile()); logger.log(Level.INFO, "MBean Descriptor : " + res.toString()); //Thread.currentThread().setContextClassLoader(cl); //Registry.setUseContextClassLoader(true); ConnectorRegistry registry = new ConnectorRegistry(); registry.loadMetadata(cl); String[] mbeans = registry.findManagedBeans(); MBeanServer server = MBeanServerFactory.newMBeanServer(DOMAIN_CONNECTOR); String objName = ":appId=" + appId + ",appType=connector,appName=" + config.getName()+ ",connectorType=" + connectorId; for (int i = 0; i < mbeans.length; i++) { ManagedBean managed = registry.findManagedBean(mbeans[i]); String clsName = managed.getType(); String domain = managed.getDomain(); if (domain == null) { domain = DOMAIN_CONNECTOR; } Class cls = Class.forName(clsName, true, cl); Object objMBean = null; // Use the factory method when it is defined. Method[] methods = cls.getMethods(); for (Method method : methods) { if (method.getName().equals(FACTORY_METHOD) && Modifier.isStatic(method.getModifiers())) { objMBean = method.invoke(null); logger.log(Level.INFO, "Create MBean using factory method."); break; } } if (objMBean == null) { objMBean = cls.newInstance(); } // Call the initialize method if the MBean extends ConnectorSupport class if (objMBean instanceof ConnectorSupport) { Method method = cls.getMethod("initialize", new Class[] {Map.class}); Map props = config.getParamValues(); method.invoke(objMBean, new Object[] {props}); } ModelMBean mm = managed.createMBean(objMBean); String beanObjName = domain + objName + ",name=" + mbeans[i]; server.registerMBean(mm, new ObjectName(beanObjName)); } registry.setMBeanServer(server); entries.put(appId, registry); return registry; }
| 1,108,808
|
public void doTag(XMLOutput output) throws Exception { if ( log.isDebugEnabled() ) { log.debug( "Running body: " + getBody() ); } getBody().run(context, output); }
|
public void doTag(XMLOutput output) throws Exception { if ( log.isDebugEnabled() ) { log.debug( "Running body: " + getBody() ); } invokeBody(output); }
| 1,108,809
|
public static void main(String[] args) throws Exception { try { if (args.length <= 0) { System.out.println("Usage: Jelly scriptFile [outputFile]"); return; } Jelly jelly = new Jelly(); jelly.setScript(args[0]); // later we might wanna add some command line arguments // checking stuff using commons-cli to specify the output file // and input file via command line arguments final Writer writer = ( args.length > 1 ) ? new FileWriter( args[1] ) : new OutputStreamWriter( System.out ); Script script = jelly.compileScript(); XMLOutput output = XMLOutput.createXMLOutput(writer); // add the system properties and the command line arguments JellyContext context = jelly.getJellyContext(); context.setVariable("args", args); script.run(context, output); // now lets wait for all threads to close Runtime.getRuntime().addShutdownHook( new Thread() { public void run() { try { writer.close(); } catch (Exception e) { // ignore errors } } } ); } catch (JellyException e) { Throwable cause = e.getCause(); if ( cause != null ) { cause.printStackTrace(); } else { e.printStackTrace(); } } }
|
public static void main(String[] args) throws Exception { try { if (args.length <= 0) { System.out.println("Usage: Jelly scriptFile [outputFile]"); return; } Jelly jelly = new Jelly(); jelly.setScript(args[0]); // later we might wanna add some command line arguments // checking stuff using commons-cli to specify the output file // and input file via command line arguments final Writer writer = ( args.length > 1 ) ? new FileWriter( args[1] ) : new OutputStreamWriter( System.out ); Script script = jelly.compileScript(); XMLOutput output = XMLOutput.createXMLOutput(writer); // add the system properties and the command line arguments JellyContext context = jelly.getJellyContext(); context.setVariable("args", args); script.run(context, output); // now lets wait for all threads to close Runtime.getRuntime().addShutdownHook( new Thread() { public void run() { try { writer.close(); } catch (Exception e) { // ignore errors } } } ); } catch (JellyException e) { Throwable cause = e.getCause(); if ( cause != null ) { cause.printStackTrace(); } else { e.printStackTrace(); } } }
| 1,108,810
|
public static void main(String[] args) throws Exception { try { if (args.length <= 0) { System.out.println("Usage: Jelly scriptFile [outputFile]"); return; } Jelly jelly = new Jelly(); jelly.setScript(args[0]); // later we might wanna add some command line arguments // checking stuff using commons-cli to specify the output file // and input file via command line arguments final Writer writer = ( args.length > 1 ) ? new FileWriter( args[1] ) : new OutputStreamWriter( System.out ); Script script = jelly.compileScript(); XMLOutput output = XMLOutput.createXMLOutput(writer); // add the system properties and the command line arguments JellyContext context = jelly.getJellyContext(); context.setVariable("args", args); script.run(context, output); // now lets wait for all threads to close Runtime.getRuntime().addShutdownHook( new Thread() { public void run() { try { writer.close(); } catch (Exception e) { // ignore errors } } } ); } catch (JellyException e) { Throwable cause = e.getCause(); if ( cause != null ) { cause.printStackTrace(); } else { e.printStackTrace(); } } }
|
public static void main(String[] args) throws Exception { try { if (args.length <= 0) { System.out.println("Usage: Jelly scriptFile [outputFile]"); return; } Jelly jelly = new Jelly(); jelly.setScript(args[0]); // later we might wanna add some command line arguments // checking stuff using commons-cli to specify the output file // and input file via command line arguments final Writer writer = ( args.length > 1 ) ? new FileWriter( args[1] ) : new OutputStreamWriter( System.out ); Script script = jelly.compileScript(); // add the system properties and the command line arguments JellyContext context = jelly.getJellyContext(); context.setVariable("args", args); script.run(context, output); // now lets wait for all threads to close Runtime.getRuntime().addShutdownHook( new Thread() { public void run() { try { writer.close(); } catch (Exception e) { // ignore errors } } } ); } catch (JellyException e) { Throwable cause = e.getCause(); if ( cause != null ) { cause.printStackTrace(); } else { e.printStackTrace(); } } }
| 1,108,811
|
public static void main(String[] args) throws Exception { try { if (args.length <= 0) { System.out.println("Usage: Jelly scriptFile [outputFile]"); return; } Jelly jelly = new Jelly(); jelly.setScript(args[0]); // later we might wanna add some command line arguments // checking stuff using commons-cli to specify the output file // and input file via command line arguments final Writer writer = ( args.length > 1 ) ? new FileWriter( args[1] ) : new OutputStreamWriter( System.out ); Script script = jelly.compileScript(); XMLOutput output = XMLOutput.createXMLOutput(writer); // add the system properties and the command line arguments JellyContext context = jelly.getJellyContext(); context.setVariable("args", args); script.run(context, output); // now lets wait for all threads to close Runtime.getRuntime().addShutdownHook( new Thread() { public void run() { try { writer.close(); } catch (Exception e) { // ignore errors } } } ); } catch (JellyException e) { Throwable cause = e.getCause(); if ( cause != null ) { cause.printStackTrace(); } else { e.printStackTrace(); } } }
|
public static void main(String[] args) throws Exception { try { if (args.length <= 0) { System.out.println("Usage: Jelly scriptFile [outputFile]"); return; } Jelly jelly = new Jelly(); jelly.setScript(args[0]); // later we might wanna add some command line arguments // checking stuff using commons-cli to specify the output file // and input file via command line arguments final Writer writer = ( args.length > 1 ) ? new FileWriter( args[1] ) : new OutputStreamWriter( System.out ); Script script = jelly.compileScript(); XMLOutput output = XMLOutput.createXMLOutput(writer); // add the system properties and the command line arguments JellyContext context = jelly.getJellyContext(); context.setVariable("args", args); script.run(context, output); // now lets wait for all threads to close Runtime.getRuntime().addShutdownHook( new Thread() { public void run() { try { output.close(); } catch (Exception e) { // ignore errors } } } ); } catch (JellyException e) { Throwable cause = e.getCause(); if ( cause != null ) { cause.printStackTrace(); } else { e.printStackTrace(); } } }
| 1,108,812
|
public void run() { try { writer.close(); } catch (Exception e) { // ignore errors } }
|
public void run() { try { output.close(); } catch (Exception e) { // ignore errors } }
| 1,108,813
|
public void run(Context context, XMLOutput output) throws Exception { // Try find find the body from the reserved 'org.apache.commons.jelly.body' variable Script script = (Script) context.getVariable( "org.apache.commons.jelly.body" ); if ( script != null ) { script.run( context, output ); } else { // note this mechanism does not work properly for arbitrarily // nested dynamic tags. A better way is required. Tag tag = findAncestorWithClass(this, DynamicTag.class); if ( tag == null ) { throw new JellyException( "Cannot invoke body, no dynamic tag is defined in this block" ); } else { tag.getBody().run(context, output); } } }
|
public void run(JellyContext context, XMLOutput output) throws Exception { // Try find find the body from the reserved 'org.apache.commons.jelly.body' variable Script script = (Script) context.getVariable( "org.apache.commons.jelly.body" ); if ( script != null ) { script.run( context, output ); } else { // note this mechanism does not work properly for arbitrarily // nested dynamic tags. A better way is required. Tag tag = findAncestorWithClass(this, DynamicTag.class); if ( tag == null ) { throw new JellyException( "Cannot invoke body, no dynamic tag is defined in this block" ); } else { tag.getBody().run(context, output); } } }
| 1,108,814
|
protected Stylesheet createStylesheet() { // add default actions Stylesheet answer = new Stylesheet(); answer.setValueOfAction( new Action() { public void run(Node node) throws Exception { String text = node.getStringValue(); if ( text != null && text.length() > 0 ) { // #### should use an 'output' property // when this variable gets reused output.write( text ); } } } ); return answer; }
|
protected Stylesheet createStylesheet(final XMLOutput output) { // add default actions Stylesheet answer = new Stylesheet(); answer.setValueOfAction( new Action() { public void run(Node node) throws Exception { String text = node.getStringValue(); if ( text != null && text.length() > 0 ) { // #### should use an 'output' property // when this variable gets reused output.write( text ); } } } ); return answer; }
| 1,108,815
|
public void doTag(XMLOutput output) throws Exception { // for use by inner classes this.output = output; Stylesheet stylesheet = getStylesheet(); stylesheet.clear(); // run the body to add the rules invokeBody(output); stylesheet.setModeName(getMode()); if (var != null) { context.setVariable(var, stylesheet); } else { Object source = getSource(); if (log.isDebugEnabled()) { log.debug("About to evaluate stylesheet on source: " + source); } stylesheet.run(source); } }
|
public void doTag(XMLOutput output) throws Exception { // for use by inner classes this.output = output; Stylesheet stylesheet = getStylesheet(); stylesheet.clear(); // run the body to add the rules invokeBody(output); stylesheet.setModeName(getMode()); if (var != null) { context.setVariable(var, stylesheet); } else { Object source = getSource(); if (log.isDebugEnabled()) { log.debug("About to evaluate stylesheet on source: " + source); } stylesheet.run(source); } }
| 1,108,816
|
public Stylesheet getStylesheet() { if ( stylesheet == null ) { stylesheet = createStylesheet(); } return stylesheet; }
|
public Stylesheet getStylesheet() { if ( stylesheet == null ) { stylesheet = createStylesheet(); } return stylesheet; }
| 1,108,817
|
public static void main(String[] args) throws Exception{ /* display info */ message(); /* get password from user */ char[] password = getPassword(); if(password == null){ return; } EncryptedKey encryptedKey = new EncryptedKey(password); /* write the encryptedKey to the key file */ KeyManager.writeKey(encryptedKey); List roles = new ArrayList(1); UserManager.getInstance().addUser(new User(AuthConstants.USER_ADMIN, Crypto.hash(password), roles, "A", 0)); /* clear the password, for security reasons */ Arrays.fill(password, ' '); System.out.println(); System.out.println("Encrypted key written to " + KeyManager.KEY_FILE_NAME + " file."); }
|
public static void main(String[] args) throws Exception{ /* display info */ message(); /* get password from user */ char[] password = getPassword(); if(password == null){ return; } EncryptedKey encryptedKey = new EncryptedKey(password); /* write the encryptedKey to the key file */ KeyManager.writeKey(encryptedKey); List roles = new ArrayList(1); UserManager.getInstance().addUser(new User(AuthConstants.USER_ADMIN, Crypto.hash(password), roles, User.STATUS_ACTIVE, 0)); /* clear the password, for security reasons */ Arrays.fill(password, ' '); System.out.println(); System.out.println("Encrypted key written to " + KeyManager.KEY_FILE_NAME + " file."); }
| 1,108,818
|
public synchronized void setupDialog() { logger.debug("running setupDialog()"); // always refresh Target Database (it might have changed) plexp.setTargetDataSource(ArchitectFrame.getMainInstance().getProject().getTargetDatabase().getDataSource()); if (d != null) { refreshConnections(); return; } d = new JDialog(ArchitectFrame.getMainInstance(), "Export ETL Transactions to PL Repository"); // set export defaults if necessary if (plexp.getFolderName() == null || plexp.getFolderName().trim().length() == 0) { plexp.setFolderName(PLUtils.toPLIdentifier(architectFrame.getProject().getName()+"_FOLDER")); } if (plexp.getJobId() == null || plexp.getJobId().trim().length() == 0) { plexp.setJobId(PLUtils.toPLIdentifier(architectFrame.getProject().getName()+"_JOB")); } JPanel plp = new JPanel(new BorderLayout(12,12)); plp.setBorder(BorderFactory.createEmptyBorder(12,12,12,12)); final PLExportPanel plPanel = new PLExportPanel(); plPanel.setPLExport(plexp); plp.add(plPanel, BorderLayout.CENTER); // make an intermediate JPanel JPanel bottomPanel = new JPanel(new GridLayout(1,2,25,0)); // 25 pixel hgap JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); JButton okButton = new JButton("Ok"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { plPanel.applyChanges(); // make sure the user selected a target database if (plexp.getTargetDataSource() == null) { JOptionPane.showMessageDialog(plPanel, "You have to select a Target database from the list.", "Error", JOptionPane.ERROR_MESSAGE); return; } if (plexp.getRepositoryDataSource() == null) { JOptionPane.showMessageDialog(plPanel, "You have to select a Repository database from the list.", "Error", JOptionPane.ERROR_MESSAGE); return; } // make sure user provided a PL Job Name if (plexp.getJobId().trim().length() == 0) { JOptionPane.showMessageDialog(plPanel, "You have to specify the PowerLoader Job ID.", "Error", JOptionPane.ERROR_MESSAGE); return; } // make sure we have an engine! if (plexp.getRunPLEngine()) { String plEngineSpec = architectFrame.getUserSettings().getETLUserSettings().getPowerLoaderEnginePath(); if (plEngineSpec == null || plEngineSpec.length() == 0) { // not set yet, so redirect the user to User Settings dialog JOptionPane.showMessageDialog (plPanel,"Please specify the location of the PL Engine (powerloader_odbc.exe)."); // ArchitectFrame.getMainInstance().prefAction.showPreferencesDialog(); return; } } String dupIdMessage = null; try { if (checkForDuplicateJobId(plexp.getJobId()) == true) { dupIdMessage = "There is already a job called \""+ plexp.getJobId()+"\".\n"+"Please choose a different job id."; } } catch (SQLException ex) { dupIdMessage = "There was a database error when checking for\n"+"duplicate job id:\n\n"+ex.getMessage(); } catch (ArchitectException ex) { dupIdMessage = "There was an application error when checking for\n"+"duplicate job id:\n\n"+ex.getMessage(); } if (dupIdMessage != null) { JOptionPane.showMessageDialog(plPanel, dupIdMessage, "Error", JOptionPane.ERROR_MESSAGE); return; } try { List targetDBWarnings = listMissingTargetTables(); if (!targetDBWarnings.isEmpty()) { // modal dialog (hold things up until the user says YES or NO) JList warnings = new JList(targetDBWarnings.toArray()); JPanel cp = new JPanel(new BorderLayout()); cp.add(new JLabel("<html>The target database schema is not identical to your Architect schema.<br><br>Here are the differences:</html>"), BorderLayout.NORTH); cp.add(new JScrollPane(warnings), BorderLayout.CENTER); cp.add(new JLabel("Do you want to continue anyway?"), BorderLayout.SOUTH); int choice = JOptionPane.showConfirmDialog(playpen, cp, "Target Database Structure Warning", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); if (choice == JOptionPane.NO_OPTION) { return; } } } catch (SQLException esql) { JOptionPane.showMessageDialog (architectFrame,"Can't export Transaction: "+esql.getMessage()); logger.error("Got exception while exporting Trans", esql); } catch (ArchitectException arex){ JOptionPane.showMessageDialog (architectFrame,"Can't export Transaction: "+arex.getMessage()); logger.error("Got exception while exporting Trans",arex); } // got this far, so it's ok to run the PL Export thread ExportTxWorker worker = new ExportTxWorker(plexp,plPanel); new ProgressWatcher(plCreateTxProgressBar, plexp, plCreateTxLabel); new Thread(worker).start(); } }); buttonPanel.add(okButton); JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { plPanel.discardChanges(); d.setVisible(false); } }); buttonPanel.add(cancelButton); // stick in the progress bar here... JPanel progressPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); plCreateTxProgressBar = new JProgressBar(); plCreateTxProgressBar.setStringPainted(true); plCreateTxProgressBar.setVisible(false); progressPanel.add(plCreateTxProgressBar); plCreateTxLabel = new JLabel ("Exporting PL Transactions..."); plCreateTxLabel.setVisible(false); progressPanel.add(plCreateTxLabel); bottomPanel.add(progressPanel); // left side, left justified bottomPanel.add(buttonPanel); // right side, right justified plp.add(bottomPanel, BorderLayout.SOUTH); d.setContentPane(plp); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); }
|
public synchronized void setupDialog() { logger.debug("running setupDialog()"); // always refresh Target Database (it might have changed) plexp.setTargetDataSource(ArchitectFrame.getMainInstance().getProject().getTargetDatabase().getDataSource()); if (d != null) { refreshConnections(); return; } d = new JDialog(ArchitectFrame.getMainInstance(), "Export ETL Transactions to PL Repository"); // set export defaults if necessary if (plexp.getFolderName() == null || plexp.getFolderName().trim().length() == 0) { plexp.setFolderName(PLUtils.toPLIdentifier(architectFrame.getProject().getName()+"_FOLDER")); } if (plexp.getJobId() == null || plexp.getJobId().trim().length() == 0) { plexp.setJobId(PLUtils.toPLIdentifier(architectFrame.getProject().getName()+"_JOB")); } JPanel plp = new JPanel(new BorderLayout(12,12)); plp.setBorder(BorderFactory.createEmptyBorder(12,12,12,12)); final PLExportPanel plPanel = new PLExportPanel(); plPanel.setPLExport(plexp); plp.add(plPanel, BorderLayout.CENTER); // make an intermediate JPanel JPanel bottomPanel = new JPanel(new GridLayout(1,2,25,0)); // 25 pixel hgap JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); JButton okButton = new JButton("Ok"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { plPanel.applyChanges(); // make sure the user selected a target database if (plexp.getTargetDataSource() == null) { JOptionPane.showMessageDialog(plPanel, "You have to select a Target database from the list.", "Error", JOptionPane.ERROR_MESSAGE); return; } if (plexp.getRepositoryDataSource() == null) { JOptionPane.showMessageDialog(plPanel, "You have to select a Repository database from the list.", "Error", JOptionPane.ERROR_MESSAGE); return; } // make sure user provided a PL Job Name if (plexp.getJobId().trim().length() == 0) { JOptionPane.showMessageDialog(plPanel, "You have to specify the PowerLoader Job ID.", "Error", JOptionPane.ERROR_MESSAGE); return; } // make sure we have an engine! if (plexp.getRunPLEngine()) { String plEngineSpec = architectFrame.getUserSettings().getETLUserSettings().getPowerLoaderEnginePath(); if (plEngineSpec == null || plEngineSpec.length() == 0) { // not set yet, so redirect the user to User Settings dialog JOptionPane.showMessageDialog (plPanel,"Please specify the location of the PL Engine (powerloader_odbc.exe)."); // ArchitectFrame.getMainInstance().prefAction.showPreferencesDialog(); return; } } String dupIdMessage = null; try { if (checkForDuplicateJobId(plexp.getJobId()) == true) { dupIdMessage = "There is already a job called \""+ plexp.getJobId()+"\".\n"+"Please choose a different job id."; } } catch (SQLException ex) { dupIdMessage = "There was a database error when checking for\n"+"duplicate job id:\n\n"+ex.getMessage(); } catch (ArchitectException ex) { dupIdMessage = "There was an application error when checking for\n"+"duplicate job id:\n\n"+ex.getMessage(); } if (dupIdMessage != null) { JOptionPane.showMessageDialog(plPanel, dupIdMessage, "Error", JOptionPane.ERROR_MESSAGE); return; } try { List targetDBWarnings = listMissingTargetTables(); if (!targetDBWarnings.isEmpty()) { // modal dialog (hold things up until the user says YES or NO) JList warnings = new JList(targetDBWarnings.toArray()); JPanel cp = new JPanel(new BorderLayout()); cp.add(new JLabel("<html>The target database schema is not identical to your Architect schema.<br><br>Here are the differences:</html>"), BorderLayout.NORTH); cp.add(new JScrollPane(warnings), BorderLayout.CENTER); cp.add(new JLabel("Do you want to continue anyway?"), BorderLayout.SOUTH); int choice = JOptionPane.showConfirmDialog(playpen, cp, "Target Database Structure Warning", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); if (choice == JOptionPane.NO_OPTION) { return; } } } catch (SQLException esql) { JOptionPane.showMessageDialog (architectFrame,"Can't export Transaction: "+esql.getMessage()); logger.error("Got exception while exporting Trans", esql); } catch (ArchitectException arex){ JOptionPane.showMessageDialog (architectFrame,"Can't export Transaction: "+arex.getMessage()); logger.error("Got exception while exporting Trans",arex); } // got this far, so it's ok to run the PL Export thread ExportTxWorker worker = new ExportTxWorker(plexp,plPanel); new ProgressWatcher(plCreateTxProgressBar, plexp, plCreateTxLabel); new Thread(worker).start(); } }); buttonPanel.add(okButton); JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { plPanel.discardChanges(); d.setVisible(false); } }); buttonPanel.add(cancelButton); // stick in the progress bar here... JPanel progressPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); plCreateTxProgressBar = new JProgressBar(); plCreateTxProgressBar.setStringPainted(true); progressPanel.add(plCreateTxProgressBar); plCreateTxLabel = new JLabel ("Exporting PL Transactions..."); plCreateTxLabel.setVisible(false); progressPanel.add(plCreateTxLabel); bottomPanel.add(progressPanel); // left side, left justified bottomPanel.add(buttonPanel); // right side, right justified plp.add(bottomPanel, BorderLayout.SOUTH); d.setContentPane(plp); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); }
| 1,108,819
|
public synchronized void setupDialog() { logger.debug("running setupDialog()"); // always refresh Target Database (it might have changed) plexp.setTargetDataSource(ArchitectFrame.getMainInstance().getProject().getTargetDatabase().getDataSource()); if (d != null) { refreshConnections(); return; } d = new JDialog(ArchitectFrame.getMainInstance(), "Export ETL Transactions to PL Repository"); // set export defaults if necessary if (plexp.getFolderName() == null || plexp.getFolderName().trim().length() == 0) { plexp.setFolderName(PLUtils.toPLIdentifier(architectFrame.getProject().getName()+"_FOLDER")); } if (plexp.getJobId() == null || plexp.getJobId().trim().length() == 0) { plexp.setJobId(PLUtils.toPLIdentifier(architectFrame.getProject().getName()+"_JOB")); } JPanel plp = new JPanel(new BorderLayout(12,12)); plp.setBorder(BorderFactory.createEmptyBorder(12,12,12,12)); final PLExportPanel plPanel = new PLExportPanel(); plPanel.setPLExport(plexp); plp.add(plPanel, BorderLayout.CENTER); // make an intermediate JPanel JPanel bottomPanel = new JPanel(new GridLayout(1,2,25,0)); // 25 pixel hgap JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); JButton okButton = new JButton("Ok"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { plPanel.applyChanges(); // make sure the user selected a target database if (plexp.getTargetDataSource() == null) { JOptionPane.showMessageDialog(plPanel, "You have to select a Target database from the list.", "Error", JOptionPane.ERROR_MESSAGE); return; } if (plexp.getRepositoryDataSource() == null) { JOptionPane.showMessageDialog(plPanel, "You have to select a Repository database from the list.", "Error", JOptionPane.ERROR_MESSAGE); return; } // make sure user provided a PL Job Name if (plexp.getJobId().trim().length() == 0) { JOptionPane.showMessageDialog(plPanel, "You have to specify the PowerLoader Job ID.", "Error", JOptionPane.ERROR_MESSAGE); return; } // make sure we have an engine! if (plexp.getRunPLEngine()) { String plEngineSpec = architectFrame.getUserSettings().getETLUserSettings().getPowerLoaderEnginePath(); if (plEngineSpec == null || plEngineSpec.length() == 0) { // not set yet, so redirect the user to User Settings dialog JOptionPane.showMessageDialog (plPanel,"Please specify the location of the PL Engine (powerloader_odbc.exe)."); // ArchitectFrame.getMainInstance().prefAction.showPreferencesDialog(); return; } } String dupIdMessage = null; try { if (checkForDuplicateJobId(plexp.getJobId()) == true) { dupIdMessage = "There is already a job called \""+ plexp.getJobId()+"\".\n"+"Please choose a different job id."; } } catch (SQLException ex) { dupIdMessage = "There was a database error when checking for\n"+"duplicate job id:\n\n"+ex.getMessage(); } catch (ArchitectException ex) { dupIdMessage = "There was an application error when checking for\n"+"duplicate job id:\n\n"+ex.getMessage(); } if (dupIdMessage != null) { JOptionPane.showMessageDialog(plPanel, dupIdMessage, "Error", JOptionPane.ERROR_MESSAGE); return; } try { List targetDBWarnings = listMissingTargetTables(); if (!targetDBWarnings.isEmpty()) { // modal dialog (hold things up until the user says YES or NO) JList warnings = new JList(targetDBWarnings.toArray()); JPanel cp = new JPanel(new BorderLayout()); cp.add(new JLabel("<html>The target database schema is not identical to your Architect schema.<br><br>Here are the differences:</html>"), BorderLayout.NORTH); cp.add(new JScrollPane(warnings), BorderLayout.CENTER); cp.add(new JLabel("Do you want to continue anyway?"), BorderLayout.SOUTH); int choice = JOptionPane.showConfirmDialog(playpen, cp, "Target Database Structure Warning", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); if (choice == JOptionPane.NO_OPTION) { return; } } } catch (SQLException esql) { JOptionPane.showMessageDialog (architectFrame,"Can't export Transaction: "+esql.getMessage()); logger.error("Got exception while exporting Trans", esql); } catch (ArchitectException arex){ JOptionPane.showMessageDialog (architectFrame,"Can't export Transaction: "+arex.getMessage()); logger.error("Got exception while exporting Trans",arex); } // got this far, so it's ok to run the PL Export thread ExportTxWorker worker = new ExportTxWorker(plexp,plPanel); new ProgressWatcher(plCreateTxProgressBar, plexp, plCreateTxLabel); new Thread(worker).start(); } }); buttonPanel.add(okButton); JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { plPanel.discardChanges(); d.setVisible(false); } }); buttonPanel.add(cancelButton); // stick in the progress bar here... JPanel progressPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); plCreateTxProgressBar = new JProgressBar(); plCreateTxProgressBar.setStringPainted(true); plCreateTxProgressBar.setVisible(false); progressPanel.add(plCreateTxProgressBar); plCreateTxLabel = new JLabel ("Exporting PL Transactions..."); plCreateTxLabel.setVisible(false); progressPanel.add(plCreateTxLabel); bottomPanel.add(progressPanel); // left side, left justified bottomPanel.add(buttonPanel); // right side, right justified plp.add(bottomPanel, BorderLayout.SOUTH); d.setContentPane(plp); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); }
|
public synchronized void setupDialog() { logger.debug("running setupDialog()"); // always refresh Target Database (it might have changed) plexp.setTargetDataSource(ArchitectFrame.getMainInstance().getProject().getTargetDatabase().getDataSource()); if (d != null) { refreshConnections(); return; } d = new JDialog(ArchitectFrame.getMainInstance(), "Export ETL Transactions to PL Repository"); // set export defaults if necessary if (plexp.getFolderName() == null || plexp.getFolderName().trim().length() == 0) { plexp.setFolderName(PLUtils.toPLIdentifier(architectFrame.getProject().getName()+"_FOLDER")); } if (plexp.getJobId() == null || plexp.getJobId().trim().length() == 0) { plexp.setJobId(PLUtils.toPLIdentifier(architectFrame.getProject().getName()+"_JOB")); } JPanel plp = new JPanel(new BorderLayout(12,12)); plp.setBorder(BorderFactory.createEmptyBorder(12,12,12,12)); final PLExportPanel plPanel = new PLExportPanel(); plPanel.setPLExport(plexp); plp.add(plPanel, BorderLayout.CENTER); // make an intermediate JPanel JPanel bottomPanel = new JPanel(new GridLayout(1,2,25,0)); // 25 pixel hgap JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); JButton okButton = new JButton("Ok"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { plPanel.applyChanges(); // make sure the user selected a target database if (plexp.getTargetDataSource() == null) { JOptionPane.showMessageDialog(plPanel, "You have to select a Target database from the list.", "Error", JOptionPane.ERROR_MESSAGE); return; } if (plexp.getRepositoryDataSource() == null) { JOptionPane.showMessageDialog(plPanel, "You have to select a Repository database from the list.", "Error", JOptionPane.ERROR_MESSAGE); return; } // make sure user provided a PL Job Name if (plexp.getJobId().trim().length() == 0) { JOptionPane.showMessageDialog(plPanel, "You have to specify the PowerLoader Job ID.", "Error", JOptionPane.ERROR_MESSAGE); return; } // make sure we have an engine! if (plexp.getRunPLEngine()) { String plEngineSpec = architectFrame.getUserSettings().getETLUserSettings().getPowerLoaderEnginePath(); if (plEngineSpec == null || plEngineSpec.length() == 0) { // not set yet, so redirect the user to User Settings dialog JOptionPane.showMessageDialog (plPanel,"Please specify the location of the PL Engine (powerloader_odbc.exe)."); // ArchitectFrame.getMainInstance().prefAction.showPreferencesDialog(); return; } } String dupIdMessage = null; try { if (checkForDuplicateJobId(plexp.getJobId()) == true) { dupIdMessage = "There is already a job called \""+ plexp.getJobId()+"\".\n"+"Please choose a different job id."; } } catch (SQLException ex) { dupIdMessage = "There was a database error when checking for\n"+"duplicate job id:\n\n"+ex.getMessage(); } catch (ArchitectException ex) { dupIdMessage = "There was an application error when checking for\n"+"duplicate job id:\n\n"+ex.getMessage(); } if (dupIdMessage != null) { JOptionPane.showMessageDialog(plPanel, dupIdMessage, "Error", JOptionPane.ERROR_MESSAGE); return; } try { List targetDBWarnings = listMissingTargetTables(); if (!targetDBWarnings.isEmpty()) { // modal dialog (hold things up until the user says YES or NO) JList warnings = new JList(targetDBWarnings.toArray()); JPanel cp = new JPanel(new BorderLayout()); cp.add(new JLabel("<html>The target database schema is not identical to your Architect schema.<br><br>Here are the differences:</html>"), BorderLayout.NORTH); cp.add(new JScrollPane(warnings), BorderLayout.CENTER); cp.add(new JLabel("Do you want to continue anyway?"), BorderLayout.SOUTH); int choice = JOptionPane.showConfirmDialog(playpen, cp, "Target Database Structure Warning", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); if (choice == JOptionPane.NO_OPTION) { return; } } } catch (SQLException esql) { JOptionPane.showMessageDialog (architectFrame,"Can't export Transaction: "+esql.getMessage()); logger.error("Got exception while exporting Trans", esql); } catch (ArchitectException arex){ JOptionPane.showMessageDialog (architectFrame,"Can't export Transaction: "+arex.getMessage()); logger.error("Got exception while exporting Trans",arex); } // got this far, so it's ok to run the PL Export thread ExportTxWorker worker = new ExportTxWorker(plexp,plPanel); new ProgressWatcher(plCreateTxProgressBar, plexp, plCreateTxLabel); new Thread(worker).start(); } }); buttonPanel.add(okButton); JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { plPanel.discardChanges(); d.setVisible(false); } }); buttonPanel.add(cancelButton); // stick in the progress bar here... JPanel progressPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); plCreateTxProgressBar = new JProgressBar(); plCreateTxProgressBar.setStringPainted(true); plCreateTxProgressBar.setVisible(false); progressPanel.add(plCreateTxProgressBar); plCreateTxLabel = new JLabel ("Exporting PL Transactions..."); progressPanel.add(plCreateTxLabel); bottomPanel.add(progressPanel); // left side, left justified bottomPanel.add(buttonPanel); // right side, right justified plp.add(bottomPanel, BorderLayout.SOUTH); d.setContentPane(plp); d.pack(); d.setLocationRelativeTo(ArchitectFrame.getMainInstance()); }
| 1,108,820
|
public void mousePressed (MouseEvent e) { if ((e.getModifiers() & InputEvent.BUTTON3_MASK) == InputEvent.BUTTON3_MASK){ final int clickX = e.getX(); final int clickY = e.getY(); double dboxX = (double)(clickX - clickXShift - (clickY-clickYShift))/boxSize; double dboxY = (double)(clickX - clickXShift + (clickY-clickYShift))/boxSize; final int boxX, boxY; if (dboxX < 0){ boxX = (int)(dboxX - 0.5); } else{ boxX = (int)(dboxX + 0.5); } if (dboxY < 0){ boxY = (int)(dboxY - 0.5); }else{ boxY = (int)(dboxY + 0.5); } if ((boxX >= lowX && boxX <= highX) && (boxY > boxX && boxY < highY) && !(worldmapRect.contains(clickX,clickY))){ if (dPrimeTable[boxX][boxY] != null){ final SwingWorker worker = new SwingWorker(){ public Object construct(){ final int leftMargin = 12; String[] displayStrings = new String[5]; if (theData.infoKnown){ displayStrings[0] = new String ("(" +Chromosome.getFilteredMarker(boxX).getName() + ", " + Chromosome.getFilteredMarker(boxY).getName() + ")"); }else{ displayStrings[0] = new String("(" + (Chromosome.realIndex[boxX]+1) + ", " + (Chromosome.realIndex[boxY]+1) + ")"); } displayStrings[1] = new String ("D': " + dPrimeTable[boxX][boxY].getDPrime()); displayStrings[2] = new String ("LOD: " + dPrimeTable[boxX][boxY].getLOD()); displayStrings[3] = new String ("r^2: " + dPrimeTable[boxX][boxY].getRSquared()); displayStrings[4] = new String ("D' conf. bounds: " + dPrimeTable[boxX][boxY].getConfidenceLow() + "-" + dPrimeTable[boxX][boxY].getConfidenceHigh()); Graphics g = caller.getGraphics(); g.setFont(boxFont); FontMetrics metrics = g.getFontMetrics(); int strlen = 0; for (int x = 0; x < 5; x++){ if (strlen < metrics.stringWidth(displayStrings[x])){ strlen = metrics.stringWidth(displayStrings[x]); } } //edge shifts prevent window from popping up partially offscreen int visRightBound = (int)(caller.getVisibleRect().getWidth() + caller.getVisibleRect().getX()); int visBotBound = (int)(caller.getVisibleRect().getHeight() + caller.getVisibleRect().getY()); int rightEdgeShift = 0; if (clickX + strlen + leftMargin +5 > visRightBound){ rightEdgeShift = clickX + strlen + leftMargin + 10 - visRightBound; } int botEdgeShift = 0; if (clickY + 5*metrics.getHeight()+10 > visBotBound){ botEdgeShift = clickY + 5*metrics.getHeight()+15 - visBotBound; } g.setColor(Color.WHITE); g.fillRect(clickX+1-rightEdgeShift, clickY+1-botEdgeShift, strlen+leftMargin+4, 5*metrics.getHeight()+9); g.setColor(Color.BLACK); g.drawRect(clickX-rightEdgeShift, clickY-botEdgeShift, strlen+leftMargin+5, 5*metrics.getHeight()+10); for (int x = 0; x < 5; x++){ g.drawString(displayStrings[x],clickX + leftMargin - rightEdgeShift, clickY+5+((x+1)*metrics.getHeight())-botEdgeShift); } return ""; } }; worker.start(); } } } }
|
public void mousePressed (MouseEvent e) { if ((e.getModifiers() & InputEvent.BUTTON3_MASK) == InputEvent.BUTTON3_MASK){ final int clickX = e.getX(); final int clickY = e.getY(); double dboxX = (double)(clickX - clickXShift - (clickY-clickYShift))/boxSize; double dboxY = (double)(clickX - clickXShift + (clickY-clickYShift))/boxSize; final int boxX, boxY; if (dboxX < 0){ boxX = (int)(dboxX - 0.5); } else{ boxX = (int)(dboxX + 0.5); } if (dboxY < 0){ boxY = (int)(dboxY - 0.5); }else{ boxY = (int)(dboxY + 0.5); } if ((boxX >= lowX && boxX <= highX) && (boxY > boxX && boxY < highY) && !(worldmapRect.contains(clickX,clickY))){ if (dPrimeTable[boxX][boxY] != null){ final SwingWorker worker = new SwingWorker(){ public Object construct(){ final int leftMargin = 12; String[] displayStrings = new String[5]; if (theData.infoKnown){ displayStrings[0] = new String ("(" +Chromosome.getFilteredMarker(boxX).getName() + ", " + Chromosome.getFilteredMarker(boxY).getName() + ")"); }else{ displayStrings[0] = new String("(" + (Chromosome.realIndex[boxX]+1) + ", " + (Chromosome.realIndex[boxY]+1) + ")"); } displayStrings[1] = new String ("D': " + dPrimeTable[boxX][boxY].getDPrime()); displayStrings[2] = new String ("LOD: " + dPrimeTable[boxX][boxY].getLOD()); displayStrings[3] = new String ("r^2: " + dPrimeTable[boxX][boxY].getRSquared()); displayStrings[4] = new String ("D' conf. bounds: " + dPrimeTable[boxX][boxY].getConfidenceLow() + "-" + dPrimeTable[boxX][boxY].getConfidenceHigh()); Graphics g = caller.getGraphics(); g.setFont(boxFont); FontMetrics metrics = g.getFontMetrics(); int strlen = 0; for (int x = 0; x < 5; x++){ if (strlen < metrics.stringWidth(displayStrings[x])){ strlen = metrics.stringWidth(displayStrings[x]); } } //edge shifts prevent window from popping up partially offscreen int visRightBound = (int)(caller.getVisibleRect().getWidth() + caller.getVisibleRect().getX()); int visBotBound = (int)(caller.getVisibleRect().getHeight() + caller.getVisibleRect().getY()); int rightEdgeShift = 0; if (clickX + strlen + leftMargin +5 > visRightBound){ rightEdgeShift = clickX + strlen + leftMargin + 10 - visRightBound; } int botEdgeShift = 0; if (clickY + 5*metrics.getHeight()+10 > visBotBound){ botEdgeShift = clickY + 5*metrics.getHeight()+15 - visBotBound; } g.setColor(Color.white); g.fillRect(clickX+1-rightEdgeShift, clickY+1-botEdgeShift, strlen+leftMargin+4, 5*metrics.getHeight()+9); g.setColor(Color.BLACK); g.drawRect(clickX-rightEdgeShift, clickY-botEdgeShift, strlen+leftMargin+5, 5*metrics.getHeight()+10); for (int x = 0; x < 5; x++){ g.drawString(displayStrings[x],clickX + leftMargin - rightEdgeShift, clickY+5+((x+1)*metrics.getHeight())-botEdgeShift); } return ""; } }; worker.start(); } } } }
| 1,108,822
|
public void mousePressed (MouseEvent e) { if ((e.getModifiers() & InputEvent.BUTTON3_MASK) == InputEvent.BUTTON3_MASK){ final int clickX = e.getX(); final int clickY = e.getY(); double dboxX = (double)(clickX - clickXShift - (clickY-clickYShift))/boxSize; double dboxY = (double)(clickX - clickXShift + (clickY-clickYShift))/boxSize; final int boxX, boxY; if (dboxX < 0){ boxX = (int)(dboxX - 0.5); } else{ boxX = (int)(dboxX + 0.5); } if (dboxY < 0){ boxY = (int)(dboxY - 0.5); }else{ boxY = (int)(dboxY + 0.5); } if ((boxX >= lowX && boxX <= highX) && (boxY > boxX && boxY < highY) && !(worldmapRect.contains(clickX,clickY))){ if (dPrimeTable[boxX][boxY] != null){ final SwingWorker worker = new SwingWorker(){ public Object construct(){ final int leftMargin = 12; String[] displayStrings = new String[5]; if (theData.infoKnown){ displayStrings[0] = new String ("(" +Chromosome.getFilteredMarker(boxX).getName() + ", " + Chromosome.getFilteredMarker(boxY).getName() + ")"); }else{ displayStrings[0] = new String("(" + (Chromosome.realIndex[boxX]+1) + ", " + (Chromosome.realIndex[boxY]+1) + ")"); } displayStrings[1] = new String ("D': " + dPrimeTable[boxX][boxY].getDPrime()); displayStrings[2] = new String ("LOD: " + dPrimeTable[boxX][boxY].getLOD()); displayStrings[3] = new String ("r^2: " + dPrimeTable[boxX][boxY].getRSquared()); displayStrings[4] = new String ("D' conf. bounds: " + dPrimeTable[boxX][boxY].getConfidenceLow() + "-" + dPrimeTable[boxX][boxY].getConfidenceHigh()); Graphics g = caller.getGraphics(); g.setFont(boxFont); FontMetrics metrics = g.getFontMetrics(); int strlen = 0; for (int x = 0; x < 5; x++){ if (strlen < metrics.stringWidth(displayStrings[x])){ strlen = metrics.stringWidth(displayStrings[x]); } } //edge shifts prevent window from popping up partially offscreen int visRightBound = (int)(caller.getVisibleRect().getWidth() + caller.getVisibleRect().getX()); int visBotBound = (int)(caller.getVisibleRect().getHeight() + caller.getVisibleRect().getY()); int rightEdgeShift = 0; if (clickX + strlen + leftMargin +5 > visRightBound){ rightEdgeShift = clickX + strlen + leftMargin + 10 - visRightBound; } int botEdgeShift = 0; if (clickY + 5*metrics.getHeight()+10 > visBotBound){ botEdgeShift = clickY + 5*metrics.getHeight()+15 - visBotBound; } g.setColor(Color.WHITE); g.fillRect(clickX+1-rightEdgeShift, clickY+1-botEdgeShift, strlen+leftMargin+4, 5*metrics.getHeight()+9); g.setColor(Color.BLACK); g.drawRect(clickX-rightEdgeShift, clickY-botEdgeShift, strlen+leftMargin+5, 5*metrics.getHeight()+10); for (int x = 0; x < 5; x++){ g.drawString(displayStrings[x],clickX + leftMargin - rightEdgeShift, clickY+5+((x+1)*metrics.getHeight())-botEdgeShift); } return ""; } }; worker.start(); } } } }
|
public void mousePressed (MouseEvent e) { if ((e.getModifiers() & InputEvent.BUTTON3_MASK) == InputEvent.BUTTON3_MASK){ final int clickX = e.getX(); final int clickY = e.getY(); double dboxX = (double)(clickX - clickXShift - (clickY-clickYShift))/boxSize; double dboxY = (double)(clickX - clickXShift + (clickY-clickYShift))/boxSize; final int boxX, boxY; if (dboxX < 0){ boxX = (int)(dboxX - 0.5); } else{ boxX = (int)(dboxX + 0.5); } if (dboxY < 0){ boxY = (int)(dboxY - 0.5); }else{ boxY = (int)(dboxY + 0.5); } if ((boxX >= lowX && boxX <= highX) && (boxY > boxX && boxY < highY) && !(worldmapRect.contains(clickX,clickY))){ if (dPrimeTable[boxX][boxY] != null){ final SwingWorker worker = new SwingWorker(){ public Object construct(){ final int leftMargin = 12; String[] displayStrings = new String[5]; if (theData.infoKnown){ displayStrings[0] = new String ("(" +Chromosome.getFilteredMarker(boxX).getName() + ", " + Chromosome.getFilteredMarker(boxY).getName() + ")"); }else{ displayStrings[0] = new String("(" + (Chromosome.realIndex[boxX]+1) + ", " + (Chromosome.realIndex[boxY]+1) + ")"); } displayStrings[1] = new String ("D': " + dPrimeTable[boxX][boxY].getDPrime()); displayStrings[2] = new String ("LOD: " + dPrimeTable[boxX][boxY].getLOD()); displayStrings[3] = new String ("r^2: " + dPrimeTable[boxX][boxY].getRSquared()); displayStrings[4] = new String ("D' conf. bounds: " + dPrimeTable[boxX][boxY].getConfidenceLow() + "-" + dPrimeTable[boxX][boxY].getConfidenceHigh()); Graphics g = caller.getGraphics(); g.setFont(boxFont); FontMetrics metrics = g.getFontMetrics(); int strlen = 0; for (int x = 0; x < 5; x++){ if (strlen < metrics.stringWidth(displayStrings[x])){ strlen = metrics.stringWidth(displayStrings[x]); } } //edge shifts prevent window from popping up partially offscreen int visRightBound = (int)(caller.getVisibleRect().getWidth() + caller.getVisibleRect().getX()); int visBotBound = (int)(caller.getVisibleRect().getHeight() + caller.getVisibleRect().getY()); int rightEdgeShift = 0; if (clickX + strlen + leftMargin +5 > visRightBound){ rightEdgeShift = clickX + strlen + leftMargin + 10 - visRightBound; } int botEdgeShift = 0; if (clickY + 5*metrics.getHeight()+10 > visBotBound){ botEdgeShift = clickY + 5*metrics.getHeight()+15 - visBotBound; } g.setColor(Color.WHITE); g.fillRect(clickX+1-rightEdgeShift, clickY+1-botEdgeShift, strlen+leftMargin+4, 5*metrics.getHeight()+9); g.setColor(Color.black); g.drawRect(clickX-rightEdgeShift, clickY-botEdgeShift, strlen+leftMargin+5, 5*metrics.getHeight()+10); for (int x = 0; x < 5; x++){ g.drawString(displayStrings[x],clickX + leftMargin - rightEdgeShift, clickY+5+((x+1)*metrics.getHeight())-botEdgeShift); } return ""; } }; worker.start(); } } } }
| 1,108,823
|
public Object construct(){ final int leftMargin = 12; String[] displayStrings = new String[5]; if (theData.infoKnown){ displayStrings[0] = new String ("(" +Chromosome.getFilteredMarker(boxX).getName() + ", " + Chromosome.getFilteredMarker(boxY).getName() + ")"); }else{ displayStrings[0] = new String("(" + (Chromosome.realIndex[boxX]+1) + ", " + (Chromosome.realIndex[boxY]+1) + ")"); } displayStrings[1] = new String ("D': " + dPrimeTable[boxX][boxY].getDPrime()); displayStrings[2] = new String ("LOD: " + dPrimeTable[boxX][boxY].getLOD()); displayStrings[3] = new String ("r^2: " + dPrimeTable[boxX][boxY].getRSquared()); displayStrings[4] = new String ("D' conf. bounds: " + dPrimeTable[boxX][boxY].getConfidenceLow() + "-" + dPrimeTable[boxX][boxY].getConfidenceHigh()); Graphics g = caller.getGraphics(); g.setFont(boxFont); FontMetrics metrics = g.getFontMetrics(); int strlen = 0; for (int x = 0; x < 5; x++){ if (strlen < metrics.stringWidth(displayStrings[x])){ strlen = metrics.stringWidth(displayStrings[x]); } } //edge shifts prevent window from popping up partially offscreen int visRightBound = (int)(caller.getVisibleRect().getWidth() + caller.getVisibleRect().getX()); int visBotBound = (int)(caller.getVisibleRect().getHeight() + caller.getVisibleRect().getY()); int rightEdgeShift = 0; if (clickX + strlen + leftMargin +5 > visRightBound){ rightEdgeShift = clickX + strlen + leftMargin + 10 - visRightBound; } int botEdgeShift = 0; if (clickY + 5*metrics.getHeight()+10 > visBotBound){ botEdgeShift = clickY + 5*metrics.getHeight()+15 - visBotBound; } g.setColor(Color.WHITE); g.fillRect(clickX+1-rightEdgeShift, clickY+1-botEdgeShift, strlen+leftMargin+4, 5*metrics.getHeight()+9); g.setColor(Color.BLACK); g.drawRect(clickX-rightEdgeShift, clickY-botEdgeShift, strlen+leftMargin+5, 5*metrics.getHeight()+10); for (int x = 0; x < 5; x++){ g.drawString(displayStrings[x],clickX + leftMargin - rightEdgeShift, clickY+5+((x+1)*metrics.getHeight())-botEdgeShift); } return ""; }
|
public Object construct(){ final int leftMargin = 12; String[] displayStrings = new String[5]; if (theData.infoKnown){ displayStrings[0] = new String ("(" +Chromosome.getFilteredMarker(boxX).getName() + ", " + Chromosome.getFilteredMarker(boxY).getName() + ")"); }else{ displayStrings[0] = new String("(" + (Chromosome.realIndex[boxX]+1) + ", " + (Chromosome.realIndex[boxY]+1) + ")"); } displayStrings[1] = new String ("D': " + dPrimeTable[boxX][boxY].getDPrime()); displayStrings[2] = new String ("LOD: " + dPrimeTable[boxX][boxY].getLOD()); displayStrings[3] = new String ("r^2: " + dPrimeTable[boxX][boxY].getRSquared()); displayStrings[4] = new String ("D' conf. bounds: " + dPrimeTable[boxX][boxY].getConfidenceLow() + "-" + dPrimeTable[boxX][boxY].getConfidenceHigh()); Graphics g = caller.getGraphics(); g.setFont(boxFont); FontMetrics metrics = g.getFontMetrics(); int strlen = 0; for (int x = 0; x < 5; x++){ if (strlen < metrics.stringWidth(displayStrings[x])){ strlen = metrics.stringWidth(displayStrings[x]); } } //edge shifts prevent window from popping up partially offscreen int visRightBound = (int)(caller.getVisibleRect().getWidth() + caller.getVisibleRect().getX()); int visBotBound = (int)(caller.getVisibleRect().getHeight() + caller.getVisibleRect().getY()); int rightEdgeShift = 0; if (clickX + strlen + leftMargin +5 > visRightBound){ rightEdgeShift = clickX + strlen + leftMargin + 10 - visRightBound; } int botEdgeShift = 0; if (clickY + 5*metrics.getHeight()+10 > visBotBound){ botEdgeShift = clickY + 5*metrics.getHeight()+15 - visBotBound; } g.setColor(Color.white); g.fillRect(clickX+1-rightEdgeShift, clickY+1-botEdgeShift, strlen+leftMargin+4, 5*metrics.getHeight()+9); g.setColor(Color.BLACK); g.drawRect(clickX-rightEdgeShift, clickY-botEdgeShift, strlen+leftMargin+5, 5*metrics.getHeight()+10); for (int x = 0; x < 5; x++){ g.drawString(displayStrings[x],clickX + leftMargin - rightEdgeShift, clickY+5+((x+1)*metrics.getHeight())-botEdgeShift); } return ""; }
| 1,108,824
|
public Object construct(){ final int leftMargin = 12; String[] displayStrings = new String[5]; if (theData.infoKnown){ displayStrings[0] = new String ("(" +Chromosome.getFilteredMarker(boxX).getName() + ", " + Chromosome.getFilteredMarker(boxY).getName() + ")"); }else{ displayStrings[0] = new String("(" + (Chromosome.realIndex[boxX]+1) + ", " + (Chromosome.realIndex[boxY]+1) + ")"); } displayStrings[1] = new String ("D': " + dPrimeTable[boxX][boxY].getDPrime()); displayStrings[2] = new String ("LOD: " + dPrimeTable[boxX][boxY].getLOD()); displayStrings[3] = new String ("r^2: " + dPrimeTable[boxX][boxY].getRSquared()); displayStrings[4] = new String ("D' conf. bounds: " + dPrimeTable[boxX][boxY].getConfidenceLow() + "-" + dPrimeTable[boxX][boxY].getConfidenceHigh()); Graphics g = caller.getGraphics(); g.setFont(boxFont); FontMetrics metrics = g.getFontMetrics(); int strlen = 0; for (int x = 0; x < 5; x++){ if (strlen < metrics.stringWidth(displayStrings[x])){ strlen = metrics.stringWidth(displayStrings[x]); } } //edge shifts prevent window from popping up partially offscreen int visRightBound = (int)(caller.getVisibleRect().getWidth() + caller.getVisibleRect().getX()); int visBotBound = (int)(caller.getVisibleRect().getHeight() + caller.getVisibleRect().getY()); int rightEdgeShift = 0; if (clickX + strlen + leftMargin +5 > visRightBound){ rightEdgeShift = clickX + strlen + leftMargin + 10 - visRightBound; } int botEdgeShift = 0; if (clickY + 5*metrics.getHeight()+10 > visBotBound){ botEdgeShift = clickY + 5*metrics.getHeight()+15 - visBotBound; } g.setColor(Color.WHITE); g.fillRect(clickX+1-rightEdgeShift, clickY+1-botEdgeShift, strlen+leftMargin+4, 5*metrics.getHeight()+9); g.setColor(Color.BLACK); g.drawRect(clickX-rightEdgeShift, clickY-botEdgeShift, strlen+leftMargin+5, 5*metrics.getHeight()+10); for (int x = 0; x < 5; x++){ g.drawString(displayStrings[x],clickX + leftMargin - rightEdgeShift, clickY+5+((x+1)*metrics.getHeight())-botEdgeShift); } return ""; }
|
public Object construct(){ final int leftMargin = 12; String[] displayStrings = new String[5]; if (theData.infoKnown){ displayStrings[0] = new String ("(" +Chromosome.getFilteredMarker(boxX).getName() + ", " + Chromosome.getFilteredMarker(boxY).getName() + ")"); }else{ displayStrings[0] = new String("(" + (Chromosome.realIndex[boxX]+1) + ", " + (Chromosome.realIndex[boxY]+1) + ")"); } displayStrings[1] = new String ("D': " + dPrimeTable[boxX][boxY].getDPrime()); displayStrings[2] = new String ("LOD: " + dPrimeTable[boxX][boxY].getLOD()); displayStrings[3] = new String ("r^2: " + dPrimeTable[boxX][boxY].getRSquared()); displayStrings[4] = new String ("D' conf. bounds: " + dPrimeTable[boxX][boxY].getConfidenceLow() + "-" + dPrimeTable[boxX][boxY].getConfidenceHigh()); Graphics g = caller.getGraphics(); g.setFont(boxFont); FontMetrics metrics = g.getFontMetrics(); int strlen = 0; for (int x = 0; x < 5; x++){ if (strlen < metrics.stringWidth(displayStrings[x])){ strlen = metrics.stringWidth(displayStrings[x]); } } //edge shifts prevent window from popping up partially offscreen int visRightBound = (int)(caller.getVisibleRect().getWidth() + caller.getVisibleRect().getX()); int visBotBound = (int)(caller.getVisibleRect().getHeight() + caller.getVisibleRect().getY()); int rightEdgeShift = 0; if (clickX + strlen + leftMargin +5 > visRightBound){ rightEdgeShift = clickX + strlen + leftMargin + 10 - visRightBound; } int botEdgeShift = 0; if (clickY + 5*metrics.getHeight()+10 > visBotBound){ botEdgeShift = clickY + 5*metrics.getHeight()+15 - visBotBound; } g.setColor(Color.WHITE); g.fillRect(clickX+1-rightEdgeShift, clickY+1-botEdgeShift, strlen+leftMargin+4, 5*metrics.getHeight()+9); g.setColor(Color.black); g.drawRect(clickX-rightEdgeShift, clickY-botEdgeShift, strlen+leftMargin+5, 5*metrics.getHeight()+10); for (int x = 0; x < 5; x++){ g.drawString(displayStrings[x],clickX + leftMargin - rightEdgeShift, clickY+5+((x+1)*metrics.getHeight())-botEdgeShift); } return ""; }
| 1,108,825
|
public void paintComponent(Graphics g){ PairwiseLinkage[][] dPrimeTable = theData.filteredDPrimeTable; Vector blocks = theData.blocks; Graphics2D g2 = (Graphics2D) g; Dimension size = getSize(); Dimension pref = getPreferredSize(); Rectangle visRect = getVisibleRect(); /* boxSize = ((clipRect.width-2*H_BORDER)/dPrimeTable.length-1); if (boxSize < 12){boxSize=12;} if (boxSize < 25){ printDetails = false; boxRadius = boxSize/2; }else{ boxRadius = boxSize/2 - 1; } */ //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. //clickxshift and clickyshift are used later to translate from x,y coords //to the pair of markers comparison at those coords if (!(theData.infoKnown)){ g2.translate((size.width - pref.width) / 2, (size.height - pref.height) / 2); clickXShift = left + (size.width-pref.width)/2; clickYShift = top + (size.height - pref.height)/2; } else { g2.translate((size.width - pref.width) / 2, 0); clickXShift = left + (size.width-pref.width)/2; clickYShift = top; } FontMetrics boxFontMetrics = g2.getFontMetrics(boxFont); int diamondX[] = new int[4]; int diamondY[] = new int[4]; Polygon diamond; left = H_BORDER; top = V_BORDER; FontMetrics metrics; int ascent; g2.setColor(this.getBackground()); g2.fillRect(0,0,pref.width,pref.height); g2.setColor(Color.BLACK); BasicStroke thickerStroke = new BasicStroke(1); BasicStroke thinnerStroke = new BasicStroke(0.35f); BasicStroke fatStroke = new BasicStroke(2.5f); float dash1[] = {5.0f}; BasicStroke dashedFatStroke = new BasicStroke(2.5f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 5.0f, dash1, 0.0f); g2.setFont(markerNameFont); metrics = g2.getFontMetrics(); ascent = metrics.getAscent(); if (theData.infoKnown) { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //// draw the marker locations int wide = (dPrimeTable.length-1) * boxSize; //TODO: talk to kirby about locusview scaling gizmo int lineLeft = wide/20; int lineSpan = (wide/10)*9; long minpos = Chromosome.getMarker(0).getPosition(); long maxpos = Chromosome.getMarker(Chromosome.getSize()-1).getPosition(); double spanpos = maxpos - minpos; g2.setStroke(thinnerStroke); g2.setColor(Color.white); g2.fillRect(left + lineLeft, 5, lineSpan, TICK_HEIGHT); g2.setColor(Color.black); g2.drawRect(left + lineLeft, 5, lineSpan, TICK_HEIGHT); for (int i = 0; i < Chromosome.getFilteredSize(); i++) { double pos = (Chromosome.getFilteredMarker(i).getPosition() - minpos) / spanpos; int xx = (int) (left + lineLeft + lineSpan*pos); g2.setStroke(thickerStroke); g2.drawLine(xx, 5, xx, 5 + TICK_HEIGHT); g2.setStroke(thinnerStroke); g2.drawLine(xx, 5 + TICK_HEIGHT, left + i*boxSize, TICK_BOTTOM); } top += TICK_BOTTOM; //// draw the marker names if (printDetails){ widestMarkerName = metrics.stringWidth(Chromosome.getFilteredMarker(0).getName()); for (int x = 1; x < dPrimeTable.length; x++) { int thiswide = metrics.stringWidth(Chromosome.getFilteredMarker(x).getName()); if (thiswide > widestMarkerName) widestMarkerName = thiswide; } g2.translate(left, top + widestMarkerName); g2.rotate(-Math.PI / 2.0); for (int x = 0; x < dPrimeTable.length; x++) { if (theData.isInBlock[Chromosome.realIndex[x]]){ g2.setFont(boldMarkerNameFont); }else{ g2.setFont(markerNameFont); } g2.drawString(Chromosome.getFilteredMarker(x).getName(),TEXT_GAP, x*boxSize + ascent/3); } 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); } blockDispHeight = ascent+boxSize/2; top += blockDispHeight; //// draw the marker numbers if (printDetails){ g2.setFont(markerNumFont); metrics = g2.getFontMetrics(); ascent = metrics.getAscent(); for (int x = 0; x < dPrimeTable.length; x++) { String mark = String.valueOf(Chromosome.realIndex[x] + 1); g2.drawString(mark, left + x*boxSize - metrics.stringWidth(mark)/2, top + ascent); } top += boxRadius/2; // give a little space between numbers and boxes } //the following values are the bounds on the boxes we want to //display given that the current window is 'visRect' lowX = (visRect.x-clickXShift-(visRect.y + visRect.height-clickYShift))/boxSize; if (lowX < 0) { lowX = 0; } highX = ((visRect.x + visRect.width)/boxSize)+1; if (highX > dPrimeTable.length-1){ highX = dPrimeTable.length-1; } lowY = ((visRect.x-clickXShift)+(visRect.y-clickYShift))/boxSize; if (lowY < lowX+1){ lowY = lowX+1; } highY = (((visRect.x-clickXShift+visRect.width) + (visRect.y-clickYShift+visRect.height))/boxSize)+1; if (highY > dPrimeTable.length){ highY = dPrimeTable.length; } // 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[x][y] == null){ continue; } double d = dPrimeTable[x][y].getDPrime(); //double l = dPrimeTable[x][y].getLOD(); Color boxColor = dPrimeTable[x][y].getColor(); // draw markers above int xx = left + (x + y) * boxSize / 2; int yy = top + (y - x) * boxSize / 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 (boxColor == Color.white) { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setColor(Color.lightGray); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } if(printDetails){ g2.setFont(boxFont); ascent = boxFontMetrics.getAscent(); int val = (int) (d * 100); g2.setColor((val < 50) ? Color.gray : Color.black); if (val != 100) { String valu = String.valueOf(val); int widf = boxFontMetrics.stringWidth(valu); g.drawString(valu, xx - widf/2, yy + ascent/2); } } } } //highlight blocks boolean even = true; 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.drawLine(left + (2*first) * boxSize/2 - boxRadius, top, left + (first + last) * boxSize/2, top + (last - first) * boxSize/2 + boxRadius); g2.drawLine(left + (first + last) * boxSize/2, top + (last - first) * boxSize/2 + boxRadius, left + (2*last) * boxSize/2+boxRadius, top); for (int j = first; j <= last; j++){ if (theData.isInBlock[j]){ g2.setStroke(fatStroke); }else{ g2.setStroke(dashedFatStroke); } g2.drawLine(left+j*boxSize-boxSize/2, top-blockDispHeight, left+j*boxSize+boxSize/2, top-blockDispHeight); /* //little vees on top of each marker g2.drawLine(left + (2*theBlock[j+1]) * boxSize/2, top + boxSize/2, left + (2*theBlock[j+1]) * boxSize/2 + boxRadius, top+1); g2.drawLine (left + (2*theBlock[j+1]) * boxSize/2, top + boxSize/2, left + (2*theBlock[j+1]-1) * boxSize/2, top); */ } //special lines for fencepost markers /*g2.drawLine(left+first*boxSize+1, top+boxRadius, left+first*boxSize+boxRadius, top+1); g2.drawLine(left+last*boxSize-1, top+boxRadius, left+last*boxSize-boxRadius, top+1); */ //lines to connect to block display g2.setStroke(fatStroke); g2.drawLine(left + first*boxSize-boxSize/2, top-1, left+first*boxSize-boxSize/2, top-blockDispHeight); g2.drawLine(left+last*boxSize+boxSize/2, top-1, left+last*boxSize+boxSize/2, top-blockDispHeight); String labelString = new String ("Block " + (i+1)); g2.drawString(labelString, left+first*boxSize-boxSize/2+TEXT_GAP, top-boxSize/2); } g2.setStroke(thickerStroke); if (pref.getWidth() > (2*visRect.width)){ //dataset is big enough to require worldmap if (noImage){ //first time through draw a worldmap if dataset is big: final int WM_BD_HEIGHT = 4; final int WM_MAX_WIDTH = visRect.width/3; double sizingScalefactor; sizingScalefactor = (double) (chartSize.width)/WM_MAX_WIDTH; double scalefactor; scalefactor = (double)(chartSize.width)/(WM_MAX_WIDTH-WM_BD_HEIGHT*4); CompoundBorder wmBorder = new CompoundBorder(BorderFactory.createRaisedBevelBorder(), BorderFactory.createLoweredBevelBorder()); worldmap = new BufferedImage((int)(chartSize.width/scalefactor)+wmBorder.getBorderInsets(this).left*2, (int)(chartSize.height/sizingScalefactor)+wmBorder.getBorderInsets(this).top*2, BufferedImage.TYPE_3BYTE_BGR); Graphics gw = worldmap.getGraphics(); Graphics2D gw2 = (Graphics2D)(gw); gw2.setColor(this.getBackground()); gw2.fillRect(1,1,worldmap.getWidth()-2,worldmap.getHeight()-2); //make a pretty border gw2.setColor(Color.BLACK); wmBorder.paintBorder(this,gw2,0,0,worldmap.getWidth()-1,worldmap.getHeight()-1); ir = wmBorder.getInteriorRectangle(this,0,0,worldmap.getWidth()-1, worldmap.getHeight()-1); ir.height -= WM_BD_HEIGHT; double prefBoxSize = boxSize/scalefactor; float[] smallDiamondX = new float[4]; float[] smallDiamondY = new float[4]; GeneralPath gp; for (int x = 0; x < dPrimeTable.length-1; x++){ for (int y = x+1; y < dPrimeTable.length; y++){ if (dPrimeTable[x][y] == null){ continue; } double xx = (x + y)*prefBoxSize/2+wmBorder.getBorderInsets(this).left; double yy = (y - x)*prefBoxSize/2+wmBorder.getBorderInsets(this).top+WM_BD_HEIGHT; 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[x][y].getColor()); gw2.fill(gp); } } //draw block display in worldmap gw2.setColor(this.getBackground()); gw2.fillRect(wmBorder.getBorderInsets(this).left, wmBorder.getBorderInsets(this).top, ir.width, WM_BD_HEIGHT); gw2.setColor(Color.black); 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*first), wmBorder.getBorderInsets(this).top+voffset, (int)((last-first)*prefBoxSize), WM_BD_HEIGHT/2); even = !even; } noImage = false; } g2.drawImage(worldmap,visRect.x, visRect.y + visRect.height - worldmap.getHeight(), this); worldmapRect = new Rectangle(visRect.x, visRect.y+visRect.height-worldmap.getHeight(), worldmap.getWidth(), worldmap.getHeight()); //draw the outline of the viewport g2.setColor(Color.BLACK); double hRatio = ir.getWidth()/pref.getWidth(); double vRatio = ir.getHeight()/pref.getHeight(); int hBump = worldmap.getWidth()-ir.width; int vBump = worldmap.getHeight()-ir.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)); } }
|
public void paintComponent(Graphics g){ PairwiseLinkage[][] dPrimeTable = theData.filteredDPrimeTable; Vector blocks = theData.blocks; Graphics2D g2 = (Graphics2D) g; Dimension size = getSize(); Dimension pref = getPreferredSize(); Rectangle visRect = getVisibleRect(); /* boxSize = ((clipRect.width-2*H_BORDER)/dPrimeTable.length-1); if (boxSize < 12){boxSize=12;} if (boxSize < 25){ printDetails = false; boxRadius = boxSize/2; }else{ boxRadius = boxSize/2 - 1; } */ //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. //clickxshift and clickyshift are used later to translate from x,y coords //to the pair of markers comparison at those coords if (!(theData.infoKnown)){ g2.translate((size.width - pref.width) / 2, (size.height - pref.height) / 2); clickXShift = left + (size.width-pref.width)/2; clickYShift = top + (size.height - pref.height)/2; } else { g2.translate((size.width - pref.width) / 2, 0); clickXShift = left + (size.width-pref.width)/2; clickYShift = top; } FontMetrics boxFontMetrics = g2.getFontMetrics(boxFont); int diamondX[] = new int[4]; int diamondY[] = new int[4]; Polygon diamond; left = H_BORDER; top = V_BORDER; FontMetrics metrics; int ascent; g2.setColor(this.getBackground()); g2.fillRect(0,0,pref.width,pref.height); g2.setColor(Color.black); BasicStroke thickerStroke = new BasicStroke(1); BasicStroke thinnerStroke = new BasicStroke(0.35f); BasicStroke fatStroke = new BasicStroke(2.5f); float dash1[] = {5.0f}; BasicStroke dashedFatStroke = new BasicStroke(2.5f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 5.0f, dash1, 0.0f); g2.setFont(markerNameFont); metrics = g2.getFontMetrics(); ascent = metrics.getAscent(); if (theData.infoKnown) { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //// draw the marker locations int wide = (dPrimeTable.length-1) * boxSize; //TODO: talk to kirby about locusview scaling gizmo int lineLeft = wide/20; int lineSpan = (wide/10)*9; long minpos = Chromosome.getMarker(0).getPosition(); long maxpos = Chromosome.getMarker(Chromosome.getSize()-1).getPosition(); double spanpos = maxpos - minpos; g2.setStroke(thinnerStroke); g2.setColor(Color.white); g2.fillRect(left + lineLeft, 5, lineSpan, TICK_HEIGHT); g2.setColor(Color.black); g2.drawRect(left + lineLeft, 5, lineSpan, TICK_HEIGHT); for (int i = 0; i < Chromosome.getFilteredSize(); i++) { double pos = (Chromosome.getFilteredMarker(i).getPosition() - minpos) / spanpos; int xx = (int) (left + lineLeft + lineSpan*pos); g2.setStroke(thickerStroke); g2.drawLine(xx, 5, xx, 5 + TICK_HEIGHT); g2.setStroke(thinnerStroke); g2.drawLine(xx, 5 + TICK_HEIGHT, left + i*boxSize, TICK_BOTTOM); } top += TICK_BOTTOM; //// draw the marker names if (printDetails){ widestMarkerName = metrics.stringWidth(Chromosome.getFilteredMarker(0).getName()); for (int x = 1; x < dPrimeTable.length; x++) { int thiswide = metrics.stringWidth(Chromosome.getFilteredMarker(x).getName()); if (thiswide > widestMarkerName) widestMarkerName = thiswide; } g2.translate(left, top + widestMarkerName); g2.rotate(-Math.PI / 2.0); for (int x = 0; x < dPrimeTable.length; x++) { if (theData.isInBlock[Chromosome.realIndex[x]]){ g2.setFont(boldMarkerNameFont); }else{ g2.setFont(markerNameFont); } g2.drawString(Chromosome.getFilteredMarker(x).getName(),TEXT_GAP, x*boxSize + ascent/3); } 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); } blockDispHeight = ascent+boxSize/2; top += blockDispHeight; //// draw the marker numbers if (printDetails){ g2.setFont(markerNumFont); metrics = g2.getFontMetrics(); ascent = metrics.getAscent(); for (int x = 0; x < dPrimeTable.length; x++) { String mark = String.valueOf(Chromosome.realIndex[x] + 1); g2.drawString(mark, left + x*boxSize - metrics.stringWidth(mark)/2, top + ascent); } top += boxRadius/2; // give a little space between numbers and boxes } //the following values are the bounds on the boxes we want to //display given that the current window is 'visRect' lowX = (visRect.x-clickXShift-(visRect.y + visRect.height-clickYShift))/boxSize; if (lowX < 0) { lowX = 0; } highX = ((visRect.x + visRect.width)/boxSize)+1; if (highX > dPrimeTable.length-1){ highX = dPrimeTable.length-1; } lowY = ((visRect.x-clickXShift)+(visRect.y-clickYShift))/boxSize; if (lowY < lowX+1){ lowY = lowX+1; } highY = (((visRect.x-clickXShift+visRect.width) + (visRect.y-clickYShift+visRect.height))/boxSize)+1; if (highY > dPrimeTable.length){ highY = dPrimeTable.length; } // 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[x][y] == null){ continue; } double d = dPrimeTable[x][y].getDPrime(); //double l = dPrimeTable[x][y].getLOD(); Color boxColor = dPrimeTable[x][y].getColor(); // draw markers above int xx = left + (x + y) * boxSize / 2; int yy = top + (y - x) * boxSize / 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 (boxColor == Color.white) { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setColor(Color.lightGray); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } if(printDetails){ g2.setFont(boxFont); ascent = boxFontMetrics.getAscent(); int val = (int) (d * 100); g2.setColor((val < 50) ? Color.gray : Color.black); if (val != 100) { String valu = String.valueOf(val); int widf = boxFontMetrics.stringWidth(valu); g.drawString(valu, xx - widf/2, yy + ascent/2); } } } } //highlight blocks boolean even = true; 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.drawLine(left + (2*first) * boxSize/2 - boxRadius, top, left + (first + last) * boxSize/2, top + (last - first) * boxSize/2 + boxRadius); g2.drawLine(left + (first + last) * boxSize/2, top + (last - first) * boxSize/2 + boxRadius, left + (2*last) * boxSize/2+boxRadius, top); for (int j = first; j <= last; j++){ if (theData.isInBlock[j]){ g2.setStroke(fatStroke); }else{ g2.setStroke(dashedFatStroke); } g2.drawLine(left+j*boxSize-boxSize/2, top-blockDispHeight, left+j*boxSize+boxSize/2, top-blockDispHeight); /* //little vees on top of each marker g2.drawLine(left + (2*theBlock[j+1]) * boxSize/2, top + boxSize/2, left + (2*theBlock[j+1]) * boxSize/2 + boxRadius, top+1); g2.drawLine (left + (2*theBlock[j+1]) * boxSize/2, top + boxSize/2, left + (2*theBlock[j+1]-1) * boxSize/2, top); */ } //special lines for fencepost markers /*g2.drawLine(left+first*boxSize+1, top+boxRadius, left+first*boxSize+boxRadius, top+1); g2.drawLine(left+last*boxSize-1, top+boxRadius, left+last*boxSize-boxRadius, top+1); */ //lines to connect to block display g2.setStroke(fatStroke); g2.drawLine(left + first*boxSize-boxSize/2, top-1, left+first*boxSize-boxSize/2, top-blockDispHeight); g2.drawLine(left+last*boxSize+boxSize/2, top-1, left+last*boxSize+boxSize/2, top-blockDispHeight); String labelString = new String ("Block " + (i+1)); g2.drawString(labelString, left+first*boxSize-boxSize/2+TEXT_GAP, top-boxSize/2); } g2.setStroke(thickerStroke); if (pref.getWidth() > (2*visRect.width)){ //dataset is big enough to require worldmap if (noImage){ //first time through draw a worldmap if dataset is big: final int WM_BD_HEIGHT = 4; final int WM_MAX_WIDTH = visRect.width/3; double sizingScalefactor; sizingScalefactor = (double) (chartSize.width)/WM_MAX_WIDTH; double scalefactor; scalefactor = (double)(chartSize.width)/(WM_MAX_WIDTH-WM_BD_HEIGHT*4); CompoundBorder wmBorder = new CompoundBorder(BorderFactory.createRaisedBevelBorder(), BorderFactory.createLoweredBevelBorder()); worldmap = new BufferedImage((int)(chartSize.width/scalefactor)+wmBorder.getBorderInsets(this).left*2, (int)(chartSize.height/sizingScalefactor)+wmBorder.getBorderInsets(this).top*2, BufferedImage.TYPE_3BYTE_BGR); Graphics gw = worldmap.getGraphics(); Graphics2D gw2 = (Graphics2D)(gw); gw2.setColor(this.getBackground()); gw2.fillRect(1,1,worldmap.getWidth()-2,worldmap.getHeight()-2); //make a pretty border gw2.setColor(Color.BLACK); wmBorder.paintBorder(this,gw2,0,0,worldmap.getWidth()-1,worldmap.getHeight()-1); ir = wmBorder.getInteriorRectangle(this,0,0,worldmap.getWidth()-1, worldmap.getHeight()-1); ir.height -= WM_BD_HEIGHT; double prefBoxSize = boxSize/scalefactor; float[] smallDiamondX = new float[4]; float[] smallDiamondY = new float[4]; GeneralPath gp; for (int x = 0; x < dPrimeTable.length-1; x++){ for (int y = x+1; y < dPrimeTable.length; y++){ if (dPrimeTable[x][y] == null){ continue; } double xx = (x + y)*prefBoxSize/2+wmBorder.getBorderInsets(this).left; double yy = (y - x)*prefBoxSize/2+wmBorder.getBorderInsets(this).top+WM_BD_HEIGHT; 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[x][y].getColor()); gw2.fill(gp); } } //draw block display in worldmap gw2.setColor(this.getBackground()); gw2.fillRect(wmBorder.getBorderInsets(this).left, wmBorder.getBorderInsets(this).top, ir.width, WM_BD_HEIGHT); gw2.setColor(Color.black); 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*first), wmBorder.getBorderInsets(this).top+voffset, (int)((last-first)*prefBoxSize), WM_BD_HEIGHT/2); even = !even; } noImage = false; } g2.drawImage(worldmap,visRect.x, visRect.y + visRect.height - worldmap.getHeight(), this); worldmapRect = new Rectangle(visRect.x, visRect.y+visRect.height-worldmap.getHeight(), worldmap.getWidth(), worldmap.getHeight()); //draw the outline of the viewport g2.setColor(Color.black); double hRatio = ir.getWidth()/pref.getWidth(); double vRatio = ir.getHeight()/pref.getHeight(); int hBump = worldmap.getWidth()-ir.width; int vBump = worldmap.getHeight()-ir.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)); } }
| 1,108,826
|
public void paintComponent(Graphics g){ PairwiseLinkage[][] dPrimeTable = theData.filteredDPrimeTable; Vector blocks = theData.blocks; Graphics2D g2 = (Graphics2D) g; Dimension size = getSize(); Dimension pref = getPreferredSize(); Rectangle visRect = getVisibleRect(); /* boxSize = ((clipRect.width-2*H_BORDER)/dPrimeTable.length-1); if (boxSize < 12){boxSize=12;} if (boxSize < 25){ printDetails = false; boxRadius = boxSize/2; }else{ boxRadius = boxSize/2 - 1; } */ //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. //clickxshift and clickyshift are used later to translate from x,y coords //to the pair of markers comparison at those coords if (!(theData.infoKnown)){ g2.translate((size.width - pref.width) / 2, (size.height - pref.height) / 2); clickXShift = left + (size.width-pref.width)/2; clickYShift = top + (size.height - pref.height)/2; } else { g2.translate((size.width - pref.width) / 2, 0); clickXShift = left + (size.width-pref.width)/2; clickYShift = top; } FontMetrics boxFontMetrics = g2.getFontMetrics(boxFont); int diamondX[] = new int[4]; int diamondY[] = new int[4]; Polygon diamond; left = H_BORDER; top = V_BORDER; FontMetrics metrics; int ascent; g2.setColor(this.getBackground()); g2.fillRect(0,0,pref.width,pref.height); g2.setColor(Color.BLACK); BasicStroke thickerStroke = new BasicStroke(1); BasicStroke thinnerStroke = new BasicStroke(0.35f); BasicStroke fatStroke = new BasicStroke(2.5f); float dash1[] = {5.0f}; BasicStroke dashedFatStroke = new BasicStroke(2.5f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 5.0f, dash1, 0.0f); g2.setFont(markerNameFont); metrics = g2.getFontMetrics(); ascent = metrics.getAscent(); if (theData.infoKnown) { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //// draw the marker locations int wide = (dPrimeTable.length-1) * boxSize; //TODO: talk to kirby about locusview scaling gizmo int lineLeft = wide/20; int lineSpan = (wide/10)*9; long minpos = Chromosome.getMarker(0).getPosition(); long maxpos = Chromosome.getMarker(Chromosome.getSize()-1).getPosition(); double spanpos = maxpos - minpos; g2.setStroke(thinnerStroke); g2.setColor(Color.white); g2.fillRect(left + lineLeft, 5, lineSpan, TICK_HEIGHT); g2.setColor(Color.black); g2.drawRect(left + lineLeft, 5, lineSpan, TICK_HEIGHT); for (int i = 0; i < Chromosome.getFilteredSize(); i++) { double pos = (Chromosome.getFilteredMarker(i).getPosition() - minpos) / spanpos; int xx = (int) (left + lineLeft + lineSpan*pos); g2.setStroke(thickerStroke); g2.drawLine(xx, 5, xx, 5 + TICK_HEIGHT); g2.setStroke(thinnerStroke); g2.drawLine(xx, 5 + TICK_HEIGHT, left + i*boxSize, TICK_BOTTOM); } top += TICK_BOTTOM; //// draw the marker names if (printDetails){ widestMarkerName = metrics.stringWidth(Chromosome.getFilteredMarker(0).getName()); for (int x = 1; x < dPrimeTable.length; x++) { int thiswide = metrics.stringWidth(Chromosome.getFilteredMarker(x).getName()); if (thiswide > widestMarkerName) widestMarkerName = thiswide; } g2.translate(left, top + widestMarkerName); g2.rotate(-Math.PI / 2.0); for (int x = 0; x < dPrimeTable.length; x++) { if (theData.isInBlock[Chromosome.realIndex[x]]){ g2.setFont(boldMarkerNameFont); }else{ g2.setFont(markerNameFont); } g2.drawString(Chromosome.getFilteredMarker(x).getName(),TEXT_GAP, x*boxSize + ascent/3); } 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); } blockDispHeight = ascent+boxSize/2; top += blockDispHeight; //// draw the marker numbers if (printDetails){ g2.setFont(markerNumFont); metrics = g2.getFontMetrics(); ascent = metrics.getAscent(); for (int x = 0; x < dPrimeTable.length; x++) { String mark = String.valueOf(Chromosome.realIndex[x] + 1); g2.drawString(mark, left + x*boxSize - metrics.stringWidth(mark)/2, top + ascent); } top += boxRadius/2; // give a little space between numbers and boxes } //the following values are the bounds on the boxes we want to //display given that the current window is 'visRect' lowX = (visRect.x-clickXShift-(visRect.y + visRect.height-clickYShift))/boxSize; if (lowX < 0) { lowX = 0; } highX = ((visRect.x + visRect.width)/boxSize)+1; if (highX > dPrimeTable.length-1){ highX = dPrimeTable.length-1; } lowY = ((visRect.x-clickXShift)+(visRect.y-clickYShift))/boxSize; if (lowY < lowX+1){ lowY = lowX+1; } highY = (((visRect.x-clickXShift+visRect.width) + (visRect.y-clickYShift+visRect.height))/boxSize)+1; if (highY > dPrimeTable.length){ highY = dPrimeTable.length; } // 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[x][y] == null){ continue; } double d = dPrimeTable[x][y].getDPrime(); //double l = dPrimeTable[x][y].getLOD(); Color boxColor = dPrimeTable[x][y].getColor(); // draw markers above int xx = left + (x + y) * boxSize / 2; int yy = top + (y - x) * boxSize / 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 (boxColor == Color.white) { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setColor(Color.lightGray); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } if(printDetails){ g2.setFont(boxFont); ascent = boxFontMetrics.getAscent(); int val = (int) (d * 100); g2.setColor((val < 50) ? Color.gray : Color.black); if (val != 100) { String valu = String.valueOf(val); int widf = boxFontMetrics.stringWidth(valu); g.drawString(valu, xx - widf/2, yy + ascent/2); } } } } //highlight blocks boolean even = true; 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.drawLine(left + (2*first) * boxSize/2 - boxRadius, top, left + (first + last) * boxSize/2, top + (last - first) * boxSize/2 + boxRadius); g2.drawLine(left + (first + last) * boxSize/2, top + (last - first) * boxSize/2 + boxRadius, left + (2*last) * boxSize/2+boxRadius, top); for (int j = first; j <= last; j++){ if (theData.isInBlock[j]){ g2.setStroke(fatStroke); }else{ g2.setStroke(dashedFatStroke); } g2.drawLine(left+j*boxSize-boxSize/2, top-blockDispHeight, left+j*boxSize+boxSize/2, top-blockDispHeight); /* //little vees on top of each marker g2.drawLine(left + (2*theBlock[j+1]) * boxSize/2, top + boxSize/2, left + (2*theBlock[j+1]) * boxSize/2 + boxRadius, top+1); g2.drawLine (left + (2*theBlock[j+1]) * boxSize/2, top + boxSize/2, left + (2*theBlock[j+1]-1) * boxSize/2, top); */ } //special lines for fencepost markers /*g2.drawLine(left+first*boxSize+1, top+boxRadius, left+first*boxSize+boxRadius, top+1); g2.drawLine(left+last*boxSize-1, top+boxRadius, left+last*boxSize-boxRadius, top+1); */ //lines to connect to block display g2.setStroke(fatStroke); g2.drawLine(left + first*boxSize-boxSize/2, top-1, left+first*boxSize-boxSize/2, top-blockDispHeight); g2.drawLine(left+last*boxSize+boxSize/2, top-1, left+last*boxSize+boxSize/2, top-blockDispHeight); String labelString = new String ("Block " + (i+1)); g2.drawString(labelString, left+first*boxSize-boxSize/2+TEXT_GAP, top-boxSize/2); } g2.setStroke(thickerStroke); if (pref.getWidth() > (2*visRect.width)){ //dataset is big enough to require worldmap if (noImage){ //first time through draw a worldmap if dataset is big: final int WM_BD_HEIGHT = 4; final int WM_MAX_WIDTH = visRect.width/3; double sizingScalefactor; sizingScalefactor = (double) (chartSize.width)/WM_MAX_WIDTH; double scalefactor; scalefactor = (double)(chartSize.width)/(WM_MAX_WIDTH-WM_BD_HEIGHT*4); CompoundBorder wmBorder = new CompoundBorder(BorderFactory.createRaisedBevelBorder(), BorderFactory.createLoweredBevelBorder()); worldmap = new BufferedImage((int)(chartSize.width/scalefactor)+wmBorder.getBorderInsets(this).left*2, (int)(chartSize.height/sizingScalefactor)+wmBorder.getBorderInsets(this).top*2, BufferedImage.TYPE_3BYTE_BGR); Graphics gw = worldmap.getGraphics(); Graphics2D gw2 = (Graphics2D)(gw); gw2.setColor(this.getBackground()); gw2.fillRect(1,1,worldmap.getWidth()-2,worldmap.getHeight()-2); //make a pretty border gw2.setColor(Color.BLACK); wmBorder.paintBorder(this,gw2,0,0,worldmap.getWidth()-1,worldmap.getHeight()-1); ir = wmBorder.getInteriorRectangle(this,0,0,worldmap.getWidth()-1, worldmap.getHeight()-1); ir.height -= WM_BD_HEIGHT; double prefBoxSize = boxSize/scalefactor; float[] smallDiamondX = new float[4]; float[] smallDiamondY = new float[4]; GeneralPath gp; for (int x = 0; x < dPrimeTable.length-1; x++){ for (int y = x+1; y < dPrimeTable.length; y++){ if (dPrimeTable[x][y] == null){ continue; } double xx = (x + y)*prefBoxSize/2+wmBorder.getBorderInsets(this).left; double yy = (y - x)*prefBoxSize/2+wmBorder.getBorderInsets(this).top+WM_BD_HEIGHT; 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[x][y].getColor()); gw2.fill(gp); } } //draw block display in worldmap gw2.setColor(this.getBackground()); gw2.fillRect(wmBorder.getBorderInsets(this).left, wmBorder.getBorderInsets(this).top, ir.width, WM_BD_HEIGHT); gw2.setColor(Color.black); 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*first), wmBorder.getBorderInsets(this).top+voffset, (int)((last-first)*prefBoxSize), WM_BD_HEIGHT/2); even = !even; } noImage = false; } g2.drawImage(worldmap,visRect.x, visRect.y + visRect.height - worldmap.getHeight(), this); worldmapRect = new Rectangle(visRect.x, visRect.y+visRect.height-worldmap.getHeight(), worldmap.getWidth(), worldmap.getHeight()); //draw the outline of the viewport g2.setColor(Color.BLACK); double hRatio = ir.getWidth()/pref.getWidth(); double vRatio = ir.getHeight()/pref.getHeight(); int hBump = worldmap.getWidth()-ir.width; int vBump = worldmap.getHeight()-ir.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)); } }
|
public void paintComponent(Graphics g){ PairwiseLinkage[][] dPrimeTable = theData.filteredDPrimeTable; Vector blocks = theData.blocks; Graphics2D g2 = (Graphics2D) g; Dimension size = getSize(); Dimension pref = getPreferredSize(); Rectangle visRect = getVisibleRect(); /* boxSize = ((clipRect.width-2*H_BORDER)/dPrimeTable.length-1); if (boxSize < 12){boxSize=12;} if (boxSize < 25){ printDetails = false; boxRadius = boxSize/2; }else{ boxRadius = boxSize/2 - 1; } */ //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. //clickxshift and clickyshift are used later to translate from x,y coords //to the pair of markers comparison at those coords if (!(theData.infoKnown)){ g2.translate((size.width - pref.width) / 2, (size.height - pref.height) / 2); clickXShift = left + (size.width-pref.width)/2; clickYShift = top + (size.height - pref.height)/2; } else { g2.translate((size.width - pref.width) / 2, 0); clickXShift = left + (size.width-pref.width)/2; clickYShift = top; } FontMetrics boxFontMetrics = g2.getFontMetrics(boxFont); int diamondX[] = new int[4]; int diamondY[] = new int[4]; Polygon diamond; left = H_BORDER; top = V_BORDER; FontMetrics metrics; int ascent; g2.setColor(this.getBackground()); g2.fillRect(0,0,pref.width,pref.height); g2.setColor(Color.BLACK); BasicStroke thickerStroke = new BasicStroke(1); BasicStroke thinnerStroke = new BasicStroke(0.35f); BasicStroke fatStroke = new BasicStroke(2.5f); float dash1[] = {5.0f}; BasicStroke dashedFatStroke = new BasicStroke(2.5f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 5.0f, dash1, 0.0f); g2.setFont(markerNameFont); metrics = g2.getFontMetrics(); ascent = metrics.getAscent(); if (theData.infoKnown) { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //// draw the marker locations int wide = (dPrimeTable.length-1) * boxSize; //TODO: talk to kirby about locusview scaling gizmo int lineLeft = wide/20; int lineSpan = (wide/10)*9; long minpos = Chromosome.getMarker(0).getPosition(); long maxpos = Chromosome.getMarker(Chromosome.getSize()-1).getPosition(); double spanpos = maxpos - minpos; g2.setStroke(thinnerStroke); g2.setColor(Color.white); g2.fillRect(left + lineLeft, 5, lineSpan, TICK_HEIGHT); g2.setColor(Color.black); g2.drawRect(left + lineLeft, 5, lineSpan, TICK_HEIGHT); for (int i = 0; i < Chromosome.getFilteredSize(); i++) { double pos = (Chromosome.getFilteredMarker(i).getPosition() - minpos) / spanpos; int xx = (int) (left + lineLeft + lineSpan*pos); g2.setStroke(thickerStroke); g2.drawLine(xx, 5, xx, 5 + TICK_HEIGHT); g2.setStroke(thinnerStroke); g2.drawLine(xx, 5 + TICK_HEIGHT, left + i*boxSize, TICK_BOTTOM); } top += TICK_BOTTOM; //// draw the marker names if (printDetails){ widestMarkerName = metrics.stringWidth(Chromosome.getFilteredMarker(0).getName()); for (int x = 1; x < dPrimeTable.length; x++) { int thiswide = metrics.stringWidth(Chromosome.getFilteredMarker(x).getName()); if (thiswide > widestMarkerName) widestMarkerName = thiswide; } g2.translate(left, top + widestMarkerName); g2.rotate(-Math.PI / 2.0); for (int x = 0; x < dPrimeTable.length; x++) { if (theData.isInBlock[Chromosome.realIndex[x]]){ g2.setFont(boldMarkerNameFont); }else{ g2.setFont(markerNameFont); } g2.drawString(Chromosome.getFilteredMarker(x).getName(),TEXT_GAP, x*boxSize + ascent/3); } 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); } blockDispHeight = ascent+boxSize/2; top += blockDispHeight; //// draw the marker numbers if (printDetails){ g2.setFont(markerNumFont); metrics = g2.getFontMetrics(); ascent = metrics.getAscent(); for (int x = 0; x < dPrimeTable.length; x++) { String mark = String.valueOf(Chromosome.realIndex[x] + 1); g2.drawString(mark, left + x*boxSize - metrics.stringWidth(mark)/2, top + ascent); } top += boxRadius/2; // give a little space between numbers and boxes } //the following values are the bounds on the boxes we want to //display given that the current window is 'visRect' lowX = (visRect.x-clickXShift-(visRect.y + visRect.height-clickYShift))/boxSize; if (lowX < 0) { lowX = 0; } highX = ((visRect.x + visRect.width)/boxSize)+1; if (highX > dPrimeTable.length-1){ highX = dPrimeTable.length-1; } lowY = ((visRect.x-clickXShift)+(visRect.y-clickYShift))/boxSize; if (lowY < lowX+1){ lowY = lowX+1; } highY = (((visRect.x-clickXShift+visRect.width) + (visRect.y-clickYShift+visRect.height))/boxSize)+1; if (highY > dPrimeTable.length){ highY = dPrimeTable.length; } // 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[x][y] == null){ continue; } double d = dPrimeTable[x][y].getDPrime(); //double l = dPrimeTable[x][y].getLOD(); Color boxColor = dPrimeTable[x][y].getColor(); // draw markers above int xx = left + (x + y) * boxSize / 2; int yy = top + (y - x) * boxSize / 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 (boxColor == Color.white) { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setColor(Color.lightGray); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } if(printDetails){ g2.setFont(boxFont); ascent = boxFontMetrics.getAscent(); int val = (int) (d * 100); g2.setColor((val < 50) ? Color.gray : Color.black); if (val != 100) { String valu = String.valueOf(val); int widf = boxFontMetrics.stringWidth(valu); g.drawString(valu, xx - widf/2, yy + ascent/2); } } } } //highlight blocks boolean even = true; 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.drawLine(left + (2*first) * boxSize/2 - boxRadius, top, left + (first + last) * boxSize/2, top + (last - first) * boxSize/2 + boxRadius); g2.drawLine(left + (first + last) * boxSize/2, top + (last - first) * boxSize/2 + boxRadius, left + (2*last) * boxSize/2+boxRadius, top); for (int j = first; j <= last; j++){ if (theData.isInBlock[j]){ g2.setStroke(fatStroke); }else{ g2.setStroke(dashedFatStroke); } g2.drawLine(left+j*boxSize-boxSize/2, top-blockDispHeight, left+j*boxSize+boxSize/2, top-blockDispHeight); /* //little vees on top of each marker g2.drawLine(left + (2*theBlock[j+1]) * boxSize/2, top + boxSize/2, left + (2*theBlock[j+1]) * boxSize/2 + boxRadius, top+1); g2.drawLine (left + (2*theBlock[j+1]) * boxSize/2, top + boxSize/2, left + (2*theBlock[j+1]-1) * boxSize/2, top); */ } //special lines for fencepost markers /*g2.drawLine(left+first*boxSize+1, top+boxRadius, left+first*boxSize+boxRadius, top+1); g2.drawLine(left+last*boxSize-1, top+boxRadius, left+last*boxSize-boxRadius, top+1); */ //lines to connect to block display g2.setStroke(fatStroke); g2.drawLine(left + first*boxSize-boxSize/2, top-1, left+first*boxSize-boxSize/2, top-blockDispHeight); g2.drawLine(left+last*boxSize+boxSize/2, top-1, left+last*boxSize+boxSize/2, top-blockDispHeight); String labelString = new String ("Block " + (i+1)); g2.drawString(labelString, left+first*boxSize-boxSize/2+TEXT_GAP, top-boxSize/2); } g2.setStroke(thickerStroke); if (pref.getWidth() > (2*visRect.width)){ //dataset is big enough to require worldmap if (noImage){ //first time through draw a worldmap if dataset is big: final int WM_BD_HEIGHT = 4; final int WM_MAX_WIDTH = visRect.width/3; double sizingScalefactor; sizingScalefactor = (double) (chartSize.width)/WM_MAX_WIDTH; double scalefactor; scalefactor = (double)(chartSize.width)/(WM_MAX_WIDTH-WM_BD_HEIGHT*4); CompoundBorder wmBorder = new CompoundBorder(BorderFactory.createRaisedBevelBorder(), BorderFactory.createLoweredBevelBorder()); worldmap = new BufferedImage((int)(chartSize.width/scalefactor)+wmBorder.getBorderInsets(this).left*2, (int)(chartSize.height/sizingScalefactor)+wmBorder.getBorderInsets(this).top*2, BufferedImage.TYPE_3BYTE_BGR); Graphics gw = worldmap.getGraphics(); Graphics2D gw2 = (Graphics2D)(gw); gw2.setColor(this.getBackground()); gw2.fillRect(1,1,worldmap.getWidth()-2,worldmap.getHeight()-2); //make a pretty border gw2.setColor(Color.black); wmBorder.paintBorder(this,gw2,0,0,worldmap.getWidth()-1,worldmap.getHeight()-1); ir = wmBorder.getInteriorRectangle(this,0,0,worldmap.getWidth()-1, worldmap.getHeight()-1); ir.height -= WM_BD_HEIGHT; double prefBoxSize = boxSize/scalefactor; float[] smallDiamondX = new float[4]; float[] smallDiamondY = new float[4]; GeneralPath gp; for (int x = 0; x < dPrimeTable.length-1; x++){ for (int y = x+1; y < dPrimeTable.length; y++){ if (dPrimeTable[x][y] == null){ continue; } double xx = (x + y)*prefBoxSize/2+wmBorder.getBorderInsets(this).left; double yy = (y - x)*prefBoxSize/2+wmBorder.getBorderInsets(this).top+WM_BD_HEIGHT; 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[x][y].getColor()); gw2.fill(gp); } } //draw block display in worldmap gw2.setColor(this.getBackground()); gw2.fillRect(wmBorder.getBorderInsets(this).left, wmBorder.getBorderInsets(this).top, ir.width, WM_BD_HEIGHT); gw2.setColor(Color.black); 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*first), wmBorder.getBorderInsets(this).top+voffset, (int)((last-first)*prefBoxSize), WM_BD_HEIGHT/2); even = !even; } noImage = false; } g2.drawImage(worldmap,visRect.x, visRect.y + visRect.height - worldmap.getHeight(), this); worldmapRect = new Rectangle(visRect.x, visRect.y+visRect.height-worldmap.getHeight(), worldmap.getWidth(), worldmap.getHeight()); //draw the outline of the viewport g2.setColor(Color.BLACK); double hRatio = ir.getWidth()/pref.getWidth(); double vRatio = ir.getHeight()/pref.getHeight(); int hBump = worldmap.getWidth()-ir.width; int vBump = worldmap.getHeight()-ir.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)); } }
| 1,108,827
|
public void actionPerformed(ActionEvent e) { if (e.getSource() == connection) { setComps(connComp, true); setComps(physicalComp, false); setComps(loadComp, false); } else if (e.getSource() == physical) { setComps(connComp, false); setComps(physicalComp, true); setComps(loadComp, false); } else if (e.getSource() == load) { setComps(connComp, false); setComps(physicalComp, false); setComps(loadComp, true); } else { throw new IllegalStateException("Unhandle Button"); } }
|
public void actionPerformed(ActionEvent e) { if (e.getSource() == connection) { setComps(connComp, true); setComps(physicalComp, false); setComps(loadComp, false); } else if (e.getSource() == physical) { setComps(connComp, false); setComps(physicalComp, true); setComps(loadComp, false); } else if (e.getSource() == load) { setComps(connComp, false); setComps(physicalComp, false); setComps(loadComp, true); } else { throw new IllegalStateException("Unhandle Button"); } }
| 1,108,828
|
private void buildPartialUI(DefaultFormBuilder builder, boolean defaultPlayPen) { String prefix; if (defaultPlayPen == true){ prefix = "source"; } else{ prefix = "target"; } CellConstraints cc = new CellConstraints(); ArchitectFrame af = ArchitectFrame.getMainInstance(); SwingUIProject project = af.getProject(); playPenRadio = new JRadioButton(); playPenRadio.setName (prefix + "PlayPenRadio"); physicalRadio = new JRadioButton(); physicalRadio.setName(prefix + "PhysicalRadio"); loadRadio = new JRadioButton(); loadRadio.setName(prefix + "LoadRadio"); buttonGroup.add(playPenRadio); buttonGroup.add(physicalRadio); buttonGroup.add(loadRadio); schemaDropdown = new JComboBox(); schemaDropdown.setEnabled(false); schemaDropdown.setName(prefix + "SchemaDropdown"); catalogDropdown = new JComboBox(); catalogDropdown.setEnabled(false); catalogDropdown.setName(prefix + "CatalogDropdown"); databaseDropdown = new JComboBox(); databaseDropdown.setName(prefix + "DatabaseDropdown"); databaseDropdown.addItem(null); // the non-selection selection for (ArchitectDataSource ds : af.getUserSettings().getConnections()) { databaseDropdown.addItem(ds); } databaseDropdown.setEnabled(false); databaseDropdown.setRenderer(dataSourceRenderer); newConnButton = new JButton(); newConnButton.setName(prefix + "NewConnButton"); newConnButton.setAction(newConnectionAction); newConnectionAction.setEnabled(false); loadFilePath = new JTextField(); loadFilePath.setName(prefix + "LoadFilePath"); loadFilePath.setEnabled(false); loadFilePath.getDocument().addDocumentListener(new DocumentListener() { public void insertUpdate(DocumentEvent e) { startCompareAction.setEnabled(isStartable()); } public void removeUpdate(DocumentEvent e) { startCompareAction.setEnabled(isStartable()); } public void changedUpdate(DocumentEvent e) { startCompareAction.setEnabled(isStartable()); } }); loadFileButton = new JButton(); loadFileButton.setName(prefix + "LoadFileButton"); loadFileButton.setAction(chooseFileAction); chooseFileAction.setEnabled(false); catalogDropdown.addActionListener(new SchemaPopulator()); databaseDropdown.addActionListener(new CatalogPopulator()); physicalComp = new ArrayList<JComponent>(); physicalComp.add(databaseDropdown); physicalComp.add(catalogDropdown); physicalComp.add(schemaDropdown); physicalComp.add(newConnButton); loadComp = new ArrayList<JComponent>(); loadComp.add(loadFilePath); loadComp.add(loadFileButton); ActionListener listener = new OptionGroupListener( playPenRadio, null, physicalRadio, physicalComp, loadRadio, loadComp); playPenRadio.addActionListener(listener); physicalRadio.addActionListener(listener); loadRadio.addActionListener(listener); if (defaultPlayPen) { playPenRadio.doClick(); } else { physicalRadio.doClick(); } // now give all our shiny new components to the builder builder.append(playPenRadio); builder.append("Current Project [" + project.getName() + "]"); builder.nextLine(); builder.append(""); // takes up blank space builder.append(physicalRadio); builder.append("Physical Database"); //builder.nextColumn(2); builder.append("Catalog"); builder.append("Schema"); builder.appendRow(builder.getLineGapSpec()); builder.appendRow("pref"); builder.nextLine(2); builder.nextColumn(4); builder.append(databaseDropdown); builder.append(catalogDropdown, schemaDropdown, newConnButton); builder.nextLine(); builder.append(""); builder.append(loadRadio); builder.append("From File:"); builder.nextLine(); builder.append(""); // takes up blank space builder.add(loadFilePath, cc.xyw(5, builder.getRow(), 5)); builder.nextColumn(8); builder.append(loadFileButton); builder.nextLine(); }
|
private void buildPartialUI(DefaultFormBuilder builder, boolean defaultPlayPen) { String prefix; if (defaultPlayPen == true){ prefix = "source"; } else{ prefix = "target"; } CellConstraints cc = new CellConstraints(); ArchitectFrame af = ArchitectFrame.getMainInstance(); SwingUIProject project = af.getProject(); playPenRadio = new JRadioButton(); playPenRadio.setName (prefix + "PlayPenRadio"); physicalRadio = new JRadioButton(); physicalRadio.setName(prefix + "PhysicalRadio"); loadRadio = new JRadioButton(); loadRadio.setName(prefix + "LoadRadio"); buttonGroup.add(playPenRadio); buttonGroup.add(physicalRadio); buttonGroup.add(loadRadio); schemaDropdown = new JComboBox(); schemaDropdown.setEnabled(false); schemaDropdown.setName(prefix + "SchemaDropdown"); catalogDropdown = new JComboBox(); catalogDropdown.setEnabled(false); catalogDropdown.setName(prefix + "CatalogDropdown"); databaseDropdown = new JComboBox(); databaseDropdown.setName(prefix + "DatabaseDropdown"); databaseDropdown.addItem(null); // the non-selection selection for (ArchitectDataSource ds : af.getUserSettings().getConnections()) { databaseDropdown.addItem(ds); } databaseDropdown.setEnabled(false); databaseDropdown.setRenderer(dataSourceRenderer); newConnButton = new JButton(); newConnButton.setName(prefix + "NewConnButton"); newConnButton.setAction(newConnectionAction); newConnectionAction.setEnabled(false); loadFilePath = new JTextField(); loadFilePath.setName(prefix + "LoadFilePath"); loadFilePath.setEnabled(false); loadFilePath.getDocument().addDocumentListener(new DocumentListener() { public void insertUpdate(DocumentEvent e) { startCompareAction.setEnabled(isStartable()); } public void removeUpdate(DocumentEvent e) { startCompareAction.setEnabled(isStartable()); } public void changedUpdate(DocumentEvent e) { startCompareAction.setEnabled(isStartable()); } }); loadFileButton = new JButton(); loadFileButton.setName(prefix + "LoadFileButton"); loadFileButton.setAction(chooseFileAction); chooseFileAction.setEnabled(false); catalogDropdown.addActionListener(new SchemaPopulator()); databaseDropdown.addActionListener(new CatalogPopulator()); physicalComp = new ArrayList<JComponent>(); physicalComp.add(databaseDropdown); physicalComp.add(catalogDropdown); physicalComp.add(schemaDropdown); physicalComp.add(newConnButton); loadComp = new ArrayList<JComponent>(); loadComp.add(loadFilePath); loadComp.add(loadFileButton); ActionListener listener = new OptionGroupListener( playPenRadio, null, physicalRadio, physicalComp, loadRadio, loadComp); playPenRadio.addActionListener(listener); physicalRadio.addActionListener(listener); loadRadio.addActionListener(listener); if (defaultPlayPen) { playPenRadio.doClick(); } else { physicalRadio.doClick(); } // now give all our shiny new components to the builder builder.append(playPenRadio); builder.append("Current Project [" + project.getName() + "]"); builder.nextLine(); builder.append(""); // takes up blank space builder.append(physicalRadio); builder.append("Physical Database"); //builder.nextColumn(2); builder.append("Catalog"); builder.append("Schema"); builder.appendRow(builder.getLineGapSpec()); builder.appendRow("pref"); builder.nextLine(2); builder.nextColumn(4); builder.append(databaseDropdown); builder.append(catalogDropdown, schemaDropdown, newConnButton); builder.nextLine(); builder.append(""); builder.append(loadRadio); builder.append("From File:"); builder.nextLine(); builder.append(""); // takes up blank space builder.add(loadFilePath, cc.xyw(5, builder.getRow(), 5)); builder.nextColumn(8); builder.append(loadFileButton); builder.nextLine(); }
| 1,108,829
|
public void modifyColumn(SQLColumn c) throws ArchitectDiffException { Map colNameMap = new HashMap(); SQLTable t = c.getParentTable(); print("\n ALTER TABLE "); printQualified(t.getPhysicalName()); print(" ALTER COLUMN "); print(columnDefinition(c,colNameMap)); endStatement(DDLStatement.StatementType.MODIFY, c); }
|
public void modifyColumn(SQLColumn c) throws ArchitectDiffException { Map colNameMap = new HashMap(); SQLTable t = c.getParentTable(); print("\n ALTER TABLE "); print( DDLUtils.toQualifiedName(t.getCatalogName(),t.getSchemaName(),t.getPhysicalName()) ); print(" ALTER COLUMN "); print(columnDefinition(c,colNameMap)); endStatement(DDLStatement.StatementType.MODIFY, c); }
| 1,108,830
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.