Java Code Examples for java.net.URL

The following are top voted examples for showing how to use java.net.URL. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: browserid-verifier   File: Verifier.java View source code 8 votes vote down vote up
private HttpsURLConnection prepareConnection(final URL verifierURL)
		throws IOException {

	final HttpsURLConnection connection = (HttpsURLConnection) verifierURL
			.openConnection();
	connection.setRequestMethod("POST");
	connection.setRequestProperty("Content-Type",
			"application/json; charset=utf-8");
	connection.setRequestProperty("Accept-Charset", "utf-8");
	connection.setDoOutput(true);

	return connection;
}
 
Example 2
Project: couchbase-lite-android-ektorp   File: CBLiteEktorpTestCase.java View source code 7 votes vote down vote up
protected  void deleteRemoteDB(URL url) {
    try {
        Log.v(TAG, String.format("Deleting %s", url.toExternalForm()));
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        String userInfo = url.getUserInfo();
        if(userInfo != null) {
            byte[] authEncBytes = Base64.encode(userInfo.getBytes(), Base64.DEFAULT);

            conn.setRequestProperty("Authorization", "Basic " + new String(authEncBytes));
        }

        conn.setRequestMethod("DELETE");
        conn.connect();
        int responseCode = conn.getResponseCode();
        Assert.assertTrue(responseCode < 300 || responseCode == 404);
    } catch (Exception e) {
        Log.e(TAG, "Exceptiong deleting remote db", e);
    }
}
 
Example 3
Project: jentrata-msh   File: Module.java View source code 6 votes vote down vote up
/**
 * Gets a resource as stream.
 * 
 * @param name the name of the resource.
 * @return an input stream of the resource.
 * 
 * @see #getResource(String)
 */
public InputStream getResourceAsStream(String name) {
    try {
        URL url = getResource(name);
        return url == null ? null : url.openStream();
    }
    catch (Exception e) {
        return null;
    }
}
 
Example 4
Project: jentrata-msh   File: InboundMessageProcessorTest.java View source code 6 votes vote down vote up
@Test
public void testCheckExpiredMessage() throws Exception {
	Method m = Class.forName("hk.hku.cecid.ebms.spa.handler.InboundMessageProcessor").
	getDeclaredMethod("checkExpiredMessage", new Class[] {EbxmlMessage.class});
	m.setAccessible(true);

	URL msgURL;
	File msgFile;
	EbxmlMessage msg;
	
	// 2008-07-21T15:26:52.075+08:00
	msgURL = FIXTURE_LOADER.getResource("test1.msg");
	msgFile = new File(msgURL.getFile());		
	msg = new EbxmlMessage(msgFile);
	Assert.assertTrue((Boolean)m.invoke(InboundMessageProcessor.getInstance(), new Object[] {msg}));		

	// 2099-07-21T15:26:52.075+08:00
	msgURL = FIXTURE_LOADER.getResource("test2.msg");
	msgFile = new File(msgURL.getFile());		
	msg = new EbxmlMessage(msgFile);
	Assert.assertFalse((Boolean)m.invoke(InboundMessageProcessor.getInstance(), new Object[] {msg}));		
	
	// Tue Jul 10 20:01:14 HKT 2007
	msgURL = FIXTURE_LOADER.getResource("test3.msg");
	msgFile = new File(msgURL.getFile());		
	msg = new EbxmlMessage(msgFile);
	Assert.assertTrue((Boolean)m.invoke(InboundMessageProcessor.getInstance(), new Object[] {msg}));		

	// Sat Jul 10 20:01:14 HKT 2038
	msgURL = FIXTURE_LOADER.getResource("test4.msg");
	msgFile = new File(msgURL.getFile());		
	msg = new EbxmlMessage(msgFile);
	Assert.assertFalse((Boolean)m.invoke(InboundMessageProcessor.getInstance(), new Object[] {msg}));

}
 
Example 5
Project: phonegap-geolocation   File: HttpEngine.java View source code 6 votes vote down vote up
private String requestString() {
  URL url = policy.getURL();
  if (includeAuthorityInRequestLine()) {
    return url.toString();
  } else {
    return requestPath(url);
  }
}
 
