Example usage for java.security Security addProvider

List of usage examples for java.security Security addProvider

Introduction

In this page you can find the example usage for java.security Security addProvider.

Prototype

public static int addProvider(Provider provider) 

Source Link

Document

Adds a provider to the next position available.

Usage

From source file:test.integ.be.fedict.commons.eid.client.JCATest.java

@Test
public void testGetEntry() throws Exception {
    Security.addProvider(new BeIDProvider());

    final KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);//from w  w  w.  ja va 2  s  .  c o m
    PrivateKeyEntry privateKeyEntry = (PrivateKeyEntry) keyStore.getEntry("Authentication", null);
    assertNotNull(privateKeyEntry);
    assertTrue(privateKeyEntry.getPrivateKey() instanceof BeIDPrivateKey);

    TrustedCertificateEntry caEntry = (TrustedCertificateEntry) keyStore.getEntry("CA", null);
    assertNotNull(caEntry);
    LOG.debug("CA entry: " + ((X509Certificate) caEntry.getTrustedCertificate()).getSubjectX500Principal());

    TrustedCertificateEntry rootEntry = (TrustedCertificateEntry) keyStore.getEntry("Root", null);
    assertNotNull(rootEntry);
    LOG.debug("root entry: " + ((X509Certificate) rootEntry.getTrustedCertificate()).getSubjectX500Principal());
}

From source file:test.integ.be.e_contract.mycarenet.cxf.ScenarioTest.java

/**
 * First we clean the eHealthBox. Then we publish to ourself. Next we
 * download this message.//  ww w  .  j  a  va2  s.  co  m
 * 
 * @throws Exception
 */
@Test
public void testScenarioInvokePlainText() throws Exception {
    // STS
    EHealthSTSClient client = new EHealthSTSClient("https://wwwacc.ehealth.fgov.be/sts_1_1/SecureTokenService");

    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);
    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");

    KeyStore eHealthKeyStore = KeyStore.getInstance("PKCS12");
    FileInputStream fileInputStream = new FileInputStream(this.config.getEHealthPKCS12Path());
    eHealthKeyStore.load(fileInputStream, this.config.getEHealthPKCS12Password().toCharArray());
    Enumeration<String> aliasesEnum = eHealthKeyStore.aliases();
    String alias = aliasesEnum.nextElement();
    X509Certificate eHealthCertificate = (X509Certificate) eHealthKeyStore.getCertificate(alias);
    PrivateKey eHealthPrivateKey = (PrivateKey) eHealthKeyStore.getKey(alias,
            this.config.getEHealthPKCS12Password().toCharArray());

    List<Attribute> attributes = new LinkedList<Attribute>();
    attributes.add(new Attribute("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));

    List<AttributeDesignator> attributeDesignators = new LinkedList<AttributeDesignator>();
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributeDesignators
            .add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:certified-namespace:ehealth",
            "urn:be:fgov:person:ssin:nurse:boolean"));

    Element assertion = client.requestAssertion(authnCertificate, authnPrivateKey, eHealthCertificate,
            eHealthPrivateKey, attributes, attributeDesignators);

    assertNotNull(assertion);

    String assertionString = client.toString(assertion);

    // eHealthBox: remove all messages.
    EHealthBoxConsultationClient eHealthBoxClient = new EHealthBoxConsultationClient(
            "https://services-acpt.ehealth.fgov.be/ehBoxConsultation/v3");
    eHealthBoxClient.setCredentials(eHealthPrivateKey, assertionString);

    GetMessageListResponseType messageList = eHealthBoxClient.getMessagesList();
    for (Message message : messageList.getMessage()) {
        String messageId = message.getMessageId();
        LOG.debug("message id: " + messageId);
        eHealthBoxClient.deleteMessage(messageId);
    }

    // eHealthBox: publish
    EHealthBoxPublicationClient publicationClient = new EHealthBoxPublicationClient(
            "https://services-acpt.ehealth.fgov.be/ehBoxPublication/v3");

    ObjectFactory objectFactory = new ObjectFactory();
    PublicationMessageType publicationMessage = objectFactory.createPublicationMessageType();
    String publicationId = UUID.randomUUID().toString().substring(1, 13);
    LOG.debug("publication id: " + publicationId);
    publicationMessage.setPublicationId(publicationId);

    DestinationContextType destinationContext = objectFactory.createDestinationContextType();
    publicationMessage.getDestinationContext().add(destinationContext);
    destinationContext.setQuality("NURSE");
    destinationContext.setType("INSS");
    destinationContext.setId(getUserIdentifier(authnCertificate));

    ContentContextType contentContext = objectFactory.createContentContextType();
    publicationMessage.setContentContext(contentContext);

    PublicationContentType publicationContent = objectFactory.createPublicationContentType();
    contentContext.setContent(publicationContent);
    PublicationDocumentType publicationDocument = objectFactory.createPublicationDocumentType();
    publicationContent.setDocument(publicationDocument);
    publicationDocument.setTitle("test");
    publicationDocument.setMimeType("text/plain");
    publicationDocument.setDownloadFileName("test.txt");
    byte[] data = "hello world".getBytes();
    publicationDocument.setEncryptableTextContent(data);
    publicationDocument.setEncryptableBinaryContent(null);
    MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
    byte[] digest = messageDigest.digest(data);
    publicationDocument.setDigest(Base64.encodeBase64String(digest));

    ContentSpecificationType contentSpecification = objectFactory.createContentSpecificationType();
    contentContext.setContentSpecification(contentSpecification);
    contentSpecification.setContentType("DOCUMENT");

    publicationClient.setCredentials(eHealthPrivateKey, assertionString);
    publicationClient.publish(publicationMessage);

    // give eHealthBox some time.
    Thread.sleep(1000 * 5);

    LOG.debug("GET MESSAGES LIST");
    messageList = eHealthBoxClient.getMessagesList();
    for (Message message : messageList.getMessage()) {
        String messageId = message.getMessageId();
        LOG.debug("message id: " + messageId);
        LOG.debug("GET FULL MESSAGE");
        String request = "<ehbox:GetFullMessageRequest xmlns:ehbox=\"urn:be:fgov:ehealth:ehbox:consultation:protocol:v3\">"
                + "<Source>INBOX</Source>" + "<MessageId>" + messageId + "</MessageId>"
                + "</ehbox:GetFullMessageRequest>";
        String response = eHealthBoxClient.invoke(request);
        LOG.debug("RESPONSE: " + response);
        JAXBContext consultationContext = JAXBContext
                .newInstance(be.e_contract.mycarenet.ehbox.jaxb.consultation.protocol.ObjectFactory.class);
        Unmarshaller consultationUnmarshaller = consultationContext.createUnmarshaller();
        Map<String, DataHandler> messageAttachments = eHealthBoxClient.getMessageAttachments();
        for (Map.Entry<String, DataHandler> messageAttachment : messageAttachments.entrySet()) {
            LOG.debug("message attachment id: " + messageAttachment.getKey());
            LOG.debug("message data handler: " + messageAttachment.getValue());
            DataHandler resultDataHandler = messageAttachment.getValue();
            DataSource resultDataSource = resultDataHandler.getDataSource();
            byte[] attachmentData = IOUtils.toByteArray(resultDataSource.getInputStream());
            LOG.debug("DataHandler.DataSource.getInputStream length: " + attachmentData.length);
        }
        consultationUnmarshaller.setAttachmentUnmarshaller(new SOAPAttachmentUnmarshaller(messageAttachments));
        JAXBElement<GetFullMessageResponseType> jaxbElement = (JAXBElement<GetFullMessageResponseType>) consultationUnmarshaller
                .unmarshal(new StringReader(response));
        GetFullMessageResponseType getFullMessageResponse = jaxbElement.getValue();
        ConsultationMessageType consultationMessage = getFullMessageResponse.getMessage();
        be.e_contract.mycarenet.ehbox.jaxb.consultation.protocol.ContentContextType consultationContentContext = consultationMessage
                .getContentContext();
        ConsultationContentType consultationContent = consultationContentContext.getContent();
        ConsultationDocumentType consultationDocument = consultationContent.getDocument();
        byte[] encryptableTextContent = consultationDocument.getEncryptableTextContent();
        if (null != encryptableTextContent) {
            LOG.debug("result EncryptableTextContent: " + encryptableTextContent.length);
        } else {
            LOG.debug("no EncryptableTextContent");
        }
        DataHandler resultDataHandler = consultationDocument.getEncryptableBinaryContent();
        if (null != resultDataHandler) {
            LOG.debug("result EncryptableBinaryContent");
            byte[] resultData = IOUtils.toByteArray(resultDataHandler.getInputStream());
            LOG.debug("result data size: " + resultData.length);
        }
        LOG.debug("DELETE MESSAGE");
        eHealthBoxClient.deleteMessage(messageId);
    }
}

