Example usage for java.net URL getUserInfo

List of usage examples for java.net URL getUserInfo

Introduction

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

Prototype

public String getUserInfo() 

Source Link

Document

Gets the userInfo part of this URL .

Usage

From source file:org.talend.datatools.xml.utils.SchemaPopulationUtil.java

/**
 * Return the root node of a schema tree.
 * /*from w ww .j  a  v a2  s .c  o m*/
 * @param fileName
 * @return
 * @throws OdaException
 * @throws MalformedURLException
 * @throws URISyntaxException
 */
public static ATreeNode getSchemaTree(String fileName, boolean incAttr)
        throws OdaException, MalformedURLException, URISyntaxException {
    includeAttribute = incAttr;
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    URI uri = null;
    File f = new File(fileName);
    if (f.exists()) {
        uri = f.toURI();
    } else {
        URL url = new URL(fileName);
        uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef());
    }

    // Then try to parse the input string as a url in web.
    if (uri == null) {
        uri = new URI(fileName);
    }

    // fixed a bug when parse one file contians Franch ,maybe need modification
    XMLSchemaLoader xsLoader = new XMLSchemaLoader();
    XSModel xsModel = xsLoader.loadURI(uri.toString());
    if (xsModel == null) {
        try {
            Grammar loadGrammar = xsLoader.loadGrammar(
                    new XMLInputSource(null, uri.toString(), null, new FileInputStream(f), "ISO-8859-1"));
            xsModel = ((XSGrammar) loadGrammar).toXSModel();
        } catch (XNIException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    ATreeNode complexTypesRoot = populateComplexTypeTree(xsModel);

    XSNamedMap map = xsModel.getComponents(XSConstants.ELEMENT_DECLARATION);

    ATreeNode root = new ATreeNode();

    root.setValue("ROOT");
    for (int i = 0; i < map.getLength(); i++) {
        ATreeNode node = new ATreeNode();
        XSElementDecl element = (XSElementDecl) map.item(i);

        String namespace = element.getNamespace();
        XSObject unique = element.getIdentityConstraints().itemByName(namespace, element.getName());
        if (unique instanceof UniqueOrKey) {
            node.getUniqueNames().clear();
            UniqueOrKey uniqueOrKey = (UniqueOrKey) unique;
            String uniqueName = "";
            StringList fieldStrs = uniqueOrKey.getFieldStrs();
            for (int j = 0; j < fieldStrs.getLength(); j++) {
                uniqueName = fieldStrs.item(j);
                if (uniqueName != null && !"".equals(uniqueName)) {
                    uniqueName = uniqueName.replace("/", "").replace(".", "");
                    node.getUniqueNames().add(uniqueName);
                }
            }
        }
        ATreeNode namespaceNode = null;
        if (namespace != null) {
            namespaceNode = new ATreeNode();
            namespaceNode.setDataType(namespace);
            namespaceNode.setType(ATreeNode.NAMESPACE_TYPE);
            namespaceNode.setValue(namespace);
        }

        node.setValue(element.getName());
        node.setType(ATreeNode.ELEMENT_TYPE);
        node.setDataType(element.getName());
        if (element.getTypeDefinition() instanceof XSComplexTypeDecl) {
            XSComplexTypeDecl complexType = (XSComplexTypeDecl) element.getTypeDefinition();
            // If the complex type is explicitly defined, that is, it has name.
            if (complexType.getName() != null) {
                node.setDataType(complexType.getName());
                ATreeNode n = findComplexElement(complexTypesRoot, complexType.getName());
                if (namespaceNode != null) {
                    node.addChild(namespaceNode);
                }
                if (n != null) {
                    node.addChild(n.getChildren());
                }
            }
            // If the complex type is implicitly defined, that is, it has no name.
            else {

                addParticleAndAttributeInfo(node, complexType, complexTypesRoot, new VisitingRecorder());
            }
        }
        root.addChild(node);
    }

    // if no base element, display all complex types / attributes directly.
    if (map.getLength() == 0) {
        root.addChild(complexTypesRoot.getChildren());
    }

    populateRoot(root);
    return root;

}

From source file:org.talend.datatools.xml.utils.SchemaPopulationUtil.java

/**
 * Return the root node of a schema tree.
 * /* w w  w  .  j  av a 2s. c om*/
 * @param fileName
 * @return
 * @throws OdaException
 * @throws MalformedURLException
 * @throws URISyntaxException
 */
public static ATreeNode getSchemaTree(String fileName, boolean incAttr, boolean forMDM, List<String> attList)
        throws OdaException, MalformedURLException, URISyntaxException {
    includeAttribute = incAttr;
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    URI uri = null;
    File f = new File(fileName);
    if (f.exists()) {
        uri = f.toURI();
    } else {
        URL url = new URL(fileName);
        uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef());
    }

    // Then try to parse the input string as a url in web.
    if (uri == null) {
        uri = new URI(fileName);
    }

    // fixed a bug when parse one file contians Franch ,maybe need modification
    XMLSchemaLoader xsLoader = new XMLSchemaLoader();
    XSModel xsModel = xsLoader.loadURI(uri.toString());
    if (xsModel == null) {
        try {
            Grammar loadGrammar = xsLoader.loadGrammar(
                    new XMLInputSource(null, uri.toString(), null, new FileInputStream(f), "ISO-8859-1"));
            xsModel = ((XSGrammar) loadGrammar).toXSModel();
        } catch (XNIException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    ATreeNode complexTypesRoot = populateComplexTypeTree(xsModel);

    XSNamedMap map = xsModel.getComponents(XSConstants.ELEMENT_DECLARATION);

    ATreeNode root = new ATreeNode();
    root.setValue("ROOT");
    for (int i = 0; i < map.getLength(); i++) {
        ATreeNode node = new ATreeNode();
        XSElementDecl element = (XSElementDecl) map.item(i);

        String namespace = element.getNamespace();
        XSObject unique = element.getIdentityConstraints().itemByName(namespace, element.getName());
        if (unique instanceof UniqueOrKey) {
            node.getUniqueNames().clear();
            UniqueOrKey uniqueOrKey = (UniqueOrKey) unique;
            String uniqueName = "";
            StringList fieldStrs = uniqueOrKey.getFieldStrs();
            for (int j = 0; j < fieldStrs.getLength(); j++) {
                uniqueName = fieldStrs.item(j);
                if (uniqueName != null && !"".equals(uniqueName)) {
                    uniqueName = uniqueName.replace("/", "").replace(".", "");
                    node.getUniqueNames().add(uniqueName);
                }
            }
        }
        ATreeNode namespaceNode = null;
        if (namespace != null) {
            namespaceNode = new ATreeNode();
            namespaceNode.setDataType(namespace);
            namespaceNode.setType(ATreeNode.NAMESPACE_TYPE);
            namespaceNode.setValue(namespace);
        }

        node.setValue(element.getName());
        node.setType(ATreeNode.ELEMENT_TYPE);
        node.setDataType(element.getName());

        if (element.getTypeDefinition() instanceof XSComplexTypeDecl) {
            XSComplexTypeDecl complexType = (XSComplexTypeDecl) element.getTypeDefinition();
            // If the complex type is explicitly defined, that is, it has name.
            if (complexType.getName() != null) {
                node.setDataType(complexType.getName());
                ATreeNode n = findComplexElement(complexTypesRoot, complexType.getName());
                if (namespaceNode != null) {
                    node.addChild(namespaceNode);
                }
                if (n != null) {
                    node.addChild(n.getChildren());
                }
            }
            // If the complex type is implicitly defined, that is, it has no name.
            else {
                // If the complex type is implicitly defined , no need to check it in explicitly complex type
                addParticleAndAttributeInfo(node, complexType, complexTypesRoot, new VisitingRecorder());
            }
        }
        String nodeType = node.getOriginalDataType();
        if (forMDM) {
            Object nodeValue = node.getValue();
            if (nodeValue != null && !attList.contains(nodeValue) && nodeType != null
                    && !attList.contains(nodeType)) {
                continue;
            }
        } else {
            if (nodeType != null && !attList.contains(nodeType)) {
                continue;
            }
        }
        if (forMDM && attList.size() == 1 && node.getValue().equals(attList.get(0))) {
            root = node;
        } else {
            root.addChild(node);
        }
    }

    // if no base element, display all complex types / attributes directly.
    if (map.getLength() == 0) {
        root.addChild(complexTypesRoot.getChildren());
    }

    populateRoot(root);
    return root;

}

From source file:net.technicpack.launchercore.mirror.MirrorStore.java

private URL addDownloadKey(URL url, String downloadHost, String downloadKey, String clientId) {
    if (downloadHost != null && !downloadHost.isEmpty()) {
        try {/*from www .j a va  2s.  co  m*/
            url = new URI(url.getProtocol(), url.getUserInfo(), downloadHost, url.getPort(), url.getPath(),
                    url.getQuery(), null).toURL();
        } catch (URISyntaxException ex) {
            //Ignore, just keep old url
        } catch (MalformedURLException ex) {
            //Ignore, just keep old url
        }
    }

    String textUrl = url.toString();

    if (url.getQuery() == null || url.getQuery().isEmpty()) {
        textUrl += "?";
    } else {
        textUrl += "&";
    }

    textUrl += "t=" + downloadKey + "&c=" + clientId;

    try {
        return new URL(textUrl);
    } catch (MalformedURLException ex) {
        throw new Error("Code error: managed to take valid url " + url.toString()
                + " and turn it into invalid URL " + textUrl);
    }
}

From source file:org.apache.chemistry.shell.Main.java

public void parseArgs(String[] args) throws IOException {
    if (args.length > 0) {
        for (int i = 0; i < args.length; i++) {
            String arg = args[i];
            if ("-u".equals(arg)) { // username
                if (++i == args.length) {
                    error("Invalid option -u without value. Username required.");
                }//from  w  w w. j  a  va 2  s  .  c om
                username = args[i];
            } else if ("-p".equals(arg)) { // password
                if (++i == args.length) {
                    error("Invalid option -p without value. Password required.");
                }
                password = args[i];
            } else if ("-t".equals(arg)) { // test mode
                testMode = true;
            } else if ("--enable-time".equals(arg)) { // enable time setting by default
                enableTime = true;
            } else if ("-e".equals(arg)) { // execute mode
                // execute one command
                execMode = true;
                StringBuilder buf = new StringBuilder();
                for (i++; i < args.length; i++) {
                    buf.append(args[i]).append(" ");
                }
                command = buf.toString();
                break;
            } else if ("-b".equals(arg)) { // batch mode
                // execute commands in the given file or if no specified
                // read from stdin
                batchMode = true;
                if (++i < args.length) {
                    // read commands from a file
                    command = args[i];
                }
                break;
            } else if ("-h".equals(arg) || "--help".equals(arg)) { // help
                // execute help command
                usage();
                System.exit(0);
            } else if (!arg.startsWith("-")) {
                url = arg;
            } else if ("-j".equals(arg)) { // use json binding
                useJSONBinding = true;
            } else if ("--compression".equals(arg)) { // use compression
                useCompression = true;
            } else if ("--version".equals(arg)) { // print actual version
                version();
                System.exit(0);
            } else if ("--insecure".equals(arg)) {
                acceptSelfSignedCertificates();
                System.setProperty("jsse.enableSNIExtension", "false");
            } else {
                System.err.println("Skipping unknown argument: " + arg);
            }
        }

        if (url != null) {
            if (!url.contains("://")) {
                url = "http://" + url;
            }
            try {
                URL u = new URL(url);
                if (username == null) {
                    String userInfo = u.getUserInfo();
                    if (userInfo != null) {
                        if (userInfo.contains(":")) {
                            int p = userInfo.indexOf(':');
                            username = userInfo.substring(0, p);
                            if (password == null && p < userInfo.length() - 1) {
                                password = userInfo.substring(p + 1);
                            }
                        } else {
                            username = userInfo;
                        }
                    }
                }
            } catch (MalformedURLException e) {
                System.err.println("Malformed URL: " + e.getLocalizedMessage());
                System.exit(1);
            }
        }
        if (url != null && username == null) {
            username = System.console().readLine("User: ");
        }
        if (username != null && password == null) {
            password = PasswordReader.read();
        }
    }
}

From source file:net.ychron.unirestinst.http.HttpClientHelper.java

private HttpRequestBase prepareRequest(HttpRequest request, boolean async) {

    Object defaultHeaders = options.getOption(Option.DEFAULT_HEADERS);
    if (defaultHeaders != null) {
        @SuppressWarnings("unchecked")
        Set<Entry<String, String>> entrySet = ((Map<String, String>) defaultHeaders).entrySet();
        for (Entry<String, String> entry : entrySet) {
            request.header(entry.getKey(), entry.getValue());
        }/*from   w  ww. ja  va 2 s  .co  m*/
    }

    if (!request.getHeaders().containsKey(USER_AGENT_HEADER)) {
        request.header(USER_AGENT_HEADER, USER_AGENT);
    }
    if (!request.getHeaders().containsKey(ACCEPT_ENCODING_HEADER)) {
        request.header(ACCEPT_ENCODING_HEADER, "gzip");
    }

    HttpRequestBase reqObj = null;

    String urlToRequest = null;
    try {
        URL url = new URL(request.getUrl());
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(),
                URLDecoder.decode(url.getPath(), "UTF-8"), "", url.getRef());
        urlToRequest = uri.toURL().toString();
        if (url.getQuery() != null && !url.getQuery().trim().equals("")) {
            if (!urlToRequest.substring(urlToRequest.length() - 1).equals("?")) {
                urlToRequest += "?";
            }
            urlToRequest += url.getQuery();
        } else if (urlToRequest.substring(urlToRequest.length() - 1).equals("?")) {
            urlToRequest = urlToRequest.substring(0, urlToRequest.length() - 1);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    switch (request.getHttpMethod()) {
    case GET:
        reqObj = new HttpGet(urlToRequest);
        break;
    case POST:
        reqObj = new HttpPost(urlToRequest);
        break;
    case PUT:
        reqObj = new HttpPut(urlToRequest);
        break;
    case DELETE:
        reqObj = new HttpDeleteWithBody(urlToRequest);
        break;
    case PATCH:
        reqObj = new HttpPatchWithBody(urlToRequest);
        break;
    case OPTIONS:
        reqObj = new HttpOptions(urlToRequest);
        break;
    case HEAD:
        reqObj = new HttpHead(urlToRequest);
        break;
    }

    Set<Entry<String, List<String>>> entrySet = request.getHeaders().entrySet();
    for (Entry<String, List<String>> entry : entrySet) {
        List<String> values = entry.getValue();
        if (values != null) {
            for (String value : values) {
                reqObj.addHeader(entry.getKey(), value);
            }
        }
    }

    // Set body
    if (!(request.getHttpMethod() == HttpMethod.GET || request.getHttpMethod() == HttpMethod.HEAD)) {
        if (request.getBody() != null) {
            HttpEntity entity = request.getBody().getEntity();
            if (async) {
                if (reqObj.getHeaders(CONTENT_TYPE) == null || reqObj.getHeaders(CONTENT_TYPE).length == 0) {
                    reqObj.setHeader(entity.getContentType());
                }
                try {
                    ByteArrayOutputStream output = new ByteArrayOutputStream();
                    entity.writeTo(output);
                    NByteArrayEntity en = new NByteArrayEntity(output.toByteArray());
                    ((HttpEntityEnclosingRequestBase) reqObj).setEntity(en);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            } else {
                ((HttpEntityEnclosingRequestBase) reqObj).setEntity(entity);
            }
        }
    }

    return reqObj;
}

From source file:com.yunmall.ymsdk.net.http.AsyncHttpClient.java

/**
 * Will encode url, if not disabled, and adds params on the end of it
 *
 * @param url             String with URL, should be valid URL without params
 * @param params          RequestParams to be appended on the end of URL
 * @param shouldEncodeUrl whether url should be encoded (replaces spaces with %20)
 * @return encoded url if requested with params appended if any available
 *///ww  w.j a v a2  s.c om
public static String getUrlWithQueryString(boolean shouldEncodeUrl, String url, RequestParams params) {
    if (url == null) {
        return null;
    }
    if (shouldEncodeUrl) {
        try {
            String decodedURL = URLDecoder.decode(url, "UTF-8");
            URL _url = new URL(decodedURL);
            URI _uri = new URI(_url.getProtocol(), _url.getUserInfo(), _url.getHost(), _url.getPort(),
                    _url.getPath(), _url.getQuery(), _url.getRef());
            url = _uri.toASCIIString();
        } catch (Exception ex) {
            // Should not really happen, added just for sake of validity
            YmLog.e(LOG_TAG, "getUrlWithQueryString encoding URL", ex);
        }
    }

    if (params != null) {
        // Construct the query string and trim it, in case it
        // includes any excessive white spaces.
        String paramString = params.getParamString().trim();

        // Only add the query string if it isn't empty and it
        // isn't equal to '?'.
        if (!paramString.equals("") && !paramString.equals("?")) {
            url += url.contains("?") ? "&" : "?";
            url += paramString;
        }
    }
    url = url.replaceAll(" ", "%20");

    return url;
}

From source file:com.crazytest.config.TestCase.java

protected void postWithoutToken(String endpoint, List<NameValuePair> params) throws Exception {
    String endpointString = hostUrl + endpoint;

    URL url = new URL(endpointString);
    URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
            url.getQuery(), url.getRef());

    HttpPost postRequest = new HttpPost(uri);
    postRequest.setEntity(new UrlEncodedFormEntity(params));

    postRequest.setHeader("Content-Type", "application/x-www-form-urlencoded");
    postRequest.setHeader("User-Agent", "Safari");
    this.postRequest = postRequest;
    LOGGER.info("request: {}", postRequest.getRequestLine());

}

From source file:com.crazytest.config.TestCase.java

protected void post(String endpoint, List<NameValuePair> params) throws Exception {
    String endpointString = hostUrl + endpoint + "?auth-key=" + this.authToken + "&token=" + this.authToken
            + "&userID=" + this.userID;

    URL url = new URL(endpointString);
    URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
            url.getQuery(), url.getRef());

    HttpPost postRequest = new HttpPost(uri);
    postRequest.setEntity(new UrlEncodedFormEntity(params));

    postRequest.setHeader("Content-Type", "application/x-www-form-urlencoded");
    postRequest.setHeader("User-Agent", "Safari");
    this.postRequest = postRequest;
    LOGGER.info("request: {}", postRequest.getRequestLine());

}

From source file:com.crazytest.config.TestCase.java

protected void postWithCredential(String endpoint, String params)
        throws UnsupportedEncodingException, URISyntaxException, MalformedURLException {
    String endpointString = hostUrl + endpoint + "?auth-key=" + this.authToken + "&token=" + this.authToken
            + "&userID=" + this.userID + params;

    URL url = new URL(endpointString);
    URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
            url.getQuery(), url.getRef());

    HttpPost postRequest = new HttpPost(uri);

    postRequest.setHeader("Content-Type", "application/x-www-form-urlencoded");
    postRequest.setHeader("User-Agent", "Safari");
    this.postRequest = postRequest;

    LOGGER.info("request: {}", postRequest.getRequestLine());
    LOGGER.info("request: {}", postRequest.getParams().getParameter("licenseeID"));
}

From source file:com.crazytest.config.TestCase.java

protected void putWithCredential(String endpoint, List<NameValuePair> params)
        throws MalformedURLException, URISyntaxException, UnsupportedEncodingException {
    String endpointString = hostUrl + endpoint + "?auth-key=" + this.authToken + "&token=" + this.authToken
            + "&userID=" + this.userID;

    URL url = new URL(endpointString);
    URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
            url.getQuery(), url.getRef());

    HttpPut putRequest = new HttpPut(uri);
    putRequest.setEntity(new UrlEncodedFormEntity(params));

    putRequest.setHeader("Content-Type", "application/x-www-form-urlencoded");
    putRequest.setHeader("User-Agent", "Safari");
    this.putRequest = putRequest;

    LOGGER.info("request: {}", putRequest.getRequestLine());
}