Configures the HTTP/HTTPS connection.
@param config
@return
@throws MalformedURLException
@throws IOException
181795
private static HttpURLConnection setup(HttpsFileUploaderConfig config) throws MalformedURLException, IOException {
        HttpURLConnection httpUrlConnection;
        boolean isHttps = false;
        URL url = config.getURL();
        if (url.getProtocol().equalsIgnoreCase("https")) {
            isHttps = true;
        }

        if (config.usesProxy()) {
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(config.getProxyAddress(), config.getProxyPort()));
            httpUrlConnection = (HttpURLConnection) url.openConnection(proxy);
        } else {
            httpUrlConnection = (HttpURLConnection) url.openConnection();
        }
        
        
        if (!config.isValidateCertificates() && isHttps) {
            SSLUtils.setNoValidate(((HttpsURLConnection) httpUrlConnection), config.getAcceptedIssuers());
        }
        
        
        httpUrlConnection.setUseCaches(false);  // do not use connection caches
        httpUrlConnection.setDoOutput(true);

        // Set timeouts
        httpUrlConnection.setConnectTimeout(config.getConnectTimeoutMs());
        httpUrlConnection.setReadTimeout(config.getReadTimeoutMs());

        httpUrlConnection.setRequestMethod("POST");
        httpUrlConnection.setRequestProperty("Connection", "Keep-Alive");
        httpUrlConnection.setRequestProperty("Cache-Control", "no-cache");
        httpUrlConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + MULTIPART_BOUNDARY);
        
        // Sets additional headers
        if (config.getAdditionalHeaders() != null) {
            for(Entry<String,String> e : config.getAdditionalHeaders().entrySet()) {
                // We use the 'set' method here and not the 'add' method because
                // it should be allowed for example for the user to override Java's default
                // User-Agent value. 
                httpUrlConnection.setRequestProperty(e.getKey(), e.getValue());
            }
        }
        
        
        if (config.endpointRequiresAuthentication()) {
            String authString = config.getEndpointUsername() + ":" + config.getEndpointPassword();

            // The only public Base64 encoder that exist in Java 7 and before is from the
            // JAXB package so we will (mis)use that here for Base64 encoding.        
            // Note: Java 8 will finally have a Base64 class in the Util package.
            String authStringEnc = javax.xml.bind.DatatypeConverter.printBase64Binary(authString.getBytes());
            httpUrlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
        }
        
        return httpUrlConnection;
    }
97641
@NonNull
  public RequestCreator config(@NonNull Bitmap.Config config) {
    data.config(config);
    return this;
  }
748916
@Override
    protected void configure(HttpSecurity http) throws Exception {
        // Gets a secure random key for the remember be token key
        SecureRandom random = new SecureRandom();
        byte[] randomBytes = new byte[64];
        random.nextBytes(randomBytes);
        String rememberBeKey = new String(Hex.encode(randomBytes));
        // @formatter:off
        http.antMatcher("/**")
            // Only BASIC authentication
            .httpBasic()
                .authenticationEntryPoint(apiBasicAuthenticationEntryPoint)
                .realmName("ontrack")
                .and()
            // Logout set-up
            .logout()
                .logoutUrl("/user/logout")
                .logoutSuccessUrl("/user/logged-out")
                .addLogoutHandler(basicRememberMeUserDetailsService())
                .and()
            // FIXME CSRF protection for a stateless API?
            //.csrf().requireCsrfProtectionMatcher(new CSRFRequestMatcher()).and()
            .csrf().disable()
            // Allows all at Web level
            .authorizeRequests()
                .antMatchers("/**").permitAll()
            // Remember be authentication token
            .and().rememberMe()
                .rememberMeServices(rememberMeServices(rememberBeKey))
                .key(rememberBeKey)
                .tokenValiditySeconds(604800)
            // Cache enabled
            .and().headers().cacheControl().disable()
        ;
        // @formatter:on
    }
