Search in sources :

Example 6 with ParamType

use of com.tremolosecurity.config.xml.ParamType in project OpenUnison by TremoloSecurity.

the class OpenUnisonUtils method importIdpMetadata.

private static void importIdpMetadata(Options options, CommandLine cmd, String unisonXMLFile, TremoloType ttRead, TremoloType ttWrite, String ksPath, KeyStore ks) throws ParserConfigurationException, SAXException, IOException, FileNotFoundException, UnmarshallingException, Exception, Base64DecodingException, CertificateException, KeyStoreException, NoSuchAlgorithmException, JAXBException, PropertyException {
    logger.info("Import SP Metadata into the IdP");
    logger.info("Loading Metadata...");
    String metadataFile = loadOption(cmd, "pathToMetaData", options);
    InitializationService.initialize();
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Element root = builder.parse(new InputSource(new InputStreamReader(new FileInputStream(metadataFile)))).getDocumentElement();
    EntityDescriptor ed = (EntityDescriptor) XMLObjectSupport.getUnmarshaller(root).unmarshall(root);
    logger.info("Loading IdP...");
    String idpName = loadOption(cmd, "idpName", options);
    ApplicationType idp = null;
    for (ApplicationType app : ttWrite.getApplications().getApplication()) {
        if (app.getName().equalsIgnoreCase(idpName)) {
            idp = app;
        }
    }
    if (idp == null) {
        throw new Exception("IdP '" + idpName + "' not found");
    }
    SPSSODescriptor sp = ed.getSPSSODescriptor("urn:oasis:names:tc:SAML:2.0:protocol");
    TrustType trust = null;
    trust = new TrustType();
    if (sp.getID() == null) {
        trust.setName(ed.getEntityID());
    } else {
        trust.setName(sp.getID());
    }
    for (AssertionConsumerService svc : sp.getAssertionConsumerServices()) {
        if (svc.getBinding().equalsIgnoreCase("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST")) {
            ParamType pt = new ParamType();
            pt.setName("httpPostRespURL");
            pt.setValue(svc.getLocation());
            trust.getParam().add(pt);
        }
    }
    ParamType pt = new ParamType();
    pt.setName("signAssertion");
    pt.setValue(Boolean.toString(sp.getWantAssertionsSigned().booleanValue()));
    trust.getParam().add(pt);
    if (pt.getValue().equalsIgnoreCase("false")) {
        pt = new ParamType();
        pt.setName("signResponse");
        pt.setValue("true");
        trust.getParam().add(pt);
    } else {
        pt = new ParamType();
        pt.setName("signResponse");
        pt.setValue("false");
        trust.getParam().add(pt);
    }
    boolean first = true;
    for (NameIDFormat nameid : sp.getNameIDFormats()) {
        if (first) {
            pt = new ParamType();
            pt.setName("defaultNameId");
            pt.setValue(nameid.getFormat());
            trust.getParam().add(pt);
            first = false;
        }
        pt = new ParamType();
        pt.setName("nameIdMap");
        pt.setValue(nameid.getFormat() + "=");
        trust.getParam().add(pt);
    }
    boolean encryptAssertion = false;
    boolean signAssertion = false;
    for (KeyDescriptor kd : sp.getKeyDescriptors()) {
        if (kd.getUse().equals(UsageType.SIGNING)) {
            String base64 = kd.getKeyInfo().getX509Datas().get(0).getX509Certificates().get(0).getValue();
            String name = "verify-" + ed.getEntityID() + "-sp-sig";
            ByteArrayInputStream bais = new ByteArrayInputStream(Base64.decode(base64));
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            Collection<? extends Certificate> c = cf.generateCertificates(bais);
            if (c.size() > 1) {
                int j = 0;
                Iterator<? extends Certificate> i = c.iterator();
                while (i.hasNext()) {
                    Certificate certificate = (Certificate) i.next();
                    ks.setCertificateEntry(name + "-" + j, certificate);
                }
            } else {
                ks.setCertificateEntry(name, c.iterator().next());
            }
            pt = new ParamType();
            pt.setName("spSigKey");
            pt.setValue(name);
            trust.getParam().add(pt);
            signAssertion = true;
        }
        if (kd.getUse().equals(UsageType.ENCRYPTION)) {
            String base64 = kd.getKeyInfo().getX509Datas().get(0).getX509Certificates().get(0).getValue();
            String name = "verify-" + ed.getEntityID() + "-sp-enc";
            ByteArrayInputStream bais = new ByteArrayInputStream(Base64.decode(base64));
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            Collection<? extends Certificate> c = cf.generateCertificates(bais);
            if (c.size() > 1) {
                int j = 0;
                Iterator<? extends Certificate> i = c.iterator();
                while (i.hasNext()) {
                    Certificate certificate = (Certificate) i.next();
                    ks.setCertificateEntry(name + "-" + j, certificate);
                }
            } else {
                ks.setCertificateEntry(name, c.iterator().next());
            }
            pt = new ParamType();
            pt.setName("spEncKey");
            pt.setValue(name);
            trust.getParam().add(pt);
            encryptAssertion = true;
        }
    }
    pt = new ParamType();
    pt.setName("encAssertion");
    pt.setValue(encryptAssertion ? "true" : "false");
    trust.getParam().add(pt);
    if (!signAssertion) {
        pt = new ParamType();
        pt.setName("spSigKey");
        pt.setValue("");
        trust.getParam().add(pt);
    }
    if (!encryptAssertion) {
        pt = new ParamType();
        pt.setName("spEncKey");
        pt.setValue("");
        trust.getParam().add(pt);
    }
    pt = new ParamType();
    pt.setName("defaultAuthCtx");
    pt.setValue("");
    trust.getParam().add(pt);
    TrustType cur = null;
    for (TrustType trustType : idp.getUrls().getUrl().get(0).getIdp().getTrusts().getTrust()) {
        if (trustType.getName().equals(trust.getName())) {
            cur = trustType;
            break;
        }
    }
    if (cur != null) {
        idp.getUrls().getUrl().get(0).getIdp().getTrusts().getTrust().remove(cur);
    }
    idp.getUrls().getUrl().get(0).getIdp().getTrusts().getTrust().add(trust);
    OpenUnisonUtils.storeMethod(unisonXMLFile, ttWrite, ksPath, ks);
}
Also used : InputSource(org.xml.sax.InputSource) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) InputStreamReader(java.io.InputStreamReader) KeyDescriptor(org.opensaml.saml.saml2.metadata.KeyDescriptor) JAXBElement(javax.xml.bind.JAXBElement) Element(org.w3c.dom.Element) TrustType(com.tremolosecurity.config.xml.TrustType) CertificateFactory(java.security.cert.CertificateFactory) FileInputStream(java.io.FileInputStream) KeyStoreException(java.security.KeyStoreException) SignatureException(org.opensaml.xmlsec.signature.support.SignatureException) SecurityException(org.opensaml.security.SecurityException) UnmarshallingException(org.opensaml.core.xml.io.UnmarshallingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CertificateEncodingException(java.security.cert.CertificateEncodingException) MarshallingException(org.opensaml.core.xml.io.MarshallingException) IOException(java.io.IOException) Base64DecodingException(org.apache.xml.security.exceptions.Base64DecodingException) ServletException(javax.servlet.ServletException) PropertyException(javax.xml.bind.PropertyException) JAXBException(javax.xml.bind.JAXBException) FileNotFoundException(java.io.FileNotFoundException) SAXException(org.xml.sax.SAXException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) CertificateException(java.security.cert.CertificateException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) AuthMechParamType(com.tremolosecurity.config.xml.AuthMechParamType) ParamType(com.tremolosecurity.config.xml.ParamType) EntityDescriptor(org.opensaml.saml.saml2.metadata.EntityDescriptor) ApplicationType(com.tremolosecurity.config.xml.ApplicationType) SPSSODescriptor(org.opensaml.saml.saml2.metadata.SPSSODescriptor) NameIDFormat(org.opensaml.saml.saml2.metadata.NameIDFormat) DocumentBuilder(javax.xml.parsers.DocumentBuilder) ByteArrayInputStream(java.io.ByteArrayInputStream) AssertionConsumerService(org.opensaml.saml.saml2.metadata.AssertionConsumerService) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 7 with ParamType

use of com.tremolosecurity.config.xml.ParamType in project OpenUnison by TremoloSecurity.

the class LoadQueueListenersFromK8s method createQueue.

private void createQueue(TremoloType tremolo, String name, JSONObject item) throws ProvisioningException {
    JSONObject spec = (JSONObject) item.get("spec");
    MessageListenerType mlt = new MessageListenerType();
    mlt.setQueueName(name);
    StringBuffer b = new StringBuffer();
    b.setLength(0);
    OpenUnisonConfigLoader.integrateIncludes(b, (String) spec.get("className"));
    mlt.setClassName(b.toString());
    JSONArray params = (JSONArray) spec.get("params");
    for (Object o : params) {
        JSONObject param = (JSONObject) o;
        ParamType pt = new ParamType();
        b.setLength(0);
        OpenUnisonConfigLoader.integrateIncludes(b, (String) param.get("name"));
        pt.setName(b.toString());
        b.setLength(0);
        OpenUnisonConfigLoader.integrateIncludes(b, (String) param.get("value"));
        pt.setValue(b.toString());
        mlt.getParams().add(pt);
    }
    HttpCon nonwatchHttp = null;
    JSONArray secretParams = (JSONArray) spec.get("secretParams");
    if (secretParams != null) {
        try {
            nonwatchHttp = this.k8sWatch.getK8s().createClient();
            String token = this.k8sWatch.getK8s().getAuthToken();
            for (Object o : secretParams) {
                JSONObject secretParam = (JSONObject) o;
                String paramName = (String) secretParam.get("name");
                String secretName = (String) secretParam.get("secretName");
                String secretKey = (String) secretParam.get("secretKey");
                String secretValue = this.k8sWatch.getSecretValue(secretName, secretKey, token, nonwatchHttp);
                ParamType pt = new ParamType();
                pt.setName(paramName);
                pt.setValue(secretValue);
                mlt.getParams().add(pt);
            }
        } catch (Exception e) {
            throw new ProvisioningException("Could not load secrets for '" + name + "'");
        } finally {
            if (nonwatchHttp != null) {
                try {
                    nonwatchHttp.getHttp().close();
                } catch (IOException e) {
                }
                nonwatchHttp.getBcm().close();
            }
        }
    }
    try {
        this.cfgMgr.getProvisioningEngine().addMessageListener(mlt);
    } catch (InstantiationException | IllegalAccessException | ClassNotFoundException | ProvisioningException | JMSException e) {
        logger.warn("Could not create listener " + name, e);
    }
}
Also used : JSONArray(org.json.simple.JSONArray) JMSException(javax.jms.JMSException) IOException(java.io.IOException) ParamType(com.tremolosecurity.config.xml.ParamType) ClientProtocolException(org.apache.http.client.ClientProtocolException) ParseException(org.json.simple.parser.ParseException) HttpResponseException(org.apache.http.client.HttpResponseException) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) IOException(java.io.IOException) JMSException(javax.jms.JMSException) HttpCon(com.tremolosecurity.provisioning.util.HttpCon) JSONObject(org.json.simple.JSONObject) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) JSONObject(org.json.simple.JSONObject) MessageListenerType(com.tremolosecurity.config.xml.MessageListenerType)