Example 6
Project: netlib   File: HttpUtilRemoteTest.java View source code 6 votes vote down vote up
@Test(timeout=15000)
public void testPostRequest() throws Exception {
    final String DATA_TO_POST = "Das sind die\nPost\nDaten";
    final String EXPECTED_RESPONSE = "<postedData>"+DATA_TO_POST+"</postedData>";
    final long TIMEOUT_MS = 3000;
    
    // prepare request
    URL url = new URL(POSTTEST_URL);
    NetLayer netLayer = NetFactory.getInstance().getNetLayerById(NetLayerIDs.TCPIP);
    int port = url.getPort();
    TcpipNetAddress httpServerNetAddress = new TcpipNetAddress(url.getHost(), port<0 ? 80 : port);
    Map<String,Object> localProperties = null;
    String pathOnHttpServer = url.getPath();
    if (pathOnHttpServer==null || pathOnHttpServer.length()<1) {
        pathOnHttpServer = "/";
    }
    log.info("pathOnHttpServer="+pathOnHttpServer);

    // execute request and check response
    NetSocket netSocket = netLayer.createNetSocket(localProperties, /*localAddress*/ null, httpServerNetAddress);
    String response = new String(HttpUtil.getInstance().post(netSocket, httpServerNetAddress, pathOnHttpServer, DATA_TO_POST.getBytes(UTF8), TIMEOUT_MS), UTF8);
    if (!response.contains(EXPECTED_RESPONSE)) {
        assertEquals("wrong result",
                EXPECTED_RESPONSE,
                response);
    }
}
 
Example 7
Project: jena   File: NTriple.java View source code 6 votes vote down vote up
@SuppressWarnings("resource")
   static private void process(String surl) {
	InputStream in = null ;
	
	URL url;
	String baseURL;

	try {
		File ff = new File(surl);
		in = new FileInputStream(ff);
		url = ff.toURI().toURL() ;
		baseURL = url.toExternalForm();
		if (baseURL.startsWith("file:/")
			&& !baseURL.startsWith("file://")) {
			baseURL = "file://" + baseURL.substring(5);
		}
	} catch (Exception ignore) {
		try {
			url = new URL(surl);
			in = url.openStream();
			baseURL = url.toExternalForm();
		} catch (Exception e) {
			System.err.println("ARP: Failed to open: " + surl);
			System.err.println(
				"    " + ParseException.formatMessage(ignore));
			System.err.println("    " + ParseException.formatMessage(e));
			return;
		}
	}
	process(in, baseURL, surl);
	try { in.close() ; } catch (IOException ex) {} 
}
 
Example 8
Project: SAPManagerPack   File: SAPUpdateManager.java View source code 6 votes vote down vote up
public URL getDownload() {
    try {
        URL dl = new URL(this.downloadUrl);
        dl.toURI();
        return dl;
    } catch( MalformedURLException | URISyntaxException e ) {
        return null;
    }
}
 
Example 9
Project: netlib   File: ParseUtil.java View source code 6 votes vote down vote up
public static java.net.URI toURI(URL url) {
    String protocol = url.getProtocol();
    String auth = url.getAuthority();
    String path = url.getPath();
    String query = url.getQuery();
    String ref = url.getRef();
    if (path != null && !(path.startsWith("/")))
        path = "/" + path;

    //
    // In java.net.URI class, a port number of -1 implies the default
    // port number. So get it stripped off before creating URI instance.
    //
    if (auth != null && auth.endsWith(":-1"))
        auth = auth.substring(0, auth.length() - 3);

    java.net.URI uri;
    try {
        uri = createURI(protocol, auth, path, query, ref);
    } catch (java.net.URISyntaxException e) {
        uri = null;
    }
    return uri;
}
 
