Example usage for java.net MalformedURLException printStackTrace

List of usage examples for java.net MalformedURLException printStackTrace

Introduction

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

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:eu.codeplumbers.cosi.services.CosiFileService.java

private void getAllRemoteFiles() {
    URL urlO = null;//from  w  w w. j  a  va2  s . co  m
    try {
        urlO = new URL(fileUrl);
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        // read the response
        int status = conn.getResponseCode();
        InputStream in = null;

        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            in = conn.getErrorStream();
        } else {
            in = conn.getInputStream();
        }

        StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "UTF-8");
        String result = writer.toString();

        JSONArray jsonArray = new JSONArray(result);

        if (jsonArray != null) {
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject fileJson = jsonArray.getJSONObject(i).getJSONObject("value");
                File file = File.getByRemoteId(fileJson.get("_id").toString());

                if (file == null) {
                    file = new File(fileJson, false);
                } else {
                    file.setName(fileJson.getString("name"));
                    file.setPath(fileJson.getString("path"));
                    file.setCreationDate(fileJson.getString("creationDate"));
                    file.setLastModification(fileJson.getString("lastModification"));
                    file.setTags(fileJson.getString("tags"));

                    if (fileJson.has("binary")) {
                        file.setBinary(fileJson.getJSONObject("binary").toString());
                    }

                    file.setIsFile(true);
                    file.setFileClass(fileJson.getString("class"));
                    file.setMimeType(fileJson.getString("mime"));
                    file.setSize(fileJson.getLong("size"));
                }

                mBuilder.setProgress(jsonArray.length(), i, false);
                mBuilder.setContentText("Indexing file : " + file.getName());
                mNotifyManager.notify(notification_id, mBuilder.build());

                EventBus.getDefault()
                        .post(new FileSyncEvent(SYNC_MESSAGE, "Indexing file : " + file.getName()));

                file.setDownloaded(FileUtils.checkFileExists(Environment.getExternalStorageDirectory()
                        + java.io.File.separator + Constants.APP_DIRECTORY + java.io.File.separator + "files"
                        + file.getPath() + "/" + file.getName()));
                file.save();

                allFiles.add(file);
            }
        } else {
            EventBus.getDefault()
                    .post(new FileSyncEvent(SERVICE_ERROR, new JSONObject(result).getString("error")));
            mNotifyManager.notify(notification_id, mBuilder.build());
            stopSelf();
        }

        in.close();
        conn.disconnect();

    } catch (MalformedURLException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (ProtocolException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (IOException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (JSONException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    }
}

From source file:net.andylizi.colormotd.anim.updater.Updater.java

private boolean checkUpdate() {
    if (new File(Bukkit.getUpdateFolderFile(), fileName).exists()) {
        cancel();//from  w  ww  .ja  v a 2s . c o  m
    }
    URL url;
    try {
        url = new URL(UPDATE_URL);
    } catch (MalformedURLException ex) {
        if (DEBUG) {
            ex.printStackTrace();
        }
        return false;
    }
    try {
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setUseCaches(false);
        conn.setRequestMethod("GET");
        conn.addRequestProperty("User-Agent", USER_AGENT);
        if (etag != null) {
            conn.addRequestProperty("If-None-Match", etag);
        }
        conn.addRequestProperty("Accept", "application/json,text/plain,*/*;charset=utf-8");
        conn.addRequestProperty("Accept-Encoding", "gzip");
        conn.addRequestProperty("Cache-Control", "no-cache");
        conn.addRequestProperty("Date", new Date().toString());
        conn.addRequestProperty("Connection", "close");

        conn.setDoInput(true);
        conn.setDoOutput(false);
        conn.setConnectTimeout(2000);
        conn.setReadTimeout(2000);

        conn.connect();

        if (conn.getHeaderField("ETag") != null) {
            etag = conn.getHeaderField("ETag");
        }
        if (DEBUG) {
            logger.log(Level.INFO, "DEBUG ResponseCode: {0}", conn.getResponseCode());
            logger.log(Level.INFO, "DEBUG ETag: {0}", etag);
        }
        if (conn.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
            return false;
        } else if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            return false;
        }

        BufferedReader input = null;
        if (conn.getContentEncoding() != null && conn.getContentEncoding().contains("gzip")) {
            input = new BufferedReader(
                    new InputStreamReader(new GZIPInputStream(conn.getInputStream()), "UTF-8"), 1);
        } else {
            input = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"), 1);
        }

        StringBuilder builder = new StringBuilder();
        String buffer = null;
        while ((buffer = input.readLine()) != null) {
            builder.append(buffer);
        }
        try {
            JSONObject jsonObj = (JSONObject) new JSONParser().parse(builder.toString());
            int build = ((Number) jsonObj.get("build")).intValue();
            if (build <= buildVersion) {
                return false;
            }
            String version = (String) jsonObj.get("version");
            String msg = (String) jsonObj.get("msg");
            String download_url = (String) jsonObj.get("url");
            newVersion = new NewVersion(version, build, msg, download_url);
            return true;
        } catch (ParseException ex) {
            if (DEBUG) {
                ex.printStackTrace();
            }
            exception = ex;
            return false;
        }
    } catch (SocketTimeoutException ex) {
        return false;
    } catch (IOException ex) {
        if (DEBUG) {
            ex.printStackTrace();
        }
        exception = ex;
        return false;
    }
}

From source file:de.codecentric.jira.jenkins.plugin.servlet.OverviewServlet.java

/**
 * This function takes get data and renders the template
 *//*from   w  w w.ja v a 2s .  c o  m*/
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    Map<String, Object> velocityValues = new HashMap<String, Object>();

    try {
        String urlJenkinsServer = req.getParameter(PARAM_JENKINS_URL);
        String view = req.getParameter(PARAM_VIEW);
        String userName = req.getParameter("userName");
        String password = req.getParameter("password");

        I18nHelper i18nHelper;
        if (old) {
            i18nHelper = OldUser.getI18nHelper(authenticationContext);
        } else {
            i18nHelper = NewUser.getI18nHelper(authenticationContext);
        }

        //check if urlJenkinsServer equals Server.name
        JenkinsServer server = serverList.find(urlJenkinsServer);
        if (server != null) {
            urlJenkinsServer = server.getUrl();
        }

        if (urlJenkinsServer.lastIndexOf('/') < urlJenkinsServer.length() - 1) {
            urlJenkinsServer += "/";
        }

        List<JenkinsJob> portletData;

        //Test if authorization is available
        if (userName == "" && password == "" && !urlJenkinsServer.startsWith("https")) {
            portletData = getJobListByServer(urlJenkinsServer, view, i18nHelper);
            velocityValues.put("user", "anonymous");
        } else if (userName == "") {
            defaultcreds = new UsernamePasswordCredentials(userName, password);
            client.getState().setCredentials(new AuthScope(null, -1, AuthScope.ANY_REALM), defaultcreds);

            portletData = getJobListByServerAuth(urlJenkinsServer, view, i18nHelper);

            velocityValues.put("user", "anonymous");
        } else {
            defaultcreds = new UsernamePasswordCredentials(userName, password);
            client.getState().setCredentials(new AuthScope(null, -1, AuthScope.ANY_REALM), defaultcreds);

            portletData = getJobListByServerAuth(urlJenkinsServer, view, i18nHelper);

            velocityValues.put("user", userName);
        }

        velocityValues.put("serverList", serverList.getServerList());
        velocityValues.put("jenkinsUrl", urlJenkinsServer);
        velocityValues.put("view", view);
        velocityValues.put("jobs", portletData);
        velocityValues.put("context", this.getServletContext());

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }

    resp.setContentType("text/html;charset=utf-8");
    templateRenderer.render(TEMPLATE_PATH, velocityValues, resp.getWriter());
}

