Example usage for java.net MalformedURLException getMessage

List of usage examples for java.net MalformedURLException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:com.baidubce.services.bos.BosClient.java

/**
 * Converts the specified request object into a URL, containing all the
 * specified parameters, the specified request endpoint, etc.
 *
 * @param request The request to convert into a URL.
 * @return A new URL representing the specified request.
 *//*from w ww .jav  a2  s . c  o m*/
private URL convertRequestToUrl(InternalRequest request) {
    String resourcePath = HttpUtils.normalizePath(request.getUri().getPath());

    // Removed the padding "/" that was already added into the request's resource path.
    if (resourcePath.startsWith("/")) {
        resourcePath = resourcePath.substring(1);
    }

    // Some http client libraries (e.g. Apache HttpClient) cannot handle
    // consecutive "/"s between URL authority and path components.
    // So we escape "////..." into "/%2F%2F%2F...", in the same way as how
    // we treat consecutive "/"s in AmazonS3Client#presignRequest(...)
    String urlPath = "/" + resourcePath;
    urlPath = urlPath.replaceAll("(?<=/)/", "%2F");
    String urlString = this.config.getEndpoint() + urlPath;

    boolean firstParam = true;
    for (String param : request.getParameters().keySet()) {
        if (firstParam) {
            urlString += "?";
            firstParam = false;
        } else {
            urlString += "&";
        }

        String value = request.getParameters().get(param);
        urlString += param + "=" + HttpUtils.normalize(value);
    }

    String authorization = request.getHeaders().get(Headers.AUTHORIZATION);
    if (authorization != null) {
        if (firstParam) {
            urlString += "?";
        } else {
            urlString += "&";
        }
        urlString += "authorization" + "=" + HttpUtils.normalize(authorization);
    }

    try {
        return new URL(urlString);
    } catch (MalformedURLException e) {
        throw new BceClientException("Unable to convert request to well formed URL: " + e.getMessage(), e);
    }
}

From source file:edu.tsinghua.lumaqq.QQShowDownloadThread.java

@Override
public void run() {
    sm = QQShowManager.getInstance();//from   ww  w. ja  v a 2 s  .  c  o  m
    // URL
    String urlString = sm.getQQShowUrlString(qqNum);
    URL url = null;
    try {
        url = new URL(urlString);
    } catch (MalformedURLException e) {
        sm.threadCallback(qqNum);
        return;
    }
    File tempFile = null;
    FileOutputStream fos = null;
    try {
        log.debug("QQ?" + urlString);
        // 
        tempFile = new File(QQShowManager.QQ_SHOW_CACHE_DIR + qqNum + "-temp.gif");
        if (!tempFile.exists())
            tempFile.createNewFile();
        // ?
        fos = new FileOutputStream(tempFile);
        // ??
        byte[] buf = new byte[1024];
        bis = new BufferedInputStream(url.openStream());
        log.debug("??");
        for (int i = bis.read(buf, 0, 1024); i != -1; i = bis.read(buf, 0, 1024))
            fos.write(buf, 0, i);
        // ???????
        fos.close();
        fos = null;
        File file = new File(QQShowManager.QQ_SHOW_CACHE_DIR + qqNum + ".gif");
        log.debug("??" + (tempFile.renameTo(file) ? "?" : ""));
        log.debug("?");
    } catch (IOException e) {
        log.error("QQ???");
        // 
        if (fos != null) {
            try {
                fos.close();
                fos = null;
            } catch (IOException e1) {
                log.error(e.getMessage());
            }
        }
        if (tempFile != null && tempFile.exists())
            tempFile.delete();
    } finally {
        try {
            if (fos != null)
                fos.close();
            if (bis != null)
                bis.close();
        } catch (IOException e1) {
            log.error(e1.getMessage());
        }
        sm.threadCallback(qqNum);
        log.debug("" + qqNum + " QQ");
    }
}

From source file:com.cjbdev.echo.iss.SpaceStationSpeechlet.java

