Example usage for java.net MalformedURLException MalformedURLException

List of usage examples for java.net MalformedURLException MalformedURLException

Introduction

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

Prototype

public MalformedURLException(String msg) 

Source Link

Document

Constructs a MalformedURLException with the specified detail message.

Usage

From source file:org.couchpotato.CouchPotato.java

public URL fileCache(String filename) throws MalformedURLException {
    // WOW this sucks i hope this works for both windows and linux
    try {/*from   w  w  w.  j  a  v a  2s  .c o  m*/
        filename = filename.replace("\\", "/");
        if (filename.startsWith("/") == false) {
            filename = "/" + filename;
        }
        return this.getUri("file.cache" + filename, null).toURL();
    } catch (URISyntaxException e) {
        throw new MalformedURLException(e.getMessage());
    }
}

From source file:org.opennms.netmgt.provision.service.vmware.VmwareRequisitionUrlConnection.java

/**
 * Constructor for creating an instance of this class.
 *
 * @param url the URL to use/*w  w  w  .  ja v a2  s . com*/
 * @throws MalformedURLException
 * @throws RemoteException
 */
public VmwareRequisitionUrlConnection(URL url) throws MalformedURLException, RemoteException {
    super(url);

    m_hostname = url.getHost();

    m_username = getUsername();
    m_password = getPassword();

    m_args = getQueryArgs();

    boolean importVMOnly = queryParameter("importVMOnly", false);
    boolean importHostOnly = queryParameter("importHostOnly", false);

    if (importHostOnly && importVMOnly) {
        throw new MalformedURLException("importHostOnly and importVMOnly can't be true simultaneously");
    }
    if (importHostOnly) {
        m_persistVMs = false;
    }
    if (importVMOnly) {
        m_persistHosts = false;
    }

    boolean importIPv4Only = queryParameter("importIPv4Only", false);
    boolean importIPv6Only = queryParameter("importIPv6Only", false);

    if (importIPv4Only && importIPv6Only) {
        throw new MalformedURLException("importIPv4Only and importIPv6Only can't be true simultaneously");
    }
    if (importIPv4Only) {
        m_persistIPv6 = false;
    }
    if (importIPv6Only) {
        m_persistIPv4 = false;
    }

    m_topologyPortGroups = queryParameter("topologyPortGroups", false);
    m_topologyNetworks = queryParameter("topologyNetworks", true);
    m_topologyDatastores = queryParameter("topologyDatastores", true);

    m_importVMPoweredOn = queryParameter("importVMPoweredOn", true);
    m_importVMPoweredOff = queryParameter("importVMPoweredOff", false);
    m_importVMSuspended = queryParameter("importVMSuspended", false);

    m_importHostPoweredOn = queryParameter("importHostPoweredOn", true);
    m_importHostPoweredOff = queryParameter("importHostPoweredOff", false);
    m_importHostStandBy = queryParameter("importHostStandBy", false);
    m_importHostUnknown = queryParameter("importHostUnknown", false);

    if (queryParameter("importHostAll", false)) {
        m_importHostPoweredOn = true;
        m_importHostPoweredOff = true;
        m_importHostStandBy = true;
        m_importHostUnknown = true;
    }

    if (queryParameter("importVMAll", false)) {
        m_importVMPoweredOff = true;
        m_importVMPoweredOn = true;
        m_importVMSuspended = true;
    }

    String path = url.getPath();

    path = path.replaceAll("^/", "");
    path = path.replaceAll("/$", "");

    String[] pathElements = path.split("/");

    if (pathElements.length == 1) {
        if ("".equals(pathElements[0])) {
            m_foreignSource = "vmware-" + m_hostname;
        } else {
            m_foreignSource = pathElements[0];
        }
    } else {
        throw new MalformedURLException(
                "Error processing path element of URL (vmware://username:password@host[/foreign-source]?keyA=valueA;keyB=valueB;...)");
    }
}

From source file:com.box.androidlib.FileTransfer.BoxFileUpload.java

