Search in sources :

Example 6 with JSONObject

use of net.sf.json.JSONObject in project hudson-2.x by hudson.

the class Hudson method doConfigSubmit.

//
//
// actions
//
//
/**
     * Accepts submission from the configuration page.
     */
public synchronized void doConfigSubmit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException {
    BulkChange bc = new BulkChange(this);
    try {
        checkPermission(ADMINISTER);
        JSONObject json = req.getSubmittedForm();
        // useSecurity = null;
        if (json.has("use_security")) {
            useSecurity = true;
            JSONObject security = json.getJSONObject("use_security");
            setSecurityRealm(SecurityRealm.all().newInstanceFromRadioList(security, "realm"));
            setAuthorizationStrategy(AuthorizationStrategy.all().newInstanceFromRadioList(security, "authorization"));
            if (security.has("markupFormatter")) {
                markupFormatter = req.bindJSON(MarkupFormatter.class, security.getJSONObject("markupFormatter"));
            } else {
                markupFormatter = null;
            }
        } else {
            useSecurity = null;
            setSecurityRealm(SecurityRealm.NO_AUTHENTICATION);
            authorizationStrategy = AuthorizationStrategy.UNSECURED;
            markupFormatter = null;
        }
        if (json.has("csrf")) {
            JSONObject csrf = json.getJSONObject("csrf");
            setCrumbIssuer(CrumbIssuer.all().newInstanceFromRadioList(csrf, "issuer"));
        } else {
            setCrumbIssuer(null);
        }
        if (json.has("viewsTabBar")) {
            viewsTabBar = req.bindJSON(ViewsTabBar.class, json.getJSONObject("viewsTabBar"));
        } else {
            viewsTabBar = new DefaultViewsTabBar();
        }
        if (json.has("myViewsTabBar")) {
            myViewsTabBar = req.bindJSON(MyViewsTabBar.class, json.getJSONObject("myViewsTabBar"));
        } else {
            myViewsTabBar = new DefaultMyViewsTabBar();
        }
        primaryView = json.has("primaryView") ? json.getString("primaryView") : getViews().iterator().next().getViewName();
        noUsageStatistics = json.has("usageStatisticsCollected") ? null : true;
        {
            String v = req.getParameter("slaveAgentPortType");
            if (!isUseSecurity() || v == null || v.equals("random")) {
                slaveAgentPort = 0;
            } else if (v.equals("disable")) {
                slaveAgentPort = -1;
            } else {
                try {
                    slaveAgentPort = Integer.parseInt(req.getParameter("slaveAgentPort"));
                } catch (NumberFormatException e) {
                    throw new FormException(Messages.Hudson_BadPortNumber(req.getParameter("slaveAgentPort")), "slaveAgentPort");
                }
            }
            // relaunch the agent
            if (tcpSlaveAgentListener == null) {
                if (slaveAgentPort != -1) {
                    tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
                }
            } else {
                if (tcpSlaveAgentListener.configuredPort != slaveAgentPort) {
                    tcpSlaveAgentListener.shutdown();
                    tcpSlaveAgentListener = null;
                    if (slaveAgentPort != -1) {
                        tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort);
                    }
                }
            }
        }
        numExecutors = json.getInt("numExecutors");
        if (req.hasParameter("master.mode")) {
            mode = Mode.valueOf(req.getParameter("master.mode"));
        } else {
            mode = Mode.NORMAL;
        }
        label = json.optString("labelString", "");
        quietPeriod = json.getInt("quiet_period");
        scmCheckoutRetryCount = json.getInt("retry_count");
        systemMessage = Util.nullify(req.getParameter("system_message"));
        jdks.clear();
        jdks.addAll(req.bindJSONToList(JDK.class, json.get("jdks")));
        boolean result = true;
        for (Descriptor<?> d : Functions.getSortedDescriptorsForGlobalConfig()) {
            result &= configureDescriptor(req, json, d);
        }
        for (JSONObject o : StructuredForm.toList(json, "plugin")) {
            pluginManager.getPlugin(o.getString("name")).getPlugin().configure(req, o);
        }
        clouds.rebuildHetero(req, json, Cloud.all(), "cloud");
        JSONObject np = json.getJSONObject("globalNodeProperties");
        if (np != null) {
            globalNodeProperties.rebuild(req, np, NodeProperty.for_(this));
        }
        version = VERSION;
        save();
        updateComputerList();
        if (result) {
            // go to the top page
            rsp.sendRedirect(req.getContextPath() + '/');
        } else {
            // back to config
            rsp.sendRedirect("configure");
        }
    } finally {
        bc.commit();
    }
}
Also used : DefaultMyViewsTabBar(hudson.views.DefaultMyViewsTabBar) MyViewsTabBar(hudson.views.MyViewsTabBar) BulkChange(hudson.BulkChange) DefaultViewsTabBar(hudson.views.DefaultViewsTabBar) DefaultMyViewsTabBar(hudson.views.DefaultMyViewsTabBar) ViewsTabBar(hudson.views.ViewsTabBar) MyViewsTabBar(hudson.views.MyViewsTabBar) DefaultMyViewsTabBar(hudson.views.DefaultMyViewsTabBar) FormException(hudson.model.Descriptor.FormException) TcpSlaveAgentListener(hudson.TcpSlaveAgentListener) JSONObject(net.sf.json.JSONObject) RawHtmlMarkupFormatter(hudson.markup.RawHtmlMarkupFormatter) MarkupFormatter(hudson.markup.MarkupFormatter) DefaultViewsTabBar(hudson.views.DefaultViewsTabBar)