private SpeechletResponse handleCityList(final Intent intent, final Session session, String option) {

    boolean shortList = true;
    Slot stateSlot = null;/*from   w  w w  .j  av a 2s. co  m*/
    Slot letterSlot = null;
    KeyValuePair statePair = null;

    StringBuilder cityStrBldr = new StringBuilder();
    StringBuilder cardStrBldr = new StringBuilder();

    try {

        stateSlot = intent.getSlot(SLOT_STATE);

        letterSlot = intent.getSlot(SLOT_LETTER);

        if (letterSlot == null || letterSlot.getValue() == null) {
            shortList = false;
        }

        String stateObject = null;

        if (stateSlot == null || stateSlot.getValue() == null) {

            return handleStateList(intent, session, STATE_UNKNOWN);
        } else {

            // lookup the state.
            stateObject = stateSlot.getValue().trim();
        }

        for (KeyValuePair item : STATE_LOOKUP) {
            if (item.getKey().toLowerCase().equals(stateObject.toLowerCase())) {
                statePair = item;
            }
        }

        if ((statePair == null) || (statePair.getValue() == null)) {

            return handleStateList(intent, session, STATE_UNKNOWN);
        }

        if (option.equals(CITY_UNKNOWN)) {

            StringBuilder rpStrBldr = new StringBuilder();

            cityStrBldr.append("<speak>");
            cityStrBldr
                    .append("<p>The location you specified does not have sighting information available.</p>");
            cityStrBldr.append("<p>For a listing of locations in " + statePair.getKey()
                    + " say list locations in " + statePair.getKey() + ".</p>");
            cityStrBldr.append("<p>Shorten the list by saying list locations in " + statePair.getKey()
                    + " starting with A or another letter.</p>");
            cityStrBldr.append("</speak>");

            rpStrBldr.append("<speak>");
            rpStrBldr.append("<p>For a listing of locations in " + statePair.getKey()
                    + " say list locations in " + statePair.getKey() + ".</p>");
            rpStrBldr.append("<p>Shorten the list by saying list locations in " + statePair.getKey()
                    + " starting with A or another letter.</p>");
            rpStrBldr.append("</speak>");

            // Create the plain text output.
            SsmlOutputSpeech smlspeech = new SsmlOutputSpeech();
            smlspeech.setSsml(cityStrBldr.toString());

            // Create reprompt
            SsmlOutputSpeech rpsmlspeech = new SsmlOutputSpeech();
            rpsmlspeech.setSsml(rpStrBldr.toString());
            Reprompt reprompt = new Reprompt();
            reprompt.setOutputSpeech(rpsmlspeech);

            return SpeechletResponse.newAskResponse(smlspeech, reprompt);

        } else {
            cityStrBldr.append("<speak>");

            if (shortList) {
                cityStrBldr.append("<p>Locations in " + statePair.getKey() + " starting with "
                        + letterSlot.getValue().toUpperCase().charAt(0)
                        + " that have sighting information are:</p>");
                cardStrBldr.append("Locations in " + WordUtils.capitalizeFully(statePair.getKey())
                        + "starting with \"" + letterSlot.getValue().toUpperCase().charAt(0)
                        + "\" that have sighting information are:\n");
            } else {
                cityStrBldr.append(
                        "<p>Locations in " + statePair.getKey() + " that have sighting information are:</p>");
                cardStrBldr.append("Locations in " + WordUtils.capitalizeFully(statePair.getKey())
                        + " that have sighting information are:\n");
            }
        }

        InputStream in = getClass().getResourceAsStream("/speechAssets/states/" + statePair.getValue());
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));

        String sCurrentLine = "";
        int counter = 0;
        while ((sCurrentLine = reader.readLine()) != null) {
            String cityArray[] = sCurrentLine.split(",");
            String city = cityArray[0];

            if (shortList) {

                if (city.toLowerCase().charAt(0) == letterSlot.getValue().toLowerCase().charAt(0)) {
                    cityStrBldr.append("<s>" + city + "</s>");
                    cardStrBldr.append(city + "\n");
                    counter++;
                }
            } else {
                cityStrBldr.append("<s>" + city + "</s>");
                cardStrBldr.append(city + "\n");
                counter++;
            }
        }

        in.close();

        // Handle if no locations are returned.
        if (counter == 0) {

            StringBuilder noStrBldr = new StringBuilder();
            StringBuilder rpStrBldr = new StringBuilder();

            noStrBldr.append("<speak>");
            noStrBldr.append("<p>There does not appear to be any locations matching your criteria.</p>");
            noStrBldr.append("<p>For a listing of locations in " + statePair.getKey()
                    + " say list locations in " + statePair.getKey() + ".</p>");
            noStrBldr.append("<p>Shorten the list by saying list locations in " + statePair.getKey()
                    + " starting with A or another letter.</p>");
            noStrBldr.append("</speak>");

            rpStrBldr.append("<speak>");
            rpStrBldr.append("<p>For a listing of locations in " + statePair.getKey()
                    + " say list locations in " + statePair.getKey() + ".</p>");
            rpStrBldr.append("<p>Shorten the list by saying list locations in " + statePair.getKey()
                    + " starting with A or another letter.</p>");
            rpStrBldr.append("</speak>");

            // Create the plain text output.
            SsmlOutputSpeech smlspeech = new SsmlOutputSpeech();
            smlspeech.setSsml(noStrBldr.toString());

            // Create reprompt
            SsmlOutputSpeech rpsmlspeech = new SsmlOutputSpeech();
            rpsmlspeech.setSsml(rpStrBldr.toString());
            Reprompt reprompt = new Reprompt();
            reprompt.setOutputSpeech(rpsmlspeech);

            return SpeechletResponse.newAskResponse(smlspeech, reprompt);
        }

    } catch (MalformedURLException muex) {
        System.out.println("MalformedURLException" + muex.getMessage());
    } catch (IOException ioex) {
        System.out.println("IOException" + ioex.getMessage());
    } catch (Exception ex) {
        System.out.println("Exeption" + ex.getMessage());
    }

    cityStrBldr.append("<p>You can get sighting information for a location by saying "
            + "give me visibility for Gaithersburg Maryland or some other location and state combination.</p>");
    cardStrBldr.append("You can get sighting information for a location by saying "
            + "give me visibility for Gaithersburg Maryland or some other location and state combination.\n");
    cityStrBldr.append("</speak>");

    // Create the Simple card content.
    SimpleCard card = new SimpleCard();
    if (shortList) {
        card.setTitle("ISS - Location Listing: " + WordUtils.capitalizeFully(statePair.getKey())
                + " starting with \"" + letterSlot.getValue().toUpperCase().charAt(0) + "\"");
    } else {
        card.setTitle("ISS - Location Listing: " + WordUtils.capitalizeFully(statePair.getKey()));
    }

    card.setContent(cardStrBldr.toString());

    // Create the ssmloutput text output.
    SsmlOutputSpeech smlspeech = new SsmlOutputSpeech();
    smlspeech.setSsml(cityStrBldr.toString());

    StringBuilder rpStrBldr = new StringBuilder();
    rpStrBldr.append("<speak>");
    rpStrBldr.append("<p>You can get sighting information for a location by saying "
            + "give me visibility for Gaithersburg Maryland or some other location and state combination.</p>");
    rpStrBldr.append("</speak>");

    SsmlOutputSpeech rpsmlspeech = new SsmlOutputSpeech();
    rpsmlspeech.setSsml(rpStrBldr.toString());

    Reprompt reprompt = new Reprompt();
    reprompt.setOutputSpeech(rpsmlspeech);

    return SpeechletResponse.newAskResponse(smlspeech, reprompt, card);
}

