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.eclipse.mylyn.internal.provisional.commons.soap.CommonsHttpSender.java

/**
 * Extracts info from message context.//from w  ww  .  j a v a 2 s  .  co  m
 * 
 * @param method
 *            Post method
 * @param httpClient
 *            The client used for posting
 * @param msgContext
 *            the message context
 * @param tmpURL
 *            the url to post to.
 * @throws Exception
 */
protected void addContextInfo(HttpMethodBase method, HttpClient httpClient, MessageContext msgContext,
        URL tmpURL) throws Exception {

    // optionally set a timeout for the request
    //      if (msgContext.getTimeout() != 0) {
    //         /* ISSUE: these are not the same, but MessageContext has only one
    //                   definition of timeout */
    //         // SO_TIMEOUT -- timeout for blocking reads
    //         httpClient.getHttpConnectionManager().getParams().setSoTimeout(msgContext.getTimeout());
    //         // timeout for initial connection
    //         httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(msgContext.getTimeout());
    //      }

    // Get SOAPAction, default to ""
    String action = msgContext.useSOAPAction() ? msgContext.getSOAPActionURI() : ""; //$NON-NLS-1$

    if (action == null) {
        action = ""; //$NON-NLS-1$
    }

    Message msg = msgContext.getRequestMessage();
    if (msg != null) {
        method.setRequestHeader(new Header(HTTPConstants.HEADER_CONTENT_TYPE,
                msg.getContentType(msgContext.getSOAPConstants())));
    }
    method.setRequestHeader(new Header(HTTPConstants.HEADER_SOAP_ACTION, "\"" + action + "\"")); //$NON-NLS-1$ //$NON-NLS-2$
    method.setRequestHeader(new Header(HTTPConstants.HEADER_USER_AGENT, Messages.getMessage("axisUserAgent"))); //$NON-NLS-1$
    String userID = msgContext.getUsername();
    String passwd = msgContext.getPassword();

    // if UserID is not part of the context, but is in the URL, use
    // the one in the URL.
    if ((userID == null) && (tmpURL.getUserInfo() != null)) {
        String info = tmpURL.getUserInfo();
        int sep = info.indexOf(':');

        if ((sep >= 0) && (sep + 1 < info.length())) {
            userID = info.substring(0, sep);
            passwd = info.substring(sep + 1);
        } else {
            userID = info;
        }
    }
    if (userID != null) {
        Credentials proxyCred = new UsernamePasswordCredentials(userID, passwd);
        // if the username is in the form "user\domain"
        // then use NTCredentials instead.
        int domainIndex = userID.indexOf("\\"); //$NON-NLS-1$
        if (domainIndex > 0) {
            String domain = userID.substring(0, domainIndex);
            if (userID.length() > domainIndex + 1) {
                String user = userID.substring(domainIndex + 1);
                proxyCred = new NTCredentials(user, passwd, NetworkUtils.getLocalHostname(), domain);
            }
        }
        httpClient.getState().setCredentials(AuthScope.ANY, proxyCred);
    }

    // add compression headers if needed
    if (msgContext.isPropertyTrue(HTTPConstants.MC_ACCEPT_GZIP)) {
        method.addRequestHeader(HTTPConstants.HEADER_ACCEPT_ENCODING, HTTPConstants.COMPRESSION_GZIP);
    }
    if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
        method.addRequestHeader(HTTPConstants.HEADER_CONTENT_ENCODING, HTTPConstants.COMPRESSION_GZIP);
    }

    // Transfer MIME headers of SOAPMessage to HTTP headers. 
    MimeHeaders mimeHeaders = msg.getMimeHeaders();
    if (mimeHeaders != null) {
        for (Iterator i = mimeHeaders.getAllHeaders(); i.hasNext();) {
            MimeHeader mimeHeader = (MimeHeader) i.next();
            //HEADER_CONTENT_TYPE and HEADER_SOAP_ACTION are already set.
            //Let's not duplicate them.
            String headerName = mimeHeader.getName();
            if (headerName.equals(HTTPConstants.HEADER_CONTENT_TYPE)
                    || headerName.equals(HTTPConstants.HEADER_SOAP_ACTION)) {
                continue;
            }
            method.addRequestHeader(mimeHeader.getName(), mimeHeader.getValue());
        }
    }

    // process user defined headers for information.
    Hashtable userHeaderTable = (Hashtable) msgContext.getProperty(HTTPConstants.REQUEST_HEADERS);

    if (userHeaderTable != null) {
        for (Iterator e = userHeaderTable.entrySet().iterator(); e.hasNext();) {
            Map.Entry me = (Map.Entry) e.next();
            Object keyObj = me.getKey();

            if (null == keyObj) {
                continue;
            }
            String key = keyObj.toString().trim();
            String value = me.getValue().toString().trim();

            if (key.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT)
                    && value.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT_100_Continue)) {
                method.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
            } else if (key.equalsIgnoreCase(HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED)) {
                String val = me.getValue().toString();
                if (null != val) {
                    httpChunkStream = JavaUtils.isTrue(val);
                }
            } else {
                // let plug-ins using SOAP be able to set their own user-agent header (i.e. for tracking purposes)
                if (HTTPConstants.HEADER_USER_AGENT.equalsIgnoreCase(key)) {
                    method.setRequestHeader(key, value);
                } else {
                    method.addRequestHeader(key, value);
                }
            }
        }
    }
}