From source file:com.sonaive.v2ex.ui.debug.RSSPullService.java

/**
 * In an IntentService, onHandleIntent is run on a background thread.  As it
 * runs, it broadcasts its current status using the LocalBroadcastManager.
 * @param workIntent The Intent that starts the IntentService. This Intent contains the
 * URL of the web site from which the RSS parser gets data.
 *//* ww w.ja  va 2s.  co m*/
@Override
protected void onHandleIntent(Intent workIntent) {

    BroadcastNotifier mBroadcaster = new BroadcastNotifier(this);
    // Gets a URL to read from the incoming Intent's "data" value
    String localUrlString = workIntent.getDataString();

    // Creates a projection to use in querying the modification date table in the provider.
    final String[] dateProjection = new String[] { ModiDates._ID, ModiDates.MODI_DATE };

    // A URL that's local to this method
    URL localURL;

    // A cursor that's local to this method.
    Cursor cursor = null;

    /*
     * A block that tries to connect to the Picasa featured picture URL passed as the "data"
     * value in the incoming Intent. The block throws exceptions (see the end of the block).
     */
    try {

        // Convert the incoming data string to a URL.
        localURL = new URL(localUrlString);

        /*
         * Tries to open a connection to the URL. If an IO error occurs, this throws an
         * IOException
         */
        URLConnection localURLConnection = localURL.openConnection();

        // If the connection is an HTTP connection, continue
        if ((localURLConnection instanceof HttpURLConnection)) {

            // Broadcasts an Intent indicating that processing has started.
            mBroadcaster.broadcastIntentWithState(Constants.STATE_ACTION_STARTED);

            // Casts the connection to a HTTP connection
            HttpURLConnection localHttpURLConnection = (HttpURLConnection) localURLConnection;

            // Sets the user agent for this request.
            localHttpURLConnection.setRequestProperty("User-Agent", Constants.USER_AGENT);

            /*
             * Queries the content provider to see if this URL was read previously, and when.
             * The content provider throws an exception if the URI is invalid.
             */
            cursor = getContentResolver().query(ModiDates.CONTENT_URI, dateProjection, null, null, null);

            // Flag to indicate that new metadata was retrieved
            boolean newMetadataRetrieved;

            /*
             * Tests to see if the table contains a modification date for the URL
             */
            if (null != cursor && cursor.moveToFirst()) {

                long storedModifiedDate = cursor.getLong(cursor.getColumnIndex(ModiDates.MODI_DATE));

                /*
                 * If the modified date isn't 0, sets another request property to ensure that
                 * data is only downloaded if it has changed since the last recorded
                 * modification date. Formats the date according to the RFC1123 format.
                 */
                if (0 != storedModifiedDate) {
                    localHttpURLConnection.setRequestProperty("If-Modified-Since",
                            org.apache.http.impl.cookie.DateUtils.formatDate(new Date(storedModifiedDate),
                                    org.apache.http.impl.cookie.DateUtils.PATTERN_RFC1123));
                }

                // Marks that new metadata does not need to be retrieved
                newMetadataRetrieved = false;

            } else {

                /*
                 * No modification date was found for the URL, so newmetadata has to be
                 * retrieved.
                 */
                newMetadataRetrieved = true;

            }

            // Reports that the service is about to connect to the RSS feed
            mBroadcaster.broadcastIntentWithState(Constants.STATE_ACTION_CONNECTING);

            // Gets a response code from the RSS server
            int responseCode = localHttpURLConnection.getResponseCode();

            switch (responseCode) {

            // If the response is OK
            case HttpStatus.SC_OK:

                // Gets the last modified data for the URL
                long lastModifiedDate = localHttpURLConnection.getLastModified();

                // Reports that the service is parsing
                mBroadcaster.broadcastIntentWithState(Constants.STATE_ACTION_PARSING);

                /*
                 * Instantiates a pull parser and uses it to parse XML from the RSS feed.
                 * The mBroadcaster argument send a broadcaster utility object to the
                 * parser.
                 */
                RSSPullParser localPicasaPullParser = new RSSPullParser();

                localPicasaPullParser.parseXml(localURLConnection.getInputStream(), mBroadcaster);

                // Reports that the service is now writing data to the content provider.
                mBroadcaster.broadcastIntentWithState(Constants.STATE_ACTION_WRITING);

                // Gets image data from the parser
                Vector<ContentValues> imageValues = localPicasaPullParser.getImages();

                // Stores the number of images
                int imageVectorSize = imageValues.size();

                // Creates one ContentValues for each image
                ContentValues[] imageValuesArray = new ContentValues[imageVectorSize];

                imageValuesArray = imageValues.toArray(imageValuesArray);

                /*
                 * Stores the image data in the content provider. The content provider
                 * throws an exception if the URI is invalid.
                 */
                getContentResolver().bulkInsert(PicasaImages.CONTENT_URI, imageValuesArray);

                // Creates another ContentValues for storing date information
                ContentValues dateValues = new ContentValues();

                // Adds the URL's last modified date to the ContentValues
                dateValues.put(ModiDates.MODI_DATE, lastModifiedDate);

                if (newMetadataRetrieved) {

                    // No previous metadata existed, so insert the data
                    getContentResolver().insert(ModiDates.CONTENT_URI, dateValues);
                } else {

                    // Previous metadata existed, so update it.
                    getContentResolver().update(ModiDates.CONTENT_URI, dateValues,
                            ModiDates._ID + "=" + cursor.getString(cursor.getColumnIndex(ModiDates._ID)), null);
                }
                break;

            }

            // Reports that the feed retrieval is complete.
            mBroadcaster.broadcastIntentWithState(Constants.STATE_ACTION_COMPLETE);
        }

        // Handles possible exceptions
    } catch (MalformedURLException localMalformedURLException) {

        localMalformedURLException.printStackTrace();

    } catch (IOException localIOException) {

        localIOException.printStackTrace();

    } catch (XmlPullParserException localXmlPullParserException) {

        localXmlPullParserException.printStackTrace();

    } finally {

        // If an exception occurred, close the cursor to prevent memory leaks.
        if (null != cursor) {
            cursor.close();
        }
    }
}

