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:org.callimachusproject.behaviours.SqlDatasourceSupport.java

private ClassLoader createClassLoader() {
    List<URL> urls = new ArrayList<URL>();
    for (RDFObject jar : this.getCalliDriverJar()) {
        try {//from   w  w  w .  j  a  va 2s  .c o m
            urls.add(new URL(jar.getResource().stringValue()));
        } catch (MalformedURLException e) {
            logger.warn(e.toString(), e);
        }
    }
    return URLClassLoader.newInstance(urls.toArray(new URL[urls.size()]));
}

From source file:it.isti.cnr.hpc.europeana.hackthon.domain.GoogleQuery2Entity.java

public List<Result> getResults(String query) throws InterruptedException {
    URL mapWikipedia;//from ww w.  j a va 2  s .com
    try {
        mapWikipedia = new URL(query);
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        logger.error(e.toString());
        return null;
    }
    URLConnection urlc;
    try {
        urlc = mapWikipedia.openConnection();
    } catch (IOException e) {
        logger.error(e.toString());
        return null;
    }
    urlc.setRequestProperty("User-Agent",
            "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11");

    InputStream is;
    try {
        is = urlc.getInputStream();
    } catch (IOException e) {
        logger.error(e.toString());
        if (e.toString().contains("sorry")) {
            logger.error("SLEEP!");
            try {
                Thread.sleep(60000 * 30);
            } catch (InterruptedException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
        return null;
    }
    try {
        Thread.sleep(500);
    } catch (InterruptedException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    }
    BufferedReader in = new BufferedReader(new InputStreamReader(is));
    String inputLine;
    boolean bodyFound = false;
    StringBuilder sb = new StringBuilder();

    try {
        while ((inputLine = in.readLine()) != null) {
            // Process each line.
            if (inputLine.contains("<body"))
                bodyFound = true;
            if (bodyFound)
                sb.append(inputLine).append(" ");
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        logger.error(e.toString());
        if (e.toString().contains("sorry")) {
            logger.error("SLEEP!");
            try {
                Thread.sleep(60000 * 30);
            } catch (InterruptedException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
        return null;
    }
    try {
        in.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        logger.error(e.toString());

        return null;
    }

    return parseResults(sb.toString());
}

From source file:org.openhab.binding.efergyengage.internal.EfergyEngageBinding.java

private void login() {
    String url = null;/*w ww. j a v a  2s.com*/
    StringBuilder body = null;

    try {
        url = EFERGY_URL + "/mobile/get_token?device=android&username=" + email + "&password=" + password;

        URL tokenUrl = new URL(url);
        URLConnection connection = tokenUrl.openConnection();

        //get token
        InputStream response = connection.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(response));
        String line = reader.readLine();
        JsonObject jobject = parser.parse(line).getAsJsonObject();
        String status = jobject.get("status").getAsString();

        if (status.equals("ok")) {
            token = jobject.get("token").getAsString();
            logger.debug("Efergy token: " + token);
        } else {
            logger.debug("Efergy login response: " + line);
            throw new EfergyEngageException(jobject.get("desc").getAsString());
        }
    } catch (MalformedURLException e) {
        logger.error("The URL '" + url + "' is malformed: " + e.toString());
    } catch (Exception e) {
        logger.error("Cannot get Efergy Engage token: " + e.toString());
    }
}

From source file:com.owly.srv.RemoteBasicStatItfImpl.java

public RemoteBasicStat getRemoteStatistic(String nameSrv, String ipSrv, String typeSrv, String typeStat,
        int clientPort) {

    URL url = null;/*from w  w  w  .j  a va2 s.com*/
    BufferedReader reader = null;
    StringBuilder stringBuilder;
    JSONObject objJSON = new JSONObject();
    JSONParser objParser = new JSONParser();
    RemoteBasicStat remoteBasicStat = new RemoteBasicStat();

    HttpURLConnection connection;

    // URL ot execute and get a Basic Stadistic.
    // Url to send to remote server
    // for example :
    // http://135.1.128.127:5000/OwlyClnt/Stats_TopCPU
    String urlToSend = "http://" + ipSrv + ":" + clientPort + "/OwlyClnt/" + typeStat;
    logger.debug("URL for HTTP request :  " + urlToSend);

    try {
        url = new URL(urlToSend);
        connection = (HttpURLConnection) url.openConnection();

        // just want to do an HTTP GET here
        connection.setRequestMethod("GET");

        // uncomment this if you want to write output to this url
        // connection.setDoOutput(true);

        // give it 15 seconds to respond
        connection.setReadTimeout(3 * 1000);
        connection.connect();

        // read the output from the server
        reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        stringBuilder = new StringBuilder();

        String line = null;
        while ((line = reader.readLine()) != null) {
            stringBuilder.append(line + "\n");
        }
        logger.debug("Response received : " + stringBuilder.toString());
        // Get the response and save into a JSON object, and parse the
        // JSON object
        objJSON = (JSONObject) objParser.parse(stringBuilder.toString());
        logger.debug("JSON received : " + objJSON.toString());

        // Add all info received in a new object of satistics
        remoteBasicStat.setRmtSeverfromJSONObject(objJSON);

        // Add more details for the stadistics.
        remoteBasicStat.setIpServer(ipSrv);
        logger.debug("IP of server : " + remoteBasicStat.getIpServer());

        remoteBasicStat.setNameServer(nameSrv);
        logger.debug("Name of Server : " + remoteBasicStat.getNameServer());

        remoteBasicStat.setTypeServer(typeSrv);
        logger.debug("Type of Server : " + remoteBasicStat.getTypeServer());

    } catch (MalformedURLException e) {
        logger.error("MalformedURLException : " + e.getMessage());
        logger.error("Exception ::", e);
    } catch (IOException e) {
        logger.error("IOException : " + e.toString());
        logger.error("Exception ::", e);
    } catch (ParseException e) {
        logger.error("ParseException : " + e.toString());
        logger.error("Exception ::", e);
    }
    return remoteBasicStat;

}

From source file:org.openhab.binding.efergyengage.internal.EfergyEngageBinding.java

private EfergyEngageMeasurement readInstant() {
    String url = null;//from   w w w  .  j a  v a2  s  .  com
    int instant;
    EfergyEngageMeasurement measurement = new EfergyEngageMeasurement();

    try {
        url = EFERGY_URL + "/mobile_proxy/getInstant?token=" + token;
        URL valueUrl = new URL(url);
        URLConnection connection = valueUrl.openConnection();

        //read response
        InputStream response = connection.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(response));
        StringBuilder body = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            body.append(line + "\n");
        }

        //read value
        parser = new JsonParser();
        JsonObject jobject = parser.parse(body.toString()).getAsJsonObject();
        if (jobject != null && jobject.get("reading") != null) {
            instant = jobject.get("reading").getAsInt();
            logger.debug("Efergy reading: " + instant);
            measurement.setValue(instant);
            measurement.setMilis(jobject.get("last_reading_time").getAsLong());
        }
    } catch (MalformedURLException e) {
        logger.error("The URL '" + url + "' is malformed: " + e.toString());
    } catch (Exception e) {
        logger.error("Cannot get Efergy Engage data: " + e.toString());
    }

    return measurement;
}

From source file:org.openhab.binding.efergyengage.internal.EfergyEngageBinding.java

private EfergyEngageMeasurement readEnergy(String period) {
    String url = null;//from   www.  j  av  a2s . c  om
    EfergyEngageMeasurement measurement = new EfergyEngageMeasurement();

    try {
        url = EFERGY_URL + "/mobile_proxy/getEnergy?token=" + token + "&period=" + period + "&offset="
                + utcOffset;
        URL valueUrl = new URL(url);
        URLConnection connection = valueUrl.openConnection();

        //read response
        InputStream response = connection.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(response));
        StringBuilder body = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            body.append(line + "\n");
        }

        //read value
        JsonObject jobject = parser.parse(body.toString()).getAsJsonObject();
        if (jobject != null && jobject.get("sum") != null && jobject.get("units") != null) {
            String energy = jobject.get("sum").getAsString();
            String units = jobject.get("units").getAsString();

            logger.debug("Efergy reading for " + period + " period: " + energy + " " + units);
            measurement.setValue(Float.valueOf(energy.trim()).floatValue());
            measurement.setUnit(units);
        }
    } catch (MalformedURLException e) {
        logger.error("The URL '" + url + "' is malformed: " + e.toString());
    } catch (Exception e) {
        logger.error("Cannot get Efergy Engage data: " + e.toString());
    }
    return measurement;
}

