Example usage for java.net URI toURL

List of usage examples for java.net URI toURL

Introduction

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

Prototype

public URL toURL() throws MalformedURLException 

Source Link

Document

Constructs a URL from this URI.

Usage

From source file:com.seajas.search.contender.service.modifier.FeedModifierService.java

/**
 * Retrieve a feed from the URL modified by the relevant modifiers.
 * //  w  ww .  j  a v a  2s  . co  m
 * @param uri
 * @param encodingOverride
 * @param userAgent
 * @param resultHeaders
 * @param suppressErrors
 * @return SyndFeed
 */
public SyndFeed getFeed(URI uri, String encodingOverride, String userAgent,
        Map<String, String> resultParameters, Map<String, String> resultHeaders, Boolean suppressErrors) {
    WebResolverSettings settings = new WebResolverSettings();

    settings.setMaximumContentLength(maximumContentLength);
    settings.setUserAgent(userAgent);
    settings.setResultParameters(resultParameters);
    settings.setResultHeaders(resultHeaders);

    try {
        SyndFeed resultFeed = null;

        // We can only retrieve unmodified feeds using conditional gets

        List<Modifier> modifiers = modifierCache.getFeedModifiersByUrlMatch(uri.toString());

        if (modifiers.size() == 0
                && (uri.getScheme().equalsIgnoreCase("http") || uri.getScheme().equalsIgnoreCase("https"))) {
            if (feedFetcher instanceof HttpClientFeedFetcher)
                resultFeed = ((HttpClientFeedFetcher) feedFetcher).retrieveFeed(userAgent, uri.toURL(),
                        resultHeaders);
            else
                resultFeed = feedFetcher.retrieveFeed(userAgent, uri.toURL());
            WebFeeds.validate(resultFeed, uri);
        } else {
            Reader reader = getContent(uri, encodingOverride, userAgent, resultHeaders);

            if (reader != null) {
                try {
                    // Run it through the modifiers

                    reader = executeModifiers(modifiers, reader, uri, settings);

                    // Fill in the result feed

                    SyndFeedInput feedInput = new SyndFeedInput();

                    resultFeed = feedInput.build(reader);
                } finally {
                    reader.close();
                }
            } else {
                logger.error("No content could be retrieved from the given URL. Skipping feed.");

                return null;
            }
        }

        return resultFeed;
    } catch (FetcherException e) {
        if (!suppressErrors)
            logger.error("Could not retrieve the given feed (" + uri + "): " + e.getMessage());
    } catch (IllegalArgumentException e) {
        if (!suppressErrors)
            logger.error("Could not retrieve the given feed (" + uri + "): " + e.getMessage(), e);
    } catch (FeedException e) {
        if (!suppressErrors)
            logger.error("Could not retrieve the given feed (" + uri + "): " + e.getMessage(), e);
    } catch (ScriptException e) {
        if (!suppressErrors)
            logger.error("Could not retrieve the given feed (" + uri + "): " + e.getMessage(), e);
    } catch (IOException e) {
        if (!suppressErrors)
            logger.error("Could not retrieve the given feed (" + uri + "): " + e.getMessage(), e);
    }

    return null;
}

From source file:jp.ne.sakura.kkkon.java.net.inetaddress.testapp.android.NetworkConnectionCheckerTestApp.java