/**
 * Execute a file upload.//from ww w.j  ava  2 s  . co m
 * 
 * @param action
 *            Set to {@link com.box.androidlib.Box#UPLOAD_ACTION_UPLOAD} or {@link com.box.androidlib.Box#UPLOAD_ACTION_OVERWRITE} or
 *            {@link com.box.androidlib.Box#UPLOAD_ACTION_NEW_COPY}
 * @param file
 *            A File resource pointing to the file you wish to upload. Make sure File.isFile() and File.canRead() are true for this resource.
 * @param filename
 *            The desired filename on Box after upload (just the file name, do not include the path)
 * @param destinationId
 *            If action is {@link com.box.androidlib.Box#UPLOAD_ACTION_UPLOAD}, then this is the folder id where the file will uploaded to. If action is
 *            {@link com.box.androidlib.Box#UPLOAD_ACTION_OVERWRITE} or {@link com.box.androidlib.Box#UPLOAD_ACTION_NEW_COPY}, then this is the file_id that
 *            is being overwritten, or copied.
 * @return A FileResponseParser with information about the upload.
 * @throws IOException
 *             Can be thrown if there is no connection, or if some other connection problem exists.
 * @throws FileNotFoundException
 *             File being uploaded either doesn't exist, is not a file, or cannot be read
 * @throws MalformedURLException
 *             Make sure you have specified a valid upload action
 */
public FileResponseParser execute(final String action, final File file, final String filename,
        final long destinationId) throws IOException, MalformedURLException, FileNotFoundException {
    if (!file.isFile() || !file.canRead()) {
        throw new FileNotFoundException("Specified upload file is either not a file, or cannot be read");
    }

    if (!action.equals(Box.UPLOAD_ACTION_UPLOAD) && !action.equals(Box.UPLOAD_ACTION_OVERWRITE)
            && !action.equals(Box.UPLOAD_ACTION_NEW_COPY)) {
        throw new MalformedURLException("action must be upload, overwrite or new_copy");
    }

    final Uri.Builder builder = new Uri.Builder();
    builder.scheme(BoxConfig.getInstance().getUploadUrlScheme());
    builder.authority(BoxConfig.getInstance().getUploadUrlAuthority());
    builder.path(BoxConfig.getInstance().getUploadUrlPath());
    builder.appendPath(action);
    builder.appendPath(mAuthToken);
    builder.appendPath(String.valueOf(destinationId));
    builder.appendQueryParameter("file_name", filename);

    // Set up post body
    final HttpPost post = new HttpPost(builder.build().toString());
    final MultipartEntityWithProgressListener reqEntity = new MultipartEntityWithProgressListener(
            HttpMultipartMode.BROWSER_COMPATIBLE);
    if (mListener != null && mHandler != null) {
        reqEntity.setProgressListener(new MultipartEntityWithProgressListener.ProgressListener() {

            @Override
            public void onTransferred(final long bytesTransferredCumulative) {
                mHandler.post(new Runnable() {

                    @Override
                    public void run() {
                        mListener.onProgress(bytesTransferredCumulative);
                    }
                });
            }
        });
    }

    reqEntity.addPart(filename, new FileBody(file) {

        @Override
        public String getFilename() {
            return filename;
        }
    });
    post.setEntity(reqEntity);

    // Send request
    final HttpResponse httpResponse;
    try {
        httpResponse = (new DefaultHttpClient()).execute(post);
    } catch (final IOException e) {
        // Detect if the download was cancelled through thread interrupt.
        // See CountingOutputStream.write() for when this exception is thrown.
        if (e.getMessage().equals(FileUploadListener.STATUS_CANCELLED)) {
            final FileResponseParser handler = new FileResponseParser();
            handler.setStatus(FileUploadListener.STATUS_CANCELLED);
            return handler;
        } else {
            throw e;
        }
    }

    String status = null;
    BoxFile boxFile = null;
    final InputStream is = httpResponse.getEntity().getContent();
    final BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    final StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }
    is.close();
    httpResponse.getEntity().consumeContent();
    final String xml = sb.toString();

    try {
        final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(new ByteArrayInputStream(xml.getBytes()));
        final Node statusNode = doc.getElementsByTagName("status").item(0);
        if (statusNode != null) {
            status = statusNode.getFirstChild().getNodeValue();
        }
        final Element fileEl = (Element) doc.getElementsByTagName("file").item(0);
        if (fileEl != null) {
            try {
                boxFile = Box.getBoxFileClass().newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            for (int i = 0; i < fileEl.getAttributes().getLength(); i++) {
                boxFile.parseAttribute(fileEl.getAttributes().item(i).getNodeName(),
                        fileEl.getAttributes().item(i).getNodeValue());
            }
        }

        // errors are NOT returned as properly formatted XML yet so in this
        // case the raw response is the error status code
        // see
        // http://developers.box.net/w/page/12923951/ApiFunction_Upload-and-Download
        if (status == null) {
            status = xml;
        }
    } catch (final SAXException e) {
        // errors are NOT returned as properly formatted XML yet so in this
        // case the raw response is the error status code
        // see
        // http://developers.box.net/w/page/12923951/ApiFunction_Upload-and-Download
        status = xml;
    } catch (final ParserConfigurationException e) {
        e.printStackTrace();
    }
    final FileResponseParser handler = new FileResponseParser();
    handler.setFile(boxFile);
    handler.setStatus(status);
    return handler;
}