Example 10
Project: ExcusePro   File: UserSettingsFragment.java View source code 6 votes vote down vote up
private void updateUI() {
    if (!isAdded()) {
        return;
    }
    if (isSessionOpen()) {
        connectedStateLabel.setTextColor(getResources().getColor(R.color.com_facebook_usersettingsfragment_connected_text_color));
        connectedStateLabel.setShadowLayer(1f, 0f, -1f,
                getResources().getColor(R.color.com_facebook_usersettingsfragment_connected_shadow_color));
        
        if (user != null) {
            ImageRequest request = getImageRequest();
            if (request != null) {
                URL requestUrl = request.getImageUrl();
                // Do we already have the right picture? If so, leave it alone.
                if (!requestUrl.equals(connectedStateLabel.getTag())) {
                    if (user.getId().equals(userProfilePicID)) {
                        connectedStateLabel.setCompoundDrawables(null, userProfilePic, null, null);
                        connectedStateLabel.setTag(requestUrl);
                    } else {
                        ImageDownloader.downloadAsync(request);
                    }
                }
            }
            connectedStateLabel.setText(user.getName());
        } else {
            connectedStateLabel.setText(getResources().getString(
                    R.string.com_facebook_usersettingsfragment_logged_in));
            Drawable noProfilePic = getResources().getDrawable(R.drawable.com_facebook_profile_default_icon);
            noProfilePic.setBounds(0, 0,
                    getResources().getDimensionPixelSize(R.dimen.com_facebook_usersettingsfragment_profile_picture_width),
                    getResources().getDimensionPixelSize(R.dimen.com_facebook_usersettingsfragment_profile_picture_height));
            connectedStateLabel.setCompoundDrawables(null, noProfilePic, null, null);
        }
    } else {
        int textColor = getResources().getColor(R.color.com_facebook_usersettingsfragment_not_connected_text_color);
        connectedStateLabel.setTextColor(textColor);
        connectedStateLabel.setShadowLayer(0f, 0f, 0f, textColor);
        connectedStateLabel.setText(getResources().getString(
                R.string.com_facebook_usersettingsfragment_not_logged_in));
        connectedStateLabel.setCompoundDrawables(null, null, null, null);
        connectedStateLabel.setTag(null);
    }
}
 
Example 11
Project: netlib   File: HttpURLConnection.java View source code 6 votes vote down vote up
static String connectRequestURI(URL url) {
    String host = url.getHost();
    int port = url.getPort();
    port = port != -1 ? port : url.getDefaultPort();

    return host + ":" + port;
}
 
Example 12
Project: java-manga-reader   File: MangaReaderAPI.java View source code 6 votes vote down vote up
/**
 * Generates the name of the manga from the URL
 */
private String getMangaName(String URL) {
	String name = URL.replace(MANGA_READER_URL, "");
	name = name.substring(0, name.indexOf("/"));
	if(isMangaHash(name)){//If it's a MangaHash, we have to parse the next / 
		name = URL.replace(MANGA_READER_URL, "");
		name = name.substring(0, name.lastIndexOf('/'));
		name = name.substring(name.lastIndexOf("/")+1);
	}
	name = name.replace('-', ' ');
	assert(!name.contains("."));
	return name;
}
 
Example 13
Project: freemind-mmx   File: MapModuleManager.java View source code 6 votes vote down vote up
private boolean sameFile(URL urlToCheck, final URL moduleUrl) {
	if (moduleUrl == null) {
		return false;
	}
	if (urlToCheck.getProtocol().equals("file")
			&& moduleUrl.getProtocol().equals("file")) {
		return (new File(urlToCheck.getFile())).equals(new File(moduleUrl
				.getFile()));
	}
	return urlToCheck.sameFile(moduleUrl);
}
 
Example 14
Project: geotools-old   File: WFSDataStoreFactory.java View source code 6 votes vote down vote up
/**
 * Checks whether [email protected] params} contains a valid set of parameters to connecto to a WFS.
 * <p>
 * Rules are:
 * <ul>
 * <li>the mandatory [email protected] #URL} is provided.
 * <li>whether both [email protected] #USERNAME} and [email protected] #PASSWORD} are provided, or none.
 * </ul>
 * Availability of the other optional parameters is not checked for existence.
 * </p>
 * 
 * @param params
 *            non null map of datastore parameters.
 * @see org.geotools.data.DataStoreFactorySpi#canProcess(java.util.Map)
 */
