Example usage for java.net URL toString

List of usage examples for java.net URL toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Constructs a string representation of this URL .

Usage

From source file:com.sittinglittleduck.DirBuster.GenBaseCase.java

public static BaseCase genURLFuzzBaseCase(Manager manager, String fuzzStart, String FuzzEnd)
        throws MalformedURLException, IOException {
    BaseCase baseCase = null;/*from w w w  .  j a v  a2s .  com*/
    int failcode = 0;
    String failString = Config.failCaseString;
    String baseResponce = "";

    /*
     * markers for using regex instead
     */
    boolean useRegexInstead = false;
    String regex = null;

    URL failurl = new URL(fuzzStart + failString + FuzzEnd);

    GetMethod httpget = new GetMethod(failurl.toString());
    // set the custom HTTP headers
    Vector HTTPheaders = manager.getHTTPHeaders();
    for (int a = 0; a < HTTPheaders.size(); a++) {
        HTTPHeader httpHeader = (HTTPHeader) HTTPheaders.elementAt(a);
        /*
         * Host header has to be set in a different way!
         */
        if (httpHeader.getHeader().startsWith("Host")) {
            httpget.getParams().setVirtualHost(httpHeader.getValue());
        } else {
            httpget.setRequestHeader(httpHeader.getHeader(), httpHeader.getValue());
        }
    }
    httpget.setFollowRedirects(Config.followRedirects);

    // save the http responce code for the base case
    failcode = manager.getHttpclient().executeMethod(httpget);
    manager.workDone();

    if (failcode == 200) {
        if (Config.debug) {
            System.out.println("DEBUG GenBaseCase: base case for " + failurl.toString() + "came back as 200!");
        }

        BufferedReader input = new BufferedReader(new InputStreamReader(httpget.getResponseBodyAsStream()));
        String tempLine;
        StringBuffer buf = new StringBuffer();
        while ((tempLine = input.readLine()) != null) {
            buf.append("\r\n" + tempLine);
        }
        baseResponce = buf.toString();
        input.close();

        // clean up the base case, based on the basecase URL
        baseResponce = FilterResponce.CleanResponce(baseResponce, failurl, failString);

        if (Config.debug) {
            System.out.println("DEBUG GenBaseCase: base case was set to :" + baseResponce);
        }
    }

    httpget.releaseConnection();

    /*
     * create the base case object
     */
    baseCase = new BaseCase(null, failcode, false, failurl, baseResponce, null, useRegexInstead, regex);

    return baseCase;
}

From source file:com.ms.commons.test.classloader.IntlTestURLClassPath.java

private static List<URL> filterMavenSurefireBooter(List<URL> urlList) {
    try {//from  w  w  w .jav  a  2  s . c om
        if (IntlTestURLClassPath.class.getClassLoader().toString()
                .contains("sun.misc.Launcher$AppClassLoader")) {
            if (RuntimeUtil.getRuntime().getEnvironment() == RuntimeEnvironment.Maven) {
                List<URL> filteredUrlList = new ArrayList<URL>();
                for (URL u : urlList) {
                    if (u.toString().contains("surefirebooter")) {
                        System.err.println("URL: " + u.toString() + " has been ingored!");
                    } else {
                        filteredUrlList.add(u);
                    }
                }
                return filteredUrlList;
            }
        }
    } catch (Exception e) {
        System.err.println("Error in: " + IntlTestURLClassPath.class + "." + "filterMavenSurefireBooter");
        e.printStackTrace();
    }

    return urlList;
}

From source file:com.streamsets.pipeline.stage.destination.mapreduce.MapreduceUtils.java

