@Test public void noNullPointerWhenWeReturnNull() throws Exception { AbstractPrintFileProcessor processor = createNewPrintFileProcessor(); PrintJob printJob = createTestPrintJob(processor); Mockito.when( printJob .getPrinter() .getConfiguration() .getSlicingProfile() .getzLiftDistanceCalculator()) .thenReturn(";"); Mockito.when(printJob.getPrintFileProcessor().getBuildAreaMM(Mockito.any(PrintJob.class))) .thenReturn(null); DataAid aid = processor.initializeJobCacheWithDataAid(printJob); try { aid.customizer.setNextStep(PrinterStep.PerformExposure); processor.printImageAndPerformPostProcessing(aid, image); Mockito.verify(printJob.getPrinter().getGCodeControl(), Mockito.times(1)) .executeGCodeWithTemplating(Mockito.any(PrintJob.class), Mockito.anyString()); } catch (IllegalArgumentException e) { Assert.assertEquals( "The result of your lift distance script needs to evaluate to an instance of java.lang.Number", e.getMessage()); } }
public static PrintJob createTestPrintJob(PrintFileProcessor processor) throws InappropriateDeviceException, Exception { PrintJob printJob = Mockito.mock(PrintJob.class); Printer printer = Mockito.mock(Printer.class); PrinterConfiguration printerConfiguration = Mockito.mock(PrinterConfiguration.class); SlicingProfile slicingProfile = Mockito.mock(SlicingProfile.class); InkConfig inkConfiguration = Mockito.mock(InkConfig.class); eGENERICGCodeControl gCode = Mockito.mock(eGENERICGCodeControl.class); SerialCommunicationsPort serialPort = Mockito.mock(SerialCommunicationsPort.class); MonitorDriverConfig monitorConfig = Mockito.mock(MonitorDriverConfig.class); MachineConfig machine = Mockito.mock(MachineConfig.class); Mockito.when(printJob.getJobFile()).thenReturn(new File("jobname.txt")); Mockito.when(printJob.getPrinter()).thenReturn(printer); Mockito.when(printer.getPrinterFirmwareSerialPort()).thenReturn(serialPort); Mockito.when(printJob.getPrintFileProcessor()).thenReturn(processor); Mockito.when(printer.getConfiguration()).thenReturn(printerConfiguration); Mockito.when(printer.waitForPauseIfRequired()).thenReturn(true); Mockito.when(printer.isPrintActive()).thenReturn(true); Mockito.when(printerConfiguration.getSlicingProfile()).thenReturn(slicingProfile); Mockito.when(slicingProfile.getSelectedInkConfig()).thenReturn(inkConfiguration); Mockito.when(slicingProfile.getDirection()).thenReturn(BuildDirection.Bottom_Up); Mockito.when(printer.getGCodeControl()).thenReturn(gCode); Mockito.when(slicingProfile.getgCodeLift()).thenReturn("Lift z"); Mockito.doCallRealMethod() .when(gCode) .executeGCodeWithTemplating(Mockito.any(PrintJob.class), Mockito.anyString()); Mockito.when(printer.getConfiguration().getMachineConfig()).thenReturn(machine); Mockito.when(printer.getConfiguration().getMachineConfig().getMonitorDriverConfig()) .thenReturn(monitorConfig); return printJob; }
public JSONObject printPlateBarcodes(HttpSession session, JSONObject json) { try { User user = securityManager.getUserByLoginName( SecurityContextHolder.getContext().getAuthentication().getName()); String serviceName = null; if (json.has("serviceName")) { serviceName = json.getString("serviceName"); } MisoPrintService<File, PrintContext<File>> mps = null; if (serviceName == null) { Collection<MisoPrintService> services = printManager.listPrintServicesByBarcodeableClass(Plate.class); if (services.size() == 1) { mps = services.iterator().next(); } else { return JSONUtils.SimpleJSONError( "No serviceName specified, but more than one available service able to print this barcode type."); } } else { mps = printManager.getPrintService(serviceName); } Queue<File> thingsToPrint = new LinkedList<File>(); JSONArray ss = JSONArray.fromObject(json.getString("plates")); for (JSONObject s : (Iterable<JSONObject>) ss) { try { Long plateId = s.getLong("plateId"); // Plate<LinkedList<Plateable>, Plateable> plate = requestManager.<LinkedList<Plateable>, // Plateable> getPlateById(plateId); Plate<? extends List<? extends Plateable>, ? extends Plateable> plate = requestManager.getPlateById(plateId); // autosave the barcode if none has been previously generated if (plate.getIdentificationBarcode() == null || "".equals(plate.getIdentificationBarcode())) { requestManager.savePlate(plate); } File f = mps.getLabelFor(plate); if (f != null) thingsToPrint.add(f); } catch (IOException e) { e.printStackTrace(); return JSONUtils.SimpleJSONError("Error printing barcodes: " + e.getMessage()); } } PrintJob pj = printManager.print(thingsToPrint, mps.getName(), user); return JSONUtils.SimpleJSONResponse("Job " + pj.getJobId() + " : Barcodes printed."); } catch (MisoPrintException e) { e.printStackTrace(); return JSONUtils.SimpleJSONError("Failed to print barcodes: " + e.getMessage()); } catch (IOException e) { e.printStackTrace(); return JSONUtils.SimpleJSONError("Failed to print barcodes: " + e.getMessage()); } }
/** Prints the drawing. */ public void print() { tool().deactivate(); PrintJob printJob = getToolkit().getPrintJob(this, "Print Drawing", null); if (printJob != null) { Graphics pg = printJob.getGraphics(); if (pg != null) { ((StandardDrawingView) view()).printAll(pg); pg.dispose(); // flush page } printJob.end(); } tool().activate(); }
public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); if (cmd.equals("print")) { PrintJob pjob = getToolkit().getPrintJob(this, "RoundedRectTest", null); if (pjob != null) { Graphics pg = pjob.getGraphics(); if (pg != null) { canvas.printAll(pg); pg.dispose(); // flush page } pjob.end(); } } }
@Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); Bundle bundle = new Bundle(); bundle.putStringArrayList(BUNDLE_KEY_LINES, lines); // Add more stuff here dest.writeBundle(bundle); }
@Test public void unsupportedBuildAreaDoesntBreakLiftDistanceCalculator() throws Exception { AbstractPrintFileProcessor processor = createNewPrintFileProcessor(); PrintJob printJob = createTestPrintJob(processor); Mockito.when( printJob .getPrinter() .getConfiguration() .getSlicingProfile() .getzLiftDistanceCalculator()) .thenReturn("var mm = $buildAreaMM * 2;mm"); Mockito.when(printJob.getPrintFileProcessor().getBuildAreaMM(Mockito.any(PrintJob.class))) .thenReturn(null); DataAid aid = processor.initializeJobCacheWithDataAid(printJob); aid.customizer.setNextStep(PrinterStep.PerformExposure); processor.printImageAndPerformPostProcessing(aid, image); Mockito.verify(printJob.getPrinter().getGCodeControl(), Mockito.times(1)) .executeGCodeWithTemplating(Mockito.any(PrintJob.class), Mockito.anyString()); }
@Override public void run() { System.out.println(String.format("[%s]: Turn on...", getPrinterName())); System.out.println(String.format("[%s]: Waiting for print job", getPrinterName())); try { PrintJob job; while (!halt && (job = queue.removeFront()) != null) { System.out.println( String.format("[%s]: Printing '%s'...", getPrinterName(), job.getJobName())); long sleepTime = job.getNumberOfPages() * MILLIS_PER_PAGE; Thread.sleep(sleepTime); System.out.println(String.format("[%s]: '%s' ok.", getPrinterName(), job.getJobName())); System.out.println(String.format("[%s]: Waiting for print job", getPrinterName())); } System.out.println(String.format("[%s]: Turn off", getPrinterName())); } catch (InterruptedException ignored) { } }
// If all is true, loop through all selections in chart, asking it to // grab the data and print each one. public void print(boolean all) { Toolkit tk = getToolkit(); PrintJob pj = tk.getPrintJob(chart, all ? "All charts" : chart.current_tradable(), print_properties); if (pj != null) { if (all) { Vector selections = chart.tradable_selections().selections(); for (int i = 0; i < selections.size(); ++i) { chart.request_data((String) selections.elementAt(i)); if (chart.request_result_id() == Ok) { print_current_chart(pj); } } } else { print_current_chart(pj); } pj.end(); } }
@Test public void syntaxErrorInTemplate() throws Exception { AbstractPrintFileProcessor processor = createNewPrintFileProcessor(); Graphics2D graphics = Mockito.mock(Graphics2D.class); PrintJob printJob = createTestPrintJob(processor); Mockito.when( printJob.getPrinter().getConfiguration().getSlicingProfile().getZLiftDistanceGCode()) .thenReturn("G99 ${ ;dependent on buildArea"); Double whenBuilAreaMMCalled = printJob.getPrintFileProcessor().getBuildAreaMM(Mockito.any(PrintJob.class)); DataAid aid = processor.initializeJobCacheWithDataAid(printJob); try { aid.customizer.setNextStep(PrinterStep.PerformExposure); processor.printImageAndPerformPostProcessing(aid, image); Assert.fail("Must throw InappropriateDeviceException"); } catch (InappropriateDeviceException e) { Mockito.verify(printJob.getPrintFileProcessor(), Mockito.times(2)) .getBuildAreaMM(Mockito.any(PrintJob.class)); } }
@Test public void unsupportedBuildAreaDoesntBreakProjectorGradient() throws InappropriateDeviceException, ScriptException, Exception { AbstractPrintFileProcessor processor = createNewPrintFileProcessor(); Graphics2D graphics = Mockito.mock(Graphics2D.class); PrintJob printJob = createTestPrintJob(processor); Mockito.when( printJob .getPrinter() .getConfiguration() .getSlicingProfile() .getProjectorGradientCalculator()) .thenReturn("var mm = $buildAreaMM * 2;java.awt.Color.ORANGE"); Mockito.when(printJob.getPrintFileProcessor().getBuildAreaMM(Mockito.any(PrintJob.class))) .thenReturn(null); DataAid aid = processor.initializeJobCacheWithDataAid(printJob); // apply image transform processor.applyBulbMask(aid, graphics, 0, 0); // processor.applyImageTransforms(aid, graphics, 0, 0); // processor.applyImageTransforms(aid, null, 0, 0); }
public void actionPerformed(ActionEvent e) { PrintJob pjob = getToolkit().getPrintJob(textViewerFrame, "Printing Nslm", null); if (pjob != null) { Graphics pg = pjob.getGraphics(); if (pg != null) { // todo: this should print from // the file not from the screen. // if (editor1!=null) { // editor1.print(pg); //print crashes, must use printAll // } // if (scroller1!=null) { // scroller1.printAll(pg); //is clipping on left // } if (scroller1 != null) { JViewport jvp = scroller1.getViewport(); jvp.printAll(pg); } pg.dispose(); } pjob.end(); } }
private void print_current_chart(PrintJob pj) { Graphics page = pj.getGraphics(); Dimension size = graph_panel.getSize(); Dimension pagesize = pj.getPageDimension(); main_graph.set_symbol(chart.current_tradable().toUpperCase()); if (size.width <= pagesize.width) { // Center the output on the page. page.translate((pagesize.width - size.width) / 2, (pagesize.height - size.height) / 2); } else { // The graph size is wider than a page, so print first // the left side, then the right side. Assumption - it is // not larger than two pages. page.translate(15, (pagesize.height - size.height) / 2); graph_panel.printAll(page); page.dispose(); page = pj.getGraphics(); page.translate(pagesize.width - size.width - 13, (pagesize.height - size.height) / 2); } graph_panel.printAll(page); page.dispose(); main_graph.set_symbol(null); }
@Test public void properGCodeCreated() throws Exception { AbstractPrintFileProcessor processor = createNewPrintFileProcessor(); Graphics2D graphics = Mockito.mock(Graphics2D.class); PrintJob printJob = createTestPrintJob(processor); Mockito.when( printJob.getPrinter().getConfiguration().getSlicingProfile().getZLiftDistanceGCode()) .thenReturn("${1 + buildAreaMM * 2}"); Double whenBuilAreaMMCalled = printJob.getPrintFileProcessor().getBuildAreaMM(Mockito.any(PrintJob.class)); Mockito.when(whenBuilAreaMMCalled).thenReturn(new Double("5.0")); DataAid aid = processor.initializeJobCacheWithDataAid(printJob); Mockito.when(printJob.getPrinter().getGCodeControl().sendGcode(Mockito.anyString())) .then( new Answer<String>() { private int count = 0; @Override public String answer(InvocationOnMock invocation) throws Throwable { switch (count) { case 0: Assert.assertEquals("11", invocation.getArguments()[0]); break; case 1: Assert.assertEquals("Lift z", invocation.getArguments()[0]); break; } count++; return (String) invocation.getArguments()[0]; } }); aid.customizer.setNextStep(PrinterStep.PerformExposure); processor.printImageAndPerformPostProcessing(aid, image); // The two executes are for getZLiftDistanceGCode and the life gcode itself Mockito.verify(printJob.getPrinter().getGCodeControl(), Mockito.times(2)) .executeGCodeWithTemplating(Mockito.any(PrintJob.class), Mockito.anyString()); }
/** This internal method begins a new page and prints the header. */ protected void newpage() { page = job.getGraphics(); // Begin the new page linenum = 0; charnum = 0; // Reset line and char number pagenum++; // Increment page number page.setFont(headerfont); // Set the header font. page.drawString(jobname, x0, headery); // Print job name left justified String s = "- " + pagenum + " -"; // Print the page number centered. int w = headermetrics.stringWidth(s); page.drawString(s, x0 + (this.width - w) / 2, headery); w = headermetrics.stringWidth(time); // Print date right justified page.drawString(time, x0 + width - w, headery); // Draw a line beneath the header int y = headery + headermetrics.getDescent() + 1; page.drawLine(x0, y, x0 + width, y); // Set the basic monospaced font for the rest of the page. page.setFont(font); }
/** * The constructor for this class has a bunch of arguments: The frame argument is required for all * printing in Java. The jobname appears left justified at the top of each printed page. The font * size is specified in points, as on-screen font sizes are. The margins are specified in inches * (or fractions of inches). */ public HardcopyWriter( Frame frame, String jobname, int fontsize, double leftmargin, double rightmargin, double topmargin, double bottommargin) throws HardcopyWriter.PrintCanceledException { // Get the PrintJob object with which we'll do all the printing. // The call is synchronized on the static printprops object, which // means that only one print dialog can be popped up at a time. // If the user clicks Cancel in the print dialog, throw an exception. Toolkit toolkit = frame.getToolkit(); // get Toolkit from Frame synchronized (printprops) { job = toolkit.getPrintJob(frame, jobname, printprops); } if (job == null) throw new PrintCanceledException("User cancelled print request"); pagesize = job.getPageDimension(); // query the page size pagedpi = job.getPageResolution(); // query the page resolution // Bug Workaround: // On windows, getPageDimension() and getPageResolution don't work, so // we've got to fake them. if (System.getProperty("os.name").regionMatches(true, 0, "windows", 0, 7)) { // Use screen dpi, which is what the PrintJob tries to emulate, anyway pagedpi = toolkit.getScreenResolution(); System.out.println(pagedpi); // Assume a 8.5" x 11" page size. A4 paper users have to change this. pagesize = new Dimension((int) (8.5 * pagedpi), 11 * pagedpi); System.out.println(pagesize); // We also have to adjust the fontsize. It is specified in points, // (1 point = 1/72 of an inch) but Windows measures it in pixels. fontsize = fontsize * pagedpi / 72; System.out.println(fontsize); System.out.flush(); } // Compute coordinates of the upper-left corner of the page. // I.e. the coordinates of (leftmargin, topmargin). Also compute // the width and height inside of the margins. x0 = (int) (leftmargin * pagedpi); y0 = (int) (topmargin * pagedpi); width = pagesize.width - (int) ((leftmargin + rightmargin) * pagedpi); height = pagesize.height - (int) ((topmargin + bottommargin) * pagedpi); // Get body font and font size font = new Font("Monospaced", Font.PLAIN, fontsize); metrics = toolkit.getFontMetrics(font); lineheight = metrics.getHeight(); lineascent = metrics.getAscent(); charwidth = metrics.charWidth('0'); // Assumes a monospaced font! // Now compute columns and lines will fit inside the margins chars_per_line = width / charwidth; lines_per_page = height / lineheight; // Get header font information // And compute baseline of page header: 1/8" above the top margin headerfont = new Font("SansSerif", Font.ITALIC, fontsize); headermetrics = toolkit.getFontMetrics(headerfont); headery = y0 - (int) (0.125 * pagedpi) - headermetrics.getHeight() + headermetrics.getAscent(); // Compute the date/time string to display in the page header DateFormat df = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT); df.setTimeZone(TimeZone.getDefault()); time = df.format(new Date()); this.jobname = jobname; // save name this.fontsize = fontsize; // save font size }
/** * This is the close() method that all Writer subclasses must implement. Print the pending page * (if any) and terminate the PrintJob. */ public void close() { synchronized (this.lock) { if (page != null) page.dispose(); // Send page to the printer job.end(); // Terminate the job } }