Search in sources :

Example 6 with Hudson

use of hudson.model.Hudson in project hudson-2.x by hudson.

the class WebAppMain method contextDestroyed.

public void contextDestroyed(ServletContextEvent event) {
    Hudson instance = Hudson.getInstance();
    if (instance != null)
        instance.cleanUp();
    // Logger is in the system classloader, so if we don't do this
    // the whole web app will never be undepoyed.
    Logger.getLogger("hudson").removeHandler(handler);
}
Also used : Hudson(hudson.model.Hudson)

Example 7 with Hudson

use of hudson.model.Hudson in project hudson-2.x by hudson.

the class WebAppMain method contextInitialized.

/**
     * Creates the sole instance of {@link Hudson} and register it to the {@link ServletContext}.
     */
public void contextInitialized(ServletContextEvent event) {
    try {
        final ServletContext context = event.getServletContext();
        // Install the current servlet context, unless its already been set
        final WebAppController controller = WebAppController.get();
        try {
            // Attempt to set the context
            controller.setContext(context);
        } catch (IllegalStateException e) {
        // context already set ignore
        }
        // Setup the default install strategy if not already configured
        try {
            controller.setInstallStrategy(new DefaultInstallStrategy());
        } catch (IllegalStateException e) {
        // strategy already set ignore
        }
        // use the current request to determine the language
        LocaleProvider.setProvider(new LocaleProvider() {

            public Locale get() {
                Locale locale = null;
                StaplerRequest req = Stapler.getCurrentRequest();
                if (req != null)
                    locale = req.getLocale();
                if (locale == null)
                    locale = Locale.getDefault();
                return locale;
            }
        });
        // quick check to see if we (seem to) have enough permissions to run. (see #719)
        JVM jvm;
        try {
            jvm = new JVM();
            new URLClassLoader(new URL[0], getClass().getClassLoader());
        } catch (SecurityException e) {
            controller.install(new InsufficientPermissionDetected(e));
            return;
        }
        try {
            // remove Sun PKCS11 provider if present. See http://wiki.hudson-ci.org/display/HUDSON/Solaris+Issue+6276483
            Security.removeProvider("SunPKCS11-Solaris");
        } catch (SecurityException e) {
        // ignore this error.
        }
        installLogger();
        File dir = getHomeDir(event);
        try {
            dir = dir.getCanonicalFile();
        } catch (IOException e) {
            dir = dir.getAbsoluteFile();
        }
        final File home = dir;
        home.mkdirs();
        LOGGER.info("Home directory: " + home);
        // check that home exists (as mkdirs could have failed silently), otherwise throw a meaningful error
        if (!home.exists()) {
            controller.install(new NoHomeDir(home));
            return;
        }
        // make sure that we are using XStream in the "enhanced" (JVM-specific) mode
        if (jvm.bestReflectionProvider().getClass() == PureJavaReflectionProvider.class) {
            // nope
            controller.install(new IncompatibleVMDetected());
            return;
        }
        // make sure this is servlet 2.4 container or above
        try {
            ServletResponse.class.getMethod("setCharacterEncoding", String.class);
        } catch (NoSuchMethodException e) {
            controller.install(new IncompatibleServletVersionDetected(ServletResponse.class));
            return;
        }
        // make sure that we see Ant 1.7
        try {
            FileSet.class.getMethod("getDirectoryScanner");
        } catch (NoSuchMethodException e) {
            controller.install(new IncompatibleAntVersionDetected(FileSet.class));
            return;
        }
        // make sure AWT is functioning, or else JFreeChart won't even load.
        if (ChartUtil.awtProblemCause != null) {
            controller.install(new AWTProblem(ChartUtil.awtProblemCause));
            return;
        }
        // check that and report an error
        try {
            File f = File.createTempFile("test", "test");
            f.delete();
        } catch (IOException e) {
            controller.install(new NoTempDir(e));
            return;
        }
        // try to correct it
        try {
            TransformerFactory.newInstance();
        // if this works we are all happy
        } catch (TransformerFactoryConfigurationError x) {
            // no it didn't.
            LOGGER.log(Level.WARNING, "XSLT not configured correctly. Hudson will try to fix this. See http://issues.apache.org/bugzilla/show_bug.cgi?id=40895 for more details", x);
            System.setProperty(TransformerFactory.class.getName(), "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl");
            try {
                TransformerFactory.newInstance();
                LOGGER.info("XSLT is set to the JAXP RI in JRE");
            } catch (TransformerFactoryConfigurationError y) {
                LOGGER.log(Level.SEVERE, "Failed to correct the problem.");
            }
        }
        installExpressionFactory(event);
        controller.install(new HudsonIsLoading());
        new Thread("hudson initialization thread") {

            @Override
            public void run() {
                try {
                    // Creating of the god object performs most of the booting muck
                    Hudson hudson = new Hudson(home, context);
                    // once its done, hook up to stapler and things should be ready to go
                    controller.install(hudson);
                    // trigger the loading of changelogs in the background,
                    // but give the system 10 seconds so that the first page
                    // can be served quickly
                    Trigger.timer.schedule(new SafeTimerTask() {

                        public void doRun() {
                            User.getUnknown().getBuilds();
                        }
                    }, 1000 * 10);
                } catch (Error e) {
                    LOGGER.log(Level.SEVERE, "Failed to initialize Hudson", e);
                    controller.install(new HudsonFailedToLoad(e));
                    throw e;
                } catch (Exception e) {
                    LOGGER.log(Level.SEVERE, "Failed to initialize Hudson", e);
                    controller.install(new HudsonFailedToLoad(e));
                }
            }
        }.start();
    } catch (Error e) {
        LOGGER.log(Level.SEVERE, "Failed to initialize Hudson", e);
        throw e;
    } catch (RuntimeException e) {
        LOGGER.log(Level.SEVERE, "Failed to initialize Hudson", e);
        throw e;
    }
}
Also used : Locale(java.util.Locale) JVM(com.thoughtworks.xstream.core.JVM) IncompatibleAntVersionDetected(hudson.util.IncompatibleAntVersionDetected) StaplerRequest(org.kohsuke.stapler.StaplerRequest) NoHomeDir(hudson.util.NoHomeDir) ServletContext(javax.servlet.ServletContext) HudsonFailedToLoad(hudson.util.HudsonFailedToLoad) TransformerFactoryConfigurationError(javax.xml.transform.TransformerFactoryConfigurationError) IncompatibleVMDetected(hudson.util.IncompatibleVMDetected) Hudson(hudson.model.Hudson) InsufficientPermissionDetected(hudson.util.InsufficientPermissionDetected) TransformerFactoryConfigurationError(javax.xml.transform.TransformerFactoryConfigurationError) IOException(java.io.IOException) WebAppController(hudson.stapler.WebAppController) HudsonIsLoading(hudson.util.HudsonIsLoading) NoTempDir(hudson.util.NoTempDir) AWTProblem(hudson.util.AWTProblem) NamingException(javax.naming.NamingException) IOException(java.io.IOException) DefaultInstallStrategy(hudson.stapler.WebAppController.DefaultInstallStrategy) LocaleProvider(org.jvnet.localizer.LocaleProvider) URLClassLoader(java.net.URLClassLoader) IncompatibleServletVersionDetected(hudson.util.IncompatibleServletVersionDetected) File(java.io.File) SafeTimerTask(hudson.triggers.SafeTimerTask)