public boolean canProcess(final Map params) {
    if (params == null) {
        return false; // throw new NullPointerException("params");
    }
    try {
        URL url = (URL) URL.lookUp(params);
        if( !"http".equalsIgnoreCase(url.getProtocol()) && !"https".equalsIgnoreCase(url.getProtocol())){
            return false; // must be http or https since we use SimpleHttpProtocol class
        }
    } catch (Exception e) {
        return false;
    }

    // check password / username
    if (params.containsKey(USERNAME.key)) {
        if (!params.containsKey(PASSWORD.key)) {
            return false; // must have both
        }
    } else {
        if (params.containsKey(PASSWORD.key)) {
            return false; // must have both
        }
    }
    return true;
}
 
Example 15
Project: ikvm-openjdk   File: MimeLauncher.java View source code 6 votes vote down vote up
protected String getTempFileName(URL url, String template) {
    String tempFilename = template;

    // Replace all but last occurrance of "%s" with timestamp to insure
    // uniqueness.  There's a subtle behavior here: if there is anything
    // _after_ the last "%s" we need to append it so that unusual launch
    // strings that have the datafile in the middle can still be used.
    int wildcard = tempFilename.lastIndexOf("%s");
    String prefix = tempFilename.substring(0, wildcard);

    String suffix = "";
    if (wildcard < tempFilename.length() - 2) {
        suffix = tempFilename.substring(wildcard + 2);
    }

    long timestamp = System.currentTimeMillis()/1000;
    int argIndex = 0;
    while ((argIndex = prefix.indexOf("%s")) >= 0) {
        prefix = prefix.substring(0, argIndex)
            + timestamp
            + prefix.substring(argIndex + 2);
    }

    // Add a file name and file-extension if known
    String filename = url.getFile();

    String extension = "";
    int dot = filename.lastIndexOf('.');

    // BugId 4084826:  Temp MIME file names not always valid.
    // Fix:  don't allow slashes in the file name or extension.
    if (dot >= 0 && dot > filename.lastIndexOf('/')) {
        extension = filename.substring(dot);
    }

    filename = "HJ" + url.hashCode();

    tempFilename = prefix + filename + timestamp + extension + suffix;

    return tempFilename;
}
 
Example 16
Project: java-manga-reader   File: MangaReaderAPI.java View source code 6 votes vote down vote up
/**
 * Generates a chapter number from the URL
 * @param URL the URL you want to generate the number of
 * @return The calculated number
 */
private double getChapNum(String URL){
	if(URL.contains("chapter")){
		String test = URL.substring(URL.lastIndexOf('-')+1);
		if(test.indexOf('.')!=-1){
			test = test.substring(0, test.indexOf('.'));
		}
		return Double.parseDouble(test);
	}
	if(hasMangaHash(URL)){//There are two types of ways of delineating Manga on the site
		String chapter = URL.replace(MANGA_READER_URL, "");
		chapter = chapter.substring(0,chapter.indexOf("/"));
		chapter = chapter.substring(chapter.indexOf('-')+1, chapter.lastIndexOf('-'));
		return Double.parseDouble(chapter);
	}
	else{
		String number = URL.substring(0,URL.lastIndexOf('/'));
		number = number.substring(number.lastIndexOf('/')+1);
		if(!StringUtil.isNum(number)){//In case it grabs the name instead
			number = URL.substring(URL.lastIndexOf('/')+1);
		}
		return Double.parseDouble(number);
	}
}
 
