Example usage for java.net URLStreamHandlerFactory URLStreamHandlerFactory

List of usage examples for java.net URLStreamHandlerFactory URLStreamHandlerFactory

Introduction

In this page you can find the example usage for java.net URLStreamHandlerFactory URLStreamHandlerFactory.

Prototype

URLStreamHandlerFactory

Source Link

Usage

From source file:org.talend.components.api.component.runtime.JarRuntimeInfoTest.java

@BeforeClass
public static void setupMavenUrlHandler() {
    try {/*from  ww w. j av  a2 s.  co  m*/
        new URL("mvn:foo/bar");
    } catch (MalformedURLException e) {
        // handles mvn local repository
        String mvnLocalRepo = System.getProperty("maven.repo.local");
        if (mvnLocalRepo != null) {
            System.setProperty("org.ops4j.pax.url.mvn.localRepository", mvnLocalRepo);
        }
        URL.setURLStreamHandlerFactory(new URLStreamHandlerFactory() {

            @Override
            public URLStreamHandler createURLStreamHandler(String protocol) {
                if (ServiceConstants.PROTOCOL.equals(protocol)) {
                    return new Handler();
                } else {
                    return null;
                }
            }
        });
    }
}

From source file:org.calrissian.mango.jms.stream.JmsFileTransferSupportTest.java

public void testFullCycle() throws Exception {
    try {/*from   w  ww.j  a  va 2s. com*/
        URL.setURLStreamHandlerFactory(new URLStreamHandlerFactory() {

            @Override
            public URLStreamHandler createURLStreamHandler(String protocol) {
                if ("testprot".equals(protocol))
                    return new URLStreamHandler() {

                        @Override
                        protected URLConnection openConnection(URL u) throws IOException {
                            return new URLConnection(u) {

                                @Override
                                public void connect() throws IOException {

                                }

                                @Override
                                public InputStream getInputStream() throws IOException {
                                    return new ByteArrayInputStream(TEST_STR.getBytes());
                                }

                                @Override
                                public String getContentType() {
                                    return "content/notnull";
                                }
                            };
                        }
                    };
                return null;
            }
        });
    } catch (Error ignored) {
    }

    final ActiveMQTopic ft = new ActiveMQTopic("testFileTransfer");

    ThreadPoolTaskExecutor te = new ThreadPoolTaskExecutor();
    te.initialize();

    JmsFileSenderListener listener = new JmsFileSenderListener();
    final String hashAlgorithm = "MD5";
    listener.setHashAlgorithm(hashAlgorithm);
    listener.setStreamRequestDestination(ft);
    listener.setPieceSize(9);
    listener.setTaskExecutor(te);

    ConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false");
    cf = new SingleTopicConnectionFactory(cf, "test");
    JmsTemplate jmsTemplate = new JmsTemplate();
    jmsTemplate.setConnectionFactory(cf);
    jmsTemplate.setReceiveTimeout(60000);
    listener.setJmsTemplate(jmsTemplate);

    Connection conn = cf.createConnection();
    conn.start();
    Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = sess.createConsumer(ft);
    consumer.setMessageListener(listener);

    JmsFileReceiver receiver = new JmsFileReceiver();
    receiver.setHashAlgorithm(hashAlgorithm);
    receiver.setStreamRequestDestination(ft);
    receiver.setJmsTemplate(jmsTemplate);
    receiver.setPieceSize(9);

    JmsFileReceiverInputStream stream = (JmsFileReceiverInputStream) receiver.receiveStream("testprot:test");
    StringBuilder buffer = new StringBuilder();
    int read;
    while ((read = stream.read()) >= 0) {
        buffer.append((char) read);
    }
    stream.close();

    assertEquals(TEST_STR, buffer.toString());

    conn.stop();

}

From source file:com.jtechme.apphub.FDroidApp.java