588013
private void setConfig(JsonSimpleConfig config)
            throws TransformerException {
        // Test our Fedora connection... things are kind of useless without it
        fedoraUrl = config.getString(null,
                Strings.CONFIG_SERVER, "url");
        fedoraNamespace = config.getString(null,
                Strings.CONFIG_SERVER, "namespace");
        fedoraUsername = config.getString(null,
                Strings.CONFIG_SERVER, "username");
        fedoraPassword = config.getString(null,
                Strings.CONFIG_SERVER, "password");
        fedoraTimeout = config.getInteger(15,
                Strings.CONFIG_SERVER, "timeout");
        if (fedoraUrl == null || fedoraNamespace == null ||
                fedoraUsername == null || fedoraPassword == null) {
            throw new TransformerException(
                    "Valid fedora configuration is missing!");
        }
        // This will throw the TransformerException for
        // us if there's something wrong
        fedoraConnect(true);
        fedoraMessageTemplate = config.getString(Strings.DEFAULT_VITAL_MESSAGE,
                Strings.CONFIG_SERVER, "message");

        // Temp space
        boolean success = false;
        String tempPath = config.getString(
                System.getProperty("java.io.tmpdir"), "tempDir");
        if (tempPath != null) {
            tmpDir = new File(tempPath);

            // Make sure it exists
            if (!tmpDir.exists()) {
                success = tmpDir.mkdirs();
            } else {
                // And it's a directory
                success = tmpDir.isDirectory();
            }
            // Now make sure it's writable
            if (success) {
                File file = new File(tmpDir, "creation.test");
                try {
                    file.createNewFile();
                    file.delete();
                    success = !file.exists();
                } catch (IOException ex) {
                    success = false;
                }

            }
        }
        if (tmpDir == null || !success) {
            throw new TransformerException(
                    "Cannot find a valid (and writable) TEMP directory!");
        }

        // Get the list of pids we are sending to VITAL
        pids = config.getJsonSimpleMap("dataStreams");
        if (pids == null || pids.isEmpty()) {
            throw new TransformerException(
                    "No datastreams configured to export!");
        }
        // And attachment handling
        JsonSimple attachmentsConfig = new JsonSimple(
                config.getObject("attachments"));
        attachDs = attachmentsConfig.getString("ATTACHMENT%02d", "dsID");
        Pattern p = Pattern.compile("%\\d*d");
        Matcher m = p.matcher(attachDs);
        if (!m.find()) {
            throw new TransformerException(
                    "'*/attachments/dsId' must have a format placeholder for incrementing integer, eg. '%d' or '%02d'. The value provided ('"
                    + attachDs + "') is invalid");
        }
        attachStatusField = attachmentsConfig.getString(null, "statusField");
        attachStatuses = getStringMap(attachmentsConfig, "status");
        attachLabelField = attachmentsConfig.getString(null, "labelField");
        attachLabels = getStringMap(attachmentsConfig, "label");
        attachControlGroup = attachmentsConfig.getString(null, "controlGroup");
        attachVersionable = attachmentsConfig.getBoolean(false, "versionable");
        attachRetainIds = attachmentsConfig.getBoolean(true, "retainIds");
        // To make life easier we're going to use the new JSON Library here
        attachAltIds = new LinkedHashMap<String, List<String>>();
        JsonSimple json;
        try {
            json = new JsonSimple(config.toString());
        } catch (IOException ex) {
            throw new TransformerException("Error parsing attachment JSON", ex);
        }
        // Use the base object for iteration
        JsonObject objAltIds = json.getObject("attachments", "altIds");
        // And the library for access methods
        JsonSimple altIds = new JsonSimple(objAltIds);
        for (Object oKey : objAltIds.keySet()) {
            String key = (String) oKey;
            List<String> ids = altIds.getStringList(key);
            if (ids.isEmpty()) {
                log.warn("WARNING: '{}' has no altIds configured.", key);
            } else {
                attachAltIds.put(key, ids);
            }
        }
        // Make sure 'default' exists, even if empty
        if (!attachAltIds.containsKey(Strings.LITERAL_DEFAULT)) {
            attachAltIds.put(Strings.LITERAL_DEFAULT, new ArrayList<String>());
        }

        // Are we sending emails on errors?
        emailQueue = config.getString(null,
                Strings.CONFIG_FAILURE, "emailQueue");
        if (emailQueue != null) {
            emailAddresses = config.getStringList(
                    Strings.CONFIG_FAILURE, "emailAddress");
            if (emailAddresses != null && !emailAddresses.isEmpty()) {
                emailSubject = config.getString(Strings.DEFAULT_EMAIL_SUBJECT,
                        Strings.CONFIG_FAILURE, "emailSubject");
                emailTemplate = config.getString(Strings.DEFAULT_EMAIL_TEMPLATE,
                        Strings.CONFIG_FAILURE, "emailTemplate");
            } else {
                log.error("No email address provided! Reverting to errors using log files");
                emailQueue = null;
            }
        } else {
            log.warn("No email queue provided. Errors will only be logged");
        }

        // Ensure we have access to messaging services
        if (emailQueue != null) {
            try {
                messaging = MessagingServices.getInstance();
            } catch (MessagingException ex) {
                throw new TransformerException(
                        "Error starting Messaging Services", ex);
            }
        }

        // Need our config file to instantiate plugins
        File sysFile = null;
        try {
            sysFile = JsonSimpleConfig.getSystemFile();
        } catch (IOException ioe) {
            log.error("Failed to read configuration: {}", ioe.getMessage());
            throw new TransformerException("Failed to read configuration", ioe);
        }

        // Start our storage layer
        try {
            storage = PluginManager.getStorage(
                    config.getString("file-system", "storage", "type"));
            storage.init(sysFile);
        } catch (PluginException pe) {
            log.error("Failed to initialise plugin: {}", pe.getMessage());
            throw new TransformerException("Failed to initialise storage", pe);
        }

        // Instantiate an indexer for searching
        try {
            indexer = PluginManager.getIndexer(
                    config.getString("solr", "indexer", "type"));
            indexer.init(sysFile);
        } catch (PluginException pe) {
            log.error("Failed to initialise plugin: {}", pe.getMessage());
            throw new TransformerException("Failed to initialise indexer", pe);
        }

        // Do we have a template?
        String templatePath = config.getString(null, "foxmlTemplate");
        if (templatePath != null) {
            foxmlTemplate = new File(templatePath);
            if (!foxmlTemplate.exists()) {
                foxmlTemplate = null;
                throw new TransformerException(
                        "The new object template provided does not exist: '" +
                        templatePath + "'");
            }
        }

        // Wait conditions
        waitProperties = new ArrayList<String>();
        Map<String, String> waitConditions =
                getStringMap(config, "waitConditions");
        if (waitConditions != null) {
            for (String type : waitConditions.keySet()) {
                String value = waitConditions.get(type);
                if (value == null) {
                    continue;
                }
                // We only support properties at this stage
                if (type.equals("property")) {
                    log.info("New wait condition: Property '{}'.", value);
                    waitProperties.add(value);
                }
            }
        }

        valid = true;
    }
