Search in sources :

Example 6 with StaplerRequest

use of org.kohsuke.stapler.StaplerRequest in project promoted-builds-plugin by jenkinsci.

the class PromotedBuildParameterDefinition method getBuilds.

/**
 * Gets a list of promoted builds for the project.
 * @return List of {@link AbstractBuild}s, which have been promoted
 * @deprecated This method retrieves the base item for relative addressing from
 * the {@link StaplerRequest}. The relative addressing may be malfunctional if
 * you use this method outside {@link StaplerRequest}s.
 * Use {@link #getRuns(hudson.model.Item)} instead
 */
@Nonnull
@Deprecated
public List getBuilds() {
    // Try to get ancestor from the object, otherwise pass null and disable the relative addressing
    final StaplerRequest currentRequest = Stapler.getCurrentRequest();
    final Item item = currentRequest != null ? currentRequest.findAncestorObject(Item.class) : null;
    return getRuns(item);
}
Also used : Item(hudson.model.Item) StaplerRequest(org.kohsuke.stapler.StaplerRequest) Nonnull(javax.annotation.Nonnull)

Example 7 with StaplerRequest

use of org.kohsuke.stapler.StaplerRequest 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 StaplerRequest

use of org.kohsuke.stapler.StaplerRequest in project hudson-2.x by hudson.

the class Functions method getRelativeLinkTo.

/**
 * Computes the relative path from the current page to the given item.
 */
public static String getRelativeLinkTo(Item p) {
    Map<Object, String> ancestors = new HashMap<Object, String>();
    View view = null;
    StaplerRequest request = Stapler.getCurrentRequest();
    for (Ancestor a : request.getAncestors()) {
        ancestors.put(a.getObject(), a.getRelativePath());
        if (a.getObject() instanceof View)
            view = (View) a.getObject();
    }
    String path = ancestors.get(p);
    if (path != null)
        return path;
    Item i = p;
    String url = "";
    while (true) {
        ItemGroup ig = i.getParent();
        url = i.getShortUrl() + url;
        if (ig == Hudson.getInstance()) {
            assert i instanceof TopLevelItem;
            if (view != null && view.contains((TopLevelItem) i)) {
                // if p and the current page belongs to the same view, then return a relative path
                return ancestors.get(view) + '/' + url;
            } else {
                // otherwise return a path from the root Hudson
                return request.getContextPath() + '/' + p.getUrl();
            }
        }
        path = ancestors.get(ig);
        if (path != null)
            return path + '/' + url;
        // if not, ig must have been the Hudson instance
        assert ig instanceof Item;
        i = (Item) ig;
    }
}
Also used : Item(hudson.model.Item) TopLevelItem(hudson.model.TopLevelItem) ItemGroup(hudson.model.ItemGroup) HashMap(java.util.HashMap) StaplerRequest(org.kohsuke.stapler.StaplerRequest) TopLevelItem(hudson.model.TopLevelItem) SearchableModelObject(hudson.search.SearchableModelObject) ModelObject(hudson.model.ModelObject) View(hudson.model.View) Ancestor(org.kohsuke.stapler.Ancestor)

Example 9 with StaplerRequest

use of org.kohsuke.stapler.StaplerRequest in project hudson-2.x by hudson.

the class UIComponentSupport method getRootPath.

@JellyAccessible
public String getRootPath() {
    StaplerRequest req = Stapler.getCurrentRequest();
    checkState(req != null, "StaplerRequest not bound");
    return req.getContextPath();
}
Also used : StaplerRequest(org.kohsuke.stapler.StaplerRequest)

Example 10 with StaplerRequest

use of org.kohsuke.stapler.StaplerRequest in project blueocean-plugin by jenkinsci.

the class BitbucketServerScmContentProviderTest method unauthorizedAccessToContentShouldFail.

@Test
public void unauthorizedAccessToContentShouldFail() throws UnirestException, IOException {
    User alice = User.get("alice");
    alice.setFullName("Alice Cooper");
    alice.addProperty(new Mailer.UserProperty("alice@jenkins-ci.org"));
    String aliceCredentialId = createCredential(BitbucketServerScm.ID, alice);
    StaplerRequest staplerRequest = mockStapler();
    MultiBranchProject mbp = mockMbp(aliceCredentialId, alice);
    try {
        // Bob trying to access content but his credential is not setup so should fail
        new BitbucketServerScmContentProvider().getContent(staplerRequest, mbp);
    } catch (ServiceException.PreconditionRequired e) {
        assertEquals("Can't access content from Bitbucket: no credential found", e.getMessage());
        return;
    }
    fail("Should have failed with PreConditionException");
}
Also used : User(hudson.model.User) ServiceException(io.jenkins.blueocean.commons.ServiceException) StaplerRequest(org.kohsuke.stapler.StaplerRequest) Mailer(hudson.tasks.Mailer) MultiBranchProject(jenkins.branch.MultiBranchProject) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

StaplerRequest (org.kohsuke.stapler.StaplerRequest)79 Test (org.junit.Test)45 MultiBranchProject (jenkins.branch.MultiBranchProject)28 JSONObject (net.sf.json.JSONObject)20 GitContent (io.jenkins.blueocean.rest.impl.pipeline.scm.GitContent)18 ServiceException (io.jenkins.blueocean.commons.ServiceException)17 BufferedReader (java.io.BufferedReader)16 StringReader (java.io.StringReader)16 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)15 User (hudson.model.User)14 Mailer (hudson.tasks.Mailer)13 StaplerResponse (org.kohsuke.stapler.StaplerResponse)8 File (java.io.File)7 BitbucketScmSaveFileRequest (io.jenkins.blueocean.blueocean_bitbucket_pipeline.BitbucketScmSaveFileRequest)6 ScmFile (io.jenkins.blueocean.rest.impl.pipeline.scm.ScmFile)5 HashMap (java.util.HashMap)5 List (java.util.List)5 Nonnull (javax.annotation.Nonnull)5 Item (hudson.model.Item)4 ArrayList (java.util.ArrayList)4