Example 17
Project: jentrata-msh   File: OutboxTask.java View source code 5 votes vote down vote up
private void sendMsgBySmtp(URL toPartyURL, EbxmlMessage ebxmlMessage,
        String contentType) throws DeliveryException, CertificateException,
        IOException {

    MessageServiceHandler msh = MessageServiceHandler.getInstance();

    String toMailAddress = toPartyURL.getPath();
    EbmsProcessor.core.log.info("Send message " + messageDVO.getMessageId()
            + " to " + toMailAddress);

    SOAPMailSender smtp = new SOAPMailSender(msh.smtpProtocol,
            msh.smtpHost, msh.smtpUsername, msh.smtpPassword);

    if (!msh.smtpPort.equalsIgnoreCase("")) {
        smtp.addProperty("mail.smtp.port", msh.smtpPort);
    }

    try {
        Session session = smtp.createSession();

        MimeMessage message = smtp.createMessage(msh.smtpFromMailAddress,
                toMailAddress, null, "ebxml",
                ebxmlMessage.getSOAPMessage(), session);
        
        message.setHeader(EbxmlMessage.SOAP_ACTION, EbxmlMessage.SOAP_ACTION_VALUE);            

        if (outboxAgreement.isEncrypt()) {
            EbmsProcessor.core.log.info("Encrypt the message");

            X509Certificate serverCert = null;
            if (outboxAgreement.getEncryptCert() != null) {
                ByteArrayInputStream bais = new ByteArrayInputStream(
                        outboxAgreement.getEncryptCert());
                CertificateFactory cf = CertificateFactory
                        .getInstance("X.509");
                serverCert = (X509Certificate) cf.generateCertificate(bais);
                bais.close();
                bais = null;
            } else {
                EbmsProcessor.core.log.error("Please upload the cert");
                throw new RuntimeException("Please upload the cert");
            }

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            message.writeTo(baos);
            MimeBodyPart mimeBodyPart = new MimeBodyPart(
                    new ByteArrayInputStream(baos.toByteArray()));
            baos.close();

            SMimeMessage smsg = new SMimeMessage(mimeBodyPart, serverCert,
                    session);

            // set encryption algorithm
            if (outboxAgreement.getEncryptAlgorithm() != null) {
                smsg.setEncryptAlgorithm(outboxAgreement
                        .getEncryptAlgorithm());
            }

            MimeBodyPart bp = smsg.encrypt().getBodyPart();
            message.setContent(bp.getContent(), bp.getContentType());
        }
        smtp.send(message);
        
    } catch (Exception e) {
        EbmsProcessor.core.log.error("Cannot send the message", e);
        throw new DeliveryException("Cannot send the message", e);
    }
}
 
Example 18
Project: jentrata-msh   File: AgreementHandler.java View source code 5 votes vote down vote up
/**
 * @param message
 * @throws DAOException
 * @throws MessageValidationException
 */
private void findPartnership(MessageDVO message) throws DAOException,
        MessageValidationException {
    PartnershipDAO partnershipDAO = (PartnershipDAO) EbmsProcessor.core.dao
            .createDAO(PartnershipDAO.class);
    PartnershipDVO partnershipDVO = (PartnershipDVO) partnershipDAO
            .createDVO();
    partnershipDVO.setCpaId(message.getCpaId());
    if (message.getMessageType().equalsIgnoreCase(
            MessageClassifier.MESSAGE_TYPE_ORDER)) {
        partnershipDVO.setService(message.getService());
        partnershipDVO.setAction(message.getAction());
    } else {
        // it is not an order msg.
        MessageDAO messageDAO = (MessageDAO) EbmsProcessor.core.dao
                .createDAO(MessageDAO.class);
        MessageDVO orgMessageDVO = (MessageDVO) messageDAO.createDVO();
        orgMessageDVO.setMessageId(message.getRefToMessageId());
        orgMessageDVO.setMessageBox(MessageClassifier.MESSAGE_BOX_INBOX);
        if (messageDAO.findMessage(orgMessageDVO)) {
            if (orgMessageDVO.getAction()
                    .equalsIgnoreCase("Acknowledgment")) {
                // it is the error message related to acknowledgement
                orgMessageDVO.setMessageId(orgMessageDVO
                        .getRefToMessageId());
                orgMessageDVO
                        .setMessageBox(MessageClassifier.MESSAGE_BOX_OUTBOX);
                if (!messageDAO.findMessage(orgMessageDVO)) {
                    throw new MessageValidationException(
                            "Cannot find the ref to message: "
                                    + orgMessageDVO.getRefToMessageId());
                }
            }
            partnershipDVO.setService(orgMessageDVO.getService());
            partnershipDVO.setAction(orgMessageDVO.getAction());
        } else {
            EbmsProcessor.core.log.debug("message type: " + message.getMessageType());
            if(message.getMessageType().equalsIgnoreCase(MessageClassifier.MESSAGE_TYPE_PING)) {
                partnershipDVO.setService(message.getService());
                partnershipDVO.setAction(message.getAction());
            } else {
                throw new MessageValidationException(
                        "Cannot find the ref to message: "
                                + message.getRefToMessageId());
            }
        }
    }

    if (partnershipDAO.findPartnershipByCPA(partnershipDVO)) {
        // there is a predefined sender channel
        signCert = partnershipDVO.getSignCert();
        encryptCert = partnershipDVO.getEncryptCert();

        // there is a predefined delivery channel
        String protocol = partnershipDVO.getTransportProtocol();
        String endpoint = partnershipDVO.getTransportEndpoint();
        try {
            if (protocol == null && endpoint == null) {
                // use perMessage to party id
                toPartyURL = new URL(message.getToPartyId());
                toPartyProtocol = toPartyURL.getProtocol();
            } else {
                toPartyURL = new URL(endpoint);
                if (protocol.equalsIgnoreCase("smtp")) {
                    toPartyProtocol = "mailto";
                } else {
                    toPartyProtocol = protocol;
                }
            }
        } catch (MalformedURLException e2) {
            EbmsProcessor.core.log.error("Url is wrong", e2);
            throw new MessageValidationException("Url is wrong", e2);
        }

        syncReply = partnershipDVO.getSyncReplyMode();
        ackRequested = partnershipDVO.getAckRequested();
        ackSignRequested = partnershipDVO.getAckSignRequested();
        dupElimination = partnershipDVO.getDupElimination();
        actor = partnershipDVO.getActor();
        disabled = partnershipDVO.getDisabled();
        retries = partnershipDVO.getRetries();
        retryInterval = partnershipDVO.getRetryInterval();
        // persistDuration = partnershipDVO.getPersistDuration();
        messageOrder = partnershipDVO.getMessageOrder();
        isSign = new Boolean(partnershipDVO.getSignRequested())
                .booleanValue();
        dsAlgorithm = partnershipDVO.getDsAlgorithm();
        mdAlgorithm = partnershipDVO.getMdAlgorithm();
        isEncrypt = new Boolean(partnershipDVO.getEncryptRequested())
                .booleanValue();
        encryptAlgorithm = partnershipDVO.getEncryptAlgorithm();
        isHostnameVerified = new Boolean(partnershipDVO
                .getIsHostnameVerified()).booleanValue();
    } else {
        EbmsProcessor.core.log.error("Partnership not found: (CPA ID: "
                + partnershipDVO.getCpaId() + ", Service: "
                + partnershipDVO.getService() + " , Action: "
                + partnershipDVO.getAction() + ")");
        throw new MessageValidationException(
                "Partnership channel not found");
    }
}
 