From source file:foam.littlej.android.app.net.MainHttpClient.java

public String SendMultiPartData(String URL, MultipartEntity postData) throws IOException {

    Log.d(CLASS_TAG, "PostFileUpload(): upload file to server.");

    // Dipo Fix//from   w  ww . ja v a 2 s.c om
    try {
        // wrap try around because this constructor can throw Error
        final HttpPost httpost = new HttpPost(URL);

        if (postData != null) {
            Log.i(CLASS_TAG, "PostFileUpload(): ");
            // NEED THIS NOW TO FIX ERROR 417
            httpost.getParams().setBooleanParameter("http.protocol.expect-continue", false);
            httpost.setEntity(postData);
            // Header
            // httpost.addHeader("Authorization","Basic "+
            // getCredentials(userName, userPassword));
            HttpResponse response = httpClient.execute(httpost);
            Preferences.httpRunning = false;

            HttpEntity respEntity = response.getEntity();
            if (respEntity != null) {
                InputStream serverInput = respEntity.getContent();

                return GetText(serverInput);

            }
        }

    } catch (MalformedURLException ex) {
        log("MalformedURLException", ex.toString());
        ex.printStackTrace();
        return "";
        // fall through and return false
    } catch (Exception ex) {
        return "";
    }
    return "";
}

