⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 defaultio.java

📁 Rapla是一个灵活的多用户资源管理系统。它提供的一些功能有:日历GUI
💻 JAVA
字号:
/*--------------------------------------------------------------------------*
 | Copyright (C) 2006 Gereon Fassbender                                     |
 |                                                                          |
 | This program is free software; you can redistribute it and/or modify     |
 | it under the terms of the GNU General Public License as published by the |
 | Free Software Foundation. A copy of the license has been included with   |
 | these distribution in the COPYING file, if not go to www.fsf.org         |
 |                                                                          |
 | As a special exception, you are granted the permissions to link this     |
 | program with every library, which license fulfills the Open Source       |
 | Definition as published by the Open Source Initiative (OSI).             |
 *--------------------------------------------------------------------------*/
package org.rapla.components.iolayer;

import java.awt.Component;
import java.awt.FileDialog;
import java.awt.Frame;
import java.awt.Toolkit;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.Transferable;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.swing.JFileChooser;

import org.apache.avalon.framework.logger.AbstractLogEnabled;
import org.apache.avalon.framework.logger.Logger;

public class DefaultIO extends AbstractLogEnabled implements IOInterface{
    /**
     * Name of all Rapla printjobs (used in dialogs, printerqueue, etc).
   */
    public final static String RAPLA_JOB= "Rapla Printjob";
    public final static String PRINT_EXPORT_CLASS = DefaultIO.class.getPackage().getName() + ".PrintExport";
    public PrinterJob job;

    public DefaultIO(Logger logger) {
        enableLogging( logger);
    }

    private PrinterJob getJob() {
        if (job == null)
            job = PrinterJob.getPrinterJob();
        return job;
    }

    public PageFormat defaultPage() throws UnsupportedOperationException {
        try {
            PageFormat format = getJob().defaultPage();
            return format;
        } catch (SecurityException ex) {
            return new PageFormat();
        }
    }

    public PageFormat showFormatDialog(PageFormat format) throws UnsupportedOperationException {
        logPaperSize (format.getPaper());
        format =  getJob().pageDialog(format);
        logPaperSize (format.getPaper());
        return format;
    }

    public void setContents(Transferable transferable, ClipboardOwner owner) {
    	Toolkit.getDefaultToolkit().getSystemClipboard().setContents(  transferable, owner );
    }

    public boolean supportsPostscriptExport() {
        if (!supportsPrintService())
            return false;

        Object exporter;
        try {
            exporter = getClass().getClassLoader().loadClass( PRINT_EXPORT_CLASS ).newInstance();
        } catch (ClassNotFoundException ex) {
            getLogger().warn("No support for " + PRINT_EXPORT_CLASS + ". Compile with jdk >=1.4.");
            return false;
        } catch (Exception ex) {
            getLogger().warn("No support for " + PRINT_EXPORT_CLASS + ". Run with jdk >= 1.4.1 : " + ex.getMessage());
            return false;
        }
        try {
            Method method = exporter.getClass().getMethod("supportsPostscriptExport",new Class[] {});
            boolean bExport = ((Boolean) method.invoke(exporter, new Object[] {})).booleanValue();
            if (!bExport)
                getLogger().warn("No support for PostscriptExport");
            return bExport;
        } catch (NoSuchMethodException ex) {
            getLogger().error(ex.getMessage());
        } catch (IllegalAccessException ex) {
            getLogger().error(ex.getMessage());
        } catch (InvocationTargetException excont) {
            Throwable ex = excont.getTargetException();
            getLogger().error(ex.getMessage(),ex);
        }
        return false;
    }

    private boolean supportsPrintService() {
        try {
            getClass().getClassLoader().loadClass("javax.print.StreamPrintServiceFactory");
            return true;
        } catch (ClassNotFoundException ex) {
            getLogger().warn("No support for javax.print.StreamPrintServiceFactory");
            return false;
        }
    }