From source file:com.cjbdev.echo.iss.SpaceStationSpeechlet.java

private SpeechletResponse handleCountryLocationList(final Intent intent, final Session session, String option) {

    boolean shortList = true;
    Slot countrySlot = null;/*from w ww .  j a va 2  s  .  c o m*/
    Slot letterSlot = null;
    KeyValuePair countryPair = null;

    StringBuilder locationStrBldr = new StringBuilder();
    StringBuilder cardStrBldr = new StringBuilder();

    try {

        countrySlot = intent.getSlot(SLOT_COUNTRY);
        letterSlot = intent.getSlot(SLOT_LETTER);

        if (letterSlot == null || letterSlot.getValue() == null) {
            shortList = false;
        }

        String countryObject = null;

        if (countrySlot == null || countrySlot.getValue() == null) {

            return handleCountryList(intent, session, COUNTRY_UNKNOWN);
        } else {

            // lookup the country.
            countryObject = countrySlot.getValue().trim();
        }

        for (KeyValuePair item : COUNTRY_LOOKUP) {
            if (item.getKey().toLowerCase().equals(countryObject.toLowerCase())) {
                countryPair = item;
            }
        }

        if ((countryPair == null) || (countryPair.getValue() == null)) {

            return handleCountryList(intent, session, COUNTRY_UNKNOWN);
        }

        if (option.equals(CITY_UNKNOWN)) {

            StringBuilder rpStrBldr = new StringBuilder();

            locationStrBldr.append("<speak>");
            locationStrBldr
                    .append("<p>The location you specified does not have sighting information available.</p>");
            locationStrBldr.append("<p>For a listing of locations in " + countryPair.getKey()
                    + " say list locations in " + countryPair.getKey() + ".</p>");
            locationStrBldr.append("<p>Shorten the list by saying list locations in " + countryPair.getKey()
                    + " starting with A or another letter.</p>");
            locationStrBldr.append("</speak>");

            rpStrBldr.append("<speak>");
            rpStrBldr.append("<p>For a listing of locations in " + countryPair.getKey()
                    + " say list locations in " + countryPair.getKey() + ".</p>");
            rpStrBldr.append("<p>Shorten the list by saying list locations in " + countryPair.getKey()
                    + " starting with A or another letter.</p>");
            rpStrBldr.append("</speak>");

            // Create the plain text output.
            SsmlOutputSpeech ssmlspeech = new SsmlOutputSpeech();
            ssmlspeech.setSsml(locationStrBldr.toString());

            // Create reprompt
            SsmlOutputSpeech rpssmlspeech = new SsmlOutputSpeech();
            rpssmlspeech.setSsml(rpStrBldr.toString());
            Reprompt reprompt = new Reprompt();
            reprompt.setOutputSpeech(rpssmlspeech);

            return SpeechletResponse.newAskResponse(ssmlspeech, reprompt);

        } else {
            locationStrBldr.append("<speak>");

            if (shortList) {
                locationStrBldr.append("<p>Locations in " + countryPair.getKey() + " starting with "
                        + letterSlot.getValue().toUpperCase().charAt(0)
                        + " that have sighting information are:</p>");
                cardStrBldr.append("Locations in " + WordUtils.capitalizeFully(countryPair.getKey())
                        + "starting with \"" + letterSlot.getValue().toUpperCase().charAt(0)
                        + "\" that have sighting information are:\n");
            } else {
                locationStrBldr.append(
                        "<p>Locations in " + countryPair.getKey() + " that have sighting information are:</p>");
                cardStrBldr.append("Locations in " + WordUtils.capitalizeFully(countryPair.getKey())
                        + " that have sighting information are:\n");
            }

        }

        InputStream in = getClass().getResourceAsStream("/speechAssets/countries/" + countryPair.getValue());
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));

        String sCurrentLine = "";
        int counter = 0;
        while ((sCurrentLine = reader.readLine()) != null) {
            String locationArray[] = sCurrentLine.split(",");
            String location = locationArray[0];

            if (shortList) {

                if (location.toLowerCase().charAt(0) == letterSlot.getValue().toLowerCase().charAt(0)) {
                    locationStrBldr.append("<s>" + location + "</s>");
                    cardStrBldr.append(location + "\n");
                    counter++;
                }
            } else {
                locationStrBldr.append("<s>" + location + "</s>");
                cardStrBldr.append(location + "\n");
                counter++;
            }
        }

        in.close();

        // Handle if no locations are returned.
        if (counter == 0) {

            StringBuilder noStrBldr = new StringBuilder();
            StringBuilder rpStrBldr = new StringBuilder();

            noStrBldr.append("<speak>");
            noStrBldr.append("<p>There does not appear to be any locations matching your criteria.</p>");
            noStrBldr.append("<p>For a listing of locations in " + countryPair.getKey()
                    + " say list locations in " + countryPair.getKey() + ".</p>");
            noStrBldr.append("<p>Shorten the list by saying list locations in " + countryPair.getKey()
                    + " starting with A or another letter.</p>");
            noStrBldr.append("</speak>");

            rpStrBldr.append("<speak>");
            rpStrBldr.append("<p>For a listing of locations in " + countryPair.getKey()
                    + " say list locations in " + countryPair.getKey() + ".</p>");
            rpStrBldr.append("<p>Shorten the list by saying list locations in " + countryPair.getKey()
                    + " starting with A or another letter.</p>");
            rpStrBldr.append("</speak>");

            // Create the plain text output.
            SsmlOutputSpeech ssmlspeech = new SsmlOutputSpeech();
            ssmlspeech.setSsml(noStrBldr.toString());

            // Create reprompt
            SsmlOutputSpeech rpssmlspeech = new SsmlOutputSpeech();
            rpssmlspeech.setSsml(rpStrBldr.toString());
            Reprompt reprompt = new Reprompt();
            reprompt.setOutputSpeech(rpssmlspeech);

            return SpeechletResponse.newAskResponse(ssmlspeech, reprompt);
        }
    } catch (MalformedURLException muex) {
        System.out.println("MalformedURLException" + muex.getMessage());
    } catch (IOException ioex) {
        System.out.println("IOException" + ioex.getMessage());
    } catch (Exception ex) {
        System.out.println("Exeption" + ex.getMessage());
    }

    locationStrBldr.append("<p>You can get sighting information for a location by saying "
            + "give me visibility for London England or some other location and country combination.</p>");
    cardStrBldr.append("You can get sighting information for a location by saying "
            + "give me visibility for London England or some other location and country combination.\n");
    locationStrBldr.append("</speak>");

    // Create the Simple card content.
    SimpleCard card = new SimpleCard();

    if (shortList) {
        card.setTitle("ISS - Location Listing: " + WordUtils.capitalizeFully(countryPair.getKey())
                + " starting with \"" + letterSlot.getValue().toUpperCase().charAt(0) + "\"");
    } else {
        card.setTitle("ISS - Location Listing: " + WordUtils.capitalizeFully(countryPair.getKey()));
    }

    card.setContent(cardStrBldr.toString());

    // Create the ssmloutput text output.
    SsmlOutputSpeech ssmlspeech = new SsmlOutputSpeech();
    ssmlspeech.setSsml(locationStrBldr.toString());

    StringBuilder rpStrBldr = new StringBuilder();
    rpStrBldr.append("<speak>");
    rpStrBldr.append("<p>You can get sighting information for a location by saying "
            + "give me visibility for London or some other location and country combination.</p>");
    rpStrBldr.append("</speak>");

    SsmlOutputSpeech rpssmlspeech = new SsmlOutputSpeech();
    rpssmlspeech.setSsml(rpStrBldr.toString());

    Reprompt reprompt = new Reprompt();
    reprompt.setOutputSpeech(rpssmlspeech);

    return SpeechletResponse.newAskResponse(ssmlspeech, reprompt, card);
}