@VisibleForTesting
static void addJarsToJob(Configuration conf, boolean allowMultiple, URL[] jarUrls, String... jarPatterns) {

    final List<String> allMatches = new LinkedList<>();
    final List<URL> patternMatches = new LinkedList<>();

    for (String pattern : jarPatterns) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Looking for pattern {}", pattern);
        }//from w w  w  .  j  a  v a  2s.  c  o  m
        for (URL url : jarUrls) {
            if (LOG.isTraceEnabled()) {
                LOG.trace("Looking in jar {}", url);
            }
            final String file = url.getFile();
            if (StringUtils.endsWithIgnoreCase(file, ".jar") && StringUtils.containsIgnoreCase(file, pattern)) {
                allMatches.add(url.toString());
                patternMatches.add(url);

                if (LOG.isDebugEnabled()) {
                    LOG.debug("Found jar {} for pattern {}", url, pattern);
                }
            }
        }

        if (patternMatches.isEmpty()) {
            throw new IllegalArgumentException(String.format("Did not find any jars for pattern %s", pattern));
        } else if (!allowMultiple && patternMatches.size() > 1) {
            throw new IllegalArgumentException(String.format("Found multiple jars for pattern %s: %s", pattern,
                    StringUtils.join(patternMatches, JAR_SEPARATOR)));
        }
        patternMatches.clear();
    }

    appendJars(conf, allMatches);
}

From source file:com.concursive.connect.web.modules.communications.utils.EmailUpdatesUtils.java

public static String getEmailHTMLMessage(Connection db, ApplicationPrefs prefs, Configuration configuration,
        EmailUpdatesQueue queue, Timestamp min, Timestamp max) throws Exception {
    // User who needs to be sent an email
    User user = UserUtils.loadUser(queue.getEnteredBy());

    Project website = ProjectUtils.loadProject("main-profile");
    int emailUpdatesSchedule = -1;
    String title = "";
    if (queue.getScheduleOften()) {
        emailUpdatesSchedule = TeamMember.EMAIL_OFTEN;
        title = website.getTitle() + " recent updates";
    } else if (queue.getScheduleDaily()) {
        emailUpdatesSchedule = TeamMember.EMAIL_DAILY;
        title = website.getTitle() + " daily update";
    } else if (queue.getScheduleWeekly()) {
        emailUpdatesSchedule = TeamMember.EMAIL_WEEKLY;
        title = website.getTitle() + " weekly update";
    } else if (queue.getScheduleMonthly()) {
        emailUpdatesSchedule = TeamMember.EMAIL_MONTHLY;
        title = website.getTitle() + " monthly update";
    }//from   w ww .  j ava  2  s . c om
    if (emailUpdatesSchedule == -1) {
        //unexpected case; throw exception
        throw new Exception("The queue does not have a valid schedule type!");
    }
    if (URLFactory.createURL(prefs.getPrefs()) == null) {
        throw new Exception(
                "The server URL is not specified. Please contact the system administrator to configure the remote server's URL!");
    }

    // Populate the message template
    freemarker.template.Template template = configuration
            .getTemplate("scheduled_activity_updates_email_body-html.ftl");
    Map bodyMappings = new HashMap();
    bodyMappings.put("title", title);
    bodyMappings.put("link", new HashMap());
    ((Map) bodyMappings.get("link")).put("settings",
            URLFactory.createURL(prefs.getPrefs()) + "/show/" + user.getProfileUniqueId());

    // Load the RSS config file to determine the objects for display
    String fileName = "scheduled_emails_en_US.xml";
    URL resource = EmailUpdatesUtils.class.getResource("/" + fileName);
    LOG.debug("Schedule emails config file: " + resource.toString());
    XMLUtils library = new XMLUtils(resource);

    String purpose = prefs.get(ApplicationPrefs.PURPOSE);
    LOG.debug("Purpose: " + purpose);
    Element emailElement = XMLUtils.getElement(library.getDocumentElement(), "email", "events",
            "site," + purpose);
    if (emailElement == null) {
        emailElement = XMLUtils.getElement(library.getDocumentElement(), "email", "events", "site");
    }
    if (emailElement != null) {
        LinkedHashMap categories = new LinkedHashMap();

        PagedListInfo info = new PagedListInfo();
        String limit = emailElement.getAttribute("limit");
        info.setItemsPerPage(limit);
        int activityCount = 0;

        //Determine the website's site-chatter data to email for this user (if any)
        ProjectHistoryList chatter = new ProjectHistoryList();
        chatter.setProjectId(website.getId());
        chatter.setLinkObject(ProjectHistoryList.SITE_CHATTER_OBJECT);
        chatter.setRangeStart(min);
        chatter.setRangeEnd(max);
        chatter.setPagedListInfo(info);
        chatter.setForMemberEmailUpdates(user.getId(), emailUpdatesSchedule);
        LinkedHashMap map = chatter.getList(db, user.getId(), URLFactory.createURL(prefs.getPrefs()));
        activityCount += map.size();
        if (map.size() != 0) {
            categories.put("Chatter", map);
        }

        // Determine the types of events to display based on the config file
        ArrayList<Element> eventElements = new ArrayList<Element>();
        XMLUtils.getAllChildren(emailElement, "event", eventElements);

        // set all the requested types based on the types we allow for the query..
        ArrayList<String> types = new ArrayList<String>();
        for (Element eventElement : eventElements) {
            String type = XMLUtils.getNodeText(eventElement);
            types.add(type);
        }
        LOG.debug("Event Types: " + types);
        // Load the categories
        ProjectCategoryList categoryList = new ProjectCategoryList();
        categoryList.setTopLevelOnly(true);
        categoryList.setEnabled(Constants.TRUE);
        categoryList.buildList(db);

        for (ProjectCategory category : categoryList) {
            ProjectHistoryList activities = new ProjectHistoryList();
            activities.setProjectCategoryId(category.getId());
            activities.setRangeStart(min);
            activities.setRangeEnd(max);
            activities.setObjectPreferences(types);
            activities.setPagedListInfo(info);
            activities.setForMemberEmailUpdates(user.getId(), emailUpdatesSchedule);
            LinkedHashMap activityMap = activities.getList(db, user.getId(),
                    URLFactory.createURL(prefs.getPrefs()));
            activityCount += activityMap.size();
            if (activityMap.size() != 0) {
                categories.put(category.getLabel(), activityMap);
            }
        }

        if (activityCount == 0) {
            //Don't send an email update
            return null;
        }
        bodyMappings.put("categories", categories);
    }

    // Parse and return
    StringWriter emailBodyTextWriter = new StringWriter();
    template.process(bodyMappings, emailBodyTextWriter);

    return emailBodyTextWriter.toString();
}