949212
public void configure(Configuration config) throws ConfigurationException
    {
        LoggingConfiguration lc = (LoggingConfiguration) config;
        String levelName = lc.getLogLevel(name);
        setLevel(levelName);
    }
632357
protected URL buildURL(Map<String,String> headers, String instanceHostPort) throws MalformedURLException {
        String origUrl = headers.get(Listener.METAINFO_REQUEST_URL);
        if (origUrl == null || !origUrl.startsWith("http")) {
            // other protocol: forward to standard services url
            return new URL("http://" + instanceHostPort + "/" + getServicesRoot() + "/Services");
        }
        else {
            URL origHttpUrl = new URL(origUrl);
            String path = origHttpUrl.getPath();
            // Re-route from SOAP to REST since MDW only cares about message Payload, plus we no longer have the SOAP Envelope in the request
            if (path != null && (path.contains("/SOAP") || path.contains("/MDWWebService")))
                path = "/" + getServicesRoot() + "/Services";

            String destUrl = origHttpUrl.getProtocol() + "://" + instanceHostPort + path;
            if (!StringHelper.isEmpty(headers.get(Listener.METAINFO_REQUEST_QUERY_STRING)))
                destUrl += "?" + headers.get(Listener.METAINFO_REQUEST_QUERY_STRING);
            return new URL(destUrl);
        }
    }
294133
public static HttpConfiguration createHttpConfiguration() {
		HttpConfiguration httpConfig = new HttpConfiguration();

		httpConfig.setSecurePort(setting.getInt("secure-port", "http", 8443));
		httpConfig.setOutputBufferSize(setting.getInt("output-buffersize", "http", 32768));
		httpConfig.setRequestHeaderSize(setting.getInt("request-headersize", "http", 8192));
		httpConfig.setResponseHeaderSize(setting.getInt("response-headersize", "http", 8192));
		httpConfig.setSendServerVersion(true);
		httpConfig.setSendDateHeader(false);

		return httpConfig;
	}
