Example usage for java.lang System getSecurityManager

List of usage examples for java.lang System getSecurityManager

Introduction

In this page you can find the example usage for java.lang System getSecurityManager.

Prototype

public static SecurityManager getSecurityManager() 

Source Link

Document

Gets the system-wide security manager.

Usage

From source file:org.java.plugin.drftpd.SynchronizedPluginLifecycleHandler.java

/**
 * Creates synchronized implementation of plug-in class loader.
 * @see org.java.plugin.standard.StandardPluginLifecycleHandler#createPluginClassLoader(
 *      org.java.plugin.registry.PluginDescriptor)
 *///from ww w.  j a v a 2 s  . com
@Override
protected org.java.plugin.PluginClassLoader createPluginClassLoader(final PluginDescriptor descr) {
    SynchronizedPluginClassLoader result;
    if (System.getSecurityManager() != null) {
        result = AccessController.doPrivileged(new PrivilegedAction<SynchronizedPluginClassLoader>() {
            public SynchronizedPluginClassLoader run() {
                return new SynchronizedPluginClassLoader(getPluginManager(), descr,
                        SynchronizedPluginLifecycleHandler.this.getClass().getClassLoader());
            }
        });
    } else {
        result = new SynchronizedPluginClassLoader(getPluginManager(), descr,
                SynchronizedPluginLifecycleHandler.this.getClass().getClassLoader());
    }
    result.setProbeParentLoaderLast(probeParentLoaderLast);
    result.setStickySynchronizing(stickySynchronizing);
    result.setLocalClassLoadingOptimization(localClassLoadingOptimization);
    result.setForeignClassLoadingOptimization(foreignClassLoadingOptimization);

    return result;
}

From source file:org.vaadin.spring.security.support.VaadinSecurityAwareProcessor.java

@Override
public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {

    AccessControlContext acc = null;

    if (System.getSecurityManager() != null && (bean instanceof VaadinSecurityAware)) {
        acc = this.applicationContext.getBeanFactory().getAccessControlContext();
    }/*  ww  w . j av  a2s  .c o m*/

    if (acc != null) {
        AccessController.doPrivileged(new PrivilegedAction<Object>() {

            @Override
            public Object run() {
                invokeAwareInterfaces(bean);
                return null;
            }

        }, acc);
    } else {
        invokeAwareInterfaces(bean);
    }

    return bean;

}

From source file:com.clustercontrol.monitor.run.util.ParallelExecution.java

/**
 * /*from  w ww  .  j a v a  2s .  com*/
 */
private ParallelExecution() {
    log.debug("init()");

    int m_maxThreadPool = HinemosPropertyUtil
            .getHinemosPropertyNum("monitor.common.thread.pool", Long.valueOf(10)).intValue();
    log.info("monitor.common.thread.pool: " + m_maxThreadPool);

    es = new MonitoredThreadPoolExecutor(m_maxThreadPool, m_maxThreadPool, 0L, TimeUnit.MICROSECONDS,
            new LinkedBlockingQueue<Runnable>(), new ThreadFactory() {
                private volatile int _count = 0;

                @Override
                public Thread newThread(Runnable r) {
                    return new Thread(r, "MonitorWorker-" + _count++);
                }
            }, new ThreadPoolExecutor.AbortPolicy());

    log.debug("ParallelExecution() ExecutorService is " + es.getClass().getCanonicalName());
    log.debug("ParallelExecution() securityManager is " + System.getSecurityManager());
}

From source file:org.apache.jasper.security.SecurityClassLoad.java