Example 19
Project: wso2-synapse   File: SimpleURLRegistry.java View source code 5 votes vote down vote up
public RegistryEntry[] getChildren(RegistryEntry entry) {
    URL url;
    if (entry == null) {
        RegistryEntryImpl entryImpl = new RegistryEntryImpl();
        entryImpl.setKey("");
        entry = entryImpl;
    }
    url = SynapseConfigUtils.getURLFromPath(root + entry.getKey(), properties.get(
            SynapseConstants.SYNAPSE_HOME) != null ?
            properties.get(SynapseConstants.SYNAPSE_HOME).toString() : "");
    if (url == null) {
        return null;
    }
    if (url.getProtocol().equals("file")) {

        File file = new File(url.getFile());
        if (!file.isDirectory()) {
            return null;
        }
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader((InputStream) url.getContent()));
            ArrayList<RegistryEntry> entryList = new ArrayList<RegistryEntry>();
            String key;
            while ((key = reader.readLine()) != null) {
                RegistryEntryImpl registryEntryImpl = new RegistryEntryImpl();
                if (entry.getKey().equals("")) {
                    registryEntryImpl.setKey(key);
                } else {
                    if (entry.getKey().endsWith("/")) {
                        registryEntryImpl.setKey(entry.getKey() + key);
                    } else {
                        registryEntryImpl.setKey(entry.getKey() + "/" + key);
                    }
                }

                entryList.add(registryEntryImpl);
            }

            RegistryEntry[] entries = new RegistryEntry[entryList.size()];
            for (int i = 0; i < entryList.size(); i++) {
                entries[i] = entryList.get(i);
            }
            return entries;
        } catch (Exception e) {
            throw new SynapseException("Error in reading the URL.");
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException ignored) {
                }
            }
        }
    } else {
        throw new SynapseException("Invalid protocol.");
    }
}
 
