Example usage for java.net MalformedURLException toString

List of usage examples for java.net MalformedURLException toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:gov.usda.DataCatalogClient.Distribution.java

private void setDownloadURL(String downloadURL_String) throws DistributionException {
    if (downloadURL_String != null) {
        try {//from   w  w  w.j av a  2  s .  c om
            this.downloadURL = new URL(downloadURL_String);
        } catch (MalformedURLException e) {
            throw new DistributionException("Invalid downloadUrl:" + e.toString());
        }
    }
}

From source file:com.weimed.app.sync.SyncAdapter.java

/**
 * Called by the Android system in response to a request to run the sync adapter. The work
 * required to read data from the network, parse it, and store it in the content provider is
 * done here. Extending AbstractThreadedSyncAdapter ensures that all methods within SyncAdapter
 * run on a background thread. For this reason, blocking I/O and other long-running tasks can be
 * run <em>in site</em>, and you don't have to set up a separate thread for them.
 .
 *
 * <p>This is where we actually perform any work required to perform a sync.
 * {@link android.content.AbstractThreadedSyncAdapter} guarantees that this will be called on a non-UI thread,
 * so it is safe to preform blocking I/O here.
 *
 * <p>The syncResult argument allows you to pass information back to the method that triggered
 * the sync.//from   w w  w.  j a v  a 2 s  .  c  o m
 */
@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider,
        SyncResult syncResult) {
    Log.i(TAG, "Beginning network synchronization");
    try {
        final URL location = new URL(NEWS_URL);
        InputStream stream = null;

        try {
            Log.i(TAG, "Streaming data from network: " + location);
            stream = downloadUrl(location);
            updateLocalJSONData(stream, syncResult);
            // Makes sure that the InputStream is closed after the app is
            // finished using it.
        } finally {
            if (stream != null) {
                stream.close();
            }
        }
    } catch (MalformedURLException e) {
        Log.e(TAG, "Feed URL is malformed", e);
        syncResult.stats.numParseExceptions++;
        return;
    } catch (IOException e) {
        Log.e(TAG, "Error reading from network: " + e.toString());
        syncResult.stats.numIoExceptions++;
        return;
    } catch (JSONException e) {
        Log.e(TAG, "Error parsing feed: " + e.toString());
        syncResult.stats.numParseExceptions++;
        return;
    } catch (ParseException e) {
        Log.e(TAG, "Error parsing feed: " + e.toString());
        syncResult.stats.numParseExceptions++;
        return;
    } catch (RemoteException e) {
        Log.e(TAG, "Error updating database: " + e.toString());
        syncResult.databaseError = true;
        return;
    } catch (OperationApplicationException e) {
        Log.e(TAG, "Error updating database: " + e.toString());
        syncResult.databaseError = true;
        return;
    }
    Log.i(TAG, "Network synchronization complete");
}

From source file:edu.caltech.ipac.firefly.server.catquery.SDSSQuery.java

@Override
protected File loadDataFile(TableServerRequest request) throws IOException, DataAccessException {

    File outFile;//from ww  w.  j a  v  a 2  s.com
    try {
        // votable has utf-16 encoding, which mismatches the returned content type
        // this confuses tools
        File csv = createFile(request, ".csv");
        String uploadFname = request.getParam(SDSSRequest.FILE_NAME);
        if (StringUtils.isEmpty(uploadFname)) {

            URL url = createGetURL(request);

            URLConnection conn = URLDownload.makeConnection(url);
            conn.setRequestProperty("Accept", "*/*");

            URLDownload.getDataToFile(conn, csv);
        } else {
            File uploadFile = ServerContext.convertToFile(uploadFname);
            File sdssUFile;
            if (uploadFile.canRead()) {
                sdssUFile = getSDSSUploadFile(uploadFile);
            } else {
                throw new EndUserException("SDSS catalog search failed",
                        "Can not read uploaded file: " + uploadFname);
            }

            URL url = new URL(SERVICE_URL_UPLOAD);
            // use uploadFname
            //POST http://skyserver.sdss3.org/public/en/tools/crossid/x_crossid.aspx

            _postBuilder = new MultiPartPostBuilder(url.toString());
            if (_postBuilder == null) {
                throw new EndUserException("Failed to create HTTP POST request", "URL " + SERVICE_URL_UPLOAD);
            }

            insertPostParams(request, sdssUFile);
            BufferedOutputStream writer = new BufferedOutputStream(new FileOutputStream(csv), 10240);
            MultiPartPostBuilder.MultiPartRespnse resp = null;
            try {
                resp = _postBuilder.post(writer);
            } finally {
                writer.close();
            }

            if (resp == null) {
                throw new IOException("Exception during post");
            } else if (resp.getStatusCode() < 200 || resp.getStatusCode() > 300) {
                // throw new IOException(resp.getStatusMsg());
                // try repeating the request through CasJobs
                boolean nearestOnly = request.getBooleanParam(SDSSRequest.NEAREST_ONLY);
                String radiusArcMin = request.getParam(SDSSRequest.RADIUS_ARCMIN);
                SDSSCasJobs.getCrossMatchResults(sdssUFile, nearestOnly, radiusArcMin, csv);
            }
        }

        // check for errors in returned file
        evaluateCVS(csv);

        DataGroup dg = DsvToDataGroup.parse(csv, CSVFormat.DEFAULT.withCommentStart('#'));
        if (dg == null) {
            _log.briefInfo("no data found for search");
            return null;
        }

        /*
        //TG No need to decrement up_id, since we are using the original upload id
        if (!StringUtils.isEmpty(uploadFname) && dg.containsKey("up_id")) {
        // increment up_id(uploaded id) by 1 if it's an multi object search
        DataType upId = dg.getDataDefintion("up_id");
        for(DataObject row : dg) {
            int id = StringUtils.getInt(String.valueOf(row.getDataElement(upId)), -1);
            if (id >= 0) {
                row.setDataElement(upId, id + 1);
            }
        }
        }
        */

        outFile = createFile(request, ".tbl");
        IpacTableWriter.save(outFile, dg);

    } catch (MalformedURLException e) {
        _log.error(e, "Bad URL");
        throw makeException(e, "SDSS Catalog Query Failed - bad url");
    } catch (IOException e) {
        _log.error(e, e.toString());
        throw makeException(e, "SDSS Catalog Query Failed - network Error");
    } catch (EndUserException e) {
        _log.error(e, e.toString());
        throw makeException(e, "SDSS Catalog Query Failed - network Error");
    } catch (Exception e) {
        _log.error(e, e.toString());
        throw makeException(e, "SDSS Catalog Query Failed");
    }
    return outFile;
}