From source file:test.integ.be.agiv.security.IPSTSTest.java

@Test
public void testRSTS_JAXWS_Client() throws Exception {
    ServletTester servletTester = new ServletTester();
    servletTester.addServlet(MyTestServlet.class, "/");

    Security.addProvider(new BouncyCastleProvider());

    KeyPair keyPair = generateKeyPair();
    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusMonths(1);
    X509Certificate certificate = generateSelfSignedCertificate(keyPair, "CN=localhost", notBefore, notAfter);
    File tmpP12File = File.createTempFile("ssl-", ".p12");
    LOG.debug("p12 file: " + tmpP12File.getAbsolutePath());
    persistKey(tmpP12File, keyPair.getPrivate(), certificate, "secret".toCharArray(), "secret".toCharArray());

    SslSocketConnector sslSocketConnector = new SslSocketConnector();
    sslSocketConnector.setKeystore(tmpP12File.getAbsolutePath());
    sslSocketConnector.setTruststore(tmpP12File.getAbsolutePath());
    sslSocketConnector.setTruststoreType("pkcs12");
    sslSocketConnector.setKeystoreType("pkcs12");
    sslSocketConnector.setPassword("secret");
    sslSocketConnector.setKeyPassword("secret");
    sslSocketConnector.setTrustPassword("secret");
    sslSocketConnector.setMaxIdleTime(30000);
    int sslPort = getFreePort();
    sslSocketConnector.setPort(sslPort);

    servletTester.getContext().getServer().addConnector(sslSocketConnector);
    String sslLocation = "https://localhost:" + sslPort + "/";

    servletTester.start();/*from  w  ww .  j a va 2  s.com*/
    String location = servletTester.createSocketConnector(true);

    SSLContext sslContext = SSLContext.getInstance("TLS");
    TrustManager trustManager = new TestTrustManager(certificate);
    sslContext.init(null, new TrustManager[] { trustManager }, null);
    SSLContext.setDefault(sslContext);

    try {
        LOG.debug("running R-STS test...");
        RSTSClient client = new RSTSClient(sslLocation);
        SecurityToken inputSecurityToken = new SecurityToken();
        byte[] key = new byte[256 / 8];
        SecureRandom random = new SecureRandom();
        random.nextBytes(key);
        inputSecurityToken.setKey(key);
        inputSecurityToken.setAttachedReference("_" + UUID.randomUUID().toString());
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.newDocument();
        Element tokenElement = document.createElement("Token");
        tokenElement.setTextContent("hello world");
        inputSecurityToken.setToken(tokenElement);

        client.getSecurityToken(inputSecurityToken, "https://auth.beta.agiv.be/ClaimsAwareService/Service.svc");
    } finally {
        servletTester.stop();
    }
}