public static void securityClassLoad(ClassLoader loader) {

    if (System.getSecurityManager() == null) {
        return;//from  w w w . j  ava 2  s .c om
    }

    String basePackage = "org.apache.jasper.";
    try {
        loader.loadClass(basePackage + "runtime.JspFactoryImpl$PrivilegedGetPageContext");
        loader.loadClass(basePackage + "runtime.JspFactoryImpl$PrivilegedReleasePageContext");

        loader.loadClass(basePackage + "runtime.JspRuntimeLibrary");
        loader.loadClass(basePackage + "runtime.JspRuntimeLibrary$PrivilegedIntrospectHelper");

        loader.loadClass(basePackage + "runtime.ServletResponseWrapperInclude");
        loader.loadClass(basePackage + "runtime.TagHandlerPool");
        loader.loadClass(basePackage + "runtime.JspFragmentHelper");

        loader.loadClass(basePackage + "runtime.ProtectedFunctionMapper");
        loader.loadClass(basePackage + "runtime.ProtectedFunctionMapper$1");
        loader.loadClass(basePackage + "runtime.ProtectedFunctionMapper$2");
        loader.loadClass(basePackage + "runtime.ProtectedFunctionMapper$3");
        loader.loadClass(basePackage + "runtime.ProtectedFunctionMapper$4");

        loader.loadClass(basePackage + "runtime.PageContextImpl");
        loader.loadClass(basePackage + "runtime.PageContextImpl$1");
        loader.loadClass(basePackage + "runtime.PageContextImpl$2");
        loader.loadClass(basePackage + "runtime.PageContextImpl$3");
        loader.loadClass(basePackage + "runtime.PageContextImpl$4");
        loader.loadClass(basePackage + "runtime.PageContextImpl$5");
        loader.loadClass(basePackage + "runtime.PageContextImpl$6");
        loader.loadClass(basePackage + "runtime.PageContextImpl$7");
        loader.loadClass(basePackage + "runtime.PageContextImpl$8");
        loader.loadClass(basePackage + "runtime.PageContextImpl$9");
        loader.loadClass(basePackage + "runtime.PageContextImpl$10");
        loader.loadClass(basePackage + "runtime.PageContextImpl$11");
        loader.loadClass(basePackage + "runtime.PageContextImpl$12");
        loader.loadClass(basePackage + "runtime.PageContextImpl$13");

        loader.loadClass(basePackage + "runtime.JspContextWrapper");

        loader.loadClass(basePackage + "servlet.JspServletWrapper");

        loader.loadClass(basePackage + "runtime.JspWriterImpl$1");
    } catch (ClassNotFoundException ex) {
        System.out.println("Jasper SecurityClassLoad preload of class failed: " + ex.getMessage());
        log.error("SecurityClassLoad", ex);
    }
}

From source file:com.scoredev.scores.HighScore.java

public void setHighScore(final int score) throws IOException {
    //check permission first
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        sm.checkPermission(new HighScorePermission(gameName));
    }/* www  .  j  av  a2  s. co  m*/

    // need a doPrivileged block to manipulate the file
    try {
        AccessController.doPrivileged(new PrivilegedExceptionAction() {
            public Object run() throws IOException {
                Hashtable scores = null;
                // try to open the existing file. Should have a locking
                // protocol (could use File.createNewFile).
                try {
                    FileInputStream fis = new FileInputStream(highScoreFile);
                    ObjectInputStream ois = new ObjectInputStream(fis);
                    scores = (Hashtable) ois.readObject();
                } catch (Exception e) {
                    // ignore, try and create new file
                }

                // if scores is null, create a new hashtable
                if (scores == null)
                    scores = new Hashtable(13);

                // update the score and save out the new high score
                scores.put(gameName, new Integer(score));
                FileOutputStream fos = new FileOutputStream(highScoreFile);
                ObjectOutputStream oos = new ObjectOutputStream(fos);
                oos.writeObject(scores);
                oos.close();
                return null;
            }
        });
    } catch (PrivilegedActionException pae) {
        throw (IOException) pae.getException();
    }
}

From source file:SwingUtil.java

/**
 * Open a JFileChooser dialog for selecting a directory and return the
 * selected directory.//from  ww  w  .jav  a  2  s.  c  o m
 *
 *
 * @param owner
 * The frame or dialog that controls the invokation of this dialog.
 * @param defaultDir
 * The directory to show when the dialog opens.
 * @param title
 * Tile for the dialog.
 *
 * @return
 * The selected directory as a File. Null if user cancels dialog without
 * a selection.
 *
 */