From source file:com.example.android.basicsyncadapter.SyncAdapter.java

/**
 * Called by the Android system in response to a request to run the sync adapter. The work required to read data from the network,
 * parse it, and store it in the content provider is done here. Extending AbstractThreadedSyncAdapter ensures that all methods
 * within SyncAdapter run on a background thread. For this reason, blocking I/O and other long-running tasks can be run
 * <em>in situ</em>, and you don't have to set up a separate thread for them.
 *
 * <p>This is where we actually perform any work required to perform a sync. {@link android.content.AbstractThreadedSyncAdapter}
 * guarantees that this will be called on a non-UI thread, so it is safe to peform blocking I/O here.
 *
 * <p>The syncResult argument allows you to pass information back to the method that triggered the sync.
 *///from w w w.j  a  v  a2s  .  c  o  m
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider,
        SyncResult syncResult) {
    Log.i(TAG, "Beginning network synchronization");
    try {
        InputStream stream = null;

        try {
            //Log.i(TAG, "Streaming data from network: " + FEED_URL);
            //stream = downloadUrl(location);
            stream = downloadUrl(FEED_URL);
            updateLocalFeedData(stream, syncResult);
        } finally {
            if (stream != null) {
                stream.close();
            }
        }
    } catch (MalformedURLException e) {
        Log.e(TAG, "Feed URL is malformed", e);
        syncResult.stats.numParseExceptions++;
        return;
    } catch (IOException e) {
        Log.e(TAG, "Error reading from network: " + e.toString());
        syncResult.stats.numIoExceptions++;
        return;
    } catch (XmlPullParserException e) {
        Log.e(TAG, "Error parsing feed: " + e.toString());
        syncResult.stats.numParseExceptions++;
        return;
    } catch (ParseException e) {
        Log.e(TAG, "Error parsing feed: " + e.toString());
        syncResult.stats.numParseExceptions++;
        return;
    } catch (RemoteException e) {
        Log.e(TAG, "Error updating database: " + e.toString());
        syncResult.databaseError = true;
        return;
    } catch (OperationApplicationException e) {
        Log.e(TAG, "Error updating database: " + e.toString());
        syncResult.databaseError = true;
        return;
    }
    Log.i(TAG, "Network synchronization complete");

    //Throw notification

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getContext())
            .setSmallIcon(R.drawable.ic_launcher).setContentTitle("Alerta de cicln tropical")
            .setContentText("Hello World!").setAutoCancel(true).setLights(0xff00ff00, 300, 100)
            .setPriority(Notification.PRIORITY_MAX);

    Intent resultIntent = new Intent(getContext(), EntryListActivity.class);
    PendingIntent resultPendingIntent = PendingIntent.getActivity(getContext(), 0, resultIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    //Add sound
    Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    //Add vibrate pattern
    long[] pattern = { 0, 200, 500 };

    mBuilder.setVibrate(pattern);
    mBuilder.setSound(alarmSound);
    mBuilder.setContentIntent(resultPendingIntent);

    int mNotificationId = 001;
    NotificationManager mNotifyMgr = (NotificationManager) getContext()
            .getSystemService(Service.NOTIFICATION_SERVICE);
    mNotifyMgr.notify(mNotificationId, mBuilder.build());

    //Wake screen
    /*WakeLock screenOn = ((PowerManager)getContext().getSystemService(Service.POWER_SERVICE)).newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK| PowerManager.ACQUIRE_CAUSES_WAKEUP, "example");
    screenOn.acquire();
            
    long endTime = System.currentTimeMillis() + 6*1000;
    while (System.currentTimeMillis() < endTime) {
    synchronized (this) {
        try {
            wait(endTime - System.currentTimeMillis());
        } catch (Exception e) {
        }
    }
    }
            
    screenOn.release();*/
}