Example 7 with JSONObject

use of net.sf.json.JSONObject in project hudson-2.x by hudson.

the class Job method submit.

/**
     * Derived class can override this to perform additional config submission
     * work.
     */
protected void submit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException {
    JSONObject json = req.getSubmittedForm();
    description = req.getParameter("description");
    keepDependencies = req.getParameter("keepDependencies") != null;
    properties.clear();
    setCascadingProjectName(StringUtils.trimToNull(req.getParameter("cascadingProjectName")));
    CopyOnWriteList parameterDefinitionProperties = new CopyOnWriteList();
    int i = 0;
    for (JobPropertyDescriptor d : JobPropertyDescriptor.getPropertyDescriptors(Job.this.getClass())) {
        if (!CascadingUtil.isCascadableJobProperty(d)) {
            String name = "jobProperty" + i;
            JSONObject config = json.getJSONObject(name);
            JobProperty prop = d.newInstance(req, config);
            if (null != prop) {
                prop.setOwner(this);
                if (prop instanceof AuthorizationMatrixProperty) {
                    properties.add(prop);
                } else if (prop instanceof ParametersDefinitionProperty) {
                    parameterDefinitionProperties.add(prop);
                }
            }
        } else {
            BaseProjectProperty property = CascadingUtil.getBaseProjectProperty(this, d.getJsonSafeClassName());
            JobProperty prop = d.newInstance(req, json.getJSONObject(d.getJsonSafeClassName()));
            if (null != prop) {
                prop.setOwner(this);
            }
            property.setValue(prop);
            addCascadingJobProperty(property);
        }
        i++;
    }
    setParameterDefinitionProperties(parameterDefinitionProperties);
    LogRotator logRotator = null;
    if (null != req.getParameter("logrotate")) {
        logRotator = LogRotator.DESCRIPTOR.newInstance(req, json.getJSONObject("logrotate"));
    }
    setLogRotator(logRotator);
}
Also used : BaseProjectProperty(org.hudsonci.model.project.property.BaseProjectProperty) JSONObject(net.sf.json.JSONObject) LogRotator(hudson.tasks.LogRotator) CopyOnWriteList(hudson.util.CopyOnWriteList) AuthorizationMatrixProperty(hudson.security.AuthorizationMatrixProperty) ExtensionPoint(hudson.ExtensionPoint)

Example 8 with JSONObject

use of net.sf.json.JSONObject in project hudson-2.x by hudson.

the class UpdateSite method verifySignature.

/**
     * Verifies the signature in the update center data file.
     */
private boolean verifySignature(JSONObject o) throws GeneralSecurityException, IOException {
    JSONObject signature = o.getJSONObject("signature");
    if (signature.isNullObject()) {
        LOGGER.severe("No signature block found");
        return false;
    }
    o.remove("signature");
    List<X509Certificate> certs = new ArrayList<X509Certificate>();
    {
        // load and verify certificates
        CertificateFactory cf = CertificateFactory.getInstance("X509");
        for (Object cert : o.getJSONArray("certificates")) {
            X509Certificate c = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(Base64.decode(cert.toString().toCharArray())));
            c.checkValidity();
            certs.add(c);
        }
        // all default root CAs in JVM are trusted, plus certs bundled in Hudson
        Set<TrustAnchor> anchors = CertificateUtil.getDefaultRootCAs();
        ServletContext context = Hudson.getInstance().servletContext;
        for (String cert : (Set<String>) context.getResourcePaths("/WEB-INF/update-center-rootCAs")) {
            // skip text files that are meant to be documentation
            if (cert.endsWith(".txt"))
                continue;
            anchors.add(new TrustAnchor((X509Certificate) cf.generateCertificate(context.getResourceAsStream(cert)), null));
        }
        CertificateUtil.validatePath(certs);
    }
    // this is for computing a digest to check sanity
    MessageDigest sha1 = MessageDigest.getInstance("SHA1");
    DigestOutputStream dos = new DigestOutputStream(new NullOutputStream(), sha1);
    // this is for computing a signature
    Signature sig = Signature.getInstance("SHA1withRSA");
    sig.initVerify(certs.get(0));
    SignatureOutputStream sos = new SignatureOutputStream(sig);
    JSONCanonicalUtils.write(o, new OutputStreamWriter(new TeeOutputStream(dos, sos), "UTF-8"));
    // did the digest match? this is not a part of the signature validation, but if we have a bug in the c14n
    // (which is more likely than someone tampering with update center), we can tell
    String computedDigest = new String(Base64.encode(sha1.digest()));
    String providedDigest = signature.getString("digest");
    if (!computedDigest.equalsIgnoreCase(providedDigest)) {
        LOGGER.severe("Digest mismatch: " + computedDigest + " vs " + providedDigest);
        return false;
    }
    if (!sig.verify(Base64.decode(signature.getString("signature").toCharArray()))) {
        LOGGER.severe("Signature in the update center doesn't match with the certificate");
        return false;
    }
    return true;
}
Also used : TeeOutputStream(org.apache.commons.io.output.TeeOutputStream) Set(java.util.Set) ArrayList(java.util.ArrayList) TrustAnchor(java.security.cert.TrustAnchor) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate) JSONObject(net.sf.json.JSONObject) SignatureOutputStream(org.jvnet.hudson.crypto.SignatureOutputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) DigestOutputStream(java.security.DigestOutputStream) Signature(java.security.Signature) ServletContext(javax.servlet.ServletContext) JSONObject(net.sf.json.JSONObject) OutputStreamWriter(java.io.OutputStreamWriter) MessageDigest(java.security.MessageDigest) NullOutputStream(org.apache.commons.io.output.NullOutputStream)