From source file:gov.va.med.imaging.proxy.ImageXChangeHttpCommonsSender.java

/**
* Extracts info from message context./*ww  w.j av a2  s.  com*/
* 
* @param method
*            Post method
* @param httpClient
*            The client used for posting
* @param msgContext
*            the message context
* @param tmpURL
*            the url to post to.
* 
* @throws Exception
*/
private void addContextInfo(HttpMethodBase method, HttpClient httpClient, MessageContext msgContext, URL tmpURL)
        throws Exception {

    // optionally set a timeout for the request
    if (msgContext.getTimeout() != 0) {
        /*
        * ISSUE: these are not the same, but MessageContext has only one
        * definition of timeout
        */
        // SO_TIMEOUT -- timeout for blocking reads
        httpClient.getHttpConnectionManager().getParams().setSoTimeout(msgContext.getTimeout());
        // timeout for initial connection
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(msgContext.getTimeout());
    }

    // Get SOAPAction, default to ""
    String action = msgContext.useSOAPAction() ? msgContext.getSOAPActionURI() : "";

    if (action == null) {
        action = "";
    }

    Message msg = msgContext.getRequestMessage();
    if (msg != null) {
        method.setRequestHeader(new Header(HTTPConstants.HEADER_CONTENT_TYPE,
                msg.getContentType(msgContext.getSOAPConstants())));
    }
    method.setRequestHeader(new Header(HTTPConstants.HEADER_SOAP_ACTION, "\"" + action + "\""));
    method.setRequestHeader(new Header(HTTPConstants.HEADER_USER_AGENT, Messages.getMessage("axisUserAgent")));
    //method.setRequestHeader(
    //   new Header(HTTPConstants.HEADER_USER_AGENT, "Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 2.0.5072)")
    //);

    String userID = msgContext.getUsername();
    String passwd = msgContext.getPassword();
    //System.out.println("ImageXChangeHttpCommonsSender setting credentials = '" + userID + ". " + passwd + "'");

    // if UserID is not part of the context, but is in the URL, use
    // the one in the URL.
    if ((userID == null) && (tmpURL.getUserInfo() != null)) {
        String info = tmpURL.getUserInfo();
        int sep = info.indexOf(':');

        if ((sep >= 0) && (sep + 1 < info.length())) {
            userID = info.substring(0, sep);
            passwd = info.substring(sep + 1);
        } else {
            userID = info;
        }
    }
    if (userID != null) {
        Credentials proxyCred = new UsernamePasswordCredentials(userID, passwd);
        // if the username is in the form "user\domain"
        // then use NTCredentials instead.
        int domainIndex = userID.indexOf("\\");
        if (domainIndex > 0) {
            String domain = userID.substring(0, domainIndex);
            if (userID.length() > domainIndex + 1) {
                String user = userID.substring(domainIndex + 1);
                proxyCred = new NTCredentials(user, passwd, NetworkUtils.getLocalHostname(), domain);
            }
        }
        httpClient.getState().setCredentials(AuthScope.ANY, proxyCred);
        //System.out.println("ImageXChangeHttpCommonsSender setting credentials = '" + userID + ". " + passwd + "'");
    }

    // add compression headers if needed
    // if we accept GZIP then add the accept-encoding header
    if (msgContext.isPropertyTrue(HTTPConstants.MC_ACCEPT_GZIP)) {
        // accept both gzip and deflate if the gzip property is set
        method.addRequestHeader(HTTPConstants.HEADER_ACCEPT_ENCODING,
                HTTPConstants.COMPRESSION_GZIP + "," + COMPRESSION_DEFLATE);
        //method.addRequestHeader(HTTPConstants.HEADER_ACCEPT_ENCODING, COMPRESSION_DEFLATE);
    }

    // if we will gzip the request then add the content-encoding header
    if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
        method.addRequestHeader(HTTPConstants.HEADER_CONTENT_ENCODING, HTTPConstants.COMPRESSION_GZIP);
    }

    // Transfer MIME headers of SOAPMessage to HTTP headers.
    MimeHeaders mimeHeaders = msg.getMimeHeaders();
    if (mimeHeaders != null) {
        for (Iterator i = mimeHeaders.getAllHeaders(); i.hasNext();) {
            MimeHeader mimeHeader = (MimeHeader) i.next();
            // HEADER_CONTENT_TYPE and HEADER_SOAP_ACTION are already set.
            // Let's not duplicate them.
            String headerName = mimeHeader.getName();
            if (headerName.equals(HTTPConstants.HEADER_CONTENT_TYPE)
                    || headerName.equals(HTTPConstants.HEADER_SOAP_ACTION))
                continue;
            method.addRequestHeader(mimeHeader.getName(), mimeHeader.getValue());
        }
    }

    // process user defined headers for information.
    Hashtable userHeaderTable = (Hashtable) msgContext.getProperty(HTTPConstants.REQUEST_HEADERS);

    if (userHeaderTable != null) {
        for (Iterator e = userHeaderTable.entrySet().iterator(); e.hasNext();) {
            Map.Entry me = (Map.Entry) e.next();
            Object keyObj = me.getKey();

            if (null == keyObj) {
                continue;
            }
            String key = keyObj.toString().trim();
            String value = me.getValue().toString().trim();

            if (key.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT)
                    && value.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT_100_Continue)) {
                method.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
            } else if (key.equalsIgnoreCase(HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED)) {
                String val = me.getValue().toString();
                if (null != val) {
                    httpChunkStream = JavaUtils.isTrue(val);
                }
            } else {
                method.addRequestHeader(key, value);
            }
        }
    }
}