From source file:ffx.FFXClassLoader.java

/**
 * {@inheritDoc}// ww w  .  ja va2  s.co  m
 *
 * Returns the URL of the given resource searching first if it exists among
 * the extension JARs given in constructor.
 */
@Override
public URL findResource(String name) {
    if (!extensionsLoaded) {
        loadExtensions();
    }

    if (name.equals("List all scripts")) {
        listScripts();
    }

    if (extensionJars != null) {
        for (JarFile extensionJar : extensionJars) {
            JarEntry jarEntry = extensionJar.getJarEntry(name);
            if (jarEntry != null) {
                String path = "jar:file:" + extensionJar.getName() + "!/" + jarEntry.getName();
                try {
                    return new URL(path);
                } catch (MalformedURLException ex) {
                    System.out.println(path + "\n" + ex.toString());
                }
            }
        }
    }

    return super.findResource(name);
}

From source file:phex.download.handler.HttpThexDownload.java

public void processDownload() throws IOException {
    SWDownloadSet downloadSet = downloadEngine.getDownloadSet();
    SWDownloadCandidate candidate = downloadSet.downloadCandidate;
    SWDownloadFile downloadFile = downloadSet.downloadFile;

    logger.debug("Download Engine starts download.");
    LengthLimitedInputStream downloadStream = null;
    try {//  ww w .  j  a  v  a2s  .  c  o m

        // determine the length to download, we start with the MAX
        // which would cause a download until the stream ends.
        long downloadLengthLeft = Long.MAX_VALUE;
        // maybe we know a reply content length
        if (replyContentLength != -1) {
            downloadLengthLeft = Math.min(replyContentLength, downloadLengthLeft);
        }

        downloadStream = new LengthLimitedInputStream(inStream, downloadLengthLeft);

        DimeParser dimeParser = new DimeParser(downloadStream);

        List<DimeRecord> records = DimeParser.getAllRecords(dimeParser);

        if (records.size() < 2) {
            throw new IOException("Required dime records not found.");
        }
        DimeRecord xmlRecord = records.get(0);
        DimeRecord hashRecord = records.get(1);

        byte[] xmlData = xmlRecord.getData();

        // it seems like Bearshare is appending artifacts to the xml dime record entry.
        // try to remove them
        if (candidate.getVendor().toLowerCase(Locale.US).contains("bearshare")) {
            int idx = xmlData.length - 1;
            while (xmlData[idx] != 0x3e) {
                idx--;
            }
            if (idx < xmlData.length - 1) {
                byte[] newXmlData = new byte[idx + 1];
                System.arraycopy(xmlData, 0, newXmlData, 0, idx + 1);
                xmlData = newXmlData;
            }
        }

        ThexHashTree xmlTree;
        try {
            xmlTree = ThexHashTreeCodec.parseThexHashTreeXML(new ByteArrayInputStream(xmlData));
        } catch (MalformedURLException exp) {// catch this exp for debugging purpose.
            logger.error("Failed to parse: '{}' from: {}", new String(xmlData, "UTF-8"), candidate.getVendor());
            candidate.addToCandidateLog("Failed to parse: '" + new String(xmlData, "UTF-8") + '\'');
            logger.error(exp.toString());
            throw new IOException("Parsing Thex HashTree failed.");
        } catch (IOException exp) {
            logger.error("Failed to parse: '{}' from: {}", new String(xmlData, "UTF-8"), candidate.getVendor());
            candidate.addToCandidateLog("Failed to parse: '" + new String(xmlData, "UTF-8") + '\'');
            throw exp;
        }

        long fileSize;
        try {
            fileSize = Long.parseLong(xmlTree.getFileSize());
        } catch (NumberFormatException exp) {
            throw new IOException("Invalid file size: " + xmlTree.getFileSize());
        }
        if (fileSize != downloadFile.getTotalDataSize()) {
            throw new IOException("Invalid file size: " + fileSize + '/' + downloadFile.getTotalDataSize());
        }

        byte[] hashData = hashRecord.getData();

        // first 24 bytes is the root we can verify...
        if (hashData.length < 24) {
            throw new IOException("Invalid hash data size.");
        }
        byte[] rootHash = new byte[24];
        System.arraycopy(hashData, 0, rootHash, 0, 24);
        String rootHashB32 = Base32.encode(rootHash);
        if (!candidate.getThexRoot().equals(rootHashB32)
                || !downloadFile.getThexVerificationData().getRootHash().equals(rootHashB32)) {
            throw new IOException("Root hash do not match.");
        }

        List<List<byte[]>> merkleNodes = TTHashCalcUtils.resolveMerkleNodes(hashData, fileSize);

        List<byte[]> lowestLevelNodes = merkleNodes.get(merkleNodes.size() - 1);
        thexData.setThexData(lowestLevelNodes, merkleNodes.size() - 1, fileSize);

        isDownloadSuccessful = true;
    } finally {// don't close managed file since it might be used by parallel threads.
        boolean isAcceptingNextSegment = isAcceptingNextRequest();
        candidate.addToCandidateLog("Is accepting next segment: " + isAcceptingNextSegment);
        // this is for keep alive support...
        if (isAcceptingNextSegment && downloadStream != null) {
            // only need to close and consume left overs if we plan to
            // continue using this connection.
            downloadStream.close();
        } else {
            stopDownload();
        }
    }
}