Example 8 with ParamType

use of com.tremolosecurity.config.xml.ParamType in project OpenUnison by TremoloSecurity.

the class SendMessageThread method initScheduler.

@Override
public void initScheduler() throws ProvisioningException {
    if (this.cfgMgr.getCfg().getProvisioning() == null || this.cfgMgr.getCfg().getProvisioning().getScheduler() == null) {
        logger.warn("Scheduler not defined");
        return;
    }
    SchedulingType sct = this.cfgMgr.getCfg().getProvisioning().getScheduler();
    Properties scheduleProps = new Properties();
    scheduleProps.setProperty("org.quartz.scheduler.instanceName", sct.getInstanceLabel());
    /*String instanceLabel = null;
		try {
			Enumeration<NetworkInterface> enumer = NetworkInterface.getNetworkInterfaces();
			while (enumer.hasMoreElements()) {
				NetworkInterface ni = enumer.nextElement();
				Enumeration<InetAddress> enumeri = ni.getInetAddresses();
				while (enumeri.hasMoreElements()) {
					InetAddress addr = enumeri.nextElement();
					if (addr.getHostAddress().startsWith(sct.getInstanceIPMask())) {
						instanceLabel = addr.getHostAddress();
					}
				}
			}
		} catch (SocketException e) {
			throw new ProvisioningException("Could not read network addresses",e);
		}
		
		if (instanceLabel == null) {
			logger.warn("No IP starts with '" + sct.getInstanceIPMask() + "'");
			instanceLabel = "AUTO";
		}*/
    scheduleProps.setProperty("org.quartz.scheduler.instanceId", UUID.randomUUID().toString());
    scheduleProps.setProperty("org.quartz.threadPool.threadCount", Integer.toString(sct.getThreadCount()));
    if (sct.isUseDB()) {
        scheduleProps.setProperty("org.quartz.jobStore.class", "org.quartz.impl.jdbcjobstore.JobStoreTX");
        scheduleProps.setProperty("org.quartz.jobStore.driverDelegateClass", sct.getScheduleDB().getDelegateClassName());
        scheduleProps.setProperty("org.quartz.jobStore.dataSource", "scheduleDB");
        scheduleProps.setProperty("org.quartz.dataSource.scheduleDB.driver", sct.getScheduleDB().getDriver());
        scheduleProps.setProperty("org.quartz.dataSource.scheduleDB.URL", sct.getScheduleDB().getUrl());
        scheduleProps.setProperty("org.quartz.dataSource.scheduleDB.user", sct.getScheduleDB().getUser());
        scheduleProps.setProperty("org.quartz.dataSource.scheduleDB.password", sct.getScheduleDB().getPassword());
        scheduleProps.setProperty("org.quartz.dataSource.scheduleDB.maxConnections", Integer.toString(sct.getScheduleDB().getMaxConnections()));
        scheduleProps.setProperty("org.quartz.dataSource.scheduleDB.validationQuery", sct.getScheduleDB().getValidationQuery());
        scheduleProps.setProperty("org.quartz.jobStore.useProperties", "true");
        scheduleProps.setProperty("org.quartz.jobStore.isClustered", "true");
    } else {
        scheduleProps.setProperty("org.quartz.jobStore.class", "org.quartz.simpl.RAMJobStore");
    }
    try {
        /*String classpath = System.getProperty("java.class.path");
			String[] classpathEntries = classpath.split(File.pathSeparator);
			for (String cp : classpathEntries) {
				System.out.println(cp);
			}*/
        PrintStream out = new PrintStream(new FileOutputStream(System.getProperty(OpenUnisonConstants.UNISON_CONFIG_QUARTZDIR) + "/quartz.properties"));
        scheduleProps.store(out, "Unison internal scheduler properties");
        out.flush();
        out.close();
    } catch (IOException e) {
        throw new ProvisioningException("Could not write to quartz.properties", e);
    }
    try {
        this.scheduler = StdSchedulerFactory.getDefaultScheduler();
        this.scheduler.start();
        this.cfgMgr.addThread(new StopScheduler(this.scheduler));
        HashSet<String> jobKeys = new HashSet<String>();
        for (JobType jobType : sct.getJob()) {
            addNewJob(jobKeys, jobType);
        }
        DynamicPortalUrlsType dynamicJobs = cfgMgr.getCfg().getProvisioning().getScheduler().getDynamicJobs();
        if (dynamicJobs != null && dynamicJobs.isEnabled()) {
            String className = dynamicJobs.getClassName();
            HashMap<String, Attribute> cfgAttrs = new HashMap<String, Attribute>();
            for (ParamType pt : dynamicJobs.getParams()) {
                Attribute attr = cfgAttrs.get(pt.getName());
                if (attr == null) {
                    attr = new Attribute(pt.getName());
                    cfgAttrs.put(pt.getName(), attr);
                }
                attr.getValues().add(pt.getValue());
            }
            DynamicJobs dynJobs = null;
            try {
                dynJobs = (DynamicJobs) Class.forName(className).newInstance();
            } catch (InstantiationException | IllegalAccessException e) {
                throw new ProvisioningException("Could not create dynmaic job", e);
            }
            dynJobs.loadDynamicJobs(cfgMgr, this, cfgAttrs, jobKeys);
        }
        for (String groupName : scheduler.getJobGroupNames()) {
            this.deleteRemovedJobs(jobKeys, groupName);
        }
    } catch (SchedulerException e) {
        throw new ProvisioningException("Could not initialize scheduler", e);
    } catch (ClassNotFoundException e) {
        throw new ProvisioningException("Could not initialize scheduler", e);
    }
}
Also used : PrintStream(java.io.PrintStream) SchedulerException(org.quartz.SchedulerException) Attribute(com.tremolosecurity.saml.Attribute) LDAPAttribute(com.novell.ldap.LDAPAttribute) HashMap(java.util.HashMap) SchedulingType(com.tremolosecurity.config.xml.SchedulingType) IOException(java.io.IOException) Properties(java.util.Properties) ParamType(com.tremolosecurity.config.xml.ParamType) DynamicJobs(com.tremolosecurity.provisioning.jobs.DynamicJobs) JobType(com.tremolosecurity.config.xml.JobType) FileOutputStream(java.io.FileOutputStream) DynamicPortalUrlsType(com.tremolosecurity.config.xml.DynamicPortalUrlsType) StopScheduler(com.tremolosecurity.provisioning.scheduler.StopScheduler) HashSet(java.util.HashSet)