730201
protected HttpURLConnection generateConn() throws IOException {
        HttpURLConnection conn;
        conn = (HttpURLConnection) new URL(url).openConnection();
        return conn;
    }
609711
public static void configureFactory( ConnectionFactory factory, Map<String,String> configuration )
	throws IOException {

		final Logger logger = Logger.getLogger( RabbitMqUtils.class.getName());
		logger.fine( "Configuring a connection factory for RabbitMQ." );

		String messageServerIp = configuration.get( RABBITMQ_SERVER_IP );
		if( messageServerIp != null ) {
			Map.Entry<String,Integer> entry = Utils.findUrlAndPort( messageServerIp );
			factory.setHost( entry.getKey());
			if( entry.getValue() > 0 )
				factory.setPort( entry.getValue());
		}

		factory.setUsername( configuration.get( RABBITMQ_SERVER_USERNAME ));
		factory.setPassword( configuration.get( RABBITMQ_SERVER_PASSWORD ));

		// Timeout for connection establishment: 5s
		factory.setConnectionTimeout( 5000 );

		// Configure automatic reconnection
		factory.setAutomaticRecoveryEnabled( true );

		// Recovery interval: 10s
		factory.setNetworkRecoveryInterval( 10000 );

		// Exchanges and so on should be redeclared if necessary
		factory.setTopologyRecoveryEnabled( true );

		// SSL
		if( Boolean.parseBoolean( configuration.get( RABBITMQ_USE_SSL ))) {
			logger.fine( "Connection factory for RabbitMQ: SSL is used." );

			InputStream clientIS = null;
			InputStream storeIS = null;
			try {
				clientIS = new FileInputStream( configuration.get( RABBITMQ_SSL_KEY_STORE_PATH ));
				storeIS = new FileInputStream( configuration.get( RABBITMQ_SSL_TRUST_STORE_PATH ));

				char[] keyStorePassphrase = configuration.get( RABBITMQ_SSL_KEY_STORE_PASSPHRASE ).toCharArray();
				KeyStore ks = KeyStore.getInstance( getValue( configuration, RABBITMQ_SSL_KEY_STORE_TYPE, DEFAULT_SSL_KEY_STORE_TYPE ));
				ks.load( clientIS, keyStorePassphrase );

				String value = getValue( configuration, RABBITMQ_SSL_KEY_MNGR_FACTORY, DEFAULT_SSL_MNGR_FACTORY );
				KeyManagerFactory kmf = KeyManagerFactory.getInstance( value );
				kmf.init( ks, keyStorePassphrase );

				char[] trustStorePassphrase = configuration.get( RABBITMQ_SSL_TRUST_STORE_PASSPHRASE ).toCharArray();
				KeyStore tks = KeyStore.getInstance( getValue( configuration, RABBITMQ_SSL_TRUST_STORE_TYPE, DEFAULT_SSL_TRUST_STORE_TYPE ));
				tks.load( storeIS, trustStorePassphrase );

				value = getValue( configuration, RABBITMQ_SSL_TRUST_MNGR_FACTORY, DEFAULT_SSL_MNGR_FACTORY );
				TrustManagerFactory tmf = TrustManagerFactory.getInstance( value );
				tmf.init( tks );

				SSLContext c = SSLContext.getInstance( getValue( configuration, RABBITMQ_SSL_PROTOCOL, DEFAULT_SSL_PROTOCOL ));
				c.init( kmf.getKeyManagers(), tmf.getTrustManagers(), null );
				factory.useSslProtocol( c );

			} catch( GeneralSecurityException e ) {
				throw new IOException( "SSL configuration for the RabbitMQ factory failed.", e );

			} finally {
				Utils.closeQuietly( storeIS );
				Utils.closeQuietly( clientIS );
			}
		}
	}