@TargetApi(9)
@Override//from w  ww.  ja  v a2s .c  om
public void onCreate() {
    if (Build.VERSION.SDK_INT >= 9 && BuildConfig.DEBUG) {
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll().penaltyLog().build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyLog().build());
    }
    updateLanguage();
    super.onCreate();
    ACRA.init(this);

    // Needs to be setup before anything else tries to access it.
    // Perhaps the constructor is a better place, but then again,
    // it is more deterministic as to when this gets called...
    Preferences.setup(this);

    // Apply the Google PRNG fixes to properly seed SecureRandom
    PRNGFixes.apply();

    // Check that the installed app cache hasn't gotten out of sync somehow.
    // e.g. if we crashed/ran out of battery half way through responding
    // to a package installed intent. It doesn't really matter where
    // we put this in the bootstrap process, because it runs on a different
    // thread, which will be delayed by some seconds to avoid an error where
    // the database is locked due to the database updater.
    InstalledAppCacheUpdater.updateInBackground(getApplicationContext());

    // If the user changes the preference to do with filtering rooted apps,
    // it is easier to just notify a change in the app provider,
    // so that the newly updated list will correctly filter relevant apps.
    Preferences.get().registerAppsRequiringRootChangeListener(new Preferences.ChangeListener() {
        @Override
        public void onPreferenceChange() {
            getContentResolver().notifyChange(AppProvider.getContentUri(), null);
        }
    });

    // This is added so that the bluetooth:// scheme we use for URLs the BluetoothDownloader
    // understands is not treated as invalid by the java.net.URL class. The actual Handler does
    // nothing, but its presence is enough.
    URL.setURLStreamHandlerFactory(new URLStreamHandlerFactory() {
        @Override
        public URLStreamHandler createURLStreamHandler(String protocol) {
            return TextUtils.equals(protocol, "bluetooth") ? new Handler() : null;
        }
    });

    final Context context = this;
    Preferences.get().registerUnstableUpdatesChangeListener(new Preferences.ChangeListener() {
        @Override
        public void onPreferenceChange() {
            AppProvider.Helper.calcDetailsFromIndex(context);
        }
    });

    // Clear cached apk files. We used to just remove them after they'd
    // been installed, but this causes problems for proprietary gapps
    // users since the introduction of verification (on pre-4.2 Android),
    // because the install intent says it's finished when it hasn't.
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    curTheme = Theme.valueOf(prefs.getString(Preferences.PREF_THEME, Preferences.DEFAULT_THEME));
    Utils.deleteFiles(Utils.getApkDownloadDir(this), null, ".apk");
    if (!Preferences.get().shouldCacheApks()) {
        Utils.deleteFiles(Utils.getApkCacheDir(this), null, ".apk");
    }

    // Index files which downloaded, but were not removed (e.g. due to F-Droid being force
    // closed during processing of the file, before getting a chance to delete). This may
    // include both "index-*-downloaded" and "index-*-extracted.xml" files. The first is from
    // either signed or unsigned repos, and the later is from signed repos.
    Utils.deleteFiles(getCacheDir(), "index-", null);

    // As above, but for legacy F-Droid clients that downloaded under a different name, and
    // extracted to the files directory rather than the cache directory.
    // TODO: This can be removed in a a few months or a year (e.g. 2016) because people will
    // have upgraded their clients, this code will have executed, and they will not have any
    // left over files any more. Even if they do hold off upgrading until this code is removed,
    // the only side effect is that they will have a few more MiB of storage taken up on their
    // device until they uninstall and re-install F-Droid.
    Utils.deleteFiles(getCacheDir(), "dl-", null);
    Utils.deleteFiles(getFilesDir(), "index-", null);

    UpdateService.schedule(getApplicationContext());
    bluetoothAdapter = getBluetoothAdapter();

    ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
            .imageDownloader(new IconDownloader(getApplicationContext()))
            .diskCache(new LimitedAgeDiskCache(
                    new File(StorageUtils.getCacheDirectory(getApplicationContext(), true), "icons"), null,
                    new FileNameGenerator() {
                        @Override
                        public String generate(String imageUri) {
                            return imageUri.substring(imageUri.lastIndexOf('/') + 1);
                        }
                    },
                    // 30 days in secs: 30*24*60*60 = 2592000
                    2592000))
            .threadPoolSize(4).threadPriority(Thread.NORM_PRIORITY - 2) // Default is NORM_PRIORITY - 1
            .build();
    ImageLoader.getInstance().init(config);

    // TODO reintroduce PinningTrustManager and MemorizingTrustManager

    // initialized the local repo information
    FDroidApp.initWifiSettings();
    startService(new Intent(this, WifiStateChangeService.class));
    // if the HTTPS pref changes, then update all affected things
    Preferences.get().registerLocalRepoHttpsListeners(new ChangeListener() {
        @Override
        public void onPreferenceChange() {
            startService(new Intent(FDroidApp.this, WifiStateChangeService.class));
        }
    });
}

