Example usage for java.lang IllegalArgumentException printStackTrace

List of usage examples for java.lang IllegalArgumentException printStackTrace

Introduction

In this page you can find the example usage for java.lang IllegalArgumentException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

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

Usage

From source file:com.snaptic.api.SnapticAPI.java

/**
 * Post a new note.//from   w w  w.  j ava 2s. c om
 *
 * @param SnapticNote note to be posted.
 * @return int returnCode enum code indicating whether call was successful or not.
 */
public int addNote(SnapticNote note) {
    int returnCode = RESULT_ERROR;

    if (note == null) {
        return returnCode;
    }

    String source = defaultSource;

    if (note.source != null && note.source.length() > 0) {
        source = note.source.toString();
    }

    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("text", note.text.toString()));
    params.add(new BasicNameValuePair("source", source));
    params.add(new BasicNameValuePair("created_at", Long.toString(note.creationTime)));
    params.add(new BasicNameValuePair("modified_at", Long.toString(note.modificationTime)));
    params.add(new BasicNameValuePair("reminder_at", Long.toString(note.reminderTime)));
    params.add(new BasicNameValuePair("latitude", Double.toString(note.latitude)));
    params.add(new BasicNameValuePair("longitude", Double.toString(note.longitude)));
    params.add(new BasicNameValuePair("altitude", Double.toString(note.altitude)));
    params.add(new BasicNameValuePair("speed", Double.toString(note.speed)));
    params.add(new BasicNameValuePair("bearing", Double.toString(note.bearing)));
    params.add(new BasicNameValuePair("accuracy_position", Double.toString(note.accuracyPosition)));
    params.add(new BasicNameValuePair("accuracy_altitude", Double.toString(note.accuracyAltitude)));

    String endpoint = API_ENDPOINT_NOTES + ".xml";
    HttpResponse response = performPOST(endpoint, params, null);

    if (response != null) {
        if (isResponseOK(response)) {
            boolean parseResult = false;

            try {
                SnapticNotesXmlParser xmlParser = new SnapticNotesXmlParser();
                ArrayList<SnapticNote> notes = new ArrayList<SnapticNote>(1);
                xmlParser.parseNotesXml(response, notes);

                if (notes.size() > 0 && notes.get(0) != null) {
                    // Copy the returned note values into the original note object
                    note.copy(notes.get(0));
                    parseResult = true;
                }
            } catch (IllegalArgumentException e) {
                log("caught an IllegalArgumentException processing response from POST " + endpoint);
                e.printStackTrace();
            } catch (XmlPullParserException e) {
                log("caught an XmlPullParserException processing response from POST " + endpoint);
                e.printStackTrace();
            } catch (IOException e) {
                log("caught an IOException processing response from POST " + endpoint);
                e.printStackTrace();
            }

            returnCode = (parseResult == true) ? RESULT_OK : RESULT_ERROR_RESPONSE;
        } else if (isResponseUnauthorized(response)) {
            returnCode = RESULT_UNAUTHORIZED;
        }

        consumeResponse(response);
    }

    return returnCode;
}

From source file:com.snaptic.api.SnapticAPI.java

/**
 * Edit an existing note./* w w  w. j ava  2s.  com*/
 *
 * @param SnapticNote note to be updated. note.id must be a valid existing note id.
 * @return int returnCode enum code indicating whether call was successful or not.
 */
public int editNote(SnapticNote note) {
    int returnCode = RESULT_ERROR;

    if (note == null) {
        return returnCode;
    }

    String source = defaultSource;

    if (note.source != null && note.source.length() > 0) {
        source = note.source.toString();
    }

    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("text", note.text.toString()));
    params.add(new BasicNameValuePair("source", source));
    params.add(new BasicNameValuePair("created_at", Long.toString(note.creationTime)));
    params.add(new BasicNameValuePair("modified_at", Long.toString(note.modificationTime)));
    params.add(new BasicNameValuePair("reminder_at", Long.toString(note.reminderTime)));
    params.add(new BasicNameValuePair("latitude", Double.toString(note.latitude)));
    params.add(new BasicNameValuePair("longitude", Double.toString(note.longitude)));
    params.add(new BasicNameValuePair("altitude", Double.toString(note.altitude)));
    params.add(new BasicNameValuePair("speed", Double.toString(note.speed)));
    params.add(new BasicNameValuePair("bearing", Double.toString(note.bearing)));
    params.add(new BasicNameValuePair("accuracy_position", Double.toString(note.accuracyPosition)));
    params.add(new BasicNameValuePair("accuracy_altitude", Double.toString(note.accuracyAltitude)));

    String endpoint = API_ENDPOINT_NOTES + '/' + note.id + ".xml";
    HttpResponse response = performPOST(endpoint, params, null);

    if (response != null) {
        if (isResponseOK(response)) {
            boolean parseResult = false;

            try {
                SnapticNotesXmlParser xmlParser = new SnapticNotesXmlParser();
                ArrayList<SnapticNote> notes = new ArrayList<SnapticNote>(1);
                xmlParser.parseNotesXml(response, notes);

                if (notes.size() > 0 && notes.get(0) != null) {
                    // Copy the returned note values into the original note object
                    note.copy(notes.get(0));
                    parseResult = true;
                }
            } catch (IllegalArgumentException e) {
                log("caught an IllegalArgumentException processing response from POST " + endpoint);
                e.printStackTrace();
            } catch (XmlPullParserException e) {
                log("caught an XmlPullParserException processing response from POST " + endpoint);
                e.printStackTrace();
            } catch (IOException e) {
                log("caught an IOException processing response from POST " + endpoint);
                e.printStackTrace();
            }

            returnCode = (parseResult == true) ? RESULT_OK : RESULT_ERROR_RESPONSE;
        } else if (isResponseUnauthorized(response)) {
            returnCode = RESULT_UNAUTHORIZED;
        }

        consumeResponse(response);
    }

    return returnCode;
}