Example 9 with ParamType

use of com.tremolosecurity.config.xml.ParamType in project OpenUnison by TremoloSecurity.

the class SendMessageThread method addTarget.

private void addTarget(ConfigManager cfgMgr, TargetType targetCfg) throws ProvisioningException {
    HashMap<String, Attribute> cfg = new HashMap<String, Attribute>();
    Iterator<ParamType> params = targetCfg.getParams().getParam().iterator();
    while (params.hasNext()) {
        ParamType param = params.next();
        Attribute attr = cfg.get(param.getName());
        if (attr == null) {
            attr = new Attribute(param.getName());
            cfg.put(attr.getName(), attr);
        }
        attr.getValues().add(param.getValue());
    }
    UserStoreProvider provider = null;
    synchronized (this.userStores) {
        try {
            provider = (UserStoreProvider) Class.forName(targetCfg.getClassName()).newInstance();
        } catch (Exception e) {
            throw new ProvisioningException("Could not initialize target " + targetCfg.getName(), e);
        }
        MapIdentity mapper = new MapIdentity(targetCfg);
        this.userStores.put(targetCfg.getName(), new ProvisioningTargetImpl(targetCfg.getName(), provider, mapper));
        provider.init(cfg, cfgMgr, targetCfg.getName());
    }
}
Also used : Attribute(com.tremolosecurity.saml.Attribute) LDAPAttribute(com.novell.ldap.LDAPAttribute) HashMap(java.util.HashMap) MapIdentity(com.tremolosecurity.provisioning.mapping.MapIdentity) ParamType(com.tremolosecurity.config.xml.ParamType) InvocationTargetException(java.lang.reflect.InvocationTargetException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) LDAPException(com.novell.ldap.LDAPException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) SocketException(java.net.SocketException) SQLException(java.sql.SQLException) SchedulerException(org.quartz.SchedulerException) IOException(java.io.IOException) MessagingException(javax.mail.MessagingException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) JMSException(javax.jms.JMSException) JAXBException(javax.xml.bind.JAXBException) FileNotFoundException(java.io.FileNotFoundException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) BadPaddingException(javax.crypto.BadPaddingException)