From source file:edu.indiana.lib.twinpeaks.search.HttpTransactionQueryBase.java

/**
 * Construct a new URL from base and relative components
 * @param baseComponent Base URL - the relative URL is added to this
 * @param relativeComponent A partial (or full) URL that represents our target
 * @return A full URL composed of the relative URL combined with "missing"
 *              portions taken from the base
 *//*w w  w  .  j  a  v  a2 s .  c o  m*/
public URL newFullUrl(String baseComponent, String relativeComponent) {
    try {
        URL baseUrl = new URL(baseComponent);
        return new URL(baseUrl, relativeComponent);

    } catch (MalformedURLException exception) {
        throw new SearchException(exception.toString());
    }
}

From source file:edu.indiana.lib.twinpeaks.search.HttpTransactionQueryBase.java

/**
 * Produce a target URL for this query by combining an anchor "href" value
 * with the base URL of the query page/*from www. ja  va2 s  .  com*/
 * @param anchor Anchor element
 */
public void setUrlFromAnchor(Element anchor) throws SearchException {
    String href = anchor.getAttribute("href");

    try {
        setUrl(newFullUrl(_transaction.getBaseUrlSpecification(), href));

    } catch (MalformedURLException exception) {
        throw new SearchException(exception.toString());
    }
}

From source file:edu.indiana.lib.twinpeaks.search.HttpTransactionQueryBase.java

/**
 * Produce a target URL for this query by combining the form "action" value
 * with the base URL of the query page//w  w w.  j a  v  a2s .  c  o m
 * @param pageDocument The search engine query page (as a DOM Document)
 * @param formName The name of the FORM to lookup
 *                           (eg <code>FORM name="formName"</code>)
 */
public void setUrlFromForm(Document pageDocument, String formName) throws SearchException {
    Element form;

    if ((form = getFormElement(pageDocument, formName)) == null) {
        throw new SearchException("No such form: " + formName);
    }

    try {
        setUrl(newFullUrl(_transaction.getBaseUrlSpecification(), form.getAttribute("action")));
    } catch (MalformedURLException exception) {
        throw new SearchException(exception.toString());
    }
}

From source file:org.powertac.server.CompetitionSetupService.java

@Override
public String bootSession(String bootFilename, String config, String logSuffix, String weatherData) {
    String error = null;//from w w  w.  j a v  a2 s. c om
    try {
        log.info("bootSession: bootFilename=" + bootFilename + ", config=" + config + ", logSuffix="
                + logSuffix);
        // process serverConfig now, because other options may override
        // parts of it
        serverProps.recycle();
        setConfigMaybe(config);

        // Use weather file instead of webservice, this sets baseTime also
        useWeatherDataMaybe(weatherData, true);

        // set the logfile suffix
        setLogSuffix(logSuffix, "boot");

        File bootFile = new File(bootFilename);
        if (!bootFile.getAbsoluteFile().getParentFile().canWrite()) {
            error = "Cannot write to bootstrap data file " + bootFilename;
            System.out.println(error);
        } else {
            startBootSession(bootFile);
        }
    } catch (NullPointerException npe) {
        error = "Bootstrap filename not given";
    } catch (MalformedURLException e) {
        // Note that this should not happen from the web interface
        error = "Malformed URL: " + e.toString();
        System.out.println(error);
    } catch (IOException e) {
        error = "Error reading configuration";
    } catch (ConfigurationException e) {
        error = "Error setting configuration";
    }
    return error;
}