public static File getDirectoryChoice(Component owner, File defaultDir, String title) {
    //
    // There is apparently a bug in the native Windows FileSystem class that
    // occurs when you use a file chooser and there is a security manager
    // active. An error dialog is displayed indicating there is no disk in
    // Drive A:. To avoid this, the security manager is temporarily set to
    // null and then reset after the file chooser is closed.
    //
    SecurityManager sm = null;
    JFileChooser chooser = null;
    File choice = null;

    sm = System.getSecurityManager();
    System.setSecurityManager(null);
    chooser = new JFileChooser();
    chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
    if ((defaultDir != null) && defaultDir.exists() && defaultDir.isDirectory()) {
        chooser.setCurrentDirectory(defaultDir);
        chooser.setSelectedFile(defaultDir);
    }
    chooser.setDialogTitle(title);
    chooser.setApproveButtonText("OK");
    int v = chooser.showOpenDialog(owner);

    owner.requestFocus();
    switch (v) {
    case JFileChooser.APPROVE_OPTION:
        if (chooser.getSelectedFile() != null) {
            if (chooser.getSelectedFile().exists()) {
                choice = chooser.getSelectedFile();
            } else {
                File parentFile = new File(chooser.getSelectedFile().getParent());

                choice = parentFile;
            }
        }
        break;
    case JFileChooser.CANCEL_OPTION:
    case JFileChooser.ERROR_OPTION:
    }
    chooser.removeAll();
    chooser = null;
    System.setSecurityManager(sm);
    return choice;
}

From source file:org.karsha.controler.UploadDocumentServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    SecurityManager sm = System.getSecurityManager();

    HttpSession session = request.getSession();
    String userPath = request.getServletPath();
    String url = "";
    List items = null;/*from   w w w  .  j  a  va2 s  .  c o m*/

    if (userPath.equals("/uploaddocuments")) {

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);

        if (isMultipart) {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(5000000);
            //  FileItemFactory factory = new DiskFileItemFactory();

            ServletFileUpload upload = new ServletFileUpload(factory);
            try {
                // items = upload.
                items = upload.parseRequest(request);
            } catch (Exception ex) {
                Logger.getLogger(UploadDocumentServlet.class.getName()).log(Level.SEVERE, null, ex);
            }

            HashMap requestParameters = new HashMap();

            try {

                Iterator iterator = items.iterator();
                while (iterator.hasNext()) {

                    FileItem item = (FileItem) iterator.next();

                    if (item.isFormField()) {

                        requestParameters.put(item.getFieldName(), item.getString());

                    } else {
                        PDFBookmark pdfBookmark = new PDFBookmark();
                        byte[] fileContent = item.get();
                        LinkedHashMap<String, String> docSectionMap = pdfBookmark
                                .splitPDFByBookmarks(fileContent);

                        if (!docSectionMap.isEmpty()) {

                            Document newDocument = new Document();
                            newDocument.setDocumentName(requestParameters.get("docName").toString());
                            newDocument.setUserId(Integer.parseInt(session.getAttribute("userId").toString()));
                            String a = requestParameters.get("collection_type_new").toString();
                            newDocument.setCollectionId(Integer.parseInt(a));
                            //  newDocument.setDocumentContent(fileContent);

                            request.setAttribute("requestParameters", requestParameters);

                            if (DocumentDB.isFileNameDuplicate(newDocument.getDocumentName())) {
                                url = "/WEB-INF/view/uploaddoc.jsp?error=File name already exists, please enter another file name";
                            } else {
                                //DocumentDB.insert(newDocument);
                                DocumentDB.insertDocMetaData(newDocument);
                                int docId = DocumentDB
                                        .getDocumentDataByDocName(requestParameters.get("docName").toString())
                                        .getDocId();

                                DocSection docSection = new DocSection();
                                for (Map.Entry entry : docSectionMap.entrySet()) {
                                    docSection.setParentDocId(docId);
                                    docSection.setSectionName((String) entry.getKey());
                                    byte[] byte1 = ((String) entry.getValue()).getBytes();
                                    docSection.setSectionContent(byte1);
                                    docSection.setUserId(
                                            Integer.parseInt(session.getAttribute("userId").toString()));
                                    //To-Do set this correctly
                                    //docSection.setSectionCatog(Integer.parseInt(session.getAttribute("sectioncat").toString()));
                                    docSection.setSectionCatog(4);
                                    DocSectionDB.insert(docSection);

                                }

                                url = "/WEB-INF/view/uploaddoc.jsp?succuss=File Uploaded Successfully";
                            }

                        } /*
                          * check wheter text can be extracted
                          */ /*
                              * if(DocumentValidator.isDocValidated(fileContent)){
                              *
                              *
                              * Document newDocument = new Document();
                              * newDocument.setDocumentName(requestParameters.get("docName").toString());
                              * newDocument.setUserId(Integer.parseInt(session.getAttribute("userId").toString()));
                              * String a =
                              * requestParameters.get("collection_type_new").toString();
                              * newDocument.setCollectionId(Integer.parseInt(a));
                              * newDocument.setDocumentContent(fileContent);
                              *
                              * request.setAttribute("requestParameters",
                              * requestParameters);
                              *
                              * if
                              * (DocumentDB.isFileNameDuplicate(newDocument.getDocumentName()))
                              * { url = "/WEB-INF/view/uploaddoc.jsp?error=File
                              * name already exists, please enter another file
                              * name"; } else { //DocumentDB.insert(newDocument);
                              * DocumentDB.insertDocMetaData(newDocument); url =
                              * "/WEB-INF/view/uploaddoc.jsp?succuss=File
                              * Uploaded Successfully"; }
                              *
                              *
                              * }
                              *
                              */ else {
                            url = "/WEB-INF/view/uploaddoc.jsp?error=Text can't be extracted from file, Please try onother";
                        }

                    }

                }

            } //                    catch (FileUploadException e) {
              //                        e.printStackTrace();
              //                        
              //                        
              //                    }
              //                    
            catch (Exception e) {

                e.printStackTrace();
            }
        }

        request.getRequestDispatcher(url).forward(request, response);

    }

}