Example 10 with ParamType

use of com.tremolosecurity.config.xml.ParamType in project OpenUnison by TremoloSecurity.

the class SendMessageThread method initializeHibernate.

private void initializeHibernate(ApprovalDBType adbt) {
    StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
    Configuration config = new Configuration();
    config.setProperty("hibernate.connection.driver_class", adbt.getDriver());
    config.setProperty("hibernate.connection.password", adbt.getPassword());
    config.setProperty("hibernate.connection.url", adbt.getUrl());
    config.setProperty("hibernate.connection.username", adbt.getUser());
    config.setProperty("hibernate.dialect", adbt.getHibernateDialect());
    if (adbt.isHibernateCreateSchema() == null || adbt.isHibernateCreateSchema()) {
        config.setProperty("hibernate.hbm2ddl.auto", "update");
    }
    config.setProperty("show_sql", "true");
    config.setProperty("hibernate.current_session_context_class", "thread");
    config.setProperty("hibernate.c3p0.max_size", Integer.toString(adbt.getMaxConns()));
    config.setProperty("hibernate.c3p0.maxIdleTimeExcessConnections", Integer.toString(adbt.getMaxIdleConns()));
    if (adbt.getValidationQuery() != null && !adbt.getValidationQuery().isEmpty()) {
        config.setProperty("hibernate.c3p0.testConnectionOnCheckout", "true");
    }
    config.setProperty("hibernate.c3p0.autoCommitOnClose", "true");
    if (adbt.getHibernateProperty() != null) {
        for (ParamType pt : adbt.getHibernateProperty()) {
            config.setProperty(pt.getName(), pt.getValue());
        }
    }
    // config.setProperty("hibernate.c3p0.debugUnreturnedConnectionStackTraces", "true");
    // config.setProperty("hibernate.c3p0.unreturnedConnectionTimeout", "30");
    String validationQuery = adbt.getValidationQuery();
    if (validationQuery == null) {
        validationQuery = "SELECT 1";
    }
    config.setProperty("hibernate.c3p0.preferredTestQuery", validationQuery);
    LoadedConfig lc = null;
    if (adbt.getHibernateConfig() == null || adbt.getHibernateConfig().trim().isEmpty()) {
        JaxbCfgHibernateConfiguration jaxbCfg = new JaxbCfgHibernateConfiguration();
        jaxbCfg.setSessionFactory(new JaxbCfgSessionFactory());
        JaxbCfgMappingReferenceType mrt = new JaxbCfgMappingReferenceType();
        mrt.setClazz(AllowedApprovers.class.getName());
        jaxbCfg.getSessionFactory().getMapping().add(mrt);
        mrt = new JaxbCfgMappingReferenceType();
        mrt.setClazz(Approvals.class.getName());
        jaxbCfg.getSessionFactory().getMapping().add(mrt);
        mrt = new JaxbCfgMappingReferenceType();
        mrt.setClazz(ApproverAttributes.class.getName());
        jaxbCfg.getSessionFactory().getMapping().add(mrt);
        mrt = new JaxbCfgMappingReferenceType();
        mrt.setClazz(Approvers.class.getName());
        jaxbCfg.getSessionFactory().getMapping().add(mrt);
        mrt = new JaxbCfgMappingReferenceType();
        mrt.setClazz(AuditLogs.class.getName());
        jaxbCfg.getSessionFactory().getMapping().add(mrt);
        mrt = new JaxbCfgMappingReferenceType();
        mrt.setClazz(AuditLogType.class.getName());
        jaxbCfg.getSessionFactory().getMapping().add(mrt);
        mrt = new JaxbCfgMappingReferenceType();
        mrt.setClazz(Escalation.class.getName());
        jaxbCfg.getSessionFactory().getMapping().add(mrt);
        mrt = new JaxbCfgMappingReferenceType();
        mrt.setClazz(Targets.class.getName());
        jaxbCfg.getSessionFactory().getMapping().add(mrt);
        mrt = new JaxbCfgMappingReferenceType();
        mrt.setClazz(UserAttributes.class.getName());
        jaxbCfg.getSessionFactory().getMapping().add(mrt);
        mrt = new JaxbCfgMappingReferenceType();
        mrt.setClazz(Users.class.getName());
        jaxbCfg.getSessionFactory().getMapping().add(mrt);
        mrt = new JaxbCfgMappingReferenceType();
        mrt.setClazz(WorkflowParameters.class.getName());
        jaxbCfg.getSessionFactory().getMapping().add(mrt);
        mrt = new JaxbCfgMappingReferenceType();
        mrt.setClazz(Workflows.class.getName());
        jaxbCfg.getSessionFactory().getMapping().add(mrt);
        lc = LoadedConfig.consume(jaxbCfg);
    } else {
        lc = LoadedConfig.baseline();
    }
    StandardServiceRegistry registry = builder.configure(lc).applySettings(config.getProperties()).build();
    try {
        sessionFactory = null;
        if (adbt.getHibernateConfig() == null || adbt.getHibernateConfig().trim().isEmpty()) {
            sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
        } else {
            sessionFactory = new MetadataSources(registry).addResource(adbt.getHibernateConfig()).buildMetadata().buildSessionFactory();
        }
        this.cfgMgr.addThread(new StopableThread() {

            @Override
            public void run() {
            // TODO Auto-generated method stub
            }

            @Override
            public void stop() {
                logger.info("Stopping hibernate");
                sessionFactory.close();
            }
        });
        org.hibernate.Session session = sessionFactory.openSession();
        this.auditLogTypes = new HashMap<String, AuditLogType>();
        List<AuditLogType> alts = session.createCriteria(AuditLogType.class).list();
        if (alts.size() == 0) {
            session.beginTransaction();
            AuditLogType alt = new AuditLogType();
            alt.setName("Add");
            session.save(alt);
            this.auditLogTypes.put("add", alt);
            alt = new AuditLogType();
            alt.setName("Delete");
            session.save(alt);
            this.auditLogTypes.put("delete", alt);
            alt = new AuditLogType();
            alt.setName("Replace");
            session.save(alt);
            this.auditLogTypes.put("replace", alt);
            session.getTransaction().commit();
        } else {
            for (AuditLogType alt : alts) {
                this.auditLogTypes.put(alt.getName().toLowerCase(), alt);
            }
        }
        session.close();
    } catch (Exception e) {
        e.printStackTrace();
        // The registry would be destroyed by the SessionFactory, but we had trouble building the SessionFactory
        // so destroy it manually.
        StandardServiceRegistryBuilder.destroy(registry);
    }
}
Also used : ApproverAttributes(com.tremolosecurity.provisioning.objects.ApproverAttributes) StandardServiceRegistryBuilder(org.hibernate.boot.registry.StandardServiceRegistryBuilder) Configuration(org.hibernate.cfg.Configuration) JaxbCfgHibernateConfiguration(org.hibernate.boot.jaxb.cfg.spi.JaxbCfgHibernateConfiguration) Escalation(com.tremolosecurity.provisioning.objects.Escalation) MetadataSources(org.hibernate.boot.MetadataSources) Approvals(com.tremolosecurity.provisioning.objects.Approvals) Users(com.tremolosecurity.provisioning.objects.Users) UserAttributes(com.tremolosecurity.provisioning.objects.UserAttributes) AllowedApprovers(com.tremolosecurity.provisioning.objects.AllowedApprovers) Approvers(com.tremolosecurity.provisioning.objects.Approvers) AllowedApprovers(com.tremolosecurity.provisioning.objects.AllowedApprovers) StopableThread(com.tremolosecurity.server.StopableThread) StandardServiceRegistry(org.hibernate.boot.registry.StandardServiceRegistry) WorkflowParameters(com.tremolosecurity.provisioning.objects.WorkflowParameters) AuditLogType(com.tremolosecurity.provisioning.objects.AuditLogType) DynamicWorkflows(com.tremolosecurity.provisioning.workflows.DynamicWorkflows) Workflows(com.tremolosecurity.provisioning.objects.Workflows) AuditLogs(com.tremolosecurity.provisioning.objects.AuditLogs) LoadedConfig(org.hibernate.boot.cfgxml.spi.LoadedConfig) DynamicTargets(com.tremolosecurity.provisioning.targets.DynamicTargets) Targets(com.tremolosecurity.provisioning.objects.Targets) JaxbCfgMappingReferenceType(org.hibernate.boot.jaxb.cfg.spi.JaxbCfgMappingReferenceType) ParamType(com.tremolosecurity.config.xml.ParamType) InvocationTargetException(java.lang.reflect.InvocationTargetException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) LDAPException(com.novell.ldap.LDAPException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) SocketException(java.net.SocketException) SQLException(java.sql.SQLException) SchedulerException(org.quartz.SchedulerException) IOException(java.io.IOException) MessagingException(javax.mail.MessagingException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) JMSException(javax.jms.JMSException) JAXBException(javax.xml.bind.JAXBException) FileNotFoundException(java.io.FileNotFoundException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) BadPaddingException(javax.crypto.BadPaddingException) JaxbCfgHibernateConfiguration(org.hibernate.boot.jaxb.cfg.spi.JaxbCfgHibernateConfiguration) JaxbCfgSessionFactory(org.hibernate.boot.jaxb.cfg.spi.JaxbCfgHibernateConfiguration.JaxbCfgSessionFactory)

Aggregations

ParamType (com.tremolosecurity.config.xml.ParamType)27 HashMap (java.util.HashMap)17 Attribute (com.tremolosecurity.saml.Attribute)14 IOException (java.io.IOException)12 LDAPAttribute (com.novell.ldap.LDAPAttribute)8 AuthMechParamType (com.tremolosecurity.config.xml.AuthMechParamType)7 DynamicPortalUrlsType (com.tremolosecurity.config.xml.DynamicPortalUrlsType)7 ProvisioningException (com.tremolosecurity.provisioning.core.ProvisioningException)7 FileNotFoundException (java.io.FileNotFoundException)7 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)7 JAXBException (javax.xml.bind.JAXBException)7 JSONObject (org.json.simple.JSONObject)7 JSONArray (org.json.simple.JSONArray)6 ApplicationType (com.tremolosecurity.config.xml.ApplicationType)5 TrustType (com.tremolosecurity.config.xml.TrustType)5 ServletException (javax.servlet.ServletException)5 LDAPException (com.novell.ldap.LDAPException)4 HttpCon (com.tremolosecurity.provisioning.util.HttpCon)4 KeyStoreException (java.security.KeyStoreException)4 UnrecoverableKeyException (java.security.UnrecoverableKeyException)4