From source file:test.integ.be.e_contract.mycarenet.ehbox.EHealthBoxClientTest.java

/**
 * Not supported according to Hannes De Clercq from eHealth.
 * //from w w  w .  j  a  va 2  s  .  c o  m
 * @throws Exception
 */
@Test
public void testGetBoxInfoSelfSigned() throws Exception {
    // STS
    EHealthSTSClient client = new EHealthSTSClient("https://wwwacc.ehealth.fgov.be/sts_1_1/SecureTokenService");

    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);
    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");

    SessionKey sessionKey = new SessionKey(2048);
    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusHours(24);
    sessionKey.setValidity(notBefore.toDate(), notAfter.toDate());
    X509Certificate eHealthCertificate = sessionKey.getCertificate();
    PrivateKey eHealthPrivateKey = sessionKey.getPrivate();

    List<Attribute> attributes = new LinkedList<Attribute>();
    attributes.add(new Attribute("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));

    List<AttributeDesignator> attributeDesignators = new LinkedList<AttributeDesignator>();
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributeDesignators
            .add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:certified-namespace:ehealth",
            "urn:be:fgov:person:ssin:nurse:boolean"));

    Element assertionElement = client.requestAssertion(authnCertificate, authnPrivateKey, eHealthCertificate,
            eHealthPrivateKey, attributes, attributeDesignators);

    assertNotNull(assertionElement);

    String assertionString = client.toString(assertionElement);

    // eHealthBox
    EHealthBoxConsultationClient eHealthBoxClient = new EHealthBoxConsultationClient(
            "https://services-acpt.ehealth.fgov.be/ehBoxConsultation/v3");
    eHealthBoxClient.setCredentials(eHealthPrivateKey, assertionString);
    eHealthBoxClient.getBoxInfo();
}

From source file:piuk.blockchain.android.WalletApplication.java

@Override
public void onCreate() {
    super.onCreate();

    PRNGFixes.apply();// w ww . j  a va  2 s  .co m

    //      ErrorReporter.getInstance().init(this);

    //blockchainServiceIntent = new Intent(this, BlockchainServiceImpl.class);
    websocketServiceIntent = new Intent(this, WebsocketService.class);

    System.setProperty("device_name", "android");

    try {
        PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);

        System.setProperty("device_version", pInfo.versionName);
    } catch (NameNotFoundException e1) {
        e1.printStackTrace();
    }

    try {
        // Need to save session cookie for kaptcha
        CookieHandler.setDefault(new CookieManager());

        Security.addProvider(new org.spongycastle.jce.provider.BouncyCastleProvider());
    } catch (Throwable e) {
        e.printStackTrace();
    }

    //loadBitcoinJWallet();

    connect();
}

From source file:test.unit.be.fedict.eid.idp.protocol.openid.OpenIDSSLProtocolServiceTest.java

@Test
public void testOpenIDSpike() throws Exception {
    LOG.debug("OpenID spike");

    // setup/*from  www  . j  av a2 s  .c  om*/
    this.servletTester = new ServletTester();
    this.servletTester.addServlet(OpenIDConsumerServlet.class, "/consumer/*");
    this.servletTester.addServlet(OpenIDIdentityServlet.class, "/identity/*");
    this.servletTester.addServlet(OpenIDProducerServlet.class, "/producer");

    Security.addProvider(new BouncyCastleProvider());

    KeyPair keyPair = generateKeyPair();
    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusMonths(1);
    X509Certificate certificate = generateSelfSignedCertificate(keyPair, "CN=localhost", notBefore, notAfter);
    File tmpP12File = File.createTempFile("ssl-", ".p12");
    tmpP12File.deleteOnExit();
    LOG.debug("p12 file: " + tmpP12File.getAbsolutePath());
    persistKey(tmpP12File, keyPair.getPrivate(), certificate, "secret".toCharArray(), "secret".toCharArray());

    SslSocketConnector sslSocketConnector = new SslSocketConnector();
    sslSocketConnector.setKeystore(tmpP12File.getAbsolutePath());
    sslSocketConnector.setTruststore(tmpP12File.getAbsolutePath());
    sslSocketConnector.setTruststoreType("pkcs12");
    sslSocketConnector.setKeystoreType("pkcs12");
    sslSocketConnector.setPassword("secret");
    sslSocketConnector.setKeyPassword("secret");
    sslSocketConnector.setTrustPassword("secret");
    sslSocketConnector.setMaxIdleTime(30000);
    int sslPort = getFreePort();
    sslSocketConnector.setPort(sslPort);
    this.servletTester.getContext().getServer().addConnector(sslSocketConnector);
    sslLocation = "https://localhost:" + sslPort;

    this.servletTester.start();
    location = this.servletTester.createSocketConnector(true);
    LOG.debug("location: " + location);

    HttpClient httpClient = new HttpClient();
    httpClient.getParams().setParameter("http.protocol.allow-circular-redirects", Boolean.TRUE);
    // GetMethod getMethod = new GetMethod(location + "/consumer");

    /*
     * Next is for ConsumerManager to be able to trust the OP.
     */
    // MySSLSocketFactory mySSLSocketFactory = new MySSLSocketFactory(
    // certificate);
    // HttpsURLConnection.setDefaultSSLSocketFactory(mySSLSocketFactory);

    ProtocolSocketFactory protocolSocketFactory = new MyProtocolSocketFactory(certificate);
    Protocol myProtocol = new Protocol("https", protocolSocketFactory, sslPort);
    Protocol.registerProtocol("https", myProtocol);
    GetMethod getMethod = new GetMethod(sslLocation + "/consumer");

    // operate
    int statusCode = httpClient.executeMethod(getMethod);

    // verify
    LOG.debug("status code: " + statusCode);
    assertEquals(HttpServletResponse.SC_OK, statusCode);

    SessionHandler sessionHandler = this.servletTester.getContext().getSessionHandler();
    SessionManager sessionManager = sessionHandler.getSessionManager();
    HashSessionManager hashSessionManager = (HashSessionManager) sessionManager;
    LOG.debug("# sessions: " + hashSessionManager.getSessions());
    assertEquals(1, hashSessionManager.getSessions());
    Map<String, HttpSession> sessionMap = hashSessionManager.getSessionMap();
    LOG.debug("session map: " + sessionMap);
    Entry<String, HttpSession> sessionEntry = sessionMap.entrySet().iterator().next();
    HttpSession httpSession = sessionEntry.getValue();
    String userId = (String) httpSession.getAttribute(OpenIDConsumerServlet.USER_ID_SESSION_ATTRIBUTE);
    LOG.debug("userId session attribute: " + userId);
    assertEquals(sslLocation + "/identity/idp/123456789", userId);
    String firstName = (String) httpSession.getAttribute(OpenIDConsumerServlet.FIRST_NAME_SESSION_ATTRIBUTE);
    assertEquals("sample-first-name", firstName);
}