From source file:io.kamax.mxisd.invitation.InvitationManager.java

private String findHomeserverForDomain(String domain) {
    Optional<String> entryOpt = dns.findHost(domain);
    if (entryOpt.isPresent()) {
        String entry = entryOpt.get();
        log.info("Found DNS overwrite for {} to {}", domain, entry);
        try {//from  w  ww . jav a2s . co  m
            return new URL(entry).toString();
        } catch (MalformedURLException e) {
            log.warn("Skipping homeserver Federation DNS overwrite for {} - not a valid URL: {}", domain,
                    entry);
        }
    }

    log.debug("Performing SRV lookup for {}", domain);
    String lookupDns = getSrvRecordName(domain);
    log.info("Lookup name: {}", lookupDns);

    try {
        List<SRVRecord> srvRecords = new ArrayList<>();
        Record[] rawRecords = new Lookup(lookupDns, Type.SRV).run();
        if (rawRecords != null && rawRecords.length > 0) {
            for (Record record : rawRecords) {
                if (Type.SRV == record.getType()) {
                    srvRecords.add((SRVRecord) record);
                } else {
                    log.info("Got non-SRV record: {}", record.toString());
                }
            }

            srvRecords.sort(Comparator.comparingInt(SRVRecord::getPriority));
            for (SRVRecord record : srvRecords) {
                log.info("Found SRV record: {}", record.toString());
                return "https://" + record.getTarget().toString(true) + ":" + record.getPort();
            }
        } else {
            log.info("No SRV record for {}", lookupDns);
        }
    } catch (TextParseException e) {
        log.warn("Unable to perform DNS SRV query for {}: {}", lookupDns, e.getMessage());
    }

    log.info("Performing basic lookup using domain name {}", domain);
    return "https://" + domain + ":8448";
}