From source file:de.fuberlin.wiwiss.marbles.MarblesServlet.java

/**
 * Discovers an URI and renders a given view for it (<code>view</code>).
 *
 * @param request/*from   w w  w . j ava  2s  .co  m*/
 * @param response
 * @throws IOException
 */
public void fresnelView(HttpServletRequest request, HttpServletResponse response) throws IOException {
    PrintWriter writer = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF-8"));
    String errorString = null;
    Selection selected = null;
    List<org.apache.commons.httpclient.URI> retrievedURLs = null;
    Resource focalResource = null;
    Configuration conf = null;
    String redirectLocation = null;

    try {
        /* Reload the Fresnel configuration using the provided language */
        String langPref = (request.getParameter("lang") != null ? request.getParameter("lang") : "en");
        loadFresnelConfig(langPref);

        conf = new Configuration(confRepository, ontoRepository);

        /* Create the focal resource */
        if (request.getParameter("uri") != null) {
            String uriString = request.getParameter("uri");
            if (uriString.startsWith("_:")) /* blank node */
                focalResource = valueFactory.createBNode(uriString.substring(2));
            else
                focalResource = valueFactory.createURI(uriString);

            /* Collect data about the focal resource */
            if (request.getParameter("skipload") == null) {
                retrievedURLs = semwebClient.discoverResource(focalResource, true /* wait */);
            } /* skip */

            /* Initiate manual owl:sameAs inference */
            if (request.getParameter("skipInference") == null) {
                sameAsInferencer.addInferredForResource(focalResource);
            }

            if (conf.hasWarnings())
                writer.println(conf.getWarningsString());

            Purpose purpose = null;

            /* Look up the requested lens purpose */
            if (request.getParameter("purpose") != null
                    && (!request.getParameter("purpose").equals("defaultPurpose")))
                purpose = new Purpose(new URIImpl(Constants.nsFresnelExt + request.getParameter("purpose")));
            else
                purpose = new Purpose(new URIImpl(
                        "http://www.w3.org/2004/09/fresnel#defaultLens")); /* this must be provided, or a random lens is chosen */

            try {
                /* Perform Fresnel selection using the requested display purpose and language */
                selected = conf.select(dataRepository, focalResource, purpose, langPref);

                /* Perform Fresnel formatting */
                selected = conf.format(dataRepository, selected);
            } catch (NoResultsException e) {

                /* 
                 * If no results are found, redirect the user to the resource
                 * if it is not an RDF document.
                 * This code is not reached when there already is some data about the resource.
                 */
                RepositoryConnection metaDataConn = null;
                try {
                    metaDataConn = metaDataRepository.getConnection();

                    /* Manual support for one level of redirects */
                    String resourceRedirect = cacheController.getCachedHeaderDataValue(metaDataConn,
                            focalResource, "location");
                    Resource resourceURI = (resourceRedirect == null ? focalResource
                            : new URIImpl(resourceRedirect));

                    /* Get target content type */
                    String contentType = cacheController.getCachedHeaderDataValue(metaDataConn, resourceURI,
                            "content-type");
                    if (contentType != null && !ContentTypes.isRDF(contentType)) {
                        redirectLocation = focalResource.toString();
                    }
                } catch (RepositoryException re) {
                    re.printStackTrace();
                } catch (IllegalArgumentException ie) {
                    ie.printStackTrace();
                } finally {
                    try {
                        if (metaDataConn != null)
                            metaDataConn.close();
                    } catch (RepositoryException re) {
                        re.printStackTrace();
                    }
                }
            }
        } /* uri != null */
    } catch (Exception e) {
        e.printStackTrace();
        errorString = e.getMessage();
    }

    /* Output */
    try {
        /* Handle redirection to non-RDF data */
        if (redirectLocation != null) {
            response.setHeader("Location", redirectLocation);
            response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
        } else { /* Perform XSL output */

            /*
             * When there are no results, we still need a selection object in 
             * order to render the fresnel tree
             */
            if (selected == null)
                selected = new Selection(conf);

            Document fresnelTree = selected.render();
            addSources(fresnelTree, retrievedURLs);

            /* Prepare XSLT */
            StreamSource styleSource = new StreamSource(
                    new File(dataRoot + "/" + xslDirectory + "/" + xslTransformation));
            net.sf.saxon.TransformerFactoryImpl tf = new net.sf.saxon.TransformerFactoryImpl();
            Transformer styleTransformer = tf.newTransformer(styleSource);

            /* Debug output */
            if (request.getParameter("debug") != null) {
                /* debug output: fresnel tree */
                StringWriter stringWriter = new StringWriter();
                Transformer treeTransformer = tf.newTransformer();
                treeTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
                treeTransformer.transform(new DOMSource(fresnelTree), new StreamResult(stringWriter));
                styleTransformer.setParameter("fresnelTree", stringWriter.getBuffer().toString());
            }

            /* Apply parameters */
            styleTransformer.setParameter("assetsURL", assetsURL != null ? assetsURL.toString() : "");
            styleTransformer.setParameter("serviceURL", serviceURL != null ? serviceURL.toString() : "");
            styleTransformer.setParameter("errorString", errorString);
            styleTransformer.setParameter("mainResource",
                    focalResource != null ? focalResource.toString() : "");
            if (request.getParameter("purpose") != null)
                styleTransformer.setParameter("purpose", request.getParameter("purpose"));
            else
                styleTransformer.setParameter("purpose", "defaultPurpose");

            if (request.getParameter("mobile") != null)
                styleTransformer.setParameter("isMobile", request.getParameter("mobile"));

            HashMap<String, String[]> newParameters = new HashMap<String, String[]>(request.getParameterMap());

            if (!newParameters.containsKey("lang"))
                newParameters.put("lang", new String[] { "en" });

            for (Object key : new String[] { "purpose", "uri" }) {
                newParameters.remove(key);
            }

            String parameterString = "";

            /* Serialize parameters for use in HTML links and forms */
            for (Object key : newParameters.keySet()) {
                parameterString += (parameterString.equals("") ? "" : "&") + key + "="
                        + ((String[]) newParameters.get(key))[0];
            }

            styleTransformer.setParameter("sessionParams", parameterString);

            /* Perform rendering */
            StreamResult res = new StreamResult(writer);
            styleTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
            styleTransformer.transform(new DOMSource(fresnelTree), res);
        }
    } catch (Exception e) {
        e.printStackTrace();
        writer.print(e.getMessage());
    } finally {
    }
}