From source file:com.twinsoft.convertigo.engine.Engine.java

public static synchronized void start() throws EngineException {
    if (Engine.theApp == null) {
        System.out.println("Starting Convertigo Enterprise Mobility Server");

        // If the engine has been stopped by the admin, we must reload
        // properties
        EnginePropertiesManager.loadProperties();

        boolean bProjectsDataCompatibilityMode = Boolean.parseBoolean(
                EnginePropertiesManager.getProperty(PropertyName.PROJECTS_DATA_COMPATIBILITY_MODE));

        if (bProjectsDataCompatibilityMode) {
            System.out.println("Projects data compatibility mode required");
            try {
                Engine.PROJECTS_PATH = new File(Engine.WEBAPP_PATH + "/projects").getCanonicalPath();
                File projectsDir = new File(Engine.PROJECTS_PATH);
                projectsDir.mkdir();//www.jav  a  2 s. com
            } catch (IOException e) {
                throw new EngineException("Unable to update projects path for compatibility mode", e);
            }
        }

        isStarted = false;
        isStartFailed = false;
        RequestableObject.nbCurrentWorkerThreads = 0;

        Engine.startStopDate = System.currentTimeMillis();

        System.out.println("Creating/updating loggers");

        String logFile = EnginePropertiesManager.getProperty(PropertyName.LOG4J_APPENDER_CEMSAPPENDER_FILE);
        System.out.println("Log file: " + logFile);

        // Main loggers
        Engine.logConvertigo = Logger.getLogger("cems");
        Engine.logEngine = Logger.getLogger("cems.Engine");
        Engine.logAdmin = Logger.getLogger("cems.Admin");
        Engine.logBeans = Logger.getLogger("cems.Beans");
        Engine.logBillers = Logger.getLogger("cems.Billers");
        Engine.logEmulators = Logger.getLogger("cems.Emulators");
        Engine.logContext = Logger.getLogger("cems.Context");
        Engine.logUser = Logger.getLogger("cems.Context.User");
        Engine.logUsageMonitor = Logger.getLogger("cems.UsageMonitor");
        Engine.logStatistics = Logger.getLogger("cems.Statistics");
        Engine.logScheduler = Logger.getLogger("cems.Scheduler");
        Engine.logSiteClipper = Logger.getLogger("cems.SiteClipper");
        /** #3437 : Disabled ExternalBrowser feature because it's not terminated
        Engine.logExternalBrowser = Logger.getLogger("cems.ExternalBrowser");
        */
        Engine.logAudit = Logger.getLogger("cems.Context.Audit");

        // Managers
        Engine.logContextManager = Logger.getLogger("cems.ContextManager");
        Engine.logCacheManager = Logger.getLogger("cems.CacheManager");
        Engine.logTracePlayerManager = Logger.getLogger("cems.TracePlayerManager");
        Engine.logJobManager = Logger.getLogger("cems.JobManager");
        Engine.logCertificateManager = Logger.getLogger("cems.CertificateManager");
        Engine.logDatabaseObjectManager = Logger.getLogger("cems.DatabaseObjectManager");
        Engine.logProxyManager = Logger.getLogger("cems.ProxyManager");
        Engine.logDevices = Logger.getLogger("cems.Devices");
        Engine.logCouchDbManager = Logger.getLogger("cems.CouchDbManager");
        Engine.logSecurityTokenManager = Logger.getLogger("cems.SecurityTokenManager");

        // Logger for compatibility issues
        Engine.log = new LogWrapper(Engine.logConvertigo);
        LogWrapper.initWrapper(Engine.logEmulators);

        try {
            Engine.logEngine.info("===========================================================");
            Engine.logEngine.info("Web app home: " + Engine.WEBAPP_PATH);
            Engine.logEngine.info("User workspace: " + Engine.USER_WORKSPACE_PATH);
            Engine.logEngine.info("Configuration path: " + Engine.CONFIGURATION_PATH);

            Engine.logEngine.info("Projects path: " + Engine.PROJECTS_PATH);
            if (bProjectsDataCompatibilityMode) {
                Engine.logEngine.warn("Projects data compatibility mode required");
            }

            Engine.logEngine.info("Log: " + Engine.LOG_PATH);

            if (cloud_customer_name != null) {
                Engine.logEngine.info("Cloud customer: " + cloud_customer_name);
            }

            // Check environment and native dependencies
            if (!isStudioMode()) {
                StartupDiagnostics.run();
            }

            // Initializing the engine
            Engine.theApp = new Engine();

            CachedIntrospector.prefetchDatabaseObjectsAsync();

            try {
                Engine.theApp.usageMonitor = new UsageMonitor();
                Engine.theApp.usageMonitor.init();

                Thread vulture = new Thread(Engine.theApp.usageMonitor);
                vulture.setName("UsageMonitor");
                vulture.setDaemon(true);
                vulture.start();
            } catch (Exception e) {
                Engine.logEngine.error("Unable to launch the usage monitor.", e);
            }

            Engine.theApp.eventManager = new EventManager();
            Engine.theApp.eventManager.init();

            Engine.theApp.databaseObjectsManager = new DatabaseObjectsManager();
            Engine.theApp.databaseObjectsManager.init();

            Engine.theApp.sqlConnectionManager = new JdbcConnectionManager();
            Engine.theApp.sqlConnectionManager.init();

            Engine.theApp.filePropertyManager = new FilePropertyManager();
            Engine.theApp.filePropertyManager.init();

            try {
                Engine.theApp.proxyManager = new ProxyManager();
                Engine.theApp.proxyManager.init();
            } catch (Exception e) {
                Engine.logEngine.error("Unable to launch the proxy manager.", e);
            }

            try {
                Engine.theApp.billingManager = new BillingManager();
                Engine.theApp.billingManager.init();
            } catch (Exception e) {
                Engine.logEngine.error("Unable to launch the billing manager.", e);
            }

            // Initialization of the trace player
            try {
                Engine.theApp.tracePlayerManager = new TracePlayerManager();
                Engine.theApp.tracePlayerManager.init();
            } catch (Exception e) {
                Engine.logEngine.error("Unable to run the trace player.", e);
            }

            try {
                Engine.theApp.minificationManager = new MinificationManager();
                Engine.theApp.minificationManager.init();
            } catch (Exception e) {
                Engine.logEngine.error("Unable to run the minification manager.", e);
            }

            try {
                Engine.theApp.couchDbManager = new CouchDbManager();
                Engine.theApp.couchDbManager.init();
            } catch (Exception e) {
                Engine.logEngine.error("Unable to run the couchDbProxy manager.", e);
            }

            try {
                Engine.theApp.pluginsManager = new PluginsManager();
                Engine.theApp.pluginsManager.init();
            } catch (Exception e) {
                Engine.logEngine.error("Unable to run the plugins manager.", e);
            }

            try {
                Engine.theApp.restApiManager = RestApiManager.getInstance();
                Engine.theApp.restApiManager.init();
            } catch (Exception e) {
                Engine.logEngine.error("Unable to run the rest api manager.", e);
            }

            Engine.logEngine.info("Current working directory is '" + System.getProperty("user.dir") + "'.");

            // Creating the Carioca Authentication objects
            Engine.logEngine.debug("Creating the Carioca Authentication objects");
            String cariocaUserName = EnginePropertiesManager
                    .getProperty(PropertyName.CARIOCA_DEFAULT_USER_NAME);
            String cariocaPassword = EnginePropertiesManager
                    .getProperty(PropertyName.CARIOCA_DEFAULT_USER_PASSWORD);
            Engine.theApp.authentications = new HashMap<String, Authentication>();

            // Initialization of the default TAS properties
            try {
                KeyManager.log = new LogWrapper(Engine.logEngine);
                Authentication auth = Engine.theApp.getAuthenticationObject("", null);
                auth.login(cariocaUserName, cariocaPassword);
            } catch (Exception e) {
                Engine.logEngine.error("The authentication to Carioca has failed (user name: \""
                        + cariocaUserName + "\", user password: \"" + cariocaPassword + "\").", e);
            }

            // TODO : retrieve SOA flag from KeyManager
            isSOA = true;

            // Creation of the session manager
            Engine.theApp.sessionManager = new SessionManager();
            Engine.theApp.sessionManager.setLog(new LogWrapper(Engine.logEngine));
            Engine.theApp.sessionManager.setProductCode(SessionManager.CONVERTIGO);

            String s = EnginePropertiesManager.getProperty(PropertyName.CONNECTORS_MONITORING);
            Engine.theApp.setMonitored(s.equalsIgnoreCase("true"));

            // Create Projects directory if needed
            File projectsDirFile = new File(Engine.PROJECTS_PATH);
            try {
                if (!projectsDirFile.exists())
                    projectsDirFile.mkdirs();
            } catch (Exception e) {
                Engine.logEngine.error("An error occured while creating projects directory.", e);
            }

            // Starts projects migration process
            MigrationManager.performProjectsMigration();

            // Security providers registration
            try {
                File dir = new File(Engine.CERTIFICATES_PATH);
                String[] files = dir.list(new FilenameFilter() {
                    public boolean accept(File dir, String name) {
                        return name.endsWith((".pkcs11"));
                    }
                });

                if (files != null && files.length > 0) {
                    Engine.logEngine.info("Registering security providers...");
                    try {
                        Class<?> sunPKCS11Class = Class.forName("sun.security.pkcs11.SunPKCS11");
                        String file;

                        for (int i = 0; i < files.length; i++) {
                            file = Engine.CERTIFICATES_PATH + "/" + files[i];
                            try {
                                Constructor<?> constructor = sunPKCS11Class
                                        .getConstructor(new Class[] { String.class });
                                Provider provider = (Provider) constructor.newInstance(new Object[] { file });
                                Security.addProvider(provider);
                                Engine.logEngine.info("Provider '" + provider.getName()
                                        + "' has been successfully registered.");
                            } catch (Exception e) {
                                Engine.logEngine.error("Unable to register security provider from file: " + file
                                        + " . Please check that the implementation library is in the Java lib path.");
                            }
                        }
                    } catch (ClassNotFoundException e) {
                        Engine.logEngine.error(
                                "Unable to find sun.security.pkcs11.SunPKCS11 class! PKCS#11 authentication won't be available. You must use JVM 1.5 or higher in order to use PKCS#11 authentication.");
                    }
                }

                Provider[] providers = Security.getProviders();
                String sProviders = "";
                for (int i = 0; i < providers.length; i++) {
                    sProviders += providers[i].getName() + ", ";
                }
                Engine.logEngine.debug("Registered providers: " + sProviders);
            } catch (Exception e) {
                Engine.logEngine.error("Unable to register security providers.", e);
            }

            // Launch the cache manager
            try {
                String cacheManagerClassName = EnginePropertiesManager
                        .getProperty(PropertyName.CACHE_MANAGER_CLASS);
                Engine.logEngine.debug("Cache manager class: " + cacheManagerClassName);
                Engine.theApp.cacheManager = (CacheManager) Class.forName(cacheManagerClassName).newInstance();
                Engine.theApp.cacheManager.init();

                Thread vulture = new Thread(Engine.theApp.cacheManager);
                Engine.theApp.cacheManager.executionThread = vulture;
                vulture.setName("CacheManager");
                vulture.setDaemon(true);
                vulture.start();
            } catch (Exception e) {
                Engine.logEngine.error("Unable to launch the cache manager.", e);
            }

            // Launch the thread manager
            try {
                Engine.theApp.threadManager = new ThreadManager();
                Engine.theApp.threadManager.init();

                Thread vulture = new Thread(Engine.theApp.threadManager);
                Engine.theApp.threadManager.executionThread = vulture;
                vulture.setName("ThreadManager");
                vulture.setDaemon(true);
                vulture.start();
            } catch (Exception e) {
                Engine.theApp.threadManager = null;
                Engine.logEngine.error("Unable to launch the thread manager.", e);
            }

            // Launch the context manager
            try {
                Engine.theApp.contextManager = new ContextManager();
                Engine.theApp.contextManager.init();

                Thread vulture = new Thread(Engine.theApp.contextManager);
                Engine.theApp.contextManager.executionThread = vulture;
                vulture.setName("ContextManager");
                vulture.setDaemon(true);
                vulture.start();
            } catch (Exception e) {
                Engine.theApp.contextManager = null;
                Engine.logEngine.error("Unable to launch the context manager.", e);
            }

            // Launch the security token manager
            Engine.theApp.securityTokenManager = new SecurityTokenManager();
            Engine.theApp.securityTokenManager.init();

            // Initialize the HttpClient
            try {
                Engine.logEngine.debug("HttpClient initializing...");

                Engine.theApp.httpClient = HttpUtils.makeHttpClient3(true);
                Engine.theApp.httpClient4 = HttpUtils.makeHttpClient4(true);

                Engine.logEngine.debug("HttpClient initialized!");
            } catch (Exception e) {
                Engine.logEngine.error("Unable to initialize the HttpClient.", e);
            }

            // Initialization of the schedule manager
            Engine.theApp.schedulerManager = new SchedulerManager(true);

            // Initialization of the RSA manager
            Engine.theApp.rsaManager = new RsaManager();
            Engine.theApp.rsaManager.init();

            // Initialization of the External Browser manager
            /** #3437 : Disabled ExternalBrowser feature because it's not terminated
            Engine.theApp.externalBrowserManager = new ExternalBrowserManager();
            Engine.theApp.externalBrowserManager.init();
            */

            // Initialization of the Schema manager
            Engine.theApp.schemaManager = new SchemaManager();
            Engine.theApp.schemaManager.init();

            // XUL initialization
            String xulrunner_url = System.getProperty("org.eclipse.swt.browser.XULRunnerPath");
            if (xulrunner_url == null || xulrunner_url.equals("")) {
                xulrunner_url = EnginePropertiesManager.getProperty(PropertyName.XULRUNNER_URL);
            }

            File f = new File(xulrunner_url);
            if (f.exists()) {
                xulrunner_url = f.getAbsolutePath();
                Engine.logEngine
                        .debug("initMozillaSWT: org.eclipse.swt.browser.XULRunnerPath=" + xulrunner_url);
                System.setProperty("org.eclipse.swt.browser.XULRunnerPath", xulrunner_url);
            } else {
                Engine.logEngine.error("Error in initMozillaSWT: " + xulrunner_url
                        + " doesn't exist, fix it with xulrunner.url");
            }

            if (Engine.isEngineMode() && Engine.isLinux()
                    && "true".equals(EnginePropertiesManager.getProperty(PropertyName.LINUX_LAUNCH_XVNC))) {

                Engine.logEngine
                        .debug("initMozillaSWT: org.eclipse.swt.browser.XULRunnerPath=" + xulrunner_url);
                final String display = System.getenv("DISPLAY");
                if (display != null) {
                    try {
                        String port = System.getProperty("xvnc.port");
                        if (port == null) {
                            port = "" + (Integer.parseInt(display.replaceAll(".*:(\\d*)", "$1")) + 5900);
                            System.setProperty("xvnc.port", port);
                        }
                        Engine.logEngine.debug("Xvnc should listen on " + port + " port");
                    } catch (Exception e) {
                    }
                    try {
                        File vncDir = new File(Engine.WEBAPP_PATH + "/WEB-INF/xvnc");
                        File Xvnc = new File(vncDir, "/Xvnc");
                        File fonts = new File(vncDir, "/fonts");
                        File wm = new File(vncDir, "/matchbox-window-manager");
                        if (vncDir.exists() && Xvnc.exists() && fonts.exists() && wm.exists()) {
                            for (File file : GenericUtils.<File>asList(Xvnc, wm)) {
                                new ProcessBuilder("/bin/chmod", "u+x", file.getAbsolutePath()).start()
                                        .waitFor();
                            }
                            String depth = EnginePropertiesManager.getProperty(PropertyName.LINUX_XVNC_DEPTH);
                            String geometry = EnginePropertiesManager
                                    .getProperty(PropertyName.LINUX_XVNC_GEOMETRY);
                            Engine.logEngine
                                    .debug("Xvnc will use depth " + depth + " and geometry " + geometry);
                            Process pr_xvnc = new ProcessBuilder(Xvnc.getAbsolutePath(), display, "-fp",
                                    fonts.getAbsolutePath(), "-depth", depth, "-geometry", geometry).start();
                            Thread.sleep(500);
                            try {
                                int exit = pr_xvnc.exitValue();
                                InputStream err = pr_xvnc.getErrorStream();
                                byte[] buf = new byte[err.available()];
                                err.read(buf);
                                Engine.logEngine.debug("Xvnc failed to run with exit code " + exit
                                        + " and this error : <<" + new String(buf, "UTF-8") + ">>");
                            } catch (Exception e) {
                                new ProcessBuilder(wm.getAbsolutePath()).start();
                                Engine.logEngine.debug("Xvnc successfully started !");
                            }
                        } else {
                            Engine.logEngine.info(
                                    vncDir.getAbsolutePath() + " not found or incomplet, cannot start Xvnc");
                        }
                    } catch (Exception e) {
                        Engine.logEngine.info("failed to launch Xvnc (maybe already launched", e);
                    }
                } else
                    Engine.logEngine
                            .warn("Trying to start Xvnc on Linux without DISPLAY environment variable !");
            }

            // SAP provider registration
            try {
                SapJcoDestinationDataProvider.init();
                Engine.logEngine.debug("SAP destination provider successfully registered");
            } catch (Throwable e) {
                Engine.logEngine.error("Error while registering SAP destination provider", e);
            }

            isStarted = true;

            Engine.logEngine.info("Convertigo engine started");
        } catch (Throwable e) {
            isStartFailed = true;
            Engine.logEngine.error("Unable to successfully start the engine.", e);
        }
    } else {
        Engine.logEngine.info("Convertigo engine already started");
    }
}