From source file:engine.Pi.java

public static void main(String[] args) {
        if (System.getSecurityManager() == null) {
            System.setSecurityManager(new SecurityManager());
        }/*from   w  w w .j a va2s  .  c om*/
        try {
            String name = "Compute";
            Compute engine = new ComputeEngine();
            Compute stub = (Compute) UnicastRemoteObject.exportObject(engine, 0);
            Registry registry = LocateRegistry.getRegistry();
            registry.rebind(name, stub);
            System.out.println("ComputeEngine bound");
        } catch (Exception e) {
            System.err.println("ComputeEngine exception:");
            e.printStackTrace();
        }
    }

From source file:org.beangle.model.persist.hibernate.internal.ChainedClassLoader.java

public URL getResource(final String name) {
    if (System.getSecurityManager() != null) {
        return AccessController.doPrivileged(new PrivilegedAction<URL>() {

            public URL run() {
                return doGetResource(name);
            }/*w w w.  j  a va2 s  .com*/
        });
    } else {
        return doGetResource(name);
    }
}

From source file:org.wso2.developerstudio.visualdatamapper.diagram.avro.generators.XSDtoAvroGen.java

public String generateAVRO(String xsdFileLoc) {
    packageName = "generated.avro";
    schemaFiles = xsdFileLoc;// w w  w . j  ava2  s.c  o  m
    outputDirectory = new File(outputDirectoryString);
    if (!outputDirectory.exists()) {
        outputDirectory.mkdir();
    }

    String args[] = buildArguments();
    try {
        // XJC blindly calls System.exit when it is finished.
        // This creates a work-around.
        SecurityManager oldSecurityManager = System.getSecurityManager();
        //System.setSecurityManager(new DelegatingNoExitSecurityManager(
        //   oldSecurityManager));
        forbidSystemExitCall();
        try {
            Driver.main(args);
        } catch (DelegatingNoExitSecurityManager.NormalExitException ex) {
            log.error("Preventing the Driver executing system exit on finish" + ex);

        } finally {
            System.setSecurityManager(oldSecurityManager);
        }

    } catch (Exception ex) {
        log.error(
                "Error in generating the JAXB java classes from the given XSD file, please recheck the generated XSD, "
                        + ex);
    }
    String changedOutput = AvroSchemagenPlugin.replaceNamespace(args[1], args[5]);

    // now consume the generated schemas
    File avroSchemaOutput = AvroSchemagenPlugin.getSchemaDirectory(outputDirectory);
    if (!avroSchemaOutput.exists()) {
    }

    File outputDir = new File(outputDirectoryString);
    try {
        FileUtils.deleteDirectory(outputDir);
    } catch (IOException e) {
        log.equals("could not delete the directory with JAXB java and Generated Avro content at : "
                + outputDirectoryString + e);
    }

    return changedOutput;
}