From source file:com.PAB.ibeaconreference.AppEngineClient.java

public void delete(URL uri, Map<String, List<String>> headers) {

    DELETE delete = new DELETE(uri, headers);
    URL url = null;//w  ww.j a  va2s . co  m
    try {
        url = new URL("http://localhost:8080/deleteservice");
    } catch (MalformedURLException exception) {
        exception.printStackTrace();
    }
    HttpURLConnection httpURLConnection = null;
    try {
        httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        httpURLConnection.setRequestMethod("DELETE");
        System.out.println("DELETE response code..! " + httpURLConnection.getResponseCode());
    } catch (IOException exception) {
        exception.printStackTrace();
    } finally {
        if (httpURLConnection != null) {
            httpURLConnection.disconnect();
        }
    }
}

From source file:app.HadoopImporterWindowTopComponent.java

public static String loadNetworkLayersForTMN(String networkName, HadoopImporterWindowTopComponent comp) {

    StringBuffer q = new StringBuffer();

    CloseableHttpClient httpClient = null;
    HttpGet httpGet = null;/*from  w  ww.  j  a  v  a2s . c o m*/
    CloseableHttpResponse response = null;

    try {

        httpClient = HttpClients.createDefault();
        httpGet = new HttpGet();

        String query = "[[Modification date::+]]|?Modification date|sort=Modification date|order=Ddesc";

        String queryForLayerSQL = "[[Category:TMN_layer]][[belongs_to_TMN::" + networkName
                + "]]|?TMN_layer_name";

        URI uri = new URI("http://semanpix.de/oldtimer/wiki/api.php?action=ask&format=json&query="
                + encodeQuery(queryForLayerSQL));

        String uri2 = "http://semanpix.de/oldtimer/wiki/api.php?action=ask&format=json&query="
                + queryForLayerSQL;

        httpGet.setURI(uri);

        System.out.println("[Request:]\n" + uri2);

        if (comp != null) {
            comp.setQuery(uri2);
        }

        response = httpClient.execute(httpGet);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        StringBuffer sb = new StringBuffer();
        String output;

        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
            sb.append(output);
        }

        if (comp != null) {
            comp.setResponse(sb.toString());
        }

        JSONObject obj1 = new JSONObject(sb.toString());

        JSONObject obj2 = obj1.getJSONObject("query");

        JSONObject obj3 = obj2.getJSONObject("results");
        Iterator<String> it = obj3.keys();
        while (it.hasNext()) {
            String key = it.next();
            JSONObject obj = obj3.getJSONObject(key);
            JSONObject obj4 = obj.getJSONObject("printouts");
            String nln = obj4.optString("TMN layer name");
            System.out.println(nln);
            q.append(nln.substring(2, nln.length() - 2) + "\n");
        }

    } catch (MalformedURLException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    } catch (URISyntaxException ex) {
        Exceptions.printStackTrace(ex);
    } catch (JSONException ex) {
        Exceptions.printStackTrace(ex);
    } finally {
        try {
            if (response != null) {
                response.close();
            }
            httpClient.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    return q.toString();

}

From source file:app.HadoopImporterWindowTopComponent.java

static public String loadTMNListeFromMetastore(HadoopImporterWindowTopComponent comp) {

    StringBuffer q = new StringBuffer();

    CloseableHttpClient httpClient = null;
    HttpGet httpGet = null;/*from  w ww  . j  av a 2 s  .com*/
    CloseableHttpResponse response = null;

    try {

        httpClient = HttpClients.createDefault();
        httpGet = new HttpGet();

        String query = "[[Modification date::+]]|?Modification date|sort=Modification date|order=Ddesc";

        String queryForLayerSQL = "[[Category:TMN]]|?TMN_name";

        URI uri = new URI("http://semanpix.de/oldtimer/wiki/api.php?action=ask&format=json&query="
                + encodeQuery(queryForLayerSQL));

        String uri2 = "http://semanpix.de/oldtimer/wiki/api.php?action=ask&format=json&query="
                + queryForLayerSQL;

        httpGet.setURI(uri);

        System.out.println("[Request:]\n" + uri2);

        if (comp != null) {
            comp.setQuery(uri2);
        }

        response = httpClient.execute(httpGet);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        StringBuffer sb = new StringBuffer();
        String output;

        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
            sb.append(output);
        }

        if (comp != null) {
            comp.setResponse(sb.toString());
        }

        JSONObject obj1 = new JSONObject(sb.toString());

        JSONObject obj2 = obj1.getJSONObject("query");

        JSONObject obj3 = obj2.getJSONObject("results");
        Iterator it = obj3.keys();
        while (it.hasNext()) {
            String key = (String) it.next();
            JSONObject obj = obj3.getJSONObject(key);
            String nlnfull = obj.optString("fulltext");
            JSONObject obj4 = obj.getJSONObject("printouts");

            String nln = obj4.optString("TMN name");

            System.out.println(nln);
            q.append(nln.substring(2, nln.length() - 2) + " : " + nlnfull + "\n");
        }

    } catch (MalformedURLException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    } catch (URISyntaxException ex) {
        Exceptions.printStackTrace(ex);
    } catch (JSONException ex) {
        Exceptions.printStackTrace(ex);
    } finally {
        try {
            if (response != null) {
                response.close();
            }
            httpClient.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    return q.toString();

}

From source file:DummyAppletContext.java

/**
 * Gets the document URL./* w  w  w.  j a  v  a2 s  .c om*/
 *
* @return      a "file:" URL for the current directory
 */
public URL getDocumentBase() {
    URL url = null;
    try {
        File dummy = new File("dummy.html");
        String path = dummy.getAbsolutePath();
        if (!File.separator.equals("/")) {
            StringBuffer buffer = new StringBuffer();
            if (path.charAt(0) != File.separator.charAt(0)) {
                buffer.append("/");
            }
            StringTokenizer st = new StringTokenizer(path, File.separator);
            while (st.hasMoreTokens()) {
                buffer.append(st.nextToken() + "/");
            }
            if (File.separator.equals("\\") && (buffer.charAt(2) == ':')) {
                buffer.setCharAt(2, '|');
            } else {
            }
            path = buffer.toString();
            path = path.substring(0, path.length() - 1);
        }
        url = new URL("file", "", -1, path);
    } catch (MalformedURLException mue) {
        mue.printStackTrace();
    }
    return url;
}

From source file:xiaofans.threadsample.RSSPullService.java

/**
 * In an IntentService, onHandleIntent is run on a background thread.  As it
 * runs, it broadcasts its current status using the LocalBroadcastManager.
 * @param workIntent The Intent that starts the IntentService. This Intent contains the
 * URL of the web site from which the RSS parser gets data.
 */// w  ww.j a v a2  s.c  o  m
@Override
protected void onHandleIntent(Intent workIntent) {
    // Gets a URL to read from the incoming Intent's "data" value
    String localUrlString = workIntent.getDataString();

    // Creates a projection to use in querying the modification date table in the provider.
    final String[] dateProjection = new String[] { DataProviderContract.ROW_ID,
            DataProviderContract.DATA_DATE_COLUMN };

    // A URL that's local to this method
    URL localURL;

    // A cursor that's local to this method.
    Cursor cursor = null;

    /*
     * A block that tries to connect to the Picasa featured picture URL passed as the "data"
     * value in the incoming Intent. The block throws exceptions (see the end of the block).
     */
    try {

        // Convert the incoming data string to a URL.
        localURL = new URL(localUrlString);

        /*
         * Tries to open a connection to the URL. If an IO error occurs, this throws an
         * IOException
         */
        URLConnection localURLConnection = localURL.openConnection();

        // If the connection is an HTTP connection, continue
        if ((localURLConnection instanceof HttpURLConnection)) {

            // Broadcasts an Intent indicating that processing has started.
            mBroadcaster.broadcastIntentWithState(Constants.STATE_ACTION_STARTED);

            // Casts the connection to a HTTP connection
            HttpURLConnection localHttpURLConnection = (HttpURLConnection) localURLConnection;

            // Sets the user agent for this request.
            localHttpURLConnection.setRequestProperty("User-Agent", Constants.USER_AGENT);

            /*
             * Queries the content provider to see if this URL was read previously, and when.
             * The content provider throws an exception if the URI is invalid.
             */
            cursor = getContentResolver().query(DataProviderContract.DATE_TABLE_CONTENTURI, dateProjection,
                    null, null, null);

            // Flag to indicate that new metadata was retrieved
            boolean newMetadataRetrieved;

            /*
             * Tests to see if the table contains a modification date for the URL
             */
            if (null != cursor && cursor.moveToFirst()) {

                // Find the URL's last modified date in the content provider
                long storedModifiedDate = cursor
                        .getLong(cursor.getColumnIndex(DataProviderContract.DATA_DATE_COLUMN));

                /*
                 * If the modified date isn't 0, sets another request property to ensure that
                 * data is only downloaded if it has changed since the last recorded
                 * modification date. Formats the date according to the RFC1123 format.
                 */
                if (0 != storedModifiedDate) {
                    localHttpURLConnection.setRequestProperty("If-Modified-Since",
                            org.apache.http.impl.cookie.DateUtils.formatDate(new Date(storedModifiedDate),
                                    org.apache.http.impl.cookie.DateUtils.PATTERN_RFC1123));
                }

                // Marks that new metadata does not need to be retrieved
                newMetadataRetrieved = false;

            } else {

                /*
                 * No modification date was found for the URL, so newmetadata has to be
                 * retrieved.
                 */
                newMetadataRetrieved = true;

            }

            // Reports that the service is about to connect to the RSS feed
            mBroadcaster.broadcastIntentWithState(Constants.STATE_ACTION_CONNECTING);

            // Gets a response code from the RSS server
            int responseCode = localHttpURLConnection.getResponseCode();

            switch (responseCode) {

            // If the response is OK
            case HttpStatus.SC_OK:

                // Gets the last modified data for the URL
                long lastModifiedDate = localHttpURLConnection.getLastModified();

                // Reports that the service is parsing
                mBroadcaster.broadcastIntentWithState(Constants.STATE_ACTION_PARSING);

                /*
                 * Instantiates a pull parser and uses it to parse XML from the RSS feed.
                 * The mBroadcaster argument send a broadcaster utility object to the
                 * parser.
                 */
                RSSPullParser localPicasaPullParser = new RSSPullParser();

                localPicasaPullParser.parseXml(localURLConnection.getInputStream(), mBroadcaster);

                // Reports that the service is now writing data to the content provider.
                mBroadcaster.broadcastIntentWithState(Constants.STATE_ACTION_WRITING);

                // Gets image data from the parser
                Vector<ContentValues> imageValues = localPicasaPullParser.getImages();

                // Stores the number of images
                int imageVectorSize = imageValues.size();

                // Creates one ContentValues for each image
                ContentValues[] imageValuesArray = new ContentValues[imageVectorSize];

                imageValuesArray = imageValues.toArray(imageValuesArray);

                /*
                 * Stores the image data in the content provider. The content provider
                 * throws an exception if the URI is invalid.
                 */
                getContentResolver().bulkInsert(DataProviderContract.PICTUREURL_TABLE_CONTENTURI,
                        imageValuesArray);

                // Creates another ContentValues for storing date information
                ContentValues dateValues = new ContentValues();

                // Adds the URL's last modified date to the ContentValues
                dateValues.put(DataProviderContract.DATA_DATE_COLUMN, lastModifiedDate);

                if (newMetadataRetrieved) {

                    // No previous metadata existed, so insert the data
                    getContentResolver().insert(DataProviderContract.DATE_TABLE_CONTENTURI, dateValues);

                } else {

                    // Previous metadata existed, so update it.
                    getContentResolver().update(DataProviderContract.DATE_TABLE_CONTENTURI, dateValues,
                            DataProviderContract.ROW_ID + "="
                                    + cursor.getString(cursor.getColumnIndex(DataProviderContract.ROW_ID)),
                            null);
                }
                break;

            }

            // Reports that the feed retrieval is complete.
            mBroadcaster.broadcastIntentWithState(Constants.STATE_ACTION_COMPLETE);
        }

        // Handles possible exceptions
    } catch (MalformedURLException localMalformedURLException) {

        localMalformedURLException.printStackTrace();

    } catch (IOException localIOException) {

        localIOException.printStackTrace();

    } catch (XmlPullParserException localXmlPullParserException) {

        localXmlPullParserException.printStackTrace();

    } finally {

        // If an exception occurred, close the cursor to prevent memory leaks.
        if (null != cursor) {
            cursor.close();
        }
    }
}

From source file:eionet.gdem.qa.XQueryService.java

/**
 * Request from XML/RPC client Stores the xqScript and starts a job in the workqueue.
 *
 * @param sourceURL - URL of the source XML
 * @param xqScript - XQueryScript to be processed
 * @param scriptType - xquery, xsl or xgawk
 *///  w w  w  .j  a v a  2  s.  c  o  m
public String analyze(String sourceURL, String xqScript, String scriptType) throws GDEMException {
    String xqFile = "";

    LOGGER.info("XML/RPC call for analyze xml: " + sourceURL);
    // save XQScript in a text file for the WQ
    try {
        xqFile = Utils.saveStrToFile(xqScript, scriptType);
    } catch (FileNotFoundException fne) {
        throw new GDEMException("Folder does not exist: :" + fne.toString());
    } catch (IOException ioe) {
        throw new GDEMException("Error storing XQScript into file:" + ioe.toString());
    }

    // name for temporary output file where the esult is stored:
    String resultFile = Properties.tmpFolder + File.separatorChar + "gdem_" + System.currentTimeMillis()
            + ".html";
    String newId = "-1"; // should not be returned with value -1;

    // start a job in the Workqueue
    try {
        // get the trusted URL from source file adapter
        sourceURL = SourceFileManager.getSourceFileAdapterURL(getTicket(), sourceURL, isTrustedMode());
        newId = xqJobDao.startXQJob(sourceURL, xqFile, resultFile);

    } catch (SQLException sqe) {
        sqe.printStackTrace();
        LOGGER.error("DB operation failed: " + sqe.toString());
        throw new GDEMException("DB operation failed: " + sqe.toString());
    } catch (MalformedURLException e) {
        e.printStackTrace();
        LOGGER.error("Source file URL is wrong: " + e.toString());
        throw new GDEMException("Source file URL is wrong: " + e.toString());
    } catch (IOException e) {
        e.printStackTrace();
        LOGGER.error("Error opening source file: " + e.toString());
        throw new GDEMException("Error opening source file: " + e.toString());
    }
    return newId;
}