Example 20
Project: concierge   File: Concierge.java View source code 5 votes vote down vote up
/**
 * 
 * @see org.osgi.framework.launch.Framework#init()
 * @category Framework
 */
public void init() throws BundleException {
	if (state == Bundle.ACTIVE || state == Bundle.STARTING
			|| state == Bundle.STOPPING) {
		return;
	}

	final StringTokenizer t = new StringTokenizer(
			properties.getProperty(FRAMEWORK_EXECUTIONENVIRONMENT), ",");
	while (t.hasMoreTokens()) {
		SUPPORTED_EE.add(t.nextToken().trim());
	}

	// set UUID
	// FIXME: need workaround for Java 1.4
	properties.setProperty(Constants.FRAMEWORK_UUID, UUID.randomUUID()
			.toString());

	// TODO: check if there is a security manager set and
	// Constants.FRAMEWORK_SECURITY; is set

	STORAGE_LOCATION = properties.getProperty(
			"org.eclipse.concierge.storage",
			properties.getProperty(Constants.FRAMEWORK_STORAGE, BASEDIR
					+ File.separatorChar + "storage"))
			+ File.separatorChar + PROFILE + File.separatorChar;

	// clean the storage if requested
	final File storage = new File(STORAGE_LOCATION);
	if (Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT.equals(properties
			.getProperty(Constants.FRAMEWORK_STORAGE_CLEAN))) {

		if (storage.exists()) {
			deleteDirectory(storage);
		}
	}

	if (!storage.exists() && !storage.mkdirs()) {
		throw new BundleException("Could not create storage directory "
				+ storage);
	}

	// set start level 0
	startlevel = 0;
	// enable event handling

	// have bundle objects for all installed bundles

	// set the collision policy
	final String bsnversion = properties
			.getProperty(Constants.FRAMEWORK_BSNVERSION);
	if (bsnversion == null) {
		collisionPolicy = COLLISION_POLICY_NONE;
	} else {
		if (bsnversion.equals(Constants.FRAMEWORK_BSNVERSION_SINGLE)) {
			collisionPolicy = COLLISION_POLICY_SINGLE;
		} else if (bsnversion
				.equals(Constants.FRAMEWORK_BSNVERSION_MULTIPLE)) {
			collisionPolicy = COLLISION_POLICY_MULTIPLE;
		} else if (bsnversion
				.equals(Constants.FRAMEWORK_BSNVERSION_MANAGED)) {
			collisionPolicy = COLLISION_POLICY_MANAGED;
		}
	}

	// set the framework props
	final String os = properties.getProperty(Constants.FRAMEWORK_OS_NAME);
	osversion = new Version(
			sanitizeVersion(properties
					.getProperty(Constants.FRAMEWORK_OS_VERSION)));
	language = new Locale(
			properties.getProperty(Constants.FRAMEWORK_LANGUAGE), "")
			.getLanguage();
	final String cpu = properties
			.getProperty(Constants.FRAMEWORK_PROCESSOR).intern();
	if (os.toLowerCase().startsWith("win")) {
		osname = "Windows";
	} else {
		osname = os;
	}

	if (cpu == "pentium" || cpu == "i386" || cpu == "i486" || cpu == "i586"
			|| cpu == "i686") {
		processor = "x86";
	} else if (cpu == "amd64" || cpu == "em64t" || cpu == "x86_64"
			|| cpu == "x86-64") {
		processor = "x86-64";
	} else {
		processor = cpu;
	}

	// get the library extensions if set
	final String libExtStr = properties
			.getProperty(Constants.FRAMEWORK_LIBRARY_EXTENSIONS);
	if (libExtStr != null) {
		libraryExtensions = Utils.splitString(libExtStr, ',');
	}

	// set execpermission if set
	execPermission = properties
			.getProperty(Constants.FRAMEWORK_EXECPERMISSION);
	if (execPermission != null) {
		execPermissionPattern = Pattern.compile("\\$\\{"
				+ properties.getProperty(
						Constants.FRAMEWORK_COMMAND_ABSPATH, "abspath")
				+ "\\}");
	}

	// create the system bundle
	headers.put(Constants.BUNDLE_MANIFESTVERSION, "2");
	headers.put(Constants.BUNDLE_NAME, BUNDLE_SYMBOLIC_NAME);
	headers.put(Constants.BUNDLE_VERSION, FRAMEWORK_VERSION);
	headers.put(BUNDLE_REQUIREDEXECUTIONENVIRONMENT,
			"OSGi/Minimum-1.1, CDC-1.1/Foundation-1.1");
	headers.put(Constants.BUNDLE_SYMBOLICNAME, "org.eclipse.concierge");
	final String extraPkgs = properties
			.getProperty(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA);
	final String sysPkgs = extraPkgs == null ? properties
			.getProperty(Constants.FRAMEWORK_SYSTEMPACKAGES) : properties
			.getProperty(Constants.FRAMEWORK_SYSTEMPACKAGES)
			+ ","
			+ extraPkgs;

	// initialize the system bundle capabilities
	final String[] framework_pkgs = Utils.splitString(sysPkgs, ',');
	exportSystemBundlePackages(framework_pkgs);

	headers.put(Constants.EXPORT_PACKAGE, sysPkgs);
	headers.put(Constants.BUNDLE_VENDOR, "Eclipse Foundation");
	bundleID_bundles.put(new Long(0), this);
	location_bundles.put(Constants.SYSTEM_BUNDLE_LOCATION, this);
	symbolicName_bundles.insert(Constants.SYSTEM_BUNDLE_SYMBOLICNAME, this);
	symbolicName_bundles.insert(BUNDLE_SYMBOLIC_NAME, this);

	final String extraCaps = properties
			.getProperty(Constants.FRAMEWORK_SYSTEMCAPABILITIES_EXTRA);
	if (extraCaps != null) {
		final String[] capStrs = Utils.splitString(extraCaps, ',');
		for (final String capStr : capStrs) {
			try {
				final BundleCapabilityImpl cap = new BundleCapabilityImpl(
						this, capStr);
				systemBundleCapabilities.add(cap);
			} catch (final BundleException be) {
				// TODO: to log
				be.printStackTrace();
			}
		}

	}

	// system bundle symbolic name
	final BundleCapabilityImpl sysbundleCap = new BundleCapabilityImpl(
			this, "osgi.wiring.bundle; osgi.wiring.bundle="
					+ Constants.SYSTEM_BUNDLE_SYMBOLICNAME);
	systemBundleCapabilities.add(sysbundleCap);

	// default org.wiring.host property
	final BundleCapabilityImpl sysbundleDefaultHostCap = new BundleCapabilityImpl(
			this, "osgi.wiring.host; osgi.wiring.host="
					+ Constants.SYSTEM_BUNDLE_SYMBOLICNAME);
	systemBundleCapabilities.add(sysbundleDefaultHostCap);

	// concierge specific org.wiring.host property
	final BundleCapabilityImpl sysbundleHostCap = new BundleCapabilityImpl(
			this,
			"osgi.wiring.host; osgi.wiring.host=org.eclipse.concierge");
	systemBundleCapabilities.add(sysbundleHostCap);

	publishCapabilities(systemBundleCapabilities);

	// add to framework wiring
	wirings.put(this, new ConciergeBundleWiring(this, null));

	// initialize the system bundle services
	registeredServices = new ArrayList<ServiceReference<?>>(2);

	// start the logger
	if (LOG_ENABLED) {
		logger = new LogServiceImpl(LOG_BUFFER_SIZE, LOG_LEVEL, LOG_QUIET);
		final ServiceReference<LogService> logref = new ServiceReferenceImpl<LogService>(
				Concierge.this, this, logger, null, new String[] {
						LogService.class.getName(),
						LogReaderService.class.getName() });
		synchronized (serviceRegistry) {
			serviceRegistry.insert(LogService.class.getName(), logref);
			serviceRegistry
					.insert(LogReaderService.class.getName(), logref);
		}

		registeredServices.add(logref);
		if (DEBUG_SERVICES) {
			logger.log(LogService.LOG_DEBUG,
					"Framework has registered LogService and LogReaderService.");
		}
	}

	// set the URLStreamHandlerFactory
	try {
		conciergeURLStreamHandlerFactory.setConcierge(this);
		URL.setURLStreamHandlerFactory(conciergeURLStreamHandlerFactory);
	} catch (final Error e) {
		// already set...
	}

	state = Bundle.STARTING;
}