From source file:org.sakaiproject.content.tool.ResourcesAction.java

public static List<ContentResource> createUrls(SessionState state, ResourceToolActionPipe pipe) {
    logger.debug("ResourcesAction.createUrls()");
    boolean item_added = false;
    String collectionId = null;// ww  w .  j a  va 2  s  .c o  m
    List<ContentResource> new_resources = new ArrayList<ContentResource>();
    MultiFileUploadPipe mfp = (MultiFileUploadPipe) pipe;
    Iterator<ResourceToolActionPipe> pipeIt = mfp.getPipes().iterator();
    while (pipeIt.hasNext()) {
        ResourceToolActionPipe fp = pipeIt.next();
        collectionId = pipe.getContentEntity().getId();
        String name = fp.getFileName();
        if (name == null || name.trim().equals("")) {
            continue;
        }
        String basename = name.trim();
        String extension = ".URL";

        try {
            ContentResourceEdit resource = ContentHostingService.addResource(collectionId,
                    Validator.escapeResourceName(basename), Validator.escapeResourceName(extension),
                    MAXIMUM_ATTEMPTS_FOR_UNIQUENESS);

            extractContent(fp, resource);

            // SAK-23171 - cleanup the URL spaces
            String originalUrl = new String(resource.getContent());
            String cleanedURL = StringUtils.trim(originalUrl);
            //cleanedURL = StringUtils.replace(cleanedURL, " ", "%20");

            // SAK-23587 - properly escape the URL where required
            try {
                URL url = new URL(cleanedURL);
                URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(),
                        url.getPath(), url.getQuery(), url.getRef());
                cleanedURL = uri.toString();
            } catch (Exception e) {
                //ok to ignore, just use the original url
                logger.debug("URL can not be encoded: " + e.getClass() + ":" + e.getCause());
            }

            if (!StringUtils.equals(originalUrl, cleanedURL)) {
                // the url was cleaned up, log it and update it
                logger.info(
                        "Resources URL cleanup changed url to '" + cleanedURL + "' from '" + originalUrl + "'");
                resource.setContent(cleanedURL.getBytes());
            }

            resource.setContentType(fp.getRevisedMimeType());
            resource.setResourceType(pipe.getAction().getTypeId());
            int notification = NotificationService.NOTI_NONE;
            Object obj = fp.getRevisedListItem();
            if (obj != null && obj instanceof ListItem) {
                ((ListItem) obj).updateContentResourceEdit(resource);
                notification = ((ListItem) obj).getNotification();
            }
            ResourcePropertiesEdit resourceProperties = resource.getPropertiesEdit();
            String displayName = null;
            if (obj != null && obj instanceof ListItem) {
                displayName = ((ListItem) obj).getName();
                List<String> alerts = ((ListItem) obj).checkRequiredProperties();
                for (String alert : alerts) {
                    addAlert(state, alert);
                }
            }
            if (displayName == null || displayName.trim().equals("")) {
                displayName = name;
            }
            if (displayName != null) {
                resourceProperties.addProperty(ResourceProperties.PROP_DISPLAY_NAME, displayName);
            }
            Map values = pipe.getRevisedResourceProperties();
            for (Iterator<Entry<String, String>> mapIter = values.entrySet().iterator(); mapIter.hasNext();) {
                Entry<String, String> entry = mapIter.next();
                resourceProperties.addProperty(entry.getKey(), entry.getValue());
            }
            try {
                ContentHostingService.commitResource(resource, notification);
                conditionsHelper.notifyCondition(resource);
                item_added = true;
                new_resources.add(resource);
            } catch (OverQuotaException e) {
                addAlert(state, trb.getFormattedMessage("alert.overquota", new String[] { name }));
                logger.debug("OverQuotaException " + e);
                try {
                    ContentHostingService.removeResource(resource.getId());
                } catch (Exception e1) {
                    logger.debug(
                            "Unable to remove partially completed resource: " + resource.getId() + "\n" + e);
                }
            } catch (ServerOverloadException e) {
                addAlert(state, trb.getFormattedMessage("alert.unable1", new String[] { name }));
                logger.debug("ServerOverloadException " + e);
                try {
                    ContentHostingService.removeResource(resource.getId());
                } catch (Exception e1) {
                    logger.debug(
                            "Unable to remove partially completed resource: " + resource.getId() + "\n" + e);
                }
            }
        } catch (PermissionException e) {
            addAlert(state, trb.getString("alert.perm"));
            logger.warn("PermissionException ", e);
        } catch (IdUnusedException e) {
            logger.warn("IdUsedException ", e);
        } catch (IdInvalidException e) {
            logger.warn("IdInvalidException ", e);
        } catch (IdUniquenessException e) {
            logger.warn("IdUniquenessException ", e);
        } catch (IdLengthException e) {
            addAlert(state, trb.getFormattedMessage("alert.toolong", new String[] { e.getMessage() }));
            // TODO Auto-generated catch block
            logger.warn("IdLengthException ", e);
        } catch (OverQuotaException e) {
            addAlert(state, trb.getFormattedMessage("alert.overquota", new String[] { name }));
            logger.warn("OverQuotaException ", e);
        } catch (ServerOverloadException e) {
            addAlert(state, trb.getFormattedMessage("alert.unable1", new String[] { name }));
            logger.warn("ServerOverloadException ", e);
        }
    }

    return (item_added ? new_resources : null);
}