From source file:net.chunkyhosting.Roe.computer.CHGManager.utilities.Install.java

public int verifyInstall() {

    String json = "NULL";

    try {/*from www. ja v a  2 s . c o  m*/

        json = CHGManager.getInstance().getNetwork()
                .downloadContentFromURL(new URL(CHGManager.getInstance().getUrl() + "/download.json"));

    } catch (MalformedURLException e) {

        return 0;

    }

    if (json == null) {

        return 1;

    } else if (json.equalsIgnoreCase("IOError")) {

        return 4;

    }

    JSONObject meh = new JSONObject(json);
    JSONArray array = meh.getJSONArray("Files");
    System.out.println(meh.toString(4));

    for (int i = 0; i < array.length(); i++) {

        JSONObject jsonObject = array.getJSONObject(i);
        File file = new File(CHGManager.getInstance().getSettings().getWorkingDirectory() + File.separator
                + jsonObject.getString("Folder") + File.separator + jsonObject.getString("FileName") + "."
                + jsonObject.getString("Extension"));
        if (!file.exists()) {

            System.err.println("File: " + jsonObject.getString("Folder") + File.separator
                    + jsonObject.getString("FileName") + "." + jsonObject.getString("Extension")
                    + ", is missing! Adding to download list.");
            try {

                this.getDownloads().put(jsonObject,
                        new URL(CHGManager.getInstance().getUrl() + "/" + jsonObject.getString("Folder")
                                + File.separator + jsonObject.getString("FileName") + "."
                                + jsonObject.getString("Extension")));

            } catch (JSONException e) {

                System.err.println("ERROR(" + e.getMessage() + "): An error occoured while adding \""
                        + jsonObject.getString("Folder") + File.separator + jsonObject.getString("FileName")
                        + "." + jsonObject.getString("Extension") + "\" to the download list!");

            } catch (MalformedURLException e) {

                System.err.println("ERROR(" + e.getMessage() + "): An error occoured while adding \""
                        + jsonObject.getString("Folder") + File.separator + jsonObject.getString("FileName")
                        + "." + jsonObject.getString("Extension") + "\" to the download list!");

            }

        }

        if (!getFileMD5(file.toString(), file.exists()).equalsIgnoreCase(jsonObject.getString("MD5"))) {

            if (!this.getDownloads().containsKey(jsonObject)) {

                file.delete();
                try {

                    this.getDownloads().put(jsonObject,
                            new URL(CHGManager.getInstance().getUrl() + "/" + jsonObject.getString("Folder")
                                    + File.separator + jsonObject.getString("FileName") + "."
                                    + jsonObject.getString("Extension")));

                } catch (JSONException e) {

                    System.err.println("ERROR(" + e.getMessage() + "): An error occoured while adding \""
                            + jsonObject.getString("Folder") + File.separator + jsonObject.getString("FileName")
                            + "." + jsonObject.getString("Extension") + "\" to the download list!");

                } catch (MalformedURLException e) {

                    System.err.println("ERROR(" + e.getMessage() + "): An error occoured while adding \""
                            + jsonObject.getString("Folder") + File.separator + jsonObject.getString("FileName")
                            + "." + jsonObject.getString("Extension") + "\" to the download list!");

                }

            }

        }

        System.out.println("File (" + file.toString() + ") MD5: " + getFileMD5(file.toString(), false) + ", "
                + jsonObject.getString("MD5"));

    }

    if (this.getDownloads().size() != 0) {

        return 2;

    }

    return 3;

}