From source file:org.wildfly.security.tool.FileSystemRealmCommand.java

/**
 * Handles creating the Elytron filesystem-realm from the input arrays
 *
 * @throws Exception Exception to be handled by Elytron Tool
 *///  w  w w . j  a  v a  2  s  .  c o m
private void createFileSystemRealm() throws Exception {
    Security.addProvider(new WildFlyElytronProvider());
    for (int i = 0; i < descriptors.size(); i++) {
        Descriptor descriptor = descriptors.get(i);
        if (descriptor.getUsersFile() == null || descriptor.getRolesFile() == null
                || descriptor.getOutputLocation() == null) {
            continue;
        }
        List<String> usersList = parseInputFile(descriptor, USERS_FILE_PARAM, i + 1);
        List<String> rolesList = parseInputFile(descriptor, ROLES_FILE_PARAM, i + 1);
        if (usersList.isEmpty() || rolesList.isEmpty()) {
            descriptor.reset();
            continue;
        }
        FileSystemSecurityRealm newFileSystemRealm = new FileSystemSecurityRealm(
                Paths.get(descriptor.getOutputLocation()));
        Map<String, ArrayList<String>> usersMap = new HashMap<>();
        for (String userMapping : usersList) {
            String[] userStringSplit = userMapping.split("=");
            String user = userStringSplit[0].trim();
            String password;
            if (userStringSplit.length == 1) {
                String message = String.format("No password was found for user %s", user);
                warningHandler(message);
                password = null;
            } else {
                password = userStringSplit[1].trim();
            }
            ArrayList<String> userAttributes = new ArrayList<>();
            userAttributes.add(password);
            usersMap.put(user, userAttributes);
        }
        for (String rolesMapping : rolesList) {
            String[] rolesStringSplit = rolesMapping.split("=");
            String user = rolesStringSplit[0].trim();
            String[] roles = new String[] {};
            if (rolesStringSplit.length < 2) {
                String message = String.format("No roles were found for user %s", user);
                warningHandler(message);
            } else {
                roles = rolesStringSplit[1].trim().split(",");
            }
            ArrayList<String> userAttributes = usersMap.get(user);
            if (userAttributes == null) {
                String message = String.format("Roles were found for user %1$s, but user %1$s was not defined.",
                        user);
                warningHandler(message);
                ArrayList<String> attributesWithEmptyPassword = new ArrayList<>();
                attributesWithEmptyPassword.add(null);
                attributesWithEmptyPassword.addAll(new ArrayList<>(Arrays.asList(roles)));
                userAttributes = attributesWithEmptyPassword;
                usersMap.put(user, userAttributes);
            } else {
                userAttributes.addAll(Arrays.asList(roles));
                usersMap.replace(user, userAttributes);
            }
            if (summaryMode) {
                summaryString.append(
                        String.format("Added roles: %s for user %s.", ArrayUtils.toString(roles), user));
                summaryString.append(System.getProperty("line.separator"));
            }
        }
        usersMap.forEach((key, value) -> {
            ModifiableRealmIdentity identity = newFileSystemRealm
                    .getRealmIdentityForUpdate(new NamePrincipal(key));
            try {
                identity.create();
                MapAttributes attributes = new MapAttributes();
                attributes.addAll("roles", value.subList(1, value.size()));
                identity.setAttributes(attributes);
                String password = value.get(0);
                if (password != null) {
                    byte[] hashed = ByteIterator.ofBytes(password.getBytes(StandardCharsets.UTF_8))
                            .asUtf8String().hexDecode().drain();
                    PasswordSpec passwordSpec = new DigestPasswordSpec(key, descriptor.getRealmName(), hashed);
                    PasswordFactory factory = PasswordFactory.getInstance(DigestPassword.ALGORITHM_DIGEST_MD5);
                    DigestPassword digestPassword = (DigestPassword) factory.generatePassword(passwordSpec);
                    identity.setCredentials(Collections.singleton(new PasswordCredential(digestPassword)));
                }
                identity.dispose();
            } catch (NullPointerException e) {
                warningHandler(String.format("Could not read realm name from the users file"));
            } catch (Exception e) {
                warningHandler(String.format("Could not create realm for user %s due to error: ", key)
                        + e.getMessage());
            }
        });
    }
}