From source file:es.upv.grycap.coreutils.fiber.net.UrlBuilder.java

/**
 * Convenient factory method that creates a new instance of this class.
 * @param baseUrl - base URL that will be used to create new URLs
 * @return A new instance of this class, allowing callers to use the methods of this class to create new URLs 
 *         from the base URL provided as argument.
 *//*from www  .  java2 s . com*/
public static UrlBuilder getUrlBuilder(final URL baseUrl) {
    URL url = null;
    try {
        url = new URL(decode(requireNonNull(baseUrl).toString(), defaultCharset().name()));
    } catch (MalformedURLException | UnsupportedEncodingException e) {
        throw new IllegalArgumentException(new StringBuilder("Cannot create a URI from the provided URL: ")
                .append(baseUrl != null ? baseUrl.toString() : "null").toString(), e);
    }
    return new UrlBuilder(url);
}

From source file:com.reprezen.kaizen.oasparser.jsonoverlay.JsonLoader.java

public static JsonNode loadString(URL url, String json) throws IOException, JsonProcessingException {
    String trimmed = json.trim();
    JsonNode tree;//from ww  w . ja  v a2s  .c o  m
    if (trimmed.startsWith("{")) {
        tree = jsonMapper.readTree(trimmed);
    } else {
        Object parsedYaml = yaml.load(trimmed); // this handles aliases - YAMLMapper doesn't
        tree = yamlMapper.convertValue(parsedYaml, JsonNode.class);
    }
    if (url != null) {
        cache.put(url.toString(), tree);
    }
    return tree;
}

From source file:jenkins.model.RunIdMigrator.java