From source file:org.apache.hadoop.sqoop.manager.LocalMySQLManager.java

/**
 * Import the table into HDFS by using mysqldump to pull out the data from
 * the database and upload the files directly to HDFS.
 *///  w w w .  j  a va  2  s .c  o m
public void importTable(String tableName, String jarFile, Configuration conf) throws IOException, ImportError {

    LOG.info("Beginning mysqldump fast path import");

    if (options.getFileLayout() != ImportOptions.FileLayout.TextFile) {
        // TODO(aaron): Support SequenceFile-based load-in
        LOG.warn("File import layout " + options.getFileLayout() + " is not supported by");
        LOG.warn("MySQL local import; import will proceed as text files.");
    }

    ArrayList<String> args = new ArrayList<String>();

    // We need to parse the connect string URI to determine the database
    // name. Using java.net.URL directly on the connect string will fail because
    // Java doesn't respect arbitrary JDBC-based schemes. So we chop off the scheme
    // (everything before '://') and replace it with 'http', which we know will work.
    String connectString = options.getConnectString();
    String databaseName = null;
    try {
        String sanitizedString = null;
        int schemeEndOffset = connectString.indexOf("://");
        if (-1 == schemeEndOffset) {
            // couldn't find one? try our best here.
            sanitizedString = "http://" + connectString;
            LOG.warn("Could not find database access scheme in connect string " + connectString);
        } else {
            sanitizedString = "http" + connectString.substring(schemeEndOffset);
        }

        URL connectUrl = new URL(sanitizedString);
        databaseName = connectUrl.getPath();
    } catch (MalformedURLException mue) {
        LOG.error("Malformed connect string URL: " + connectString + "; reason is " + mue.toString());
    }

    if (null == databaseName) {
        throw new ImportError("Could not determine database name");
    }

    // database name was found from the 'path' part of the URL; trim leading '/'
    while (databaseName.startsWith("/")) {
        databaseName = databaseName.substring(1);
    }

    LOG.info("Performing import of table " + tableName + " from database " + databaseName);

    args.add(MYSQL_DUMP_CMD); // requires that this is on the path.
    args.add("--skip-opt");
    args.add("--compact");
    args.add("--no-create-db");
    args.add("--no-create-info");

    String username = options.getUsername();
    if (null != username) {
        args.add("--user=" + username);
    }

    String password = options.getPassword();
    if (null != password) {
        // TODO(aaron): This is really insecure.
        args.add("--password=" + password);
    }

    args.add("--quick"); // no buffering
    // TODO(aaron): Add a flag to allow --lock-tables instead for MyISAM data
    args.add("--single-transaction");

    args.add(databaseName);
    args.add(tableName);

    Process p = null;
    try {
        // begin the import in an external process.
        LOG.debug("Starting mysqldump with arguments:");
        for (String arg : args) {
            LOG.debug("  " + arg);
        }

        p = Runtime.getRuntime().exec(args.toArray(new String[0]));

        // read from the pipe, into HDFS.
        InputStream is = p.getInputStream();
        OutputStream os = null;

        BufferedReader r = null;
        BufferedWriter w = null;

        try {
            r = new BufferedReader(new InputStreamReader(is));

            // create the paths/files in HDFS 
            FileSystem fs = FileSystem.get(conf);
            String warehouseDir = options.getWarehouseDir();
            Path destDir = null;
            if (null != warehouseDir) {
                destDir = new Path(new Path(warehouseDir), tableName);
            } else {
                destDir = new Path(tableName);
            }

            LOG.debug("Writing to filesystem: " + conf.get("fs.default.name"));
            LOG.debug("Creating destination directory " + destDir);
            fs.mkdirs(destDir);
            Path destFile = new Path(destDir, "data-00000");
            LOG.debug("Opening output file: " + destFile);
            if (fs.exists(destFile)) {
                Path canonicalDest = destFile.makeQualified(fs);
                throw new IOException("Destination file " + canonicalDest + " already exists");
            }

            os = fs.create(destFile);
            w = new BufferedWriter(new OutputStreamWriter(os));

            // Actually do the read/write transfer loop here.
            int preambleLen = -1; // set to this for "undefined"
            while (true) {
                String inLine = r.readLine();
                if (null == inLine) {
                    break; // EOF.
                }

                // this line is of the form "INSERT .. VALUES ( actual value text );"
                // strip the leading preamble up to the '(' and the trailing ');'.
                if (preambleLen == -1) {
                    // we haven't determined how long the preamble is. It's constant
                    // across all lines, so just figure this out once.
                    String recordStartMark = "VALUES (";
                    preambleLen = inLine.indexOf(recordStartMark) + recordStartMark.length();
                }

                // chop off the leading and trailing text as we write the
                // output to HDFS.
                w.write(inLine, preambleLen, inLine.length() - 2 - preambleLen);
                w.newLine();
            }
        } finally {
            LOG.info("Transfer loop complete.");
            if (null != r) {
                try {
                    r.close();
                } catch (IOException ioe) {
                    LOG.info("Error closing FIFO stream: " + ioe.toString());
                }
            }

            if (null != w) {
                try {
                    w.close();
                } catch (IOException ioe) {
                    LOG.info("Error closing HDFS stream: " + ioe.toString());
                }
            }
        }
    } finally {
        int result = 0;
        if (null != p) {
            while (true) {
                try {
                    result = p.waitFor();
                } catch (InterruptedException ie) {
                    // interrupted; loop around.
                    continue;
                }

                break;
            }
        }

        if (0 != result) {
            throw new IOException("mysqldump terminated with status " + Integer.toString(result));
        }
    }
}