Example 9 with JSONObject

use of net.sf.json.JSONObject in project hudson-2.x by hudson.

the class Run method doConfigSubmit.

public HttpResponse doConfigSubmit(StaplerRequest req) throws IOException, ServletException, FormException {
    checkPermission(UPDATE);
    BulkChange bc = new BulkChange(this);
    try {
        JSONObject json = req.getSubmittedForm();
        submit(json);
        bc.commit();
    } finally {
        bc.abort();
    }
    return HttpResponses.redirectToDot();
}
Also used : JSONObject(net.sf.json.JSONObject) BulkChange(hudson.BulkChange)

Example 10 with JSONObject

use of net.sf.json.JSONObject in project head by mifos.

the class DatabaseConfiguration method readVCAPConfiguration.

private void readVCAPConfiguration() throws ConfigurationException {
    final String vcapServicesVar = System.getenv(VCAP_SERVICES_VAR);
    if (vcapServicesVar != null) {
        // use database configuration from the system variable to replace the default config
        final JSONObject json = (JSONObject) JSONSerializer.toJSON(vcapServicesVar);
        String mysqlKey = null;
        @SuppressWarnings("rawtypes") final Iterator iterator = json.keys();
        while (iterator.hasNext()) {
            final String key = (String) iterator.next();
            if (key.startsWith("mysql")) {
                mysqlKey = key;
                break;
            }
        }
        if (mysqlKey == null) {
            throw new ConfigurationException(INVALID_STRUCTURE);
        }
        final JSON mysqlJson = (JSON) json.get(mysqlKey);
        JSONObject dbJson;
        if (mysqlJson.isArray()) {
            final JSONArray mysqlJsonArray = (JSONArray) mysqlJson;
            if (mysqlJsonArray.size() < 1) {
                throw new ConfigurationException(INVALID_STRUCTURE);
            }
            dbJson = (JSONObject) mysqlJsonArray.get(0);
        } else {
            dbJson = (JSONObject) mysqlJson;
        }
        final JSONObject credentialsJson = (JSONObject) dbJson.get("credentials");
        this.dbName = credentialsJson.getString("name");
        this.host = credentialsJson.getString("host");
        this.port = credentialsJson.getString("port");
        this.user = credentialsJson.getString("user");
        this.password = credentialsJson.getString("password");
        this.dbPentahoDW = credentialsJson.getString("dbPentahoDW");
    }
}
Also used : JSONObject(net.sf.json.JSONObject) ConfigurationException(org.mifos.config.exceptions.ConfigurationException) Iterator(java.util.Iterator) JSONArray(net.sf.json.JSONArray) JSON(net.sf.json.JSON)

Aggregations

JSONObject (net.sf.json.JSONObject)493 Test (org.junit.Test)99 JSONArray (net.sf.json.JSONArray)94 IOException (java.io.IOException)49 HashMap (java.util.HashMap)48 ArrayList (java.util.ArrayList)36 JSON (net.sf.json.JSON)26 PrintWriter (java.io.PrintWriter)25 Map (java.util.Map)23 File (java.io.File)21 InputStream (java.io.InputStream)18 URISyntaxException (java.net.URISyntaxException)15 UnsupportedEncodingException (java.io.UnsupportedEncodingException)14 JsonConfig (net.sf.json.JsonConfig)14 FreeStyleBuild (hudson.model.FreeStyleBuild)13 URI (java.net.URI)13 URL (java.net.URL)13 JSONException (net.sf.json.JSONException)13 Context (org.zaproxy.zap.model.Context)12 Transactional (org.springframework.transaction.annotation.Transactional)11