/** Called when the activity is first created. */
@Override//ww  w. j a va  2s  .c  om
public void onCreate(Bundle savedInstanceState) {
    final Context context = this.getApplicationContext();

    {
        NetworkConnectionChecker.initialize();
    }

    super.onCreate(savedInstanceState);

    /* Create a TextView and set its content.
     * the text is retrieved by calling a native
     * function.
     */
    LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.VERTICAL);

    TextView tv = new TextView(this);
    tv.setText("reachable=");
    layout.addView(tv);
    this.textView = tv;

    Button btn1 = new Button(this);
    btn1.setText("invoke Exception");
    btn1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            final int count = 2;
            int[] array = new int[count];
            int value = array[count]; // invoke IndexOutOfBOundsException
        }
    });
    layout.addView(btn1);

    {
        Button btn = new Button(this);
        btn.setText("disp isReachable");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                final boolean isReachable = NetworkConnectionChecker.isReachable();
                Toast toast = Toast.makeText(context, "IsReachable=" + isReachable, Toast.LENGTH_LONG);
                toast.show();
            }
        });
        layout.addView(btn);
    }

    {
        Button btn = new Button(this);
        btn.setText("upload http AsyncTask");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                AsyncTask<String, Void, Boolean> asyncTask = new AsyncTask<String, Void, Boolean>() {

                    @Override
                    protected Boolean doInBackground(String... paramss) {
                        Boolean result = true;
                        Log.d(TAG, "upload AsyncTask tid=" + android.os.Process.myTid());
                        try {
                            //$(BRAND)/$(PRODUCT)/$(DEVICE)/$(BOARD):$(VERSION.RELEASE)/$(ID)/$(VERSION.INCREMENTAL):$(TYPE)/$(TAGS)
                            Log.d(TAG, "fng=" + Build.FINGERPRINT);
                            final List<NameValuePair> list = new ArrayList<NameValuePair>(16);
                            list.add(new BasicNameValuePair("fng", Build.FINGERPRINT));

                            HttpPost httpPost = new HttpPost(paramss[0]);
                            //httpPost.getParams().setParameter( CoreConnectionPNames.SO_TIMEOUT, new Integer(5*1000) );
                            httpPost.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
                            DefaultHttpClient httpClient = new DefaultHttpClient();
                            Log.d(TAG, "socket.timeout=" + httpClient.getParams()
                                    .getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1));
                            Log.d(TAG, "connection.timeout=" + httpClient.getParams()
                                    .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1));
                            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
                                    new Integer(5 * 1000));
                            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
                                    new Integer(5 * 1000));
                            Log.d(TAG, "socket.timeout=" + httpClient.getParams()
                                    .getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1));
                            Log.d(TAG, "connection.timeout=" + httpClient.getParams()
                                    .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1));
                            // <uses-permission android:name="android.permission.INTERNET"/>
                            // got android.os.NetworkOnMainThreadException, run at UI Main Thread
                            HttpResponse response = httpClient.execute(httpPost);
                            Log.d(TAG, "response=" + response.getStatusLine().getStatusCode());
                        } catch (Exception e) {
                            Log.d(TAG, "got Exception. msg=" + e.getMessage(), e);
                            result = false;
                        }
                        Log.d(TAG, "upload finish");
                        return result;
                    }

                };

                asyncTask.execute("http://kkkon.sakura.ne.jp/android/bug");
                asyncTask.isCancelled();
            }
        });
        layout.addView(btn);
    }

    {
        Button btn = new Button(this);
        btn.setText("pre DNS query(0.0.0.0)");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                isReachable = false;
                Thread thread = new Thread(new Runnable() {

                    public void run() {
                        try {
                            destHost = InetAddress.getByName("0.0.0.0");
                            if (null != destHost) {
                                try {
                                    if (destHost.isReachable(5 * 1000)) {
                                        Log.d(TAG, "destHost=" + destHost.toString() + " reachable");
                                    } else {
                                        Log.d(TAG, "destHost=" + destHost.toString() + " not reachable");
                                    }
                                } catch (IOException e) {

                                }
                            }
                        } catch (UnknownHostException e) {

                        }
                        Log.d(TAG, "destHost=" + destHost);
                    }
                });
                thread.start();
                try {
                    thread.join(1000);
                } catch (InterruptedException e) {

                }
            }
        });
        layout.addView(btn);
    }
    {
        Button btn = new Button(this);
        btn.setText("pre DNS query(www.google.com)");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                isReachable = false;
                Thread thread = new Thread(new Runnable() {

                    public void run() {
                        Log.d(TAG, "start");
                        try {
                            InetAddress dest = InetAddress.getByName("www.google.com");
                            if (null == dest) {
                                dest = destHost;
                            }

                            if (null != dest) {
                                final String[] uris = new String[] { "http://www.google.com/",
                                        "https://www.google.com/" };
                                for (final String destURI : uris) {
                                    URI uri = null;
                                    try {
                                        uri = new URI(destURI);
                                    } catch (URISyntaxException e) {
                                        //Log.d( TAG, e.toString() );
                                    }

                                    if (null != uri) {
                                        URL url = null;
                                        try {
                                            url = uri.toURL();
                                        } catch (MalformedURLException ex) {
                                            Log.d(TAG, "got exception:" + ex.toString(), ex);
                                        }

                                        URLConnection conn = null;
                                        if (null != url) {
                                            Log.d(TAG, "openConnection before");
                                            try {
                                                conn = url.openConnection();
                                                if (null != conn) {
                                                    conn.setConnectTimeout(3 * 1000);
                                                    conn.setReadTimeout(3 * 1000);
                                                }
                                            } catch (IOException e) {
                                                //Log.d( TAG, "got Exception" + e.toString(), e );
                                            }
                                            Log.d(TAG, "openConnection after");
                                            if (conn instanceof HttpURLConnection) {
                                                HttpURLConnection httpConn = (HttpURLConnection) conn;
                                                int responceCode = -1;
                                                try {
                                                    Log.d(TAG, "getResponceCode before");
                                                    responceCode = httpConn.getResponseCode();
                                                    Log.d(TAG, "getResponceCode after");
                                                } catch (IOException ex) {
                                                    Log.d(TAG, "got exception:" + ex.toString(), ex);
                                                }
                                                Log.d(TAG, "responceCode=" + responceCode);
                                                if (0 < responceCode) {
                                                    isReachable = true;
                                                    destHost = dest;
                                                }
                                                Log.d(TAG,
                                                        " HTTP ContentLength=" + httpConn.getContentLength());
                                                httpConn.disconnect();
                                                Log.d(TAG,
                                                        " HTTP ContentLength=" + httpConn.getContentLength());
                                            }
                                        }
                                    } // if uri

                                    if (isReachable) {
                                        //break;
                                    }
                                } // for uris
                            } else {
                            }
                        } catch (UnknownHostException e) {
                            Log.d(TAG, "dns error" + e.toString());
                            destHost = null;
                        }
                        {
                            if (null != destHost) {
                                Log.d(TAG, "destHost=" + destHost);
                            }
                        }
                        Log.d(TAG, "end");
                    }
                });
                thread.start();
                try {
                    thread.join();
                    {
                        final String addr = (null == destHost) ? ("") : (destHost.toString());
                        final String reachable = (isReachable) ? ("reachable") : ("not reachable");
                        Toast toast = Toast.makeText(context, "DNS result=\n" + addr + "\n " + reachable,
                                Toast.LENGTH_LONG);
                        toast.show();
                    }
                } catch (InterruptedException e) {

                }
            }
        });
        layout.addView(btn);
    }

    {
        Button btn = new Button(this);
        btn.setText("pre DNS query(kkkon.sakura.ne.jp)");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                isReachable = false;
                Thread thread = new Thread(new Runnable() {

                    public void run() {
                        Log.d(TAG, "start");
                        try {
                            InetAddress dest = InetAddress.getByName("kkkon.sakura.ne.jp");
                            if (null == dest) {
                                dest = destHost;
                            }
                            if (null != dest) {
                                try {
                                    if (dest.isReachable(5 * 1000)) {
                                        Log.d(TAG, "destHost=" + dest.toString() + " reachable");
                                        isReachable = true;
                                    } else {
                                        Log.d(TAG, "destHost=" + dest.toString() + " not reachable");
                                    }
                                    destHost = dest;
                                } catch (IOException e) {

                                }
                            } else {
                            }
                        } catch (UnknownHostException e) {
                            Log.d(TAG, "dns error" + e.toString());
                            destHost = null;
                        }
                        {
                            if (null != destHost) {
                                Log.d(TAG, "destHost=" + destHost);
                            }
                        }
                        Log.d(TAG, "end");
                    }
                });
                thread.start();
                try {
                    thread.join();
                    {
                        final String addr = (null == destHost) ? ("") : (destHost.toString());
                        final String reachable = (isReachable) ? ("reachable") : ("not reachable");
                        Toast toast = Toast.makeText(context, "DNS result=\n" + addr + "\n " + reachable,
                                Toast.LENGTH_LONG);
                        toast.show();
                    }
                } catch (InterruptedException e) {

                }
            }
        });
        layout.addView(btn);
    }

    {
        Button btn = new Button(this);
        btn.setText("pre DNS query(kkkon.sakura.ne.jp) support proxy");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                isReachable = false;
                Thread thread = new Thread(new Runnable() {

                    public void run() {
                        try {
                            String target = null;
                            {
                                ProxySelector proxySelector = ProxySelector.getDefault();
                                Log.d(TAG, "proxySelector=" + proxySelector);
                                if (null != proxySelector) {
                                    URI uri = null;
                                    try {
                                        uri = new URI("http://www.google.com/");
                                    } catch (URISyntaxException e) {
                                        Log.d(TAG, e.toString());
                                    }
                                    List<Proxy> proxies = proxySelector.select(uri);
                                    if (null != proxies) {
                                        for (final Proxy proxy : proxies) {
                                            Log.d(TAG, " proxy=" + proxy);
                                            if (null != proxy) {
                                                if (Proxy.Type.HTTP == proxy.type()) {
                                                    final SocketAddress sa = proxy.address();
                                                    if (sa instanceof InetSocketAddress) {
                                                        final InetSocketAddress isa = (InetSocketAddress) sa;
                                                        target = isa.getHostName();
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            if (null == target) {
                                target = "kkkon.sakura.ne.jp";
                            }
                            InetAddress dest = InetAddress.getByName(target);
                            if (null == dest) {
                                dest = destHost;
                            }
                            if (null != dest) {
                                try {
                                    if (dest.isReachable(5 * 1000)) {
                                        Log.d(TAG, "destHost=" + dest.toString() + " reachable");
                                        isReachable = true;
                                    } else {
                                        Log.d(TAG, "destHost=" + dest.toString() + " not reachable");
                                        {
                                            ProxySelector proxySelector = ProxySelector.getDefault();
                                            //Log.d( TAG, "proxySelector=" + proxySelector );
                                            if (null != proxySelector) {
                                                URI uri = null;
                                                try {
                                                    uri = new URI("http://www.google.com/");
                                                } catch (URISyntaxException e) {
                                                    //Log.d( TAG, e.toString() );
                                                }

                                                if (null != uri) {
                                                    List<Proxy> proxies = proxySelector.select(uri);
                                                    if (null != proxies) {
                                                        for (final Proxy proxy : proxies) {
                                                            //Log.d( TAG, " proxy=" + proxy );
                                                            if (null != proxy) {
                                                                if (Proxy.Type.HTTP == proxy.type()) {
                                                                    URL url = uri.toURL();
                                                                    URLConnection conn = null;
                                                                    if (null != url) {
                                                                        try {
                                                                            conn = url.openConnection(proxy);
                                                                            if (null != conn) {
                                                                                conn.setConnectTimeout(
                                                                                        3 * 1000);
                                                                                conn.setReadTimeout(3 * 1000);
                                                                            }
                                                                        } catch (IOException e) {
                                                                            Log.d(TAG, "got Exception"
                                                                                    + e.toString(), e);
                                                                        }
                                                                        if (conn instanceof HttpURLConnection) {
                                                                            HttpURLConnection httpConn = (HttpURLConnection) conn;
                                                                            if (0 < httpConn
                                                                                    .getResponseCode()) {
                                                                                isReachable = true;
                                                                            }
                                                                            Log.d(TAG, " HTTP ContentLength="
                                                                                    + httpConn
                                                                                            .getContentLength());
                                                                            Log.d(TAG, " HTTP res=" + httpConn
                                                                                    .getResponseCode());
                                                                            //httpConn.setInstanceFollowRedirects( false );
                                                                            //httpConn.setRequestMethod( "HEAD" );
                                                                            //conn.connect();
                                                                            httpConn.disconnect();
                                                                            Log.d(TAG, " HTTP ContentLength="
                                                                                    + httpConn
                                                                                            .getContentLength());
                                                                            Log.d(TAG, " HTTP res=" + httpConn
                                                                                    .getResponseCode());
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }

                                    }
                                    destHost = dest;
                                } catch (IOException e) {
                                    Log.d(TAG, "got Excpetion " + e.toString());
                                }
                            } else {
                            }
                        } catch (UnknownHostException e) {
                            Log.d(TAG, "dns error" + e.toString());
                            destHost = null;
                        }
                        {
                            if (null != destHost) {
                                Log.d(TAG, "destHost=" + destHost);
                            }
                        }
                    }
                });
                thread.start();
                try {
                    thread.join();
                    {
                        final String addr = (null == destHost) ? ("") : (destHost.toString());
                        final String reachable = (isReachable) ? ("reachable") : ("not reachable");
                        Toast toast = Toast.makeText(context, "DNS result=\n" + addr + "\n " + reachable,
                                Toast.LENGTH_LONG);
                        toast.show();
                    }
                } catch (InterruptedException e) {

                }
            }
        });
        layout.addView(btn);
    }

    setContentView(layout);
}

From source file:org.limewire.util.IOUtils.java

/**
 * Get the contents of a <code>URI</code> as a <code>byte[]</code>.
 * /*from w ww .  j a va2 s  .c  o m*/
 * @param uri
 *            the <code>URI</code> to read
 * @return the requested byte array
 * @throws NullPointerException
 *             if the uri is null
 * @throws IOException
 *             if an I/O exception occurs
 * @since 2.4
 */
public static byte[] toByteArray(URI uri) throws IOException {
    return IOUtils.toByteArray(uri.toURL());
}

From source file:microsoft.exchange.webservices.data.ExchangeServiceBase.java

/**
 * Creates an HttpWebRequest instance and initialises it with the
 * appropriate parameters, based on the configuration of this service
 * object./*from w w  w. jav  a2  s  . com*/
 *
 * @param url                The URL that the HttpWebRequest should target.
 * @param acceptGzipEncoding If true, ask server for GZip compressed content.
 * @param allowAutoRedirect  If true, redirection responses will be automatically followed.
 * @return An initialised instance of HttpWebRequest.
 * @throws ServiceLocalException       the service local exception
 * @throws java.net.URISyntaxException the uRI syntax exception
 */
protected HttpWebRequest prepareHttpWebRequestForUrl(URI url, boolean acceptGzipEncoding,
        boolean allowAutoRedirect) throws ServiceLocalException, URISyntaxException {
    // Verify that the protocol is something that we can handle
    if (!url.getScheme().equalsIgnoreCase("HTTP") && !url.getScheme().equalsIgnoreCase("HTTPS")) {
        String strErr = String.format(Strings.UnsupportedWebProtocol, url.getScheme());
        throw new ServiceLocalException(strErr);
    }

    request = new HttpClientWebRequest(this.httpConnectionManager);
    try {
        request.setUrl(url.toURL());
    } catch (MalformedURLException e) {
        String strErr = String.format("Incorrect format : %s", url);
        throw new ServiceLocalException(strErr);
    }
    request.setPreAuthenticate(this.preAuthenticate);
    request.setTimeout(this.timeout);
    request.setContentType("text/xml; charset=utf-8");
    request.setAccept("text/xml");
    request.setUserAgent(this.userAgent);
    request.setAllowAutoRedirect(allowAutoRedirect);
    //request.setKeepAlive(true);

    if (acceptGzipEncoding) {
        request.setAcceptGzipEncoding(acceptGzipEncoding);
    }

    if (this.webProxy != null) {
        request.setProxy(this.webProxy);
    }

    //if (this.getHttpHeaders().size() > 0){
    request.setHeaders(this.getHttpHeaders());
    //}

    request.setUseDefaultCredentials(useDefaultCredentials);
    if (!useDefaultCredentials) {
        ExchangeCredentials serviceCredentials = this.credentials;
        if (null == serviceCredentials) {
            throw new ServiceLocalException(Strings.CredentialsRequired);
        }

        if (cookieStore != null) {
            request.setUserCookie(cookieStore.getCookies());
        }

        // Make sure that credentials have been authenticated if required
        serviceCredentials.preAuthenticate();

        // Apply credentials to the request
        serviceCredentials.prepareWebRequest(request);
    }

    try {
        request.prepareConnection();
    } catch (Exception e) {
        String strErr = String.format("%s : Connection error ", url);
        throw new ServiceLocalException(strErr);
    }

    this.httpResponseHeaders.clear();

    return request;
}

From source file:launcher.net.CustomIOUtils.java

/**
 * Get the contents of a <code>URI</code> as a <code>byte[]</code>.
 * //from w ww. ja v  a  2 s. c o m
 * @param uri
 *            the <code>URI</code> to read
 * @return the requested byte array
 * @throws NullPointerException
 *             if the uri is null
 * @throws IOException
 *             if an I/O exception occurs
 * @since 2.4
 */
public static byte[] toByteArray(URI uri) throws IOException {
    return CustomIOUtils.toByteArray(uri.toURL());
}

From source file:launcher.net.CustomIOUtils.java

/**
 * Gets the contents at the given URI./*from   w  w  w . j  ava2 s  .co  m*/
 * 
 * @param uri
 *            The URI source.
 * @param encoding
 *            The encoding name for the URL contents.
 * @return The contents of the URL as a String.
 * @throws IOException if an I/O exception occurs.
 * @since 2.3.
 */
public static String toString(URI uri, Charset encoding) throws IOException {
    return toString(uri.toURL(), Charsets.toCharset(encoding));
}

From source file:net.pms.dlna.RootFolder.java

/**
 * Returns iTunes folder. Used by manageRoot, so it is usually used as a
 * folder at the root folder. Only works on Mac OS X or Windows.
 *
 * The iTunes XML is parsed fully when this method is called, so it can
 * take some time for larger (+1000 albums) databases.
 *
 * This method does not support genius playlists and does not provide a
 * media library./*  w ww. j a v a2  s .  c o  m*/
 *
 * @see RootFolder#getiTunesFile()
 */
private DLNAResource getiTunesFolder() {
    DLNAResource res = null;

    logger.info("Start building iTunes folder...");

    if (Platform.isMac() || Platform.isWindows()) {
        Map<String, Object> iTunesLib;
        List<?> Playlists;
        Map<?, ?> Playlist;
        Map<?, ?> Tracks;
        Map<?, ?> track;
        List<?> PlaylistTracks;

        try {
            String iTunesFile = getiTunesFile();

            if (iTunesFile != null && (new File(iTunesFile)).exists()) {
                iTunesLib = Plist.load(URLDecoder.decode(iTunesFile, System.getProperty("file.encoding"))); // loads the (nested) properties.
                Tracks = (Map<?, ?>) iTunesLib.get("Tracks"); // the list of tracks
                Playlists = (List<?>) iTunesLib.get("Playlists"); // the list of Playlists
                res = new VirtualFolder("iTunes Library", null);

                VirtualFolder playlistsFolder = null;

                for (Object item : Playlists) {
                    Playlist = (Map<?, ?>) item;

                    if (Playlist.containsKey("Visible") && Playlist.get("Visible").equals(Boolean.FALSE))
                        continue;

                    if (Playlist.containsKey("Music") && Playlist.get("Music").equals(Boolean.TRUE)) {
                        // Create virtual folders for artists, albums and genres

                        VirtualFolder musicFolder = new VirtualFolder(Playlist.get("Name").toString(), null);
                        res.addChild(musicFolder);

                        VirtualFolder virtualFolderArtists = new VirtualFolder(Messages.getString("PMS.13"),
                                null);
                        VirtualFolder virtualFolderAlbums = new VirtualFolder(Messages.getString("PMS.16"),
                                null);
                        VirtualFolder virtualFolderGenres = new VirtualFolder(Messages.getString("PMS.19"),
                                null);
                        VirtualFolder virtualFolderAllTracks = new VirtualFolder(Messages.getString("PMS.11"),
                                null);

                        PlaylistTracks = (List<?>) Playlist.get("Playlist Items"); // list of tracks in a playlist

                        String artistName;
                        String albumName;
                        String genreName;
                        if (PlaylistTracks != null) {
                            for (Object t : PlaylistTracks) {
                                Map<?, ?> td = (Map<?, ?>) t;
                                track = (Map<?, ?>) Tracks.get(td.get("Track ID").toString());

                                if (track != null && track.get("Location") != null
                                        && track.get("Location").toString().startsWith("file://")) {

                                    String name = Normalizer.normalize((String) track.get("Name"),
                                            Normalizer.Form.NFC);
                                    // remove dots from name to prevent media renderer from trimming
                                    name = name.replace('.', '-');

                                    if (track.containsKey("Protected")
                                            && track.get("Protected").equals(Boolean.TRUE))
                                        name = String.format(Messages.getString("RootFolder.1"), name);

                                    boolean isCompilation = (track.containsKey("Compilation")
                                            && track.get("Compilation").equals(Boolean.TRUE));

                                    artistName = (String) (isCompilation ? "Compilation"
                                            : track.containsKey("Album Artist") ? track.get("Album Artist")
                                                    : track.get("Artist"));
                                    albumName = (String) track.get("Album");
                                    genreName = (String) track.get("Genre");

                                    if (artistName == null) {
                                        artistName = "Unknown Artist";
                                    } else {
                                        artistName = Normalizer.normalize(artistName, Normalizer.Form.NFC);
                                    }

                                    if (albumName == null) {
                                        albumName = "Unknown Album";
                                    } else {
                                        albumName = Normalizer.normalize(albumName, Normalizer.Form.NFC);
                                    }

                                    if (genreName == null) {
                                        genreName = "Unknown Genre";
                                    } else if ("".equals(genreName.replaceAll("[^a-zA-Z]", ""))) {
                                        // This prevents us from adding blank or numerical genres
                                        genreName = "Unknown Genre";
                                    } else {
                                        genreName = Normalizer.normalize(genreName, Normalizer.Form.NFC);
                                    }

                                    // Replace &nbsp with space and then trim
                                    artistName = artistName.replace('\u0160', ' ').trim();
                                    albumName = albumName.replace('\u0160', ' ').trim();
                                    genreName = genreName.replace('\u0160', ' ').trim();

                                    URI tURI2 = new URI(track.get("Location").toString());
                                    File refFile = new File(
                                            URLDecoder.decode(tURI2.toURL().getFile(), "UTF-8"));
                                    RealFile file = new RealFile(refFile, name);

                                    // ARTISTS FOLDER - Put the track into the artist's album folder and the artist's "All tracks" folder
                                    {
                                        VirtualFolder individualArtistFolder = null;
                                        VirtualFolder individualArtistAllTracksFolder = null;
                                        VirtualFolder individualArtistAlbumFolder = null;

                                        for (DLNAResource artist : virtualFolderArtists.getChildren()) {
                                            if (areNamesEqual(artist.getName(), artistName)) {
                                                individualArtistFolder = (VirtualFolder) artist;
                                                for (DLNAResource album : individualArtistFolder
                                                        .getChildren()) {
                                                    if (areNamesEqual(album.getName(), albumName)) {
                                                        individualArtistAlbumFolder = (VirtualFolder) album;
                                                    }
                                                }
                                                break;
                                            }
                                        }

                                        if (individualArtistFolder == null) {
                                            individualArtistFolder = new VirtualFolder(artistName, null);
                                            virtualFolderArtists.addChild(individualArtistFolder);
                                            individualArtistAllTracksFolder = new VirtualFolder(
                                                    Messages.getString("PMS.11"), null);
                                            individualArtistFolder.addChild(individualArtistAllTracksFolder);
                                        } else {
                                            individualArtistAllTracksFolder = (VirtualFolder) individualArtistFolder
                                                    .getChildren().get(0);
                                        }

                                        if (individualArtistAlbumFolder == null) {
                                            individualArtistAlbumFolder = new VirtualFolder(albumName, null);
                                            individualArtistFolder.addChild(individualArtistAlbumFolder);
                                        }

                                        individualArtistAlbumFolder.addChild(file.clone());
                                        individualArtistAllTracksFolder.addChild(file);
                                    }

                                    // ALBUMS FOLDER - Put the track into its album folder
                                    {
                                        if (!isCompilation)
                                            albumName += "  " + artistName;

                                        VirtualFolder individualAlbumFolder = null;
                                        for (DLNAResource album : virtualFolderAlbums.getChildren()) {
                                            if (areNamesEqual(album.getName(), albumName)) {
                                                individualAlbumFolder = (VirtualFolder) album;
                                                break;
                                            }
                                        }
                                        if (individualAlbumFolder == null) {
                                            individualAlbumFolder = new VirtualFolder(albumName, null);
                                            virtualFolderAlbums.addChild(individualAlbumFolder);
                                        }
                                        individualAlbumFolder.addChild(file.clone());
                                    }

                                    // GENRES FOLDER - Put the track into its genre folder
                                    {
                                        VirtualFolder individualGenreFolder = null;
                                        for (DLNAResource genre : virtualFolderGenres.getChildren()) {
                                            if (areNamesEqual(genre.getName(), genreName)) {
                                                individualGenreFolder = (VirtualFolder) genre;
                                                break;
                                            }
                                        }
                                        if (individualGenreFolder == null) {
                                            individualGenreFolder = new VirtualFolder(genreName, null);
                                            virtualFolderGenres.addChild(individualGenreFolder);
                                        }
                                        individualGenreFolder.addChild(file.clone());
                                    }

                                    // ALL TRACKS - Put the track into the global "All tracks" folder
                                    virtualFolderAllTracks.addChild(file.clone());
                                }
                            }
                        }

                        musicFolder.addChild(virtualFolderArtists);
                        musicFolder.addChild(virtualFolderAlbums);
                        musicFolder.addChild(virtualFolderGenres);
                        musicFolder.addChild(virtualFolderAllTracks);

                        // Sort the virtual folders alphabetically
                        Collections.sort(virtualFolderArtists.getChildren(), new Comparator<DLNAResource>() {
                            @Override
                            public int compare(DLNAResource o1, DLNAResource o2) {
                                VirtualFolder a = (VirtualFolder) o1;
                                VirtualFolder b = (VirtualFolder) o2;
                                return a.getName().compareToIgnoreCase(b.getName());
                            }
                        });

                        Collections.sort(virtualFolderAlbums.getChildren(), new Comparator<DLNAResource>() {
                            @Override
                            public int compare(DLNAResource o1, DLNAResource o2) {
                                VirtualFolder a = (VirtualFolder) o1;
                                VirtualFolder b = (VirtualFolder) o2;
                                return a.getName().compareToIgnoreCase(b.getName());
                            }
                        });

                        Collections.sort(virtualFolderGenres.getChildren(), new Comparator<DLNAResource>() {
                            @Override
                            public int compare(DLNAResource o1, DLNAResource o2) {
                                VirtualFolder a = (VirtualFolder) o1;
                                VirtualFolder b = (VirtualFolder) o2;
                                return a.getName().compareToIgnoreCase(b.getName());
                            }
                        });

                    } else {
                        // Add all playlists
                        VirtualFolder pf = new VirtualFolder(Playlist.get("Name").toString(), null);
                        PlaylistTracks = (List<?>) Playlist.get("Playlist Items"); // list of tracks in a playlist

                        if (PlaylistTracks != null) {
                            for (Object t : PlaylistTracks) {
                                Map<?, ?> td = (Map<?, ?>) t;
                                track = (Map<?, ?>) Tracks.get(td.get("Track ID").toString());

                                if (track != null && track.get("Location") != null
                                        && track.get("Location").toString().startsWith("file://")) {
                                    String name = Normalizer.normalize(track.get("Name").toString(),
                                            Normalizer.Form.NFC);
                                    // remove dots from name to prevent media renderer from trimming
                                    name = name.replace('.', '-');

                                    if (track.containsKey("Protected")
                                            && track.get("Protected").equals(Boolean.TRUE))
                                        name = String.format(Messages.getString("RootFolder.1"), name);

                                    URI tURI2 = new URI(track.get("Location").toString());
                                    RealFile file = new RealFile(
                                            new File(URLDecoder.decode(tURI2.toURL().getFile(), "UTF-8")),
                                            name);
                                    pf.addChild(file);
                                }
                            }
                        }

                        int kind = Playlist.containsKey("Distinguished Kind")
                                ? ((Number) Playlist.get("Distinguished Kind")).intValue()
                                : -1;
                        if (kind >= 0 && kind != 17 && kind != 19 && kind != 20) {
                            // System folder, but not voice memos (17) and purchased items (19 & 20)
                            res.addChild(pf);

                        } else {
                            // User playlist or playlist folder
                            if (playlistsFolder == null) {
                                playlistsFolder = new VirtualFolder("Playlists", null);
                                res.addChild(playlistsFolder);
                            }
                            playlistsFolder.addChild(pf);
                        }
                    }
                }
            } else {
                logger.info("Could not find the iTunes file");
            }
        } catch (Exception e) {
            logger.error("Something went wrong with the iTunes Library scan: ", e);
        }
    }

    logger.info("Done building iTunes folder.");

    return res;
}

From source file:org.opendatakit.api.odktables.TableService.java

private TableResource getResource(UriInfo info, String appId, TableEntry entry) {
    String tableId = entry.getTableId();
    String schemaETag = entry.getSchemaETag();

    UriBuilder uriBuilder = info.getBaseUriBuilder();
    uriBuilder.path(OdkTables.class);
    uriBuilder.path(OdkTables.class, "getTablesService");
    URI self = uriBuilder.clone().build(appId, tableId);
    UriBuilder realized = uriBuilder.clone().path(TableService.class, "getRealizedTable");
    URI data = realized.clone().path(RealizedTableService.class, "getData").build(appId, tableId, schemaETag);
    URI instanceFiles = realized.clone().path(RealizedTableService.class, "getInstanceFileService").build(appId,
            tableId, schemaETag);/*from  w ww. j a va 2  s .  c  o m*/
    URI diff = realized.clone().path(RealizedTableService.class, "getDiff").build(appId, tableId, schemaETag);
    URI acl = uriBuilder.clone().path(TableService.class, "getAcl").build(appId, tableId);
    URI definition = realized.clone().build(appId, tableId, schemaETag);

    TableResource resource = new TableResource(entry);
    try {
        resource.setSelfUri(self.toURL().toExternalForm());
        resource.setDefinitionUri(definition.toURL().toExternalForm());
        resource.setDataUri(data.toURL().toExternalForm());
        resource.setInstanceFilesUri(instanceFiles.toURL().toExternalForm());
        resource.setDiffUri(diff.toURL().toExternalForm());
        resource.setAclUri(acl.toURL().toExternalForm());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    return resource;
}

From source file:org.codice.alliance.nsili.client.SampleNsiliClient.java

public void downloadProductFromDAG(DAG dag) {
    LOGGER.info("Downloading products...");

    for (Node node : dag.nodes) {
        if (node.attribute_name.equals(NsiliConstants.PRODUCT_URL)) {
            URI fileDownloadUri = null;
            try {
                fileDownloadUri = getEncodedUriFromString(node.value.extract_string());
            } catch (URISyntaxException | MalformedURLException e) {
                LOGGER.error("Unable to encode fileDownloadUrl. {}", e);
                return;
            }/*from   w w w. jav  a  2s  .  c  om*/

            final String productPath = "product.jpg";
            LOGGER.info("Downloading product : {}", fileDownloadUri);
            try {
                try (BufferedInputStream inputStream = new BufferedInputStream(
                        fileDownloadUri.toURL().openStream());
                        FileOutputStream outputStream = new FileOutputStream(new File(productPath))) {

                    final byte data[] = new byte[1024];
                    int count;
                    while ((count = inputStream.read(data, 0, 1024)) != -1) {
                        outputStream.write(data, 0, count);
                    }

                    LOGGER.info("Successfully downloaded product from {}.", fileDownloadUri);
                    Files.deleteIfExists(Paths.get(productPath));
                }
            } catch (IOException e) {
                LOGGER.error("Unable to download product from {}.", fileDownloadUri, e);
            }
        }
    }
}