From source file:com.opoopress.maven.plugins.plugin.PluginMojo.java

@Override
protected void executeInternal(ConfigImpl config) throws MojoExecutionException, MojoFailureException {
    String pluginDir = config.get("plugin_dir");
    File plugins = new File(config.getBasedir(), pluginDir);

    URL url = null;//  w  w w  .j  ava 2 s. c o  m

    if (plugin != null) {
        String str = plugin.toLowerCase();
        //url
        if (str.startsWith("http://") || str.startsWith("https://")) {
            try {
                url = new URL(plugin);
            } catch (MalformedURLException e) {
                throw new MojoFailureException("Not a valid url: " + plugin, e);
            }
        } else {
            //groupId:artifactId:version[:packaging][:classifier]
            String[] tokens = StringUtils.split(plugin, ":");
            if (tokens.length < 3 || tokens.length > 5) {
                throw new MojoFailureException(
                        "Invalid plugin artifact, you must specify groupId:artifactId:version[:packaging][:classifier] "
                                + plugin);
            }
            groupId = tokens[0];
            artifactId = tokens[1];
            version = tokens[2];
            if (tokens.length >= 4) {
                type = tokens[3];
            }
            if (tokens.length == 5) {
                classifier = tokens[4];
            } else {
                classifier = null;
            }
        }
    }

    //url
    if (url != null) {
        String filename = URIUtil.getName(plugin);
        File pluginFile = new File(plugins, filename);
        if (pluginFile.exists()) {
            getLog().info("Plugin already exists: " + pluginFile);
            return;
        }

        try {
            new ProgressURLDownloader().setQuiet(false).download(url, pluginFile);
        } catch (IOException e) {
            throw new MojoFailureException("Download plugin file failed: " + e.getMessage(), e);
        }
        return;
    }

    //artifact
    if (StringUtils.isBlank(groupId) || StringUtils.isBlank(artifactId)) {

        if (version != null) {
            String filename = artifactId + "-" + version + (classifier != null ? "-" + classifier : "") + "."
                    + type;

            File pluginFile = new File(plugins, filename);
            if (pluginFile.exists()) {
                getLog().info("Plugin already exists: " + pluginFile);
                return;
            }
        }

        ArtifactDownloader downloader = new DefaultArtifactDownloader(getLog(), artifactFactory,
                artifactResolver, localRepository, remoteArtifactRepositories, remoteRepositories,
                repositoryLayouts, artifactRepositoryFactory, artifactMetadataSource, enableOpooPressRepos);

        File file = downloader.download(groupId, artifactId, version, classifier, type);

        File pluginFile = new File(plugins, file.getName());
        if (pluginFile.exists()) {
            getLog().info("Plugin already exists: " + pluginFile);
        } else {
            getLog().info("Install plugin: " + pluginFile);
            try {
                FileUtils.copyFile(file, pluginFile);
            } catch (IOException e) {
                throw new MojoFailureException("Copy plugin file failed: " + e.getMessage(), e);
            }
        }
    }
}