Example 8 with Hudson

use of hudson.model.Hudson in project hudson-2.x by hudson.

the class ClientAuthenticationCache method get.

/**
     * Gets the persisted authentication for this Hudson.
     *
     * @return {@link Hudson#ANONYMOUS} if no such credential is found, or if the stored credential is invalid.
     */
public Authentication get() {
    Hudson h = Hudson.getInstance();
    Secret userName = Secret.decrypt(props.getProperty(getPropertyKey()));
    // failed to decrypt
    if (userName == null)
        return Hudson.ANONYMOUS;
    try {
        UserDetails u = h.getSecurityRealm().loadUserByUsername(userName.toString());
        return new UsernamePasswordAuthenticationToken(u.getUsername(), u.getPassword(), u.getAuthorities());
    } catch (AuthenticationException e) {
        return Hudson.ANONYMOUS;
    } catch (DataAccessException e) {
        return Hudson.ANONYMOUS;
    }
}
Also used : Secret(hudson.util.Secret) UserDetails(org.acegisecurity.userdetails.UserDetails) AuthenticationException(org.acegisecurity.AuthenticationException) Hudson(hudson.model.Hudson) UsernamePasswordAuthenticationToken(org.acegisecurity.providers.UsernamePasswordAuthenticationToken) DataAccessException(org.springframework.dao.DataAccessException)