1275936
public static URL buildUrl(String scheme, String host, int port, String path, Map<String, String> parameters) throws MalformedURLException {
        checkSchemeAndPort(scheme, port);
        StringBuilder buffer = new StringBuilder();
        if (!host.startsWith(scheme + "://")) {
            buffer.append(scheme).append("://");
        }
        buffer.append(host);
        if (port > 0) {
            buffer.append(':');
            buffer.append(port);
        }
        if (path == null) {
            path = "/";
        }
        buffer.append(path);

        if (!parameters.isEmpty()) {
            buffer.append('?');
        }
        int size = parameters.size();
        for (Map.Entry<String, String> entry : parameters.entrySet()) {
            buffer.append(entry.getKey());
            buffer.append('=');
            Object value = entry.getValue();
            if (value != null) {
                String string = value.toString();
                try {
                    string = URLEncoder.encode(string, UTF8);
                } catch (UnsupportedEncodingException e) {
                    // Should never happen, but just in case
                }
                buffer.append(string);
            }
            if (--size != 0) {
                buffer.append('&');
            }
        }

        /*
         * RequestContext requestContext = RequestContext.getRequestContext(); Auth auth = requestContext.getAuth(); if (auth != null &&
         * !ignoreMethod(getMethod(parameters))) { buffer.append("&api_sig="); buffer.append(AuthUtilities.getSignature(sharedSecret, parameters)); }
         */

        return new URL(buffer.toString());
    }
31578
public HttpHost getProxy(ProxyConfig proxyConfig) {
		if (proxyConfig == null) {
			return null;
		}
		String host = proxyConfig.getHost();
		String port = proxyConfig.getPort();
		HttpHost proxy = null;
		if (!host.isEmpty() && !port.isEmpty()) {
			proxy = new HttpHost(host, Integer.parseInt(port));

		}
		return proxy;
	}
1188644
public static SSLContext sslContext(AbstractConfig config, String key) {
    final String trustManagerFactoryType = config.getString(key);
    try {
      return SSLContext.getInstance(trustManagerFactoryType);
    } catch (NoSuchAlgorithmException e) {
      ConfigException exception = new ConfigException(
          key,
          trustManagerFactoryType,
          "Unknown Algorithm."
      );
      exception.initCause(e);
      throw exception;
    }
  }
1165085
public void reconfigure(final String config)
	{
		try
		{
			final File tempFile = File.createTempFile("nginx", ".conf");
			try
			{
				FileHelper.write(tempFile, config);

				final Execed process = Exec.rootUtility(new File(binPath, "nginx-reconfigure").getAbsolutePath(),
				                                        tempFile.getAbsolutePath());

				process.waitForExit(new Timeout(30, TimeUnit.SECONDS).start(), 0);
			}
			finally
			{
				FileUtils.deleteQuietly(tempFile);
			}
		}
		catch (IOException e)
		{
			throw new RuntimeException("Error executing nginx-reload command", e);
		}

		reload();
	}
1117601
public static URL correct(final URL url) throws MalformedURLException {
        if (url == null) {
            throw new MalformedURLException("The url is null");
        }
        return new URL(correct(url.toString(), false));
    }
1143793
public static ServerSocketFactory createSSLServerSocketFactory(Configuration config) throws Exception {
		SSLContext sslContext = createInternalSSLContext(config);
		if (sslContext == null) {
			throw new IllegalConfigurationException("SSL is not enabled");
		}

		String[] protocols = getEnabledProtocols(config);
		String[] cipherSuites = getEnabledCipherSuites(config);

		SSLServerSocketFactory factory = sslContext.getServerSocketFactory();
		return new ConfiguringSSLServerSocketFactory(factory, protocols, cipherSuites);
	}
1284032
function (config) {
            var url = config.url,
                viewerAPI = scope.getConfig().api;

            if (url) {
                viewerAPI.download = function () {
                    download(url);
                };
            }
        }
1350752
protected static Properties loadConfig(URL url) {
    InputStream is = null;
    try {
      URLConnection connection = url.openConnection();
      if(connection instanceof HttpURLConnection) {
        HttpURLConnection conn = (HttpURLConnection)connection;
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(5000);        
      }
      is = connection.getInputStream();
      return loadConfig(url.toString(), is);     
    } catch (Exception ex) {
      ex.printStackTrace(System.err);
      throw new IllegalArgumentException("Failed to load configuration from [" + url + "]", ex);
    }finally {
      if(is!=null) try { is.close(); } catch (Exception ex) { /* No Op */ }
    }
  }