From source file:org.apache.jmeter.protocol.http.util.LoopbackHttpClientSocketFactory.java

/**
 * Convenience method to set up the necessary HttpClient protocol and URL handler.
 *
 * Only works for HttpClient, because it's not possible (or at least very difficult)
 * to provide a different socket factory for the HttpURLConnection class.
 *///w w  w .  j  a v a2s. c o m
public static void setup() {
    final String LOOPBACK = "loopback"; // $NON-NLS-1$

    // This ensures tha HttpClient knows about the protocol
    Protocol.registerProtocol(LOOPBACK, new Protocol(LOOPBACK, new LoopbackHttpClientSocketFactory(), 1));

    // Now allow the URL handling to work.
    URLStreamHandlerFactory ushf = new URLStreamHandlerFactory() {
        @Override
        public URLStreamHandler createURLStreamHandler(String protocol) {
            if (protocol.equalsIgnoreCase(LOOPBACK)) {
                return new URLStreamHandler() {
                    @Override
                    protected URLConnection openConnection(URL u) throws IOException {
                        return null;// not needed for HttpClient
                    }
                };
            }
            return null;
        }
    };

    java.net.URL.setURLStreamHandlerFactory(ushf);
}

From source file:org.fdroid.fdroid.FDroidApp.java

@TargetApi(9)
@Override//from w w w.j a  va2s  . com
public void onCreate() {
    super.onCreate();
    if (Build.VERSION.SDK_INT >= 9 && BuildConfig.DEBUG) {
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll().penaltyLog().build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyLog().build());
    }
    updateLanguage();
    ACRA.init(this);

    // Needs to be setup before anything else tries to access it.
    // Perhaps the constructor is a better place, but then again,
    // it is more deterministic as to when this gets called...
    Preferences.setup(this);
    curTheme = Preferences.get().getTheme();

    // Apply the Google PRNG fixes to properly seed SecureRandom
    PRNGFixes.apply();

    // Check that the installed app cache hasn't gotten out of sync somehow.
    // e.g. if we crashed/ran out of battery half way through responding
    // to a package installed intent. It doesn't really matter where
    // we put this in the bootstrap process, because it runs on a different
    // thread, which will be delayed by some seconds to avoid an error where
    // the database is locked due to the database updater.
    InstalledAppCacheUpdater.updateInBackground(getApplicationContext());

    // make sure the current proxy stuff is configured
    Preferences.get().configureProxy();

    // If the user changes the preference to do with filtering rooted apps,
    // it is easier to just notify a change in the app provider,
    // so that the newly updated list will correctly filter relevant apps.
    Preferences.get().registerAppsRequiringRootChangeListener(new Preferences.ChangeListener() {
        @Override
        public void onPreferenceChange() {
            getContentResolver().notifyChange(AppProvider.getContentUri(), null);
        }
    });

    // This is added so that the bluetooth:// scheme we use for URLs the BluetoothDownloader
    // understands is not treated as invalid by the java.net.URL class. The actual Handler does
    // nothing, but its presence is enough.
    URL.setURLStreamHandlerFactory(new URLStreamHandlerFactory() {
        @Override
        public URLStreamHandler createURLStreamHandler(String protocol) {
            return TextUtils.equals(protocol, "bluetooth") ? new Handler() : null;
        }
    });

    final Context context = this;
    Preferences.get().registerUnstableUpdatesChangeListener(new Preferences.ChangeListener() {
        @Override
        public void onPreferenceChange() {
            AppProvider.Helper.calcDetailsFromIndex(context);
        }
    });

    // Clear cached apk files. We used to just remove them after they'd
    // been installed, but this causes problems for proprietary gapps
    // users since the introduction of verification (on pre-4.2 Android),
    // because the install intent says it's finished when it hasn't.
    if (!Preferences.get().shouldCacheApks()) {
        Utils.deleteFiles(Utils.getApkCacheDir(this), null, ".apk");
    }

    // Index files which downloaded, but were not removed (e.g. due to F-Droid being force
    // closed during processing of the file, before getting a chance to delete). This may
    // include both "index-*-downloaded" and "index-*-extracted.xml" files. The first is from
    // either signed or unsigned repos, and the later is from signed repos.
    Utils.deleteFiles(getCacheDir(), "index-", null);

    // As above, but for legacy F-Droid clients that downloaded under a different name, and
    // extracted to the files directory rather than the cache directory.
    // TODO: This can be removed in a a few months or a year (e.g. 2016) because people will
    // have upgraded their clients, this code will have executed, and they will not have any
    // left over files any more. Even if they do hold off upgrading until this code is removed,
    // the only side effect is that they will have a few more MiB of storage taken up on their
    // device until they uninstall and re-install F-Droid.
    Utils.deleteFiles(getCacheDir(), "dl-", null);
    Utils.deleteFiles(getFilesDir(), "index-", null);

    UpdateService.schedule(getApplicationContext());
    bluetoothAdapter = getBluetoothAdapter();

    ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
            .imageDownloader(new IconDownloader(getApplicationContext()))
            .diskCache(new LimitedAgeDiskCache(
                    new File(StorageUtils.getCacheDirectory(getApplicationContext(), true), "icons"), null,
                    new FileNameGenerator() {
                        @Override
                        public String generate(String imageUri) {
                            return imageUri.substring(imageUri.lastIndexOf('/') + 1);
                        }
                    },
                    // 30 days in secs: 30*24*60*60 = 2592000
                    2592000))
            .threadPoolSize(4).threadPriority(Thread.NORM_PRIORITY - 2) // Default is NORM_PRIORITY - 1
            .build();
    ImageLoader.getInstance().init(config);

    // TODO reintroduce PinningTrustManager and MemorizingTrustManager

    // initialized the local repo information
    FDroidApp.initWifiSettings();
    startService(new Intent(this, WifiStateChangeService.class));
    // if the HTTPS pref changes, then update all affected things
    Preferences.get().registerLocalRepoHttpsListeners(new ChangeListener() {
        @Override
        public void onPreferenceChange() {
            startService(new Intent(FDroidApp.this, WifiStateChangeService.class));
        }
    });

    configureTor(Preferences.get().isTorEnabled());
}

From source file:org.talend.components.marketo.MarketoRuntimeInfoTest.java

@BeforeClass
public static void setupMavenUrlHandler() {
    try {/*from w  ww .j av a  2s  .co  m*/
        new URL("mvn:foo/bar");
    } catch (MalformedURLException e) {
        // handles mvn local repository
        String mvnLocalRepo = System.getProperty("maven.repo.local");
        LOG.info("local repos {}", mvnLocalRepo);
        if (mvnLocalRepo != null) {
            System.setProperty("org.ops4j.pax.url.mvn.localRepository", mvnLocalRepo);
        }
        URL.setURLStreamHandlerFactory(new URLStreamHandlerFactory() {

            @Override
            public URLStreamHandler createURLStreamHandler(String protocol) {
                if (ServiceConstants.PROTOCOL.equals(protocol)) {
                    return new Handler();
                } else {
                    return null;
                }
            }
        });
    }
}