Example 9 with Hudson

use of hudson.model.Hudson in project hudson-2.x by hudson.

the class ProxyConfiguration method open.

/**
     * This method should be used wherever {@link URL#openConnection()} to internet URLs is invoked directly.
     */
public static URLConnection open(URL url) throws IOException {
    // this code might run on slaves
    Hudson hudson = Hudson.getInstance();
    ProxyConfiguration proxyConfig = hudson != null ? hudson.proxy : null;
    if (proxyConfig == null) {
        return url.openConnection();
    }
    if (proxyConfig.noProxyFor != null) {
        StringTokenizer tokenizer = new StringTokenizer(proxyConfig.noProxyFor, ",");
        while (tokenizer.hasMoreTokens()) {
            String noProxyHost = tokenizer.nextToken().trim();
            if (noProxyHost.contains("*")) {
                if (url.getHost().trim().contains(noProxyHost.replaceAll("\\*", ""))) {
                    return url.openConnection(Proxy.NO_PROXY);
                }
            } else if (url.getHost().trim().equals(noProxyHost)) {
                return url.openConnection(Proxy.NO_PROXY);
            }
        }
    }
    URLConnection urlConnection = url.openConnection(proxyConfig.createProxy());
    if (proxyConfig.isAuthNeeded()) {
        String credentials = proxyConfig.getUserName() + ":" + proxyConfig.getPassword();
        String encoded = new String(Base64.encodeBase64(credentials.getBytes()));
        urlConnection.setRequestProperty("Proxy-Authorization", "Basic " + encoded);
    }
    boolean connected = false;
    int count = 0;
    while (!connected) {
        try {
            urlConnection.connect();
            connected = true;
        } catch (SocketTimeoutException exc) {
            LOGGER.fine("Connection timed out. trying again " + count);
            if (++count > TIME_OUT_RETRY_COUNT) {
                throw new IOException("Could not connect to " + url.toExternalForm() + ". Connection timed out after " + TIME_OUT_RETRY_COUNT + " tries.");
            }
            connected = false;
        } catch (UnknownHostException exc) {
            throw new IOException2("Could not connect to " + url.toExternalForm() + ". Check your internet connection.", exc);
        } catch (ConnectException exc) {
            throw new IOException2("Could not connect to " + url.toExternalForm() + ". Check your internet connection.", exc);
        }
    }
    return urlConnection;
}
Also used : StringTokenizer(java.util.StringTokenizer) SocketTimeoutException(java.net.SocketTimeoutException) UnknownHostException(java.net.UnknownHostException) Hudson(hudson.model.Hudson) IOException(java.io.IOException) URLConnection(java.net.URLConnection) IOException2(hudson.util.IOException2) ConnectException(java.net.ConnectException)

Example 10 with Hudson

use of hudson.model.Hudson in project hudson-2.x by hudson.

the class Functions method getCrumbRequestField.

public static String getCrumbRequestField() {
    Hudson h = Hudson.getInstance();
    CrumbIssuer issuer = h != null ? h.getCrumbIssuer() : null;
    return issuer != null ? issuer.getDescriptor().getCrumbRequestField() : "";
}
Also used : CrumbIssuer(hudson.security.csrf.CrumbIssuer) Hudson(hudson.model.Hudson)

Aggregations

Hudson (hudson.model.Hudson)43 FreeStyleProjectMock (hudson.model.FreeStyleProjectMock)8 ArrayList (java.util.ArrayList)8 Test (org.junit.Test)8 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)8 Job (hudson.model.Job)7 IOException (java.io.IOException)7 Before (org.junit.Before)7 FreeStyleProject (hudson.model.FreeStyleProject)5 AbstractProject (hudson.model.AbstractProject)4 File (java.io.File)3 Descriptor (hudson.model.Descriptor)2 TopLevelItem (hudson.model.TopLevelItem)2 UpdateSite (hudson.model.UpdateSite)2 CrumbIssuer (hudson.security.csrf.CrumbIssuer)2 Publisher (hudson.tasks.Publisher)2 JSONObject (net.sf.json.JSONObject)2 CmdLineException (org.kohsuke.args4j.CmdLineException)2 StaplerRequest (org.kohsuke.stapler.StaplerRequest)2 Provides (com.google.inject.Provides)1