From source file:org.eclipse.smarthome.binding.digitalstrom.internal.lib.serverconnection.impl.HttpTransportImpl.java

private SSLSocketFactory generateSSLContextWhichAcceptAllSSLCertificats() {
    Security.addProvider(Security.getProvider("SunJCE"));
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        @Override//w w w  .j  a v a2 s.c  o m
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {

        }

        @Override
        public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {

        }
    } };

    try {
        SSLContext sslContext = SSLContext.getInstance("SSL");

        sslContext.init(null, trustAllCerts, new SecureRandom());

        return sslContext.getSocketFactory();
    } catch (KeyManagementException e) {
        logger.error("A KeyManagementException occurred", e);
    } catch (NoSuchAlgorithmException e) {
        logger.error("A NoSuchAlgorithmException occurred", e);
    }
    return null;
}

From source file:com.netscape.cmscore.apps.CMSEngine.java

/**
 * initialize all static, dynamic and final static subsystems.
 *
 * @param owner null/*from  w  ww. j a  v  a  2  s .  co  m*/
 * @param config main config store.
 * @exception EBaseException if any error occur in subsystems during
 *                initialization.
 */
public void init(ISubsystem owner, IConfigStore config) throws EBaseException {
    mOwner = owner;
    mConfig = config;
    int state = mConfig.getInteger("cs.state");

    serverStatus = "starting";

    instanceDir = config.getString("instanceRoot");
    instanceId = config.getString("instanceId");

    if (state == 1) {
        // configuration is complete, initialize password store
        try {
            initializePasswordStore(config);
        } catch (IOException e) {
            logger.error("Unable to initialize password store: " + e.getMessage(), e);
            throw new EBaseException("Exception while initializing password store: " + e);
        }
    }

    // my default is 1 day
    String flush_timeout = config.getString("securitydomain.flushinterval", "86400000");
    String secdomain_source = config.getString("securitydomain.source", "memory");
    String secdomain_check_interval = config.getString("securitydomain.checkinterval", "5000");

    String tsClass = config.getString("timeSourceClass", null);

    if (tsClass != null) {
        try {
            mTimeSource = (ITimeSource) Class.forName(tsClass).newInstance();
        } catch (Exception e) {
            // nothing to do
        }
    }
    if (mTimeSource == null) {
        // if time source is not set, set it to simple time source
        mTimeSource = new SimpleTimeSource();
    }

    Security.addProvider(new netscape.security.provider.CMS());

    loadSubsystems();
    initSubsystems();

    logger.debug("Java version: " + System.getProperty("java.version"));
    java.security.Provider ps[] = java.security.Security.getProviders();

    if (ps == null || ps.length <= 0) {
        logger.debug("CMSEngine: Java Security Provider NONE");
    } else {
        for (int x = 0; x < ps.length; x++) {
            logger.debug("CMSEngine: Java Security Provider " + x + " class=" + ps[x]);
        }
    }
    parseServerXML();
    fixProxyPorts();

    String sd = mConfig.getString("securitydomain.select", "");

    if ((state == 1) && (!sd.equals("existing"))) {
        // check session domain table only if this is a
        // configured security domain host

        if (secdomain_source.equals("ldap")) {
            mSecurityDomainSessionTable = new LDAPSecurityDomainSessionTable(
                    (new Long(flush_timeout)).longValue());
        } else {
            mSecurityDomainSessionTable = new SecurityDomainSessionTable((new Long(flush_timeout)).longValue());
        }

        mSDTimer = new Timer();
        SessionTimer timertask = new SessionTimer(mSecurityDomainSessionTable);

        mSDTimer.schedule(timertask, 5, (new Long(secdomain_check_interval)).longValue());
    }

    serverStatus = "running";
}