Search in sources :

Example 41 with PrivilegedAction

use of java.security.PrivilegedAction in project jdk8u_jdk by JetBrains.

the class CPrinterJob method print.

@Override
public void print(PrintRequestAttributeSet attributes) throws PrinterException {
    // NOTE: Some of this code is copied from RasterPrinterJob.
    // this code uses javax.print APIs
    // this will make it print directly to the printer
    // this will not work if the user clicks on the "Preview" button
    // However if the printer is a StreamPrintService, its the right path.
    PrintService psvc = getPrintService();
    if (psvc == null) {
        throw new PrinterException("No print service found.");
    }
    if (psvc instanceof StreamPrintService) {
        spoolToService(psvc, attributes);
        return;
    }
    setAttributes(attributes);
    // throw exception for invalid destination
    if (destinationAttr != null) {
        validateDestination(destinationAttr);
    }
    /* Get the range of pages we are to print. If the
         * last page to print is unknown, then we print to
         * the end of the document. Note that firstPage
         * and lastPage are 0 based page indices.
         */
    int firstPage = getFirstPage();
    int lastPage = getLastPage();
    if (lastPage == Pageable.UNKNOWN_NUMBER_OF_PAGES) {
        int totalPages = mDocument.getNumberOfPages();
        if (totalPages != Pageable.UNKNOWN_NUMBER_OF_PAGES) {
            lastPage = mDocument.getNumberOfPages() - 1;
        }
    }
    try {
        synchronized (this) {
            performingPrinting = true;
            userCancelled = false;
        }
        //Add support for PageRange
        PageRanges pr = (attributes == null) ? null : (PageRanges) attributes.get(PageRanges.class);
        int[][] prMembers = (pr == null) ? new int[0][0] : pr.getMembers();
        int loopi = 0;
        do {
            if (EventQueue.isDispatchThread()) {
                // This is an AWT EventQueue, and this print rendering loop needs to block it.
                onEventThread = true;
                printingLoop = AccessController.doPrivileged(new PrivilegedAction<SecondaryLoop>() {

                    @Override
                    public SecondaryLoop run() {
                        return Toolkit.getDefaultToolkit().getSystemEventQueue().createSecondaryLoop();
                    }
                });
                try {
                    //  it wait and block this thread.
                    if (printLoop(false, firstPage, lastPage)) {
                        // Start a secondary loop on EDT until printing operation is finished or cancelled
                        printingLoop.enter();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                // Fire off the print rendering loop on the AppKit, and block this thread
                //  until it is done.
                // But don't actually block... we need to come back here!
                onEventThread = false;
                try {
                    printLoop(true, firstPage, lastPage);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (++loopi < prMembers.length) {
                firstPage = prMembers[loopi][0] - 1;
                lastPage = prMembers[loopi][1] - 1;
            }
        } while (loopi < prMembers.length);
    } finally {
        synchronized (this) {
            // NOTE: Native code shouldn't allow exceptions out while
            // printing. They should cancel the print loop.
            performingPrinting = false;
            notify();
        }
        if (printingLoop != null) {
            printingLoop.exit();
        }
    }
// Normalize the collated, # copies, numPages, first/last pages. Need to
//  make note of pageRangesAttr.
// Set up NSPrintInfo with the java settings (PageFormat & Paper).
// Create an NSView for printing. Have knowsPageRange return YES, and give the correct
//  range, or MAX? if unknown. Have rectForPage do a peekGraphics check before returning
//  the rectangle. Have drawRect do the real render of the page. Have printJobTitle do
//  the right thing.
// Call NSPrintOperation, it will call NSView.drawRect: for each page.
// NSView.drawRect: will create a CPrinterGraphics with the current CGContextRef, and then
//  pass this Graphics onto the Printable with the appropriate PageFormat and index.
// Need to be able to cancel the NSPrintOperation (using code from RasterPrinterJob, be
//  sure to initialize userCancelled and performingPrinting member variables).
// Extensions available from AppKit: Print to PDF or EPS file!
}
Also used : PageRanges(javax.print.attribute.standard.PageRanges) PrivilegedAction(java.security.PrivilegedAction) java.awt.print(java.awt.print) javax.print(javax.print) sun.print(sun.print)

Example 42 with PrivilegedAction

use of java.security.PrivilegedAction in project jdk8u_jdk by JetBrains.

the class SubjectDelegator method delegatedContext.

/* Return the AccessControlContext appropriate to execute an
       operation on behalf of the delegatedSubject.  If the
       authenticatedAccessControlContext does not have permission to
       delegate to that subject, throw SecurityException.  */
public AccessControlContext delegatedContext(AccessControlContext authenticatedACC, Subject delegatedSubject, boolean removeCallerContext) throws SecurityException {
    if (System.getSecurityManager() != null && authenticatedACC == null) {
        throw new SecurityException("Illegal AccessControlContext: null");
    }
    // Check if the subject delegation permission allows the
    // authenticated subject to assume the identity of each
    // principal in the delegated subject
    //
    Collection<Principal> ps = getSubjectPrincipals(delegatedSubject);
    final Collection<Permission> permissions = new ArrayList<>(ps.size());
    for (Principal p : ps) {
        final String pname = p.getClass().getName() + "." + p.getName();
        permissions.add(new SubjectDelegationPermission(pname));
    }
    PrivilegedAction<Void> action = new PrivilegedAction<Void>() {

        public Void run() {
            for (Permission sdp : permissions) {
                AccessController.checkPermission(sdp);
            }
            return null;
        }
    };
    AccessController.doPrivileged(action, authenticatedACC);
    return getDelegatedAcc(delegatedSubject, removeCallerContext);
}
Also used : PrivilegedAction(java.security.PrivilegedAction) Permission(java.security.Permission) SubjectDelegationPermission(javax.management.remote.SubjectDelegationPermission) SubjectDelegationPermission(javax.management.remote.SubjectDelegationPermission) Principal(java.security.Principal)

Example 43 with PrivilegedAction

use of java.security.PrivilegedAction in project jdk8u_jdk by JetBrains.

the class ICC_Profile method activateDeferredProfile.

void activateDeferredProfile() throws ProfileDataException {
    byte[] profileData;
    FileInputStream fis;
    final String fileName = deferralInfo.filename;
    profileActivator = null;
    deferralInfo = null;
    PrivilegedAction<FileInputStream> pa = new PrivilegedAction<FileInputStream>() {

        public FileInputStream run() {
            File f = getStandardProfileFile(fileName);
            if (f != null) {
                try {
                    return new FileInputStream(f);
                } catch (FileNotFoundException e) {
                }
            }
            return null;
        }
    };
    if ((fis = AccessController.doPrivileged(pa)) == null) {
        throw new ProfileDataException("Cannot open file " + fileName);
    }
    try {
        profileData = getProfileDataFromStream(fis);
        fis.close();
    /* close the file */
    } catch (IOException e) {
        ProfileDataException pde = new ProfileDataException("Invalid ICC Profile Data" + fileName);
        pde.initCause(e);
        throw pde;
    }
    if (profileData == null) {
        throw new ProfileDataException("Invalid ICC Profile Data" + fileName);
    }
    try {
        cmmProfile = CMSManager.getModule().loadProfile(profileData);
    } catch (CMMException c) {
        ProfileDataException pde = new ProfileDataException("Invalid ICC Profile Data" + fileName);
        pde.initCause(c);
        throw pde;
    }
}
Also used : PrivilegedAction(java.security.PrivilegedAction) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) File(java.io.File) FileInputStream(java.io.FileInputStream)

Example 44 with PrivilegedAction

use of java.security.PrivilegedAction in project jdk8u_jdk by JetBrains.

the class RenderingEngine method getInstance.

/**
     * Returns an instance of {@code RenderingEngine} as determined
     * by the installation environment and runtime flags.
     * <p>
     * A specific instance of the {@code RenderingEngine} can be
     * chosen by specifying the runtime flag:
     * <pre>
     *     java -Dsun.java2d.renderer=&lt;classname&gt;
     * </pre>
     *
     * If no specific {@code RenderingEngine} is specified on the command
     * or Ductus renderer is specified, it will attempt loading the
     * sun.dc.DuctusRenderingEngine class using Class.forName as a fastpath;
     * if not found, use the ServiceLoader.
     * If no specific {@code RenderingEngine} is specified on the command
     * line then the last one returned by enumerating all subclasses of
     * {@code RenderingEngine} known to the ServiceLoader is used.
     * <p>
     * Runtime tracing of the actions of the {@code RenderingEngine}
     * can be enabled by specifying the runtime flag:
     * <pre>
     *     java -Dsun.java2d.renderer.trace=&lt;any string&gt;
     * </pre>
     * @return an instance of {@code RenderingEngine}
     * @since 1.7
     */
public static synchronized RenderingEngine getInstance() {
    if (reImpl != null) {
        return reImpl;
    }
    reImpl = AccessController.doPrivileged(new PrivilegedAction<RenderingEngine>() {

        public RenderingEngine run() {
            final String ductusREClass = "sun.dc.DuctusRenderingEngine";
            String reClass = System.getProperty("sun.java2d.renderer", ductusREClass);
            try {
                Class<?> cls = Class.forName(reClass);
                return (RenderingEngine) cls.newInstance();
            } catch (ReflectiveOperationException ignored) {
            // not found
            }
            ServiceLoader<RenderingEngine> reLoader = ServiceLoader.loadInstalled(RenderingEngine.class);
            RenderingEngine service = null;
            for (RenderingEngine re : reLoader) {
                service = re;
                if (re.getClass().getName().equals(reClass)) {
                    break;
                }
            }
            return service;
        }
    });
    if (reImpl == null) {
        throw new InternalError("No RenderingEngine module found");
    }
    GetPropertyAction gpa = new GetPropertyAction("sun.java2d.renderer.trace");
    String reTrace = AccessController.doPrivileged(gpa);
    if (reTrace != null) {
        reImpl = new Tracer(reImpl);
    }
    return reImpl;
}
Also used : GetPropertyAction(sun.security.action.GetPropertyAction) PrivilegedAction(java.security.PrivilegedAction)

Example 45 with PrivilegedAction

use of java.security.PrivilegedAction in project jdk8u_jdk by JetBrains.

the class FtpClient method openPassiveDataConnection.

/**
     * Opens a "PASSIVE" connection with the server and returns the connected
     * <code>Socket</code>.
     *
     * @return the connected <code>Socket</code>
     * @throws IOException if the connection was unsuccessful.
     */
private Socket openPassiveDataConnection(String cmd) throws sun.net.ftp.FtpProtocolException, IOException {
    String serverAnswer;
    int port;
    InetSocketAddress dest = null;
    /**
         * Here is the idea:
         *
         * - First we want to try the new (and IPv6 compatible) EPSV command
         *   But since we want to be nice with NAT software, we'll issue the
         *   EPSV ALL command first.
         *   EPSV is documented in RFC2428
         * - If EPSV fails, then we fall back to the older, yet ok, PASV
         * - If PASV fails as well, then we throw an exception and the calling
         *   method will have to try the EPRT or PORT command
         */
    if (issueCommand("EPSV ALL")) {
        // We can safely use EPSV commands
        issueCommandCheck("EPSV");
        serverAnswer = getResponseString();
        if (epsvPat == null) {
            epsvPat = Pattern.compile("^229 .* \\(\\|\\|\\|(\\d+)\\|\\)");
        }
        Matcher m = epsvPat.matcher(serverAnswer);
        if (!m.find()) {
            throw new sun.net.ftp.FtpProtocolException("EPSV failed : " + serverAnswer);
        }
        // Yay! Let's extract the port number
        String s = m.group(1);
        port = Integer.parseInt(s);
        InetAddress add = server.getInetAddress();
        if (add != null) {
            dest = new InetSocketAddress(add, port);
        } else {
            // This means we used an Unresolved address to connect in
            // the first place. Most likely because the proxy is doing
            // the name resolution for us, so let's keep using unresolved
            // address.
            dest = InetSocketAddress.createUnresolved(serverAddr.getHostName(), port);
        }
    } else {
        // EPSV ALL failed, so Let's try the regular PASV cmd
        issueCommandCheck("PASV");
        serverAnswer = getResponseString();
        if (pasvPat == null) {
            pasvPat = Pattern.compile("227 .* \\(?(\\d{1,3},\\d{1,3},\\d{1,3},\\d{1,3}),(\\d{1,3}),(\\d{1,3})\\)?");
        }
        Matcher m = pasvPat.matcher(serverAnswer);
        if (!m.find()) {
            throw new sun.net.ftp.FtpProtocolException("PASV failed : " + serverAnswer);
        }
        // Get port number out of group 2 & 3
        port = Integer.parseInt(m.group(3)) + (Integer.parseInt(m.group(2)) << 8);
        // IP address is simple
        String s = m.group(1).replace(',', '.');
        dest = new InetSocketAddress(s, port);
    }
    // Got everything, let's open the socket!
    Socket s;
    if (proxy != null) {
        if (proxy.type() == Proxy.Type.SOCKS) {
            s = AccessController.doPrivileged(new PrivilegedAction<Socket>() {

                public Socket run() {
                    return new Socket(proxy);
                }
            });
        } else {
            s = new Socket(Proxy.NO_PROXY);
        }
    } else {
        s = new Socket();
    }
    InetAddress serverAddress = AccessController.doPrivileged(new PrivilegedAction<InetAddress>() {

        @Override
        public InetAddress run() {
            return server.getLocalAddress();
        }
    });
    // Bind the socket to the same address as the control channel. This
    // is needed in case of multi-homed systems.
    s.bind(new InetSocketAddress(serverAddress, 0));
    if (connectTimeout >= 0) {
        s.connect(dest, connectTimeout);
    } else {
        if (defaultConnectTimeout > 0) {
            s.connect(dest, defaultConnectTimeout);
        } else {
            s.connect(dest);
        }
    }
    if (readTimeout >= 0) {
        s.setSoTimeout(readTimeout);
    } else if (defaultSoTimeout > 0) {
        s.setSoTimeout(defaultSoTimeout);
    }
    if (useCrypto) {
        try {
            s = sslFact.createSocket(s, dest.getHostName(), dest.getPort(), true);
        } catch (Exception e) {
            throw new sun.net.ftp.FtpProtocolException("Can't open secure data channel: " + e);
        }
    }
    if (!issueCommand(cmd)) {
        s.close();
        if (getLastReplyCode() == FtpReplyCode.FILE_UNAVAILABLE) {
            // Ensure backward compatibility
            throw new FileNotFoundException(cmd);
        }
        throw new sun.net.ftp.FtpProtocolException(cmd + ":" + getResponseString(), getLastReplyCode());
    }
    return s;
}
Also used : sun.net.ftp(sun.net.ftp) Matcher(java.util.regex.Matcher) ParseException(java.text.ParseException) PrivilegedAction(java.security.PrivilegedAction) java.net(java.net) SSLSocket(javax.net.ssl.SSLSocket)

Aggregations

PrivilegedAction (java.security.PrivilegedAction)359 IOException (java.io.IOException)85 Subject (javax.security.auth.Subject)61 AccessControlContext (java.security.AccessControlContext)31 File (java.io.File)29 HashMap (java.util.HashMap)29 UserGroupInformation (org.apache.hadoop.security.UserGroupInformation)29 Method (java.lang.reflect.Method)24 ArrayList (java.util.ArrayList)23 ClientResponse (com.sun.jersey.api.client.ClientResponse)21 InputStream (java.io.InputStream)21 URL (java.net.URL)21 FileNotFoundException (java.io.FileNotFoundException)18 UnsupportedEncodingException (java.io.UnsupportedEncodingException)18 Iterator (java.util.Iterator)18 MalformedURLException (java.net.MalformedURLException)17 List (java.util.List)17 UnknownHostException (java.net.UnknownHostException)16 Principal (java.security.Principal)15 PrivilegedActionException (java.security.PrivilegedActionException)15