From source file:freed.cam.apis.camera2.modules.PictureModuleApi2.java

@NonNull
private void process_rawSensor(ImageHolder image, File file) {
    Log.d(TAG, "Create DNG");

    DngCreator dngCreator = new DngCreator(cameraHolder.characteristics, image.getCaptureResult());
    //Orientation 90 is not a valid EXIF orientation value, fuck off that is valid!
    try {/* www  . j  a  va2 s.co m*/
        dngCreator.setOrientation(image.captureResult.get(CaptureResult.JPEG_ORIENTATION));
    } catch (IllegalArgumentException ex) {
        ex.printStackTrace();
    }

    if (appSettingsManager.getApiString(AppSettingsManager.SETTING_LOCATION).equals(KEYS.ON))
        dngCreator
                .setLocation(cameraUiWrapper.getActivityInterface().getLocationHandler().getCurrentLocation());
    try {
        if (!appSettingsManager.GetWriteExternal())
            dngCreator.writeImage(new FileOutputStream(file), image.getImage());
        else {
            DocumentFile df = cameraUiWrapper.getActivityInterface().getFreeDcamDocumentFolder();
            DocumentFile wr = df.createFile("image/*", file.getName());
            dngCreator.writeImage(
                    cameraUiWrapper.getContext().getContentResolver().openOutputStream(wr.getUri()),
                    image.getImage());
        }
        cameraUiWrapper.getActivityInterface().ScanFile(file);
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    image.getImage().close();
    image = null;
}

From source file:com.code.android.vibevault.SearchScreen.java

/** Bookkeeping method to deal with dialogs over orientation changes.
*
*//*from w w w .  j  av a2s. co m*/
private void onTaskCompleted() {
    if (dialogShown) {
        try {
            dismissDialog(VibeVault.SEARCHING_DIALOG_ID);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
        dialogShown = false;
    }
}

From source file:edu.bsu.android.apps.geofence.Other.java

/**
 * Called when the user clicks the "Remove geofence 1" button
 * //from   ww  w.  j a v  a 2 s.c o  m
 * @param view The view that triggered this callback
 */
public void onUnregisterGeofence1Clicked(View view) {
    /*
     * Remove the geofence by creating a List of geofences to remove and sending it to Location Services. The List contains the id of geofence 1
     * ("1"). The removal happens asynchronously; Location Services calls onRemoveGeofencesByPendingIntentResult() (implemented in the current
     * Activity) when the removal is done.
     */

    // Create a List of 1 Geofence with the ID "1" and store it in the global list
    mGeofenceIdsToRemove = Collections.singletonList("1");

    /*
     * Record the removal as remove by list. If a connection error occurs, the app can automatically restart the removal if Google Play services
     * can fix the error
     */
    mRemoveType = GeofenceUtils.REMOVE_TYPE.LIST;

    /*
     * Check for Google Play services. Do this after setting the request type. If connecting to Google Play services fails, onActivityResult is
     * eventually called, and it needs to know what type of request was in progress.
     */
    if (!servicesConnected()) {

        return;
    }

    // Try to remove the geofence
    try {
        mGeofenceRemover.removeGeofencesById(mGeofenceIdsToRemove);

        // Catch errors with the provided geofence IDs
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (UnsupportedOperationException e) {
        // Notify user that previous request hasn't finished.
        Toast.makeText(this, R.string.remove_geofences_already_requested_error, Toast.LENGTH_LONG).show();
    }
}

From source file:edu.bsu.android.apps.geofence.Other.java

/**
 * Called when the user clicks the "Remove geofence 2" button
 * /*from w  ww .j a  v  a 2s .c om*/
 * @param view The view that triggered this callback
 */
public void onUnregisterGeofence2Clicked(View view) {
    /*
     * Remove the geofence by creating a List of geofences to remove and sending it to Location Services. The List contains the id of geofence 2,
     * which is "2". The removal happens asynchronously; Location Services calls onRemoveGeofencesByPendingIntentResult() (implemented in the
     * current Activity) when the removal is done.
     */

    /*
     * Record the removal as remove by list. If a connection error occurs, the app can automatically restart the removal if Google Play services
     * can fix the error
     */
    mRemoveType = GeofenceUtils.REMOVE_TYPE.LIST;

    // Create a List of 1 Geofence with the ID "2" and store it in the global list
    mGeofenceIdsToRemove = Collections.singletonList("2");

    /*
     * Check for Google Play services. Do this after setting the request type. If connecting to Google Play services fails, onActivityResult is
     * eventually called, and it needs to know what type of request was in progress.
     */
    if (!servicesConnected()) {

        return;
    }

    // Try to remove the geofence
    try {
        mGeofenceRemover.removeGeofencesById(mGeofenceIdsToRemove);

        // Catch errors with the provided geofence IDs
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (UnsupportedOperationException e) {
        // Notify user that previous request hasn't finished.
        Toast.makeText(this, R.string.remove_geofences_already_requested_error, Toast.LENGTH_LONG).show();
    }
}

From source file:de.geeksfactory.opacclient.apis.Pica.java

protected DetailledItem parse_result(String html) {
    Document doc = Jsoup.parse(html);
    doc.setBaseUri(opac_url);//from w ww  .  j a  v  a2 s.c  o m

    DetailledItem result = new DetailledItem();
    for (Element a : doc.select("a[href*=PPN")) {
        Map<String, String> hrefq = getQueryParamsFirst(a.absUrl("href"));
        String ppn = hrefq.get("PPN");
        result.setId(ppn);
        break;
    }

    // GET COVER
    if (doc.select("td.preslabel:contains(ISBN) + td.presvalue").size() > 0) {
        Element isbnElement = doc.select("td.preslabel:contains(ISBN) + td.presvalue").first();
        String isbn = "";
        for (Node child : isbnElement.childNodes()) {
            if (child instanceof TextNode) {
                isbn = ((TextNode) child).text().trim();
                break;
            }
        }
        result.setCover(ISBNTools.getAmazonCoverURL(isbn, true));
    }

    // GET TITLE AND SUBTITLE
    String titleAndSubtitle;
    Element titleAndSubtitleElem = null;
    String titleRegex = ".*(Titel|Aufsatz|Zeitschrift|Gesamttitel"
            + "|Title|Article|Periodical|Collective\\stitle" + "|Titre|Article|P.riodique|Titre\\sg.n.ral).*";
    String selector = "td.preslabel:matches(" + titleRegex + ") + td.presvalue";
    if (doc.select(selector).size() > 0) {
        titleAndSubtitleElem = doc.select(selector).first();
        titleAndSubtitle = titleAndSubtitleElem.text().trim();
        int slashPosition = Math.min(titleAndSubtitle.indexOf("/"), titleAndSubtitle.indexOf(":"));
        String title;
        if (slashPosition > 0) {
            title = titleAndSubtitle.substring(0, slashPosition).trim();
            String subtitle = titleAndSubtitle.substring(slashPosition + 1).trim();
            result.addDetail(new Detail(stringProvider.getString(StringProvider.SUBTITLE), subtitle));
        } else {
            title = titleAndSubtitle;
        }
        result.setTitle(title);
    } else {
        result.setTitle("");
    }

    // Details
    int line = 0;
    Elements lines = doc.select("td.preslabel + td.presvalue");
    if (titleAndSubtitleElem != null) {
        lines.remove(titleAndSubtitleElem);
    }
    for (Element element : lines) {
        Element titleElem = element.firstElementSibling();
        String detail = "";
        if (element.select("div").size() > 1 && element.select("div").text().equals(element.text())) {
            boolean first = true;
            for (Element div : element.select("div")) {
                if (!div.text().replace("\u00a0", " ").trim().equals("")) {
                    if (!first) {
                        detail += "\n" + div.text().replace("\u00a0", " ").trim();
                    } else {
                        detail += div.text().replace("\u00a0", " ").trim();
                        first = false;
                    }
                }
            }
        } else {
            detail = element.text().replace("\u00a0", " ").trim();
        }
        String title = titleElem.text().replace("\u00a0", " ").trim();

        if (element.select("hr").size() > 0)
        // after the separator we get the copies
        {
            break;
        }

        if (detail.length() == 0 && title.length() == 0) {
            line++;
            continue;
        }
        if (title.contains(":")) {
            title = title.substring(0, title.indexOf(":")); // remove colon
        }
        result.addDetail(new Detail(title, detail));

        if (element.select("a").size() == 1 && !element.select("a").get(0).text().trim().equals("")) {
            String url = element.select("a").first().absUrl("href");
            if (!url.startsWith(opac_url)) {
                result.addDetail(new Detail(stringProvider.getString(StringProvider.LINK), url));
            }
        }

        line++;
    }
    line++; // next line after separator

    // Copies
    Copy copy = new Copy();
    String location = "";

    // reservation info will be stored as JSON
    JSONArray reservationInfo = new JSONArray();

    while (line < lines.size()) {
        Element element = lines.get(line);
        if (element.select("hr").size() == 0) {
            Element titleElem = element.firstElementSibling();
            String detail = element.text().trim();
            String title = titleElem.text().replace("\u00a0", " ").trim();

            if (detail.length() == 0 && title.length() == 0) {
                line++;
                continue;
            }

            if (title.contains("Standort") || title.contains("Vorhanden in") || title.contains("Location")) {
                location += detail;
            } else if (title.contains("Sonderstandort")) {
                location += " - " + detail;
            } else if (title.contains("Systemstelle") || title.contains("Subject")) {
                copy.setDepartment(detail);
            } else if (title.contains("Fachnummer") || title.contains("locationnumber")) {
                copy.setLocation(detail);
            } else if (title.contains("Signatur") || title.contains("Shelf mark")) {
                copy.setShelfmark(detail);
            } else if (title.contains("Anmerkung")) {
                location += " (" + detail + ")";
            } else if (title.contains("Link")) {
                result.addDetail(new Detail(title.replace(":", "").trim(), detail));
            } else if (title.contains("Status") || title.contains("Ausleihinfo")
                    || title.contains("Ausleihstatus") || title.contains("Request info")) {
                // Find return date
                Pattern pattern = Pattern.compile("(till|bis) (\\d{2}-\\d{2}-\\d{4})");
                Matcher matcher = pattern.matcher(detail);
                if (matcher.find()) {
                    DateTimeFormatter fmt = DateTimeFormat.forPattern("dd-MM-yyyy").withLocale(Locale.GERMAN);
                    try {
                        copy.setStatus(detail.substring(0, matcher.start() - 1).trim());
                        copy.setReturnDate(fmt.parseLocalDate(matcher.group(2)));
                    } catch (IllegalArgumentException e) {
                        e.printStackTrace();
                        copy.setStatus(detail);
                    }
                } else {
                    copy.setStatus(detail);
                }
                // Get reservation info
                if (element.select("a:has(img[src*=inline_arrow])").size() > 0) {
                    Element a = element.select("a:has(img[src*=inline_arrow])").first();
                    boolean multipleCopies = a.text().matches(".*(Exemplare|Volume list).*");
                    JSONObject reservation = new JSONObject();
                    try {
                        reservation.put("multi", multipleCopies);
                        reservation.put("link", _extract_url(a.absUrl("href")));
                        reservation.put("desc", location);
                        reservationInfo.put(reservation);
                    } catch (JSONException e1) {
                        e1.printStackTrace();
                    }
                    result.setReservable(true);
                }
            }
        } else {
            copy.setBranch(location);
            result.addCopy(copy);
            location = "";
            copy = new Copy();
        }
        line++;
    }

    if (copy.notEmpty()) {
        copy.setBranch(location);
        result.addCopy(copy);
    }

    if (reservationInfo.length() == 0) {
        // No reservation info found yet, because we didn't find any copies.
        // If there is a reservation link somewhere in the rows we interpreted
        // as details, we still want to use it.
        if (doc.select("td a:has(img[src*=inline_arrow])").size() > 0) {
            Element a = doc.select("td a:has(img[src*=inline_arrow])").first();
            boolean multipleCopies = a.text().matches(".*(Exemplare|Volume list).*");
            JSONObject reservation = new JSONObject();
            try {
                reservation.put("multi", multipleCopies);
                reservation.put("link", _extract_url(a.attr("href")));
                reservation.put("desc", location);
                reservationInfo.put(reservation);
            } catch (JSONException e1) {
                e1.printStackTrace();
            }
            result.setReservable(true);
        }
    }
    result.setReservation_info(reservationInfo.toString());

    // Volumes
    if (doc.select("a[href^=FAM?PPN=]").size() > 0) {
        String href = doc.select("a[href^=FAM?PPN=]").attr("href");
        String ppn = getQueryParamsFirst(href).get("PPN");
        Map<String, String> data = new HashMap<>();
        data.put("ppn", ppn);
        result.setVolumesearch(data);
    }

    return result;
}

From source file:com.aniruddhc.acemusic.player.AsyncTasks.AsyncGetGooglePlayMusicMetadataTask.java

public String getMetadataFromGooglePlayMusicApp() {

    //Grab a handle on the mApp.
    Uri googlePlayMusicContentProviderUri = Uri.parse("content://com.google.android.music.MusicContent/audio");
    String[] projection = { "title", "artist", "album", "AlbumArtist", "duration", "track", "year", "Genre",
            "TrackType AS track_type", /*"_count",*/ "Rating", "AlbumArtLocation AS album_art",
            "SourceType AS source_type", "SourceId", "ArtistArtLocation", /*, "artistId",*/ "StoreAlbumId" };

    /* source_type values:
     * 0: Local file (not used)./*from   ww w .  j av a2  s.co m*/
     * 1: Unknown.
     * 2: Personal, free GMusic library (used).
     * 3: All Access (not used).
     */
    String selection = "source_type=2 AND track_type=0";

    //Catch any exceptions that may be thrown as a result of unknown columns in GMusic's content mApp.
    Cursor cursor = null;
    boolean projectionFailed = false;
    try {
        cursor = mContext.getContentResolver().query(googlePlayMusicContentProviderUri, projection, selection,
                null, null);
    } catch (IllegalArgumentException e) {
        e.printStackTrace();

        //Problematic columns are commented out here.
        String[] failSafeProjection = { "title", "artist", "album", "AlbumArtist", "duration", "track", "year",
                "Genre", "TrackType AS track_type", /*"_count",*/ "Rating",
                "AlbumArtLocation AS album_art", /* "SourceType AS source_type", */
                "SourceId", /* "ArtistArtLocation", "artistId",*/ "StoreAlbumId" };

        cursor = mContext.getContentResolver().query(googlePlayMusicContentProviderUri, failSafeProjection,
                "track_type=0", null, null);
        projectionFailed = true;

    }

    //Clear out all the current Google Play Music songs in the database.
    mApp.getDBAccessHelper().deleteAllGooglePlayMusicSongs();

    //Insert the songs and their metadata into Jams' local database.
    /* To improve database insertion performance, we'll use a single transaction 
     * for the entire operation. SQLite journals each database insertion and 
     * creates a new transaction by default. We'll override this functionality 
     * and create a single transaction for all the database record insertions. 
     * In theory, this should reduce NAND memory overhead times and result in 
     * a 2x to 5x performance increase.
     */
    try {
        //We'll initialize the DB transaction manually.
        mApp.getDBAccessHelper().getWritableDatabase().beginTransaction();

        //Avoid "Divide by zero" errors.
        int scanningSongsIncrement;
        if (cursor != null) {
            if (cursor.getCount() != 0) {
                scanningSongsIncrement = 800000 / cursor.getCount();
            } else {
                scanningSongsIncrement = 800000 / 1;
            }

        } else {
            return "FAIL";
        }

        currentTask = mContext.getResources().getString(R.string.syncing_with_google_play_music);
        for (int i = 0; i < cursor.getCount(); i++) {

            cursor.moveToPosition(i);
            currentProgressValue = currentProgressValue + scanningSongsIncrement;
            publishProgress();

            //Get the song's metadata.
            String songTitle = cursor.getString(cursor.getColumnIndex("title"));
            String songArtist = cursor.getString(cursor.getColumnIndex("Artist"));
            String songAlbum = cursor.getString(cursor.getColumnIndex("Album"));
            String songAlbumArtist = cursor.getString(cursor.getColumnIndex("AlbumArtist"));
            String songDuration = cursor.getString(cursor.getColumnIndex("Duration"));
            String songTrackNumber = cursor.getString(cursor.getColumnIndex("Track"));
            String songYear = cursor.getString(cursor.getColumnIndex("Year"));
            String songGenre = cursor.getString(cursor.getColumnIndex("Genre"));
            //String songPlayCount = cursor.getString(cursor.getColumnIndex("_count"));
            String songRating = cursor.getString(cursor.getColumnIndex("Rating"));
            String songSource = DBAccessHelper.GMUSIC;
            String songAlbumArtPath = cursor.getString(cursor.getColumnIndex("album_art"));
            String songID = cursor.getString(cursor.getColumnIndex("SourceId"));
            //String artistID = cursor.getString(cursor.getColumnIndex("artistId"));
            String storeAlbumID = cursor.getString(cursor.getColumnIndex("StoreAlbumId"));

            String songArtistArtPath = "";
            if (projectionFailed == false) {
                songArtistArtPath = cursor.getString(cursor.getColumnIndex("ArtistArtLocation"));
            } else {
                //Fall back on album art.
                songArtistArtPath = cursor.getString(cursor.getColumnIndex("album_art"));
            }

            //Prepare the genres ArrayList.
            if (!genresList.contains(songGenre)) {
                genresList.add(songGenre);
            }

            //Filter out track numbers and remove any bogus values.
            if (songTrackNumber != null) {
                if (songTrackNumber.contains("/")) {
                    int index = songTrackNumber.lastIndexOf("/");
                    songTrackNumber = songTrackNumber.substring(0, index);
                }

            }

            if (songYear.equals("0")) {
                songYear = "";
            }

            //Check if any of the other tags were empty/null and set them to "Unknown xxx" values.
            if (songArtist == null || songArtist.isEmpty() || songArtist.equals(" ")) {
                songArtist = "Unknown Artist";
            }

            if (songAlbumArtist == null || songAlbumArtist.isEmpty() || songAlbumArtist.equals(" ")) {
                songAlbumArtist = "Unknown Album Artist";
            }

            if (songAlbum == null || songAlbum.isEmpty() || songAlbum.equals(" ")) {
                songAlbum = "Unknown Album";
            }

            if (songGenre == null || songGenre.isEmpty() || songGenre.equals(" ")) {
                songGenre = "Unknown Genre";
            }

            ContentValues values = new ContentValues();
            values.put(DBAccessHelper.SONG_TITLE, songTitle);
            values.put(DBAccessHelper.SONG_ARTIST, songArtist);
            values.put(DBAccessHelper.SONG_ALBUM, songAlbum);
            values.put(DBAccessHelper.SONG_ALBUM_ARTIST, songAlbumArtist);
            values.put(DBAccessHelper.SONG_DURATION, songDuration);
            values.put(DBAccessHelper.SONG_FILE_PATH, songID);
            values.put(DBAccessHelper.SONG_TRACK_NUMBER, songTrackNumber);
            values.put(DBAccessHelper.SONG_GENRE, songGenre);
            //values.put(DBAccessHelper.SONG_PLAY_COUNT, songPlayCount);
            values.put(DBAccessHelper.SONG_YEAR, songYear);
            values.put(DBAccessHelper.SONG_LAST_MODIFIED, "");
            values.put(DBAccessHelper.BLACKLIST_STATUS, "FALSE"); //Keep the song whitelisted by default.
            values.put(DBAccessHelper.ADDED_TIMESTAMP, date.getTime());
            values.put(DBAccessHelper.RATING, songRating);
            values.put(DBAccessHelper.SONG_SOURCE, songSource);
            values.put(DBAccessHelper.SONG_ALBUM_ART_PATH, songAlbumArtPath);
            values.put(DBAccessHelper.SONG_ID, songID);
            values.put(DBAccessHelper.ARTIST_ART_LOCATION, songArtistArtPath);
            //values.put(DBAccessHelper.ARTIST_ID, artistID);
            values.put(DBAccessHelper.ALBUM_ID, storeAlbumID);

            /* We're gonna have to save the song ID into the SONG_FILE_PATH 
             * field. Google Play Music playlist songs don't have a file path, but we're using a 
             * JOIN in PlaylistsFlippedFragment that relies on this field, so we'll need to use the 
             * song ID as a placeholder instead.
             */
            values.put(DBAccessHelper.SONG_FILE_PATH, songID);

            //Add all the entries to the database to build the songs library.
            mApp.getDBAccessHelper().getWritableDatabase().insert(DBAccessHelper.MUSIC_LIBRARY_TABLE, null,
                    values);

        }

        mApp.getDBAccessHelper().getWritableDatabase().setTransactionSuccessful();

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        //Close the transaction.
        mApp.getDBAccessHelper().getWritableDatabase().endTransaction();

        if (cursor != null) {
            cursor.close();
            cursor = null;
        }

    }

    /****************************************************************************
     * BUILD PLAYLISTS LIBRARY
     ****************************************************************************/
    //getPlaylistsWebClient();
    //getPlaylistsMobileClient();

    //Update the genres library.
    updateGenreSongCount();

    return "SUCCESS";
}

From source file:com.jelly.music.player.AsyncTasks.AsyncGetGooglePlayMusicMetadataTask.java

public String getMetadataFromGooglePlayMusicApp() {

    //Grab a handle on the mApp.
    Uri googlePlayMusicContentProviderUri = Uri.parse("content://com.google.android.music.MusicContent/audio");
    String[] projection = { "title", "artist", "album", "AlbumArtist", "duration", "track", "year", "Genre",
            "TrackType AS track_type", /*"_count",*/ "Rating", "AlbumArtLocation AS album_art",
            "SourceType AS source_type", "SourceId", "ArtistArtLocation", /*, "artistId",*/ "StoreAlbumId" };

    /* source_type values:
     * 0: Local file (not used).//from  ww w  .j a v  a 2  s  .  c  o  m
     * 1: Unknown.
     * 2: Personal, free GMusic library (used).
     * 3: All Access (not used).
     */
    String selection = "source_type=2 AND track_type=0";

    //Catch any exceptions that may be thrown as a result of unknown columns in GMusic's content mApp.
    Cursor cursor = null;
    boolean projectionFailed = false;
    try {
        cursor = mContext.getContentResolver().query(googlePlayMusicContentProviderUri, projection, selection,
                null, null);
    } catch (IllegalArgumentException e) {
        e.printStackTrace();

        //Problematic columns are commented out here.
        String[] failSafeProjection = { "title", "artist", "album", "AlbumArtist", "duration", "track", "year",
                "Genre", "TrackType AS track_type", /*"_count",*/ "Rating",
                "AlbumArtLocation AS album_art", /* "SourceType AS source_type", */
                "SourceId", /* "ArtistArtLocation", "artistId",*/ "StoreAlbumId" };

        cursor = mContext.getContentResolver().query(googlePlayMusicContentProviderUri, failSafeProjection,
                "track_type=0", null, null);
        projectionFailed = true;

    }

    //Clear out all the current Google Play Music songs in the database.
    mApp.getDBAccessHelper().deleteAllGooglePlayMusicSongs();

    //Insert the songs and their metadata into jelly' local database.
    /* To improve database insertion performance, we'll use a single transaction 
     * for the entire operation. SQLite journals each database insertion and 
     * creates a new transaction by default. We'll override this functionality 
     * and create a single transaction for all the database record insertions. 
     * In theory, this should reduce NAND memory overhead times and result in 
     * a 2x to 5x performance increase.
     */
    try {
        //We'll initialize the DB transaction manually.
        mApp.getDBAccessHelper().getWritableDatabase().beginTransaction();

        //Avoid "Divide by zero" errors.
        int scanningSongsIncrement;
        if (cursor != null) {
            if (cursor.getCount() != 0) {
                scanningSongsIncrement = 800000 / cursor.getCount();
            } else {
                scanningSongsIncrement = 800000 / 1;
            }

        } else {
            return "FAIL";
        }

        currentTask = mContext.getResources().getString(R.string.syncing_with_google_play_music);
        for (int i = 0; i < cursor.getCount(); i++) {

            cursor.moveToPosition(i);
            currentProgressValue = currentProgressValue + scanningSongsIncrement;
            publishProgress();

            //Get the song's metadata.
            String songTitle = cursor.getString(cursor.getColumnIndex("title"));
            String songArtist = cursor.getString(cursor.getColumnIndex("Artist"));
            String songAlbum = cursor.getString(cursor.getColumnIndex("Album"));
            String songAlbumArtist = cursor.getString(cursor.getColumnIndex("AlbumArtist"));
            String songDuration = cursor.getString(cursor.getColumnIndex("Duration"));
            String songTrackNumber = cursor.getString(cursor.getColumnIndex("Track"));
            String songYear = cursor.getString(cursor.getColumnIndex("Year"));
            String songGenre = cursor.getString(cursor.getColumnIndex("Genre"));
            //String songPlayCount = cursor.getString(cursor.getColumnIndex("_count"));
            String songRating = cursor.getString(cursor.getColumnIndex("Rating"));
            String songSource = DBAccessHelper.GMUSIC;
            String songAlbumArtPath = cursor.getString(cursor.getColumnIndex("album_art"));
            String songID = cursor.getString(cursor.getColumnIndex("SourceId"));
            //String artistID = cursor.getString(cursor.getColumnIndex("artistId"));
            String storeAlbumID = cursor.getString(cursor.getColumnIndex("StoreAlbumId"));

            String songArtistArtPath = "";
            if (projectionFailed == false) {
                songArtistArtPath = cursor.getString(cursor.getColumnIndex("ArtistArtLocation"));
            } else {
                //Fall back on album art.
                songArtistArtPath = cursor.getString(cursor.getColumnIndex("album_art"));
            }

            //Prepare the genres ArrayList.
            if (!genresList.contains(songGenre)) {
                genresList.add(songGenre);
            }

            //Filter out track numbers and remove any bogus values.
            if (songTrackNumber != null) {
                if (songTrackNumber.contains("/")) {
                    int index = songTrackNumber.lastIndexOf("/");
                    songTrackNumber = songTrackNumber.substring(0, index);
                }

            }

            if (songYear.equals("0")) {
                songYear = "";
            }

            //Check if any of the other tags were empty/null and set them to "Unknown xxx" values.
            if (songArtist == null || songArtist.isEmpty() || songArtist.equals(" ")) {
                songArtist = "Unknown Artist";
            }

            if (songAlbumArtist == null || songAlbumArtist.isEmpty() || songAlbumArtist.equals(" ")) {
                songAlbumArtist = "Unknown Album Artist";
            }

            if (songAlbum == null || songAlbum.isEmpty() || songAlbum.equals(" ")) {
                songAlbum = "Unknown Album";
            }

            if (songGenre == null || songGenre.isEmpty() || songGenre.equals(" ")) {
                songGenre = "Unknown Genre";
            }

            ContentValues values = new ContentValues();
            values.put(DBAccessHelper.SONG_TITLE, songTitle);
            values.put(DBAccessHelper.SONG_ARTIST, songArtist);
            values.put(DBAccessHelper.SONG_ALBUM, songAlbum);
            values.put(DBAccessHelper.SONG_ALBUM_ARTIST, songAlbumArtist);
            values.put(DBAccessHelper.SONG_DURATION, songDuration);
            values.put(DBAccessHelper.SONG_FILE_PATH, songID);
            values.put(DBAccessHelper.SONG_TRACK_NUMBER, songTrackNumber);
            values.put(DBAccessHelper.SONG_GENRE, songGenre);
            //values.put(DBAccessHelper.SONG_PLAY_COUNT, songPlayCount);
            values.put(DBAccessHelper.SONG_YEAR, songYear);
            values.put(DBAccessHelper.SONG_LAST_MODIFIED, "");
            values.put(DBAccessHelper.BLACKLIST_STATUS, "FALSE"); //Keep the song whitelisted by default.
            values.put(DBAccessHelper.ADDED_TIMESTAMP, date.getTime());
            values.put(DBAccessHelper.RATING, songRating);
            values.put(DBAccessHelper.SONG_SOURCE, songSource);
            values.put(DBAccessHelper.SONG_ALBUM_ART_PATH, songAlbumArtPath);
            values.put(DBAccessHelper.SONG_ID, songID);
            values.put(DBAccessHelper.ARTIST_ART_LOCATION, songArtistArtPath);
            //values.put(DBAccessHelper.ARTIST_ID, artistID);
            values.put(DBAccessHelper.ALBUM_ID, storeAlbumID);

            /* We're gonna have to save the song ID into the SONG_FILE_PATH 
             * field. Google Play Music playlist songs don't have a file path, but we're using a 
             * JOIN in PlaylistsFlippedFragment that relies on this field, so we'll need to use the 
             * song ID as a placeholder instead.
             */
            values.put(DBAccessHelper.SONG_FILE_PATH, songID);

            //Add all the entries to the database to build the songs library.
            mApp.getDBAccessHelper().getWritableDatabase().insert(DBAccessHelper.MUSIC_LIBRARY_TABLE, null,
                    values);

        }

        mApp.getDBAccessHelper().getWritableDatabase().setTransactionSuccessful();

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        //Close the transaction.
        mApp.getDBAccessHelper().getWritableDatabase().endTransaction();

        if (cursor != null) {
            cursor.close();
            cursor = null;
        }

    }

    /****************************************************************************
     * BUILD PLAYLISTS LIBRARY
     ****************************************************************************/
    //getPlaylistsWebClient();
    //getPlaylistsMobileClient();

    //Update the genres library.
    updateGenreSongCount();

    return "SUCCESS";
}