From source file:com.box.androidlib.BoxFileUpload.java

/**
 * Execute a file upload./*from   ww w.j  a  v  a2 s .  c  o m*/
 * 
 * @param action
 *            Set to {@link com.box.androidlib.Box#UPLOAD_ACTION_UPLOAD} or {@link com.box.androidlib.Box#UPLOAD_ACTION_OVERWRITE} or
 *            {@link com.box.androidlib.Box#UPLOAD_ACTION_NEW_COPY}
 * @param sourceInputStream
 *            Input stream targeting the data for the file you wish to create/upload to Box.
 * @param filename
 *            The desired filename on Box after upload (just the file name, do not include the path)
 * @param destinationId
 *            If action is {@link com.box.androidlib.Box#UPLOAD_ACTION_UPLOAD}, then this is the folder id where the file will uploaded to. If action is
 *            {@link com.box.androidlib.Box#UPLOAD_ACTION_OVERWRITE} or {@link com.box.androidlib.Box#UPLOAD_ACTION_NEW_COPY}, then this is the file_id that
 *            is being overwritten, or copied.
 * @return A FileResponseParser with information about the upload.
 * @throws IOException
 *             Can be thrown if there is no connection, or if some other connection problem exists.
 * @throws FileNotFoundException
 *             File being uploaded either doesn't exist, is not a file, or cannot be read
 * @throws MalformedURLException
 *             Make sure you have specified a valid upload action
 */
public FileResponseParser execute(final String action, final InputStream sourceInputStream,
        final String filename, final long destinationId)
        throws IOException, MalformedURLException, FileNotFoundException {

    if (!action.equals(Box.UPLOAD_ACTION_UPLOAD) && !action.equals(Box.UPLOAD_ACTION_OVERWRITE)
            && !action.equals(Box.UPLOAD_ACTION_NEW_COPY)) {
        throw new MalformedURLException("action must be upload, overwrite or new_copy");
    }

    final Uri.Builder builder = new Uri.Builder();
    builder.scheme(BoxConfig.getInstance().getUploadUrlScheme());
    builder.encodedAuthority(BoxConfig.getInstance().getUploadUrlAuthority());
    builder.path(BoxConfig.getInstance().getUploadUrlPath());
    builder.appendPath(action);
    builder.appendPath(mAuthToken);
    builder.appendPath(String.valueOf(destinationId));
    if (action.equals(Box.UPLOAD_ACTION_OVERWRITE)) {
        builder.appendQueryParameter("file_name", filename);
    } else if (action.equals(Box.UPLOAD_ACTION_NEW_COPY)) {
        builder.appendQueryParameter("new_file_name", filename);
    }

    List<BasicNameValuePair> customQueryParams = BoxConfig.getInstance().getCustomQueryParameters();
    if (customQueryParams != null && customQueryParams.size() > 0) {
        for (BasicNameValuePair param : customQueryParams) {
            builder.appendQueryParameter(param.getName(), param.getValue());
        }
    }

    if (BoxConfig.getInstance().getHttpLoggingEnabled()) {
        //            DevUtils.logcat("Uploading : " + filename + "  Action= " + action + " DestinionID + " + destinationId);
        DevUtils.logcat("Upload URL : " + builder.build().toString());
    }
    // Set up post body
    final HttpPost post = new HttpPost(builder.build().toString());
    final MultipartEntityWithProgressListener reqEntity = new MultipartEntityWithProgressListener(
            HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName(HTTP.UTF_8));

    if (mListener != null && mHandler != null) {
        reqEntity.setProgressListener(new MultipartEntityWithProgressListener.ProgressListener() {

            @Override
            public void onTransferred(final long bytesTransferredCumulative) {
                mHandler.post(new Runnable() {

                    @Override
                    public void run() {
                        mListener.onProgress(bytesTransferredCumulative);
                    }
                });
            }
        });
    }

    reqEntity.addPart("file_name", new InputStreamBody(sourceInputStream, filename) {

        @Override
        public String getFilename() {
            return filename;
        }
    });
    post.setEntity(reqEntity);

    // Send request
    final HttpResponse httpResponse;
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpProtocolParams.setUserAgent(httpClient.getParams(), BoxConfig.getInstance().getUserAgent());
    post.setHeader("Accept-Language", BoxConfig.getInstance().getAcceptLanguage());
    try {
        httpResponse = httpClient.execute(post);
    } catch (final IOException e) {
        // Detect if the download was cancelled through thread interrupt. See CountingOutputStream.write() for when this exception is thrown.
        if (BoxConfig.getInstance().getHttpLoggingEnabled()) {
            //                DevUtils.logcat("IOException Uploading " + filename + " Exception Message: " + e.getMessage() + e.toString());
            DevUtils.logcat(" Exception : " + e.toString());
            e.printStackTrace();
            DevUtils.logcat("Upload URL : " + builder.build().toString());
        }
        if ((e.getMessage() != null && e.getMessage().equals(FileUploadListener.STATUS_CANCELLED))
                || Thread.currentThread().isInterrupted()) {
            final FileResponseParser handler = new FileResponseParser();
            handler.setStatus(FileUploadListener.STATUS_CANCELLED);
            return handler;
        } else {
            throw e;
        }
    } finally {
        if (httpClient != null && httpClient.getConnectionManager() != null) {
            httpClient.getConnectionManager().closeIdleConnections(500, TimeUnit.MILLISECONDS);
        }
    }
    if (BoxConfig.getInstance().getHttpLoggingEnabled()) {
        DevUtils.logcat("HTTP Response Code: " + httpResponse.getStatusLine().getStatusCode());
        Header[] headers = httpResponse.getAllHeaders();
        //            DevUtils.logcat("User-Agent : " + HttpProtocolParams.getUserAgent(httpClient.getParams()));
        //            for (Header header : headers) {
        //                DevUtils.logcat("Response Header: " + header.toString());
        //            }
    }

    // Server returned a 503 Service Unavailable. Usually means a temporary unavailability.
    if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_SERVICE_UNAVAILABLE) {
        final FileResponseParser handler = new FileResponseParser();
        handler.setStatus(ResponseListener.STATUS_SERVICE_UNAVAILABLE);
        return handler;
    }

    String status = null;
    BoxFile boxFile = null;
    final InputStream is = httpResponse.getEntity().getContent();
    final BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    final StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }
    is.close();
    httpResponse.getEntity().consumeContent();
    final String xml = sb.toString();

    try {
        final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(new ByteArrayInputStream(xml.getBytes()));
        final Node statusNode = doc.getElementsByTagName("status").item(0);
        if (statusNode != null) {
            status = statusNode.getFirstChild().getNodeValue();
        }
        final Element fileEl = (Element) doc.getElementsByTagName("file").item(0);
        if (fileEl != null) {
            try {
                boxFile = Box.getBoxFileClass().newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            for (int i = 0; i < fileEl.getAttributes().getLength(); i++) {
                boxFile.parseAttribute(fileEl.getAttributes().item(i).getNodeName(),
                        fileEl.getAttributes().item(i).getNodeValue());
            }
        }

        // errors are NOT returned as properly formatted XML yet so in this case the raw response is the error status code see
        // http://developers.box.net/w/page/12923951/ApiFunction_Upload-and-Download
        if (status == null) {
            status = xml;
        }
    } catch (final SAXException e) {
        // errors are NOT returned as properly formatted XML yet so in this case the raw response is the error status code see
        // http://developers.box.net/w/page/12923951/ApiFunction_Upload-and-Download
        status = xml;
    } catch (final ParserConfigurationException e) {
        e.printStackTrace();
    }
    final FileResponseParser handler = new FileResponseParser();
    handler.setFile(boxFile);
    handler.setStatus(status);
    return handler;
}

From source file:org.kalypso.contribs.eclipse.core.resources.ResourceUtilities.java

private static IPath findPathFromUrlException(final URL location)
        throws MalformedURLException, UnsupportedEncodingException {
    if (location == null)
        return null;

    final URL urlNoQuery = UrlUtilities.removeQuery(location);

    final String protocol = urlNoQuery.getProtocol();

    // if( urlpath != null && urlpath.startsWith( PlatformURLResourceConnection.RESOURCE_URL_STRING ) )
    // {//w w  w  .j av  a2  s.c o  m
    // final String path = urlpath.substring( PlatformURLResourceConnection.RESOURCE_URL_STRING.length() - 1 );
    //      return new Path( path.replaceAll( "//", "/" ) ); //$NON-NLS-1$ //$NON-NLS-2$
    // }

    // FIXME: check
    if (PlatformURLHandler.PROTOCOL.equals(protocol)) {
        String spec = urlNoQuery.getFile().trim();
        if (spec.startsWith("/")) //$NON-NLS-1$
            spec = spec.substring(1);
        final int ix = spec.indexOf("/"); //$NON-NLS-1$
        if (ix == -1)
            throw new MalformedURLException(NLS.bind(CommonMessages.url_invalidURL, location.toExternalForm()));

        final String type = spec.substring(0, ix);
        if (PlatformURLResourceConnection.RESOURCE.equals(type)) {
            final String filePath = URLDecoder.decode(spec.substring(ix), "UTF-8"); //$NON-NLS-1$
            return new Path(filePath.replaceAll("//", "/")); //$NON-NLS-1$ //$NON-NLS-2$
        }
    } else if (protocol.equals("http") || protocol.equals("file")) //$NON-NLS-1$ //$NON-NLS-2$
    {
        // Checks if the full path lies in the Workspace, if it does, the java.io.File path is converted
        // to an eclipse path
        // WARNING: this is quite ugly and probalbly doesn't work as it is intended to do
        // especially, if we are working with pathes into the .metadata section we get bugs
        final IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
        URL rootUrl = null;
        try {
            rootUrl = root.getLocation().toFile().toURI().toURL();
        } catch (final MalformedURLException e) {
            // just return null
            e.printStackTrace();
            return null;
        }

        final String noQuery = urlNoQuery.toString();

        if (noQuery.startsWith(rootUrl.toString())) //$NON-NLS-1$
        {
            // split the string at the common part (path to workspace) and always take the second
            // part as the relative eclipse workspace path
            final String[] array = noQuery.split(rootUrl.toString());
            if (array.length < 2)
                return null;

            if (array[1].startsWith(".metadata")) //$NON-NLS-1$
                return null;

            final String filePath = URLDecoder.decode(array[1], "UTF-8"); //$NON-NLS-1$
            return new Path(filePath);
        }
    }

    return null;
}

From source file:gov.nih.nci.ncicb.tcga.dcc.common.web.StaticContentServlet.java

private void prepareResponse(HttpServletResponse response, URL[] resources, String rawResourcePath)
        throws IOException {
    long lastModified = -1;
    int contentLength = 0;
    String mimeType = null;/*w  ww . j  av  a 2s .  com*/
    for (int i = 0; i < resources.length; i++) {
        final URLConnection resourceConn = resources[i].openConnection();
        //Setting the last modified http for the requested resource
        if (resourceConn.getLastModified() > lastModified) {
            lastModified = resourceConn.getLastModified();
        }
        //Setting the mime type of the resource requested
        String currentMimeType = getServletContext().getMimeType(resources[i].getPath());
        if (log.isDebugEnabled()) {
            log.debug("Current MimeType: " + currentMimeType);
        }
        if (currentMimeType == null) {
            int index = resources[i].getPath().lastIndexOf('.');
            if (index > 0) {
                String extension = resources[i].getPath().substring(resources[i].getPath().lastIndexOf('.'));
                currentMimeType = (String) defaultMimeTypes.get(extension);
            } else {
                currentMimeType = "text/html"; //html will be the default mime.
            }
        }
        if (mimeType == null) {
            mimeType = currentMimeType;
        } else if (!mimeType.equals(currentMimeType)) {
            //This does not apply to us yet since we don't use combined resource url but maybe in the future ...
            throw new MalformedURLException("Combined resource path: " + rawResourcePath
                    + " is invalid. All resources in a combined resource path must be of the same mime type.");
        }
        contentLength += resourceConn.getContentLength();
    }
    response.setContentType(mimeType);
    response.setHeader(HTTP_CONTENT_LENGTH_HEADER, Long.toString(contentLength));
    response.setDateHeader(HTTP_LAST_MODIFIED_HEADER, lastModified);
    if (cacheTimeout > 0) {
        configureCaching(response, cacheTimeout);
    }
}

From source file:org.ofbiz.testtools.seleniumxml.SeleniumXml.java

private static void initConfig() throws IOException {
    try {/*  ww w .  j a v  a2s .  c o m*/
        String configFile = System.getProperty(PROPS_NAME);
        if (configFile == null) {
            String errMsg = "The Java environment (-Dxxx=yyy) variable with name " + PROPS_NAME
                    + " is not set, cannot resolve location.";
            throw new MalformedURLException(errMsg);
        }
        BasicConfigurator.configure();
        InputStream in = new FileInputStream(configFile);
        props.load(in);
        in.close();

    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    }
}

From source file:org.apache.mina.springrpc.MinaClientInterceptor.java

private URL getURL() throws MalformedURLException {
    URL url = new URL(null, getServiceUrl(), new DummyURLStreamHandler());
    String protocol = url.getProtocol();
    if (protocol != null && !"tcp".equals(protocol)) {
        throw new MalformedURLException("Invalid URL scheme '" + protocol + "'");
    }/*  ww w  . j  ava 2  s .  c  om*/
    return url;
}

From source file:com.recomdata.datasetexplorer.proxy.HttpClient.java

/**
 * private method to get the URLConnection
 * @param str URL string//w ww. j  a  va2s .co  m
 */
private URLConnection getURLConnection(String str) throws MalformedURLException {
    try {

        if (isHttps) {

            /* when communicating with the server which has unsigned or invalid
             * certificate (https), SSLException or IOException is thrown.
             * the following line is a hack to avoid that
             */
            Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
            System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
            if (isProxy) {
                System.setProperty("https.proxyHost", proxyHost);
                System.setProperty("https.proxyPort", proxyPort + "");
            }
        } else {
            if (isProxy) {
                System.setProperty("http.proxyHost", proxyHost);
                System.setProperty("http.proxyPort", proxyPort + "");
            }

        }
        SSLUtilities.trustAllHostnames();
        SSLUtilities.trustAllHttpsCertificates();
        URL url = new URL(str);
        URLConnection uc = url.openConnection();
        if (isHttps) {
            /*((HttpsURLConnection)uc).setHostnameVerifier(new HostnameVerifier()
            {
               public boolean verify (String hostname, String 
                session)
                                      {
                                        return true;
                                      }
            });*/
        }
        // set user agent to mimic a common browser
        String ua = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)";
        uc.setRequestProperty("user-agent", ua);

        return uc;
    } catch (MalformedURLException me) {
        throw new MalformedURLException(str + " is not a valid URL");
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:org.apache.cxf.transport.http.asyncclient.AsyncHTTPConduit.java

@Override
protected void setupConnection(Message message, Address address, HTTPClientPolicy csPolicy) throws IOException {
    if (factory.isShutdown()) {
        message.put(USE_ASYNC, Boolean.FALSE);
        super.setupConnection(message, address, csPolicy);
        return;//  www.j av a  2  s.  c  o m
    }
    boolean addressChanged = false;
    // need to do some clean up work on the URI address
    URI uri = address.getURI();
    String uriString = uri.toString();
    if (uriString.startsWith("hc://")) {
        try {
            uriString = uriString.substring(5);
            uri = new URI(uriString);
            addressChanged = true;
        } catch (URISyntaxException ex) {
            throw new MalformedURLException("unsupport uri: " + uriString);
        }
    }
    String s = uri.getScheme();
    if (!"http".equals(s) && !"https".equals(s)) {
        throw new MalformedURLException("unknown protocol: " + s);
    }

    Object o = message.getContextualProperty(USE_ASYNC);
    if (o == null) {
        o = factory.getUseAsyncPolicy();
    }
    switch (UseAsyncPolicy.getPolicy(o)) {
    case ALWAYS:
        o = true;
        break;
    case NEVER:
        o = false;
        break;
    case ASYNC_ONLY:
    default:
        o = !message.getExchange().isSynchronous();
        break;
    }

    // check tlsClientParameters from message header
    TLSClientParameters clientParameters = message.get(TLSClientParameters.class);
    if (clientParameters == null) {
        clientParameters = tlsClientParameters;
    }
    if (uri.getScheme().equals("https") && clientParameters != null
            && clientParameters.getSSLSocketFactory() != null) {
        //if they configured in an SSLSocketFactory, we cannot do anything
        //with it as the NIO based transport cannot use socket created from
        //the SSLSocketFactory.
        o = false;
    }
    if (!MessageUtils.isTrue(o)) {
        message.put(USE_ASYNC, Boolean.FALSE);
        super.setupConnection(message, addressChanged ? new Address(uriString, uri) : address, csPolicy);
        return;
    }
    if (StringUtils.isEmpty(uri.getPath())) {
        //hc needs to have the path be "/" 
        uri = uri.resolve("/");
        addressChanged = true;
    }

    message.put(USE_ASYNC, Boolean.TRUE);
    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("Asynchronous connection to " + uri.toString() + " has been set up");
    }
    message.put("http.scheme", uri.getScheme());
    String httpRequestMethod = (String) message.get(Message.HTTP_REQUEST_METHOD);
    if (httpRequestMethod == null) {
        httpRequestMethod = "POST";
        message.put(Message.HTTP_REQUEST_METHOD, httpRequestMethod);
    }
    final CXFHttpRequest e = new CXFHttpRequest(httpRequestMethod);
    BasicHttpEntity entity = new BasicHttpEntity() {
        public boolean isRepeatable() {
            return e.getOutputStream().retransmitable();
        }
    };
    entity.setChunked(true);
    entity.setContentType((String) message.get(Message.CONTENT_TYPE));
    e.setURI(uri);

    e.setEntity(entity);

    RequestConfig.Builder b = RequestConfig.custom().setConnectTimeout((int) csPolicy.getConnectionTimeout())
            .setSocketTimeout((int) csPolicy.getReceiveTimeout())
            .setConnectionRequestTimeout((int) csPolicy.getReceiveTimeout());
    Proxy p = proxyFactory.createProxy(csPolicy, uri);
    if (p != null && p.type() != Proxy.Type.DIRECT) {
        InetSocketAddress isa = (InetSocketAddress) p.address();
        HttpHost proxy = new HttpHost(isa.getHostName(), isa.getPort());
        b.setProxy(proxy);
    }
    e.setConfig(b.build());

    message.put(CXFHttpRequest.class, e);
}