private static String getUnmigrationCommandLine(File jenkinsHome) {
    StringBuilder cp = new StringBuilder();
    for (Class<?> c : new Class<?>[] { RunIdMigrator.class,
            /* TODO how to calculate transitive dependencies automatically? */Charsets.class,
            WriterOutputStream.class, BuildException.class, FastDateFormat.class }) {
        URL location = c.getProtectionDomain().getCodeSource().getLocation();
        String locationS = location.toString();
        if (location.getProtocol().equals("file")) {
            try {
                locationS = new File(location.toURI()).getAbsolutePath();
            } catch (URISyntaxException x) {
                // never mind
            }/*from w  ww. j  a  v  a2s . c  o  m*/
        }
        if (cp.length() > 0) {
            cp.append(File.pathSeparator);
        }
        cp.append(locationS);
    }
    return String.format("java -classpath \"%s\" %s \"%s\"", cp, RunIdMigrator.class.getName(), jenkinsHome);
}

From source file:com.salas.bb.whatshot.LinkResolver.java

/**
 * Returns a scan limit for a link./*from  www. j  a v  a2  s .co m*/
 *
 * @param link link.
 *
 * @return limit.
 */
private static int getScanLimit(URL link) {
    int limit = DEFAULT_SCAN_LIMIT;

    if (link != null) {
        String ls = link.toString();
        Set<Map.Entry<Pattern, Integer>> entries = customScanLimits.entrySet();
        for (Map.Entry<Pattern, Integer> entry : entries) {
            if (entry.getKey().matcher(ls).find())
                return entry.getValue();
        }
    }

    return limit;
}

From source file:com.cup.jmx.modeler.modules.MbeansDescriptorsDigesterSource.java