From source file:com.qut.middleware.esoemanager.manager.logic.impl.ServiceCryptoImpl.java

private String generateSubjectDN(String service) {
    try {/*ww  w  .ja  v a 2s .co  m*/
        String result = new String();
        URL serviceURL = new URL(service);
        String[] components = serviceURL.getHost().split("\\.");
        for (String component : components) {
            if (result.length() != 0)
                result = result + ",";

            result = result + "dc=" + component;
        }
        return result;
    } catch (MalformedURLException e) {
        this.logger.error("Error attempting to generate certificate subjectDN " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        return "dc=" + service;
    }
}

From source file:sk.styk.martin.bakalarka.downloaders.DownloadTask.java

@Override
public void run() {

    logger.info("Starting download from " + urlString);

    URL url = null;//from   ww w  .  j a v  a  2s.c  o  m
    try {
        url = new URL(urlString);
    } catch (MalformedURLException e) {
        logger.error("Malformed URL : " + urlString);
    }
    try {
        file.createNewFile();
    } catch (IOException e) {
        logger.error("File can not be created " + urlString);
    }
    try {
        FileUtils.copyURLToFile(url, file);
    } catch (IOException e) {
        file.delete();
        logger.error("File can not be downloaded " + urlString + "\n" + e.toString());
    }

    logger.info("Finished download from " + urlString);

}