List of usage examples for java.awt Dimension setSize
public void setSize(Dimension d)
From source file:org.sugarcrm.voodoodriver.Utils.java
/** * Take a screen shot and save it to the specified file. * * @param outputFile file to save the screenshot into * @param reporter {@link Reporter} object for logging errors * @param logOK whether logging to reporter is OK. false if this * is called from a reporter object. * @return whether the screenshot was taken successfully *//*from w w w . j a va 2 s . c o m*/ public static boolean takeScreenShot(String outputFile, Reporter reporter, boolean logOK) { Robot r = null; reporter.Log("Taking Screenshot."); File tmp = new File(outputFile); if (tmp.exists() && logOK) { String msg; msg = String.format("Existing screenshot '%s' will be overwritten.", outputFile); reporter.Warn(msg); } try { r = new Robot(); } catch (java.awt.AWTException e) { if (logOK) { reporter.ReportError("Screenshot failed (running headless?)"); reporter.ReportException(e); } return false; } Rectangle rec = new Rectangle(); Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); dim.setSize(dim); rec.setSize(dim); BufferedImage img = r.createScreenCapture(rec); try { ImageIO.write(img, "png", new File(outputFile)); } catch (java.io.IOException e) { if (logOK) { reporter.ReportError("Screenshot failed (I/O Error)"); reporter.ReportException(e); } return false; } reporter.Log(String.format("Screenshot file: %s", outputFile)); reporter.Log("Screenshot finished."); return true; }
From source file:edu.harvard.mcz.imagecapture.jobs.JobAllImageFilesScan.java
private void checkFiles(File startPoint, Counter counter) { // pick jpeg files // for each file check name against database, if not found, check barcodes, scan and parse text, create records. log.debug("Scanning directory: " + startPoint.getPath()); File[] containedFiles = startPoint.listFiles(); log.debug("Directory contains " + containedFiles.length + " entries."); if (containedFiles.length > 0) { // create thumbnails in a separate thread (new Thread(new ThumbnailBuilderInternal(startPoint))).start(); }/*from w w w .j av a2 s . c o m*/ for (int i = 0; i < containedFiles.length; i++) { if (runStatus != RunStatus.STATUS_TERMINATED) { log.debug("Scanning directory: " + startPoint.getPath()); File fileToCheck = containedFiles[i]; Singleton.getSingletonInstance().getMainFrame() .setStatusMessage("Scanning: " + fileToCheck.getName()); log.debug("Scanning: " + fileToCheck.getName()); if (fileToCheck.isDirectory()) { if (fileToCheck.canRead()) { // Skip thumbs directories if (!fileToCheck.getName().equals("thumbs")) { checkFiles(fileToCheck, counter); counter.incrementDirectories(); } } else { counter.incrementDirectoriesFailed(); } } else { // check JPEG files for barcodes if (!fileToCheck.getName().matches(Singleton.getSingletonInstance().getProperties() .getProperties().getProperty(ImageCaptureProperties.KEY_IMAGEREGEX))) { log.debug("Skipping file [" + fileToCheck.getName() + "], doesn't match expected filename pattern " + Singleton.getSingletonInstance().getProperties().getProperties() .getProperty(ImageCaptureProperties.KEY_IMAGEREGEX)); } else { if (firstFile == null) { firstFile = fileToCheck.getName(); } lastFile = fileToCheck.getName(); Singleton.getSingletonInstance().getProperties().getProperties() .setProperty(ImageCaptureProperties.KEY_LASTPATH, fileToCheck.getPath()); String filename = fileToCheck.getName(); counter.incrementFilesSeen(); log.debug("Checking image file: " + filename); CandidateImageFile.debugCheckHeightWidth(fileToCheck); // scan file for barcodes and ocr of unit tray label text CandidateImageFile scannableFile = null; try { // PositionTemplateDetector detector = new ConfiguredBarcodePositionTemplateDetector(); boolean isSpecimenImage = false; boolean isDrawerImage = false; boolean reattach = false; // image is detached instance and should be reattached instead of persisted denovo. // try { // Check for an existing image record. ICImageLifeCycle imageCont = new ICImageLifeCycle(); ICImage tryMe = new ICImage(); tryMe.setFilename(filename); String path = ImageCaptureProperties.getPathBelowBase(fileToCheck); tryMe.setPath(path); List<ICImage> matches = imageCont.findByExample(tryMe); log.debug(matches.size()); if (matches != null && matches.size() == 1 && matches.get(0).getRawBarcode() == null && matches.get(0).getRawExifBarcode() == null && (matches.get(0).getDrawerNumber() == null || matches.get(0).getDrawerNumber().trim().length() == 0)) { // likely case for a failure to read data out of the image file // try to update the image file record. try { tryMe = imageCont.merge(matches.get(0)); matches.remove(0); reattach = true; log.debug(tryMe); } catch (SaveFailedException e) { log.error(e.getMessage(), e); } } else if (matches != null && matches.size() == 1 && matches.get(0).getSpecimen() == null) { // likely case for a failure to create a specimen record in a previous run // try to update the image file record try { tryMe = imageCont.merge(matches.get(0)); matches.remove(0); reattach = true; log.debug(tryMe); } catch (SaveFailedException e) { log.error(e.getMessage(), e); } } if (matches != null && matches.size() == 0) { // No database record for this file. // ** Identify the template. // String templateId = detector.detectTemplateForImage(fileToCheck); // log.debug("Detected Template: " + templateId); // PositionTemplate template = new PositionTemplate(templateId); // // Found a barcode in a templated position in the image. // // ** Scan the file based on this template. // scannableFile = new CandidateImageFile(fileToCheck, template); // Construct a CandidateImageFile with constructor that self detects template scannableFile = new CandidateImageFile(fileToCheck); PositionTemplate template = scannableFile.getTemplateUsed(); String templateId = template.getName(); log.debug("Detected Template: " + templateId); log.debug(scannableFile.getCatalogNumberBarcodeStatus()); String barcode = scannableFile.getBarcodeTextAtFoundTemplate(); if (scannableFile .getCatalogNumberBarcodeStatus() != CandidateImageFile.RESULT_BARCODE_SCANNED) { log.error("Error scanning for barcode: " + barcode); barcode = ""; } log.debug(barcode); System.out.println("Barcode=" + barcode); String exifComment = scannableFile.getExifUserCommentText(); log.debug(exifComment); TaxonNameReturner parser = null; String rawOCR = ""; UnitTrayLabel labelRead = null; String state = WorkFlowStatus.STAGE_0; labelRead = scannableFile.getTaxonLabelQRText(template); if (labelRead == null) { try { labelRead = scannableFile .getTaxonLabelQRText(new PositionTemplate("Test template 2")); } catch (NoSuchTemplateException e) { try { labelRead = scannableFile .getTaxonLabelQRText(new PositionTemplate("Small template 2")); } catch (NoSuchTemplateException e1) { log.error("Neither Test template 2 nor Small template 2 found"); } } } else { log.debug(labelRead.toJSONString()); } if (labelRead != null) { rawOCR = labelRead.toJSONString(); state = WorkFlowStatus.STAGE_1; parser = (TaxonNameReturner) labelRead; } else { PositionTemplate shifted = null; try { shifted = new PositionTemplate("Test template 2"); } catch (NoSuchTemplateException e) { try { shifted = new PositionTemplate("Small template 2"); } catch (NoSuchTemplateException e1) { log.error("Neither Test template 2 nor Small template 2 found"); } } if (shifted != null) { int x = 5; int xmax = 9; Dimension utpos = shifted.getUtBarcodePosition(); while (x < xmax) { utpos.setSize(new Dimension(utpos.width + x, utpos.height)); shifted.setUtBarcodePosition(utpos); labelRead = scannableFile.getTaxonLabelQRText(shifted); x++; if (labelRead != null) { x = xmax; log.debug("Failover found: " + labelRead.getFamily() + " " + labelRead.getSubfamily() + " " + labelRead.getGenus()); } } } try { rawOCR = scannableFile.getLabelOCRText(template); } catch (OCRReadException e) { log.error(e); rawOCR = ""; log.error("Couldn't OCR file." + e.getMessage()); RunnableJobError error = new RunnableJobError(filename, "OCR Failed", barcode, exifComment, "Couldn't find text to OCR", null, null, e, RunnableJobError.TYPE_NO_TEMPLATE); counter.appendError(error); } if (labelRead == null) { if (rawOCR == null) { rawOCR = ""; } state = WorkFlowStatus.STAGE_0; parser = new UnitTrayLabelParser(rawOCR); // Provide error message to distinguish between entirely OCR or if (((UnitTrayLabelParser) parser).isParsedFromJSON()) { RunnableJobError error = new RunnableJobError(filename, "OCR Failover found barcode.", barcode, exifComment, "Couldn't read Taxon barcode, failed over to OCR, but OCR found taxon barcode.", (TaxonNameReturner) parser, null, null, RunnableJobError.TYPE_FAILOVER_TO_OCR); counter.appendError(error); } else { RunnableJobError error = new RunnableJobError(filename, "Failover to OCR.", barcode, exifComment, "Couldn't read Taxon barcode, failed over to OCR only.", (TaxonNameReturner) parser, null, null, RunnableJobError.TYPE_FAILOVER_TO_OCR); counter.appendError(error); } } else { state = WorkFlowStatus.STAGE_1; parser = labelRead; } } // Test: is exifComment a barcode: // Case 1: This is an image of papers associated with a container (a unit tray or a box). // This case can be identified by there being no barcode data associated with the image. // Action: // A) Check the exifComment to see what metadata is there, if blank, User needs to fix. // exifComment may contain a drawer number, identifying this as a drawer image. Save as such. // Options: A drawer, for which number is captured. A unit tray, capture ?????????. A specimen // where barcode wasn't read, allow capture of barcode and treat as Case 2. // B) Create an image record and store the image metadata (with a null specimen_id). // Case 2: This is an image of a specimen and associated labels or an image assocated with // a specimen with the specimen's barcode label in the image. // This case can be identified by there being a barcode in a templated position or there // being a barcode in the exif comment tag. // Action: // A) Check if a specimen record exists, if not, create one from the barcode and OCR data. // B) Create an image record and store the image metadata. if (Singleton.getSingletonInstance().getBarcodeMatcher().matchesPattern(exifComment) || Singleton.getSingletonInstance().getBarcodeMatcher() .matchesPattern(barcode)) { isSpecimenImage = true; System.out.println("Specimen Image"); } else { if (exifComment != null && exifComment.matches( Singleton.getSingletonInstance().getProperties().getProperties() .getProperty(ImageCaptureProperties.KEY_REGEX_DRAWERNUMBER))) { isDrawerImage = true; System.out.println("Drawer Image"); } else { if (templateId.equals(PositionTemplate.TEMPLATE_NO_COMPONENT_PARTS)) { log.debug( "Image doesn't appear to contain a barcode in a templated position."); counter.incrementFilesFailed(); RunnableJobError error = new RunnableJobError(filename, barcode, barcode, exifComment, "Image doesn't appear to contain a barcode in a templated position.", null, null, null, RunnableJobError.TYPE_NO_TEMPLATE); counter.appendError(error); } // Nothing found. Need to ask. // TODO: list failures on completion. counter.incrementFilesFailed(); } } String rawBarcode = barcode; if (isSpecimenImage) { if (!rawBarcode.equals(exifComment)) { // Use the exifComment if it is a barcode boolean barcodeInImageMetadata = false; if (Singleton.getSingletonInstance().getBarcodeMatcher() .matchesPattern(exifComment)) { barcodeInImageMetadata = true; } // Log the missmatch if (barcodeInImageMetadata || Singleton.getSingletonInstance() .getProperties().getProperties() .getProperty(ImageCaptureProperties.KEY_REDUNDANT_COMMENT_BARCODE) .equals("true")) { // If so configured, or if image metadata contains a barcode that doesn't match the barcode in the image // report on barcode/comment missmatch as an error condition. try { RunnableJobError error = new RunnableJobError(filename, barcode, barcode, exifComment, "Barcode/Comment missmatch.", parser, (DrawerNameReturner) parser, null, RunnableJobError.TYPE_MISMATCH); counter.appendError(error); } catch (Exception e) { // we don't want an exception to stop processing log.error(e); } } else { // Just write into debug log // This would normally the case where the image metadata doesn't contain a barcode but the image does, and reporting of this state as an error has been turned off. log.debug("Barcode/Comment missmatch: [" + barcode + "]!=[" + exifComment + "]"); } } Singleton.getSingletonInstance().getMainFrame() .setStatusMessage("Creating new specimen record."); Specimen s = new Specimen(); if ((!Singleton.getSingletonInstance().getBarcodeMatcher() .matchesPattern(barcode)) && Singleton.getSingletonInstance().getBarcodeMatcher() .matchesPattern(exifComment)) { // special case: coudn't read QR code barcode from image, but it was present in exif comment. s.setBarcode(exifComment); barcode = exifComment; } else { if (!Singleton.getSingletonInstance().getBarcodeMatcher() .matchesPattern(barcode)) { // Won't be able to save the specimen record if we end up here. log.error( "Neither exifComment nor QR Code barcode match the expected pattern for a barcode, but isSpecimenImage got set to true."); } s.setBarcode(barcode); } s.setWorkFlowStatus(state); if (labelRead != null) { // We got json data from a barcode. s.setFamily(parser.getFamily()); s.setSubfamily(parser.getSubfamily()); s.setTribe(parser.getTribe()); } else { // We failed over to OCR, try lookup in DB. s.setFamily(""); // make sure there's a a non-null value in family. if (parser.getTribe().trim().equals("")) { HigherTaxonLifeCycle hls = new HigherTaxonLifeCycle(); if (hls.isMatched(parser.getFamily(), parser.getSubfamily())) { // If there is a match, use it. String[] higher = hls.findMatch(parser.getFamily(), parser.getSubfamily()); s.setFamily(higher[0]); s.setSubfamily(higher[1]); } else { // otherwise use the raw OCR output. s.setFamily(parser.getFamily()); s.setSubfamily(parser.getSubfamily()); } s.setTribe(""); } else { HigherTaxonLifeCycle hls = new HigherTaxonLifeCycle(); if (hls.isMatched(parser.getFamily(), parser.getSubfamily(), parser.getTribe())) { String[] higher = hls.findMatch(parser.getFamily(), parser.getSubfamily(), parser.getTribe()); s.setFamily(higher[0]); s.setSubfamily(higher[1]); s.setTribe(higher[2]); } else { s.setFamily(parser.getFamily()); s.setSubfamily(parser.getSubfamily()); s.setTribe(parser.getTribe()); } } } if (state.equals(WorkFlowStatus.STAGE_0)) { // Look up likely matches for the OCR of the higher taxa in the HigherTaxon authority file. if (!parser.getFamily().equals("")) { // check family against database (with a soundex match) HigherTaxonLifeCycle hls = new HigherTaxonLifeCycle(); String match = hls.findMatch(parser.getFamily()); if (match != null && !match.trim().equals("")) { s.setFamily(match); } } } // trim family to fit (in case multiple parts of taxon name weren't parsed // and got concatenated into family field. if (s.getFamily().length() > 40) { s.setFamily(s.getFamily().substring(0, 40)); } s.setGenus(parser.getGenus()); s.setSpecificEpithet(parser.getSpecificEpithet()); s.setSubspecificEpithet(parser.getSubspecificEpithet()); s.setInfraspecificEpithet(parser.getInfraspecificEpithet()); s.setInfraspecificRank(parser.getInfraspecificRank()); s.setAuthorship(parser.getAuthorship()); s.setDrawerNumber(((DrawerNameReturner) parser).getDrawerNumber()); s.setCollection(((CollectionReturner) parser).getCollection()); s.setCreatingPath(ImageCaptureProperties.getPathBelowBase(fileToCheck)); s.setCreatingFilename(fileToCheck.getName()); if (parser.getIdentifiedBy() != null && parser.getIdentifiedBy().length() > 0) { s.setIdentifiedBy(parser.getIdentifiedBy()); } log.debug(s.getCollection()); // TODO: non-general workflows // TODO: Refactor special case handling of non-general workflows // ********* Special Cases ********** if (s.getWorkFlowStatus().equals(WorkFlowStatus.STAGE_0)) { // ***** Special case, images in ent-formicidae // get family set to Formicidae if in state OCR. if (path.contains("formicidae")) { s.setFamily("Formicidae"); } } s.setLocationInCollection(LocationInCollection.getDefaultLocation()); if (s.getFamily().equals("Formicidae")) { // ***** Special case, families in Formicidae are in Ant collection s.setLocationInCollection(LocationInCollection.GENERALANT); } // ********* End Special Cases ********** s.setCreatedBy(ImageCaptureApp.APP_NAME + " " + ImageCaptureApp.APP_VERSION); SpecimenLifeCycle sh = new SpecimenLifeCycle(); try { // *** Save a database record of the specimen. sh.persist(s); counter.incrementSpecimens(); s.attachNewPart(); } catch (SpecimenExistsException e) { log.debug(e.getMessage()); // Expected case on scanning a second image for a specimen. // Doesn't need to be reported as a parsing error. // // Look up the existing record to link this specimen to it. try { List<Specimen> checkResult = sh.findByBarcode(barcode); if (checkResult.size() == 1) { s = checkResult.get(0); } } catch (Exception e2) { s = null; // so that saving the image record doesn't fail on trying to save linked transient specimen record. String errorMessage = "Linking Error: \nFailed to link image to existing specimen record.\n"; RunnableJobError error = new RunnableJobError(filename, barcode, rawBarcode, exifComment, errorMessage, (TaxonNameReturner) parser, (DrawerNameReturner) parser, e2, RunnableJobError.TYPE_SAVE_FAILED); counter.appendError(error); } } catch (SaveFailedException e) { // Couldn't save for some reason other than the // specimen record already existing. Check for possible // save problems resulting from parsing errors. log.debug(e.getMessage()); try { List<Specimen> checkResult = sh.findByBarcode(barcode); if (checkResult.size() == 1) { s = checkResult.get(0); } String badParse = ""; // Drawer number with length limit (and specimen that fails to save at over this length makes // a good canary for labels that parse very badly. if (((DrawerNameReturner) parser).getDrawerNumber() .length() > MetadataRetriever.getFieldLength(Specimen.class, "DrawerNumber")) { badParse = "Parsing problem. \nDrawer number is too long: " + s.getDrawerNumber() + "\n"; } RunnableJobError error = new RunnableJobError(filename, barcode, rawBarcode, exifComment, badParse, (TaxonNameReturner) parser, (DrawerNameReturner) parser, null, RunnableJobError.TYPE_BAD_PARSE); counter.appendError(error); } catch (Exception err) { log.error(e); log.error(err); // TODO: Add a general error handling/inform user class. String badParse = ""; // Drawer number with length limit (and specimen that fails to save at over this length makes // a good canary for labels that parse very badly. if (s.getDrawerNumber() == null) { badParse = "Parsing problem. \nDrawer number is null: \n"; } else { if (s.getDrawerNumber().length() > MetadataRetriever .getFieldLength(Specimen.class, "DrawerNumber")) { // This was an OK test for testing OCR, but in production ends up in records not being // created for files, which ends up being a larger quality control problem than records // with bad OCR. // Won't fail this way anymore - drawer number is now enforced in Specimen.setDrawerNumber() badParse = "Parsing problem. \nDrawer number is too long: " + s.getDrawerNumber() + "\n"; } } RunnableJobError error = new RunnableJobError(filename, barcode, rawBarcode, exifComment, badParse, (TaxonNameReturner) parser, (DrawerNameReturner) parser, err, RunnableJobError.TYPE_SAVE_FAILED); counter.appendError(error); counter.incrementFilesFailed(); s = null; } } if (s != null) { tryMe.setSpecimen(s); } } tryMe.setRawBarcode(rawBarcode); if (isDrawerImage) { tryMe.setDrawerNumber(exifComment); } else { tryMe.setRawExifBarcode(exifComment); tryMe.setDrawerNumber(((DrawerNameReturner) parser).getDrawerNumber()); } tryMe.setRawOcr(rawOCR); tryMe.setTemplateId(template.getTemplateId()); tryMe.setPath(path); // TODO: Create md5hash of image file, persist with image if (tryMe.getMd5sum() == null || tryMe.getMd5sum().length() == 0) { try { tryMe.setMd5sum(DigestUtils.md5Hex(new FileInputStream(fileToCheck))); } catch (FileNotFoundException e) { log.error(e.getMessage()); } catch (IOException e) { log.error(e.getMessage()); } } try { if (reattach) { // Update image file record imageCont.attachDirty(tryMe); log.debug("Updated " + tryMe.toString()); counter.incrementFilesUpdated(); } else { // *** Save a database record of the image file. imageCont.persist(tryMe); log.debug("Saved " + tryMe.toString()); counter.incrementFilesDatabased(); } } catch (SaveFailedException e) { // TODO Auto-generated catch block log.error(e.getMessage(), e); counter.incrementFilesFailed(); String failureMessage = "Failed to save image record. " + e.getMessage(); RunnableJobError error = new RunnableJobError(filename, "Save Failed", tryMe.getFilename(), tryMe.getPath(), failureMessage, null, null, null, RunnableJobError.TYPE_SAVE_FAILED); counter.appendError(error); } if (isSpecimenImage) { if (Singleton.getSingletonInstance().getProperties().getProperties() .getProperty(ImageCaptureProperties.KEY_REDUNDANT_COMMENT_BARCODE) .equals("true")) { // If so configured, log as error if (!tryMe.getRawBarcode().equals(tryMe.getRawExifBarcode())) { log.error( "Warning: Scanned Image has missmatch between barcode and comment."); } } } } else { if (matches == null) { counter.incrementFilesFailed(); String failureMessage = "Probable bad data in database. Null match searching for image file. Notify the database administrator."; RunnableJobError error = new RunnableJobError(filename, "Bad Data", tryMe.getFilename(), tryMe.getPath(), failureMessage, null, null, null, RunnableJobError.TYPE_SAVE_FAILED); counter.appendError(error); } else { // found an already databased file (where we have barcode/specimen or drawer number data). log.debug("Record exists, skipping file " + filename); counter.incrementFilesExisting(); } } // } catch (NoSuchTemplateException e) { // log.error("Detected Template for image doesn't exist. " + e.getMessage()); //} } catch (UnreadableFileException e) { counter.incrementFilesFailed(); log.error("Couldn't read file." + e.getMessage()); //} catch (OCRReadException e) { // counter.incrementFilesFailed(); // log.error("Couldn't OCR file." + e.getMessage()); } } } // report progress Singleton.getSingletonInstance().getMainFrame() .setStatusMessage("Scanned: " + fileToCheck.getName()); Float seen = 0.0f + counter.getFilesSeen(); Float total = 0.0f + counter.getTotal(); // thumbPercentComplete = (int) ((seen/total)*100); setPercentComplete((int) ((seen / total) * 100)); } Singleton.getSingletonInstance().getMainFrame().notifyListener(runStatus, this); } }