From source file:com.dtolabs.rundeck.core.execution.commands.ScriptURLCommandInterpreter.java

public InterpreterResult interpretCommand(ExecutionContext context, ExecutionItem item, INodeEntry node)
        throws InterpreterException {
    if (!cacheDir.isDirectory() && !cacheDir.mkdirs()) {
        throw new RuntimeException("Unable to create cachedir: " + cacheDir.getAbsolutePath());
    }/*  ww w  . jav a  2 s.  c  om*/
    final ScriptURLCommandExecutionItem script = (ScriptURLCommandExecutionItem) item;
    final ExecutionService executionService = framework.getExecutionService();
    //create node context for node and substitute data references in command
    final Map<String, Map<String, String>> nodeDataContext = DataContextUtils.addContext("node",
            DataContextUtils.nodeData(node), context.getDataContext());

    final String finalUrl = expandUrlString(script.getURLString(), nodeDataContext);
    final URL url;
    try {
        url = new URL(finalUrl);
    } catch (MalformedURLException e) {
        throw new InterpreterException(e);
    }
    if (null != context.getExecutionListener()) {
        context.getExecutionListener().log(4, "Requesting URL: " + url.toExternalForm());
    }

    String cleanUrl = url.toExternalForm().replaceAll("^(https?://)([^:@/]+):[^@/]*@", "$1$2:****@");
    String tempFileName = hashURL(url.toExternalForm()) + ".temp";
    File destinationTempFile = new File(cacheDir, tempFileName);
    File destinationCacheData = new File(cacheDir, tempFileName + ".cache.properties");

    //update from URL if necessary
    final URLFileUpdaterBuilder urlFileUpdaterBuilder = new URLFileUpdaterBuilder().setUrl(url)
            .setAcceptHeader("*/*").setTimeout(DEFAULT_TIMEOUT);
    if (USE_CACHE) {
        urlFileUpdaterBuilder.setCacheMetadataFile(destinationCacheData).setCachedContent(destinationTempFile)
                .setUseCaching(true);
    }
    final URLFileUpdater updater = urlFileUpdaterBuilder.createURLFileUpdater();
    try {
        if (null != interaction) {
            //allow mock
            updater.setInteraction(interaction);
        }
        UpdateUtils.update(updater, destinationTempFile);

        logger.debug("Updated nodes resources file: " + destinationTempFile);
    } catch (UpdateUtils.UpdateException e) {
        if (!destinationTempFile.isFile() || destinationTempFile.length() < 1) {
            throw new InterpreterException("Error requesting URL Script: " + cleanUrl + ": " + e.getMessage(),
                    e);
        } else {
            logger.error("Error requesting URL script: " + cleanUrl + ": " + e.getMessage(), e);
        }
    }

    final String filepath; //result file path
    try {
        filepath = executionService.fileCopyFile(context, destinationTempFile, node);
    } catch (FileCopierException e) {
        throw new InterpreterException(e);
    }

    try {
        /**
         * TODO: Avoid this horrific hack. Discover how to get SCP task to preserve the execute bit.
         */
        if (!"windows".equalsIgnoreCase(node.getOsFamily())) {
            //perform chmod+x for the file

            final NodeExecutorResult nodeExecutorResult = framework.getExecutionService()
                    .executeCommand(context, new String[] { "chmod", "+x", filepath }, node);
            if (!nodeExecutorResult.isSuccess()) {
                return nodeExecutorResult;
            }
        }

        final String[] args = script.getArgs();
        //replace data references
        String[] newargs = null;
        if (null != args && args.length > 0) {
            newargs = new String[args.length + 1];
            final String[] replargs = DataContextUtils.replaceDataReferences(args, nodeDataContext);
            newargs[0] = filepath;
            System.arraycopy(replargs, 0, newargs, 1, replargs.length);
        } else {
            newargs = new String[] { filepath };
        }

        return framework.getExecutionService().executeCommand(context, newargs, node);
    } catch (ExecutionException e) {
        throw new InterpreterException(e);
    }
}