protected static Digester createDigester() {

    Digester digester = new Digester();
    digester.setNamespaceAware(false);// w w w .  jav  a2s .c  o  m
    digester.setValidating(false);
    URL url = Registry.getRegistry(null, null).getClass()
            .getResource("/com/cup/jmx/modeler/mbeans-descriptors.dtd");
    digester.register("-//Apache Software Foundation//DTD Model MBeans Configuration File", url.toString());

    // Configure the parsing rules
    digester.addObjectCreate("mbeans-descriptors/mbean", "com.cup.jmx.modeler.ManagedBean");
    digester.addSetProperties("mbeans-descriptors/mbean");
    digester.addSetNext("mbeans-descriptors/mbean", "add", "java.lang.Object");

    digester.addObjectCreate("mbeans-descriptors/mbean/attribute", "com.cup.jmx.modeler.AttributeInfo");
    digester.addSetProperties("mbeans-descriptors/mbean/attribute");
    digester.addSetNext("mbeans-descriptors/mbean/attribute", "addAttribute",
            "com.cup.jmx.modeler.AttributeInfo");

    /*digester.addObjectCreate
    ("mbeans-descriptors/mbean/attribute/descriptor/field",
    "com.cup.jmx.modeler.FieldInfo");
    digester.addSetProperties
    ("mbeans-descriptors/mbean/attribute/descriptor/field");
    digester.addSetNext
    ("mbeans-descriptors/mbean/attribute/descriptor/field",
        "addField",
    "com.cup.jmx.modeler.FieldInfo");
            
    digester.addObjectCreate
    ("mbeans-descriptors/mbean/constructor",
    "com.cup.jmx.modeler.ConstructorInfo");
    digester.addSetProperties
    ("mbeans-descriptors/mbean/constructor");
    digester.addSetNext
    ("mbeans-descriptors/mbean/constructor",
        "addConstructor",
    "com.cup.jmx.modeler.ConstructorInfo");
            
    digester.addObjectCreate
    ("mbeans-descriptors/mbean/constructor/descriptor/field",
    "com.cup.jmx.modeler.FieldInfo");
    digester.addSetProperties
    ("mbeans-descriptors/mbean/constructor/descriptor/field");
    digester.addSetNext
    ("mbeans-descriptors/mbean/constructor/descriptor/field",
        "addField",
    "com.cup.jmx.modeler.FieldInfo");
            
    digester.addObjectCreate
    ("mbeans-descriptors/mbean/constructor/parameter",
    "com.cup.jmx.modeler.ParameterInfo");
    digester.addSetProperties
    ("mbeans-descriptors/mbean/constructor/parameter");
    digester.addSetNext
    ("mbeans-descriptors/mbean/constructor/parameter",
        "addParameter",
    "com.cup.jmx.modeler.ParameterInfo");
            
    digester.addObjectCreate
    ("mbeans-descriptors/mbean/descriptor/field",
    "com.cup.jmx.modeler.FieldInfo");
    digester.addSetProperties
    ("mbeans-descriptors/mbean/descriptor/field");
    digester.addSetNext
    ("mbeans-descriptors/mbean/descriptor/field",
        "addField",
    "com.cup.jmx.modeler.FieldInfo");
    */
    digester.addObjectCreate("mbeans-descriptors/mbean/notification", "com.cup.jmx.modeler.NotificationInfo");
    digester.addSetProperties("mbeans-descriptors/mbean/notification");
    digester.addSetNext("mbeans-descriptors/mbean/notification", "addNotification",
            "com.cup.jmx.modeler.NotificationInfo");

    digester.addObjectCreate("mbeans-descriptors/mbean/notification/descriptor/field",
            "com.cup.jmx.modeler.FieldInfo");
    digester.addSetProperties("mbeans-descriptors/mbean/notification/descriptor/field");
    digester.addSetNext("mbeans-descriptors/mbean/notification/descriptor/field", "addField",
            "com.cup.jmx.modeler.FieldInfo");

    digester.addCallMethod("mbeans-descriptors/mbean/notification/notification-type", "addNotifType", 0);

    digester.addObjectCreate("mbeans-descriptors/mbean/operation", "com.cup.jmx.modeler.OperationInfo");
    digester.addSetProperties("mbeans-descriptors/mbean/operation");
    digester.addSetNext("mbeans-descriptors/mbean/operation", "addOperation",
            "com.cup.jmx.modeler.OperationInfo");

    digester.addObjectCreate("mbeans-descriptors/mbean/operation/descriptor/field",
            "com.cup.jmx.modeler.FieldInfo");
    digester.addSetProperties("mbeans-descriptors/mbean/operation/descriptor/field");
    digester.addSetNext("mbeans-descriptors/mbean/operation/descriptor/field", "addField",
            "com.cup.jmx.modeler.FieldInfo");

    digester.addObjectCreate("mbeans-descriptors/mbean/operation/parameter",
            "com.cup.jmx.modeler.ParameterInfo");
    digester.addSetProperties("mbeans-descriptors/mbean/operation/parameter");
    digester.addSetNext("mbeans-descriptors/mbean/operation/parameter", "addParameter",
            "com.cup.jmx.modeler.ParameterInfo");

    return digester;

}

From source file:de.quadrillenschule.azocamsyncd.astromode.SmartPhoneWrapper.java

public static SmartPhoneStatus remove(PhotoSerie ps) throws IOException {

    lastStatus = SmartPhoneStatus.TRYING;
    URL url;
    String retval;//w  w w  .  j  ava 2 s .c o  m
    try {
        url = new URL(PROTOCOL + "://" + LAST_WORKING_IP + ":" + PORT + "/" + WebService.WebCommands.removejob
                + "/?" + WebService.WebParameters.jobid + "=" + ps.getId());
        System.out.println("Trying " + url.toString());
        URLConnection uc = url.openConnection();
        uc.setConnectTimeout(3000);
        StringWriter sw = new StringWriter();
        IOUtils.copy((InputStream) uc.getContent(), System.out);

    } catch (MalformedURLException ex) {
        Logger.getLogger(SmartPhoneWrapper.class.getName()).log(Level.SEVERE, null, ex);
        return SmartPhoneStatus.ERROR;

    }
    return SmartPhoneStatus.CONNECTED;
}