    protected void callExport(Printable printable, PageFormat format,OutputStream out) throws UnsupportedOperationException,IOException {
        Object exporter;
        try 
        {
            exporter = getClass().getClassLoader().loadClass( PRINT_EXPORT_CLASS ).newInstance();
        } 
        catch (Exception ex) 
        {
            throw new UnsupportedOperationException("JDK < 1.4 PrintService unavailable");
        }
        try 
        {
            Method method = exporter.getClass().getMethod("save",new Class[] {Printable.class,PageFormat.class,OutputStream.class});
            method.invoke(exporter, new Object[] {printable,format,out});
        } 
        catch (InvocationTargetException excont) 
        {
            Throwable ex = excont.getTargetException();
            if (ex instanceof IOException)
            {
                throw (IOException)ex;
            }
            if (ex instanceof UnsupportedOperationException)
            {
                throw (UnsupportedOperationException)ex;
            }
            getLogger().error(ex.getMessage(),ex);
            throw new IOException(ex.getMessage());
        } 
        catch (Exception ex) 
        {
            throw new UnsupportedOperationException(ex.getMessage());
        }
    }

    public String saveAsPostscriptShowDialog(String dir,Printable printable,PageFormat format,boolean askFormat,Component owner) throws UnsupportedOperationException,IOException {
        if (askFormat) { format= showFormatDialog(format); }
        JFileChooser chooser = new JFileChooser();

        if (dir != null)
            chooser.setCurrentDirectory(new File(dir));

        // Note: source for ExampleFileFilter can be found in FileChooserDemo,
        // under the demo/jfc directory in the Java 2 SDK, Standard Edition.
        int returnVal = chooser.showOpenDialog(owner);
        if(returnVal != JFileChooser.APPROVE_OPTION)
            return null;

        OutputStream out = new FileOutputStream(chooser.getSelectedFile());
        callExport(printable,format,out);
        return chooser.getSelectedFile().getPath();
    }

    public void saveAsPostscript(Printable printable,PageFormat format,OutputStream out) throws UnsupportedOperationException,IOException {
        callExport(printable,format,out);
    }

    /**
   Prints an awt or swing component.
   @param askFormat If true a dialog will show up to allow the user to edit printformat.
   */
    public boolean print(Printable printable, PageFormat format, boolean askFormat) throws PrinterException {
        getJob().setPrintable(printable, format);
        getJob().setJobName(RAPLA_JOB);

        if (askFormat) {
            if (getJob().printDialog()) {
                logPaperSize (format.getPaper());
                getJob().print();
                return true;
            }
        } else {
            getJob().print();
            return true;
        }
        getJob().cancel();
        return false;
    }

    void logPaperSize(Paper paper) {
        if (getLogger().isDebugEnabled())
            getLogger().debug(
                         (paper.getImageableX()/72) * INCH_TO_MM
                         +", " +(paper.getImageableY()/72) * INCH_TO_MM
                         +", " +(paper.getImageableWidth() /72) * INCH_TO_MM
                         +", " +(paper.getImageableHeight() /72) * INCH_TO_MM
                         );
    }

    public String saveFile(Frame frame,String dir, String[] fileExtensions, String filename, byte[] content) throws IOException {
        final FileDialog fd = new FileDialog(frame, "Save File", FileDialog.SAVE);
        
        if ( dir == null)
        {
            dir = getDirectory();
        }
        
        fd.setFile(filename);
        fd.setDirectory(dir);
        fd.setLocation(50, 50);
        fd.setVisible( true);
        final String savedFileName = fd.getFile();

        if (savedFileName == null) {
            return null;
        }
        
        String path = createFullPath(fd);
        final File savedFile = new File( path);
        writeFile(savedFile, content);
        return path;
    }

    public FileContent openFile(Frame frame,String dir, String[] fileExtensions) throws IOException {
        final FileDialog fd = new FileDialog(frame, "Open File", FileDialog.LOAD);
        
        if ( dir == null)
        {
            dir = getDirectory();
        }
        
        fd.setDirectory(dir);
        fd.setLocation(50, 50);
        fd.setVisible( true);
        final String openFileName = fd.getFile();

        if (openFileName == null) {
            return null;
        }
        String path = createFullPath(fd);
        final FileInputStream openFile = new FileInputStream( path);
        FileContent content = new FileContent();
        content.setName( openFileName);
        content.setInputStream( openFile );
        return content;
    }

    
    private String getDirectory() {
        final String userHome = System.getProperty("user.home");

        if (userHome == null) {
            final File execDir = new File("");
            return execDir.getAbsolutePath();
        }

        return userHome;
    }

    private String createFullPath(final FileDialog fd) {
        return fd.getDirectory()
                + System.getProperty("file.separator").charAt(0) + fd.getFile();
    }

    private void writeFile(final File savedFile, byte[] content) throws IOException {
        final FileOutputStream out;
        out = new FileOutputStream(savedFile);
        out.write( content);
        out.flush();
        out.close();
    }

}




⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -