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:api.wireless.gdata.docs.client.DocsClient.java

public Feed<DocumentEntry> searchDocumentsFullText(String query)
        throws IOException, ServiceException, ParseException {
    String[] parameters = null;// w ww .j  a v  a 2  s  .c om
    try {
        parameters = new String[] { "q=" + URLEncoder.encode(query, "UTF-8") };
    } catch (UnsupportedEncodingException e) {
        throw new MalformedURLException("Unable to create parameters");
    }
    URL url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED, parameters);

    Feed<DocumentEntry> docs = getFeed(DocumentEntry.class, url);

    return docs;
}

From source file:org.openremote.android.console.net.ORConnection.java

/**
 * TODO//from  ww  w.j  a va  2  s .com
 *
 * Establish the httpconnection with url for caller and then the caller can deal with the
 * httprequest result within ORConnectionDelegate instance. if check failed, return null.
 *
 * @param context         global Android application context
 * @param httpMethod      enum POST or GET
 * @param url             the URL to connect to
 * @param useHTTPAuth     indicates whether the HTTP 'Authentication' header should be added
 *                        to the HTTP request
 *
 * @return TODO
 *
 * @throws IOException  if the URL cannot be resolved by DNS (UnknownHostException),
 *                      if the URL was not correctly formed (MalformedURLException),
 *                      if the connection timed out (SocketTimeoutException),
 *                      there was an error in the HTTP protocol (ClientProtocolException),
 *                      or any other IO error occured (generic IOException)
 */
public static HttpResponse checkURLWithHTTPProtocol(Context context, ORHttpMethod httpMethod, String urlString,
        boolean useHTTPAuth) throws IOException {
    // TODO : could move this method to ORNetworkCheck class, no one else is using it.
    //
    // TODO : use URL in the API instead of string
    //
    // Validate the URL by creating a proper URL instance from the string... it will throw
    // an MalformedURLException (IOException) in case the URL was invalid.
    //
    // This can go away when the API is fixed...

    URL targetURL = new URL(urlString);
    URI targetURI;

    try {
        targetURI = targetURL.toURI();
    } catch (URISyntaxException e) {
        // Not sure if we're ever going to hit this, but in case we do, just convert to
        // MalformedURLException...

        throw new MalformedURLException(
                "Could not convert " + urlString + " to a compliant URI: " + e.getMessage());
    }

    HttpRequestBase request = null;
    HttpResponse response = null;

    HttpParams params = new BasicHttpParams();

    // TODO : seems like timeouts ought to be externalized...

    HttpConnectionParams.setConnectionTimeout(params, 5 * 1000);
    HttpConnectionParams.setSoTimeout(params, 5 * 1000);

    HttpClient client = new DefaultHttpClient(params);

    switch (httpMethod) {
    case POST:
        request = new HttpPost(targetURI);
        break;

    case GET:
        request = new HttpGet(targetURI);
        break;

    default:
        throw new IOException("Unsupported HTTP Method: " + httpMethod);
    }

    if (useHTTPAuth) {
        SecurityUtil.addCredentialToHttpRequest(context, request);
    }

    if ("https".equals(targetURL.getProtocol())) {
        Scheme sch = new Scheme(targetURL.getProtocol(), new SelfCertificateSSLSocketFactory(context),
                targetURL.getPort());

        client.getConnectionManager().getSchemeRegistry().register(sch);
    }

    try {
        response = client.execute(request);
    } catch (IllegalArgumentException e) {
        throw new MalformedURLException("Illegal argument: " + e.getMessage());
    }

    return response;
}

From source file:org.exoplatform.services.rss.parser.RSSParser.java

public synchronized <T extends IRSSChannel, E extends IRSSItem> RSSDocument<T, E> createDocument(URL url,
        String charset, Class<T> channelClazz, Class<E> itemClazz) throws Exception {
    GetMethod get = null;/* w w w  . j av  a  2s . c om*/
    try {
        HttpClientImpl httpClientService = new HttpClientImpl(url);
        get = httpClientService.getMethod(url.getFile());
        get.setFollowRedirects(true);
        int statusCode = httpClientService.getHttpClient().executeMethod(get);
        if (statusCode != HttpStatus.SC_OK) {
            throw new MalformedURLException("Server response code " + statusCode);
        }
        InputStream input = get.getResponseBodyAsStream();
        DataBuffer buffer = new DataBuffer();
        byte[] data = buffer.loadInputStream(input).toByteArray();
        return createDocument(data, charset, channelClazz, itemClazz);
    } finally {
        if (get != null)
            get.releaseConnection();
    }
}

From source file:org.nordapp.web.servlet.SessionCallServlet.java

/**
 * @param req The request//from   w  w w . j a va  2  s .  co m
 * @param resp The response
 * @param data The data
 * @throws IOException 
 */
private void process(SessionControl ctrl, HttpServletRequest req, HttpServletResponse resp,
        Map<String, Object> data) throws IOException {

    //
    // Session service
    //
    String cert = null;

    //The '0' session of the mandator
    Session mSession = SessionServiceImpl.getSession(context, cert, ctrl.getMandatorID(), "0");
    Integer baseIndex = ((Integer) mSession.getValue(Session.ENGINE_BASE_INDEX)).intValue();
    //String sessionId = session.getId();

    String[] elem = RequestPath.getPath(req, ctrl.getPathStartIndex());
    if (elem.length == 0)
        throw new MalformedURLException("The URL needs the form '" + req.getServletPath()
                + (ctrl.getPathStartIndex() == 0 ? "" : "mandator-id/session-id") + "/function-id' but was '"
                + req.getRequestURI() + "'");

    BigInteger engineId = ctrl.decodeCert();
    String functionId = elem[0];

    StringBuffer buffer = new StringBuffer();
    List<String> states = new ArrayList<String>();
    ResponseHandler rsHdl = new ResponseHandler(context, ctrl);

    EngineBaseService engineBaseService = null;
    Engine engine = null;
    BigInteger anonId = null;
    boolean anonymous = false;
    try {
        //
        // Gets the engine base service
        //
        engineBaseService = EngineBaseServiceImpl.getService(context, ctrl.getMandatorID(),
                String.valueOf(baseIndex));
        if (engineBaseService == null)
            throw new IOException(
                    "The mandator base service is not available (maybe down or a version conflict).");

        //
        // Run the step
        //
        Mandator mandator = MandatorServiceImpl.getMandator(context, ctrl.getMandatorID());
        if (mandator == null)
            throw new IOException("The mandator service is not available (maybe down or a version conflict).");

        //
        // getEngine() creates one, if there is no engine.
        //

        Map<String, Object> params = new HashMap<String, Object>();
        params.put(EngineBaseService.IS_AVAILABLE, Boolean.TRUE);
        params.put(EngineBaseService.IS_LOGIN, Boolean.TRUE);
        engine = engineBaseService.queryEngine(engineId, params);

        if (engine == null) {

            String key = ctrl.getGroupID() + "." + ctrl.getArtifactID() + ".anonymous-support";
            if (Boolean.valueOf(mandator.getProperty(key)).booleanValue()) {
                key = ctrl.getGroupID() + "." + ctrl.getArtifactID() + ".anonymous-session";
                String val = mandator.getProperty(key);
                anonId = val == null ? BigInteger.ONE : new BigInteger(val);

                //
                // TODO cache this to avoid the initialization each call
                //

                //setup the bundles
                engineBaseService.setupStore(anonId);
                //uses the login-flag to signal the init state
                engine = engineBaseService.getEngine(anonId);
                //cleanup the old state
                if (!engine.hasNext()) {
                    engine.reinit();
                }

                anonymous = true;
            } else
                throw new IllegalAccessException("There is no login to this session (needs login).");

            //engineBaseService.dropEngine(engineId);
        }

        //
        // Set the parameter to the user-session
        //
        if (!anonymous) {
            mSession = SessionServiceImpl.getSession(context, cert, ctrl.getMandatorID(),
                    ctrl.decodeCert().toString());

            if (mSession != null && data != null && data.size() > 0) {
                for (String key : data.keySet()) {
                    Object value = data.get(key);

                    logger.trace("Set data to session mandatorId:{}, sessionId:{}, key:{}, value:{}",
                            ctrl.getMandatorID(), ctrl.getCertID(), key, value);
                    mSession.setValue(key, value);
                } //for
            } //fi
        }

        try {
            engine.setLocalValue(Mandator.MANDATORID, ctrl.getMandatorID());
            engine.setLocalValue("anonymous", new Boolean(anonymous));
            engine.setLocalValue("sessionId", ctrl.decodeCert().toString());
            engine.setLocalValue("nativeSessionId", ctrl.decodeCert());
            engine.setLocalValue("immediate.result", null);
            engine.setLocalValue("immediate.fields", data == null ? null : Collections.unmodifiableMap(data));
            engine.setLocalValue("immediate.states", states);

            engine.call(functionId);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Object val = engine.getLocalValue("immediate.result");
        if (val != null) {
            logger.trace("immediate.results:{}", val);
            //Gson gson = new Gson();
            buffer.append(String.valueOf(val));
        }

    } catch (Exception e) {
        logger.error("Error running the step.", e);
    } finally {

        if (anonymous) {

            //
            // TODO cache this to avoid the initialization each call
            //

            engine.exit();
            try {
                engineBaseService.dropEngine(anonId);
            } catch (Exception e) {
                logger.error("Error running the step.", e);
            }
        } //fi
    }

    //
    //
    //
    byte[] bytes = buffer.toString().getBytes();

    //
    // Set RESTful states to HTTP links
    //

    LinkHeader lhdr = new LinkHeaderImpl();
    if (ctrl.isStateful()) {
        StateUtil.setDefault(lhdr, req);

        lhdr.setLink_mandator(ctrl.getMandatorID());
        lhdr.setLink_uuid(ctrl.getCertID());

        for (String state : states) {
            if (state == null)
                continue;
            int k = state.trim().lastIndexOf(' ');
            if (k < 1 || k == (state.length() - 1))
                continue;
            lhdr.add(state.substring(0, k), state.substring(k + 1));
        }
        //StateUtil.setState(context, ctrl, lhdr, "init.state");
        logger.debug(lhdr.toString());
    }
    rsHdl.setLinkHeader(resp, lhdr.toString());

    //
    // Send the resource
    //
    rsHdl.avoidCaching(resp);
    rsHdl.sendData(bytes, resp);

}

From source file:HTMLRewriter.java

/**
 * Does the conversion of the HTML//from   www. j  a  v a  2s .  c o  m
 * @param HTMLrdr Reader for HTML to be converted
 * @param BaseUrl URL from which this HTML was taken. We be the base-Url
 * for all URL-rewritings.
 * @throws MalformedURLException If the BaseUrl is not a valid URL or if an URL inside
 * the document could not be converted. Should not happen
 * normally, even in badly formatted HTML.
 * @return HTML-String with rewritten URLs and removed (according
 * to constructor-settings) tags
 */
public synchronized String convertURLs(Reader HTMLrdr, String BaseUrl) throws MalformedURLException {
    HTMLEditorKit.Parser parse = new HTMLRewriter.ParserGetter().getParser();
    String res = "";
    try {
        if (cb.result != null) {
            cb.result = null;
            cb.result = new StringWriter();
        }
        cb.baseUrl = new URL(BaseUrl);
        parse.parse(HTMLrdr, cb, true);
        res = cb.getResult();
    } catch (Exception e) {
        //logger.error( "Unable to convertURLS", e );
        throw new MalformedURLException(e.toString());
    }
    return res;
}

From source file:opendap.metacat.DDXRetriever.java

/**
 * Given a URL to a DDX, get the DDX document. If the DDXRetriever was
 * built with caching turned on, this uses a poor man's HTTP/1.1 cache
 * based on Last Modified Times. //from   w ww  . j  a  v a  2s  .c  om
 * 
 * If caching is on, then calling this on a series of DDX URLs will fill
 * the cache. If the cache is saved and later used again it is possible
 * to re-read the URLs straight from the cache.
 *  
 * @see getCache()
 * @param DDXURL Get the DDX referenced by this URL
 * @return The DDX document, in a String
 * @throws Exception 
 */
public String getDDXDoc(String DDXURL) throws Exception {
    String ddx = null;

    URL url = new URL(DDXURL);
    URLConnection connection = url.openConnection();

    if (DDXCache.getLastVisited(DDXURL) != 0 && DDXCache.getCachedResponse(DDXURL) != null)
        connection.setIfModifiedSince(DDXCache.getLastVisited(DDXURL));

    // Here's where we'd poke in a header to ask for the DAP3.2 DDX

    connection.connect();

    // Cast to a HttpURLConnection
    if (connection instanceof HttpURLConnection) {
        HttpURLConnection httpConnection = (HttpURLConnection) connection;
        int code = httpConnection.getResponseCode();

        // If we have something, process. Since a conditional get was
        // used, the response might be empty (code == 304) and nothing
        // should be done in that case
        switch (code) {
        case 200:
            ddx = convertStreamToString(httpConnection.getInputStream());
            // Update the last visited and document caches
            if (!readOnly) {
                Date date = new Date();
                DDXCache.setLastVisited(DDXURL, date.getTime());
                DDXCache.setCachedResponse(DDXURL, ddx);
            }
            break;

        case 304:
            ddx = DDXCache.getCachedResponse(DDXURL);
            if (!readOnly) {
                // Update the last visited cache to now
                Date date = new Date();
                DDXCache.setLastVisited(DDXURL, date.getTime());
            }
            break;

        default:
            log.error("Expected a 200 or 304 HTTP return code. Got: " + new Integer(code).toString());
        }
    } else {
        throw new MalformedURLException("Expected a HTTP URL (" + DDXURL + ").");
    }

    return ddx;
}

From source file:org.javaweb.utils.HttpRequestUtils.java

/**
 * ??HTTP,??HTTP??DNS,?//from  w  w  w  .  j  a  va 2s.c om
 *
 * @param request
 * @return
 */
public static HttpResponse httpRequest(HttpURLRequest request) {
    HttpURLConnection httpURLConnection = null;
    InputStream in = null;
    HttpResponse response = new HttpResponse(request.getUrl());

    try {
        response.setRequestTime(System.currentTimeMillis());// 

        try {
            response.dnsParse();// DNS?

            String protocol = request.getUrl().getProtocol();// ???

            if (!protocol.equals("http") && !protocol.equals("https")) {
                throw new MalformedURLException("?? http & https ??.");
            } else if ("https".equalsIgnoreCase(protocol)) {
                SslUtils.ignoreSsl();
            }

            String data = null;

            if (request.getRequestDataMap() != null && request.getRequestDataMap().size() > 0) {
                data = HttpRequestUtils.toURLParameterString(request.getRequestDataMap(), request.getCharset());
            } else {
                data = request.getRequestData();
            }

            URL url = request.getUrl();

            if ("GET".equalsIgnoreCase(request.getMethod()) && StringUtils.isNotEmpty(data)) {
                url = new URL(request.getUrl()
                        + (StringUtils.isNotEmpty(request.getUrl().getQuery()) ? "&" : "?") + data);
            }

            httpURLConnection = (HttpURLConnection) url.openConnection();

            setRequestProperties(httpURLConnection, request);// ?
            setRequestData(httpURLConnection, request, data);// ?

            httpURLConnection.connect();

            response.setRequest(request);

            setResponse(httpURLConnection, response);// HTTP??

            // ?HTTP?
            try {
                in = httpURLConnection.getInputStream();
            } catch (IOException e) {
                in = httpURLConnection.getErrorStream();
            }

            if (in != null) {
                response.setBodyBytes(IOUtils.toByteArray(in));
            }
        } catch (UnknownHostException e) {
            response.setException(e);
        }
    } catch (IOException e) {
        response.setException(e);
    } finally {
        IOUtils.closeQuietly(in);

        if (httpURLConnection != null) {
            httpURLConnection.disconnect();
        }

        response.setResponseTime(System.currentTimeMillis());// ?
    }

    return response;
}

From source file:org.wso2.carbon.databridge.agent.thrift.DataPublisher.java

/**
 * To create the Data Publisher and the respective agent to publish events
 *
 * @param authenticationUrl the secure authentication url, use <ssl/https>://<HOST>:<PORT>
 * @param receiverUrl       the event receiver url
 *                          use <tcp/http></tcp/http>://<HOST>:<PORT> for normal data transfer and
 *                          use <ssl/https></ssl/https>://<HOST>:<PORT> for secure data transfer
 * @param userName          user name/* ww w.ja  va2 s  .com*/
 * @param password          password
 * @param agent             the underlining agent
 * @throws java.net.MalformedURLException
 * @throws org.wso2.carbon.databridge.agent.thrift.exception.AgentException
 *
 * @throws org.wso2.carbon.databridge.commons.exception.AuthenticationException
 *
 * @throws org.wso2.carbon.databridge.commons.exception.TransportException
 *
 */
public DataPublisher(String authenticationUrl, String receiverUrl, String userName, String password,
        Agent agent) throws MalformedURLException, AgentException, AuthenticationException, TransportException {
    /**
     * Only if the agent is not null, then the agent will be set to agent holder.
     * Ie, only for the first datapublisher which is setting the agent,
     * will be actually used and the rest of the agents passed-in will be neglected.
     */
    if (null == agent) {
        agent = AgentHolder.getOrCreateAgent();
    } else if (AgentHolder.getAgent() == null) {
        AgentHolder.setAgent(agent);
    }
    AgentServerURL authenticationURL = new AgentServerURL(authenticationUrl);
    if (!authenticationURL.isSecured()) {
        throw new MalformedURLException(
                "Authentication url protocol is not ssl/https, expected = <ssl/https>://<HOST>:<PORT> but actual = "
                        + authenticationUrl);
    }
    AgentServerURL receiverURL = new AgentServerURL(receiverUrl);
    checkHostAddress(receiverURL.getHost());
    checkHostAddress(authenticationURL.getHost());
    this.start(new ReceiverConfiguration(userName, password, receiverURL.getProtocol(), receiverURL.getHost(),
            receiverURL.getPort(), authenticationURL.getProtocol(), authenticationURL.getHost(),
            authenticationURL.getPort(), receiverURL.isSecured()), AgentHolder.getAgent());

}

From source file:org.openecomp.sdnc.sli.aai.AAIRequest.java

protected String getRequestPath() throws MalformedURLException {
    Set<String> uniqueResources = extractUniqueResourceSetFromKeys(requestProperties.stringPropertyNames());
    BitSet bitset = new BitSet();
    for (String key : uniqueResources) {
        if (tagValues.containsKey(key)) {
            Object tmpValue = tagValues.get(key);
            if (tmpValue != null) {
                String value = tmpValue.toString();
                int bitIndex = Integer.parseInt(value);
                bitset.set(bitIndex);/*from   w  w w .ja va2  s.  c o  m*/
            }
        }
    }

    String path = bitsetPaths.get(bitset);
    if (path == null) {
        throw new MalformedURLException(
                "PATH not found for key string containing valies :" + requestProperties.toString());
    }
    return path;
}

From source file:com.ikanow.infinit.e.harvest.extraction.document.file.FileHarvester.java

/**
 * Same as the traverse method but returns the InfiniteFile if it finds searchFile
 * returns null otherwise/*  w  ww. ja  va  2 s  .c  om*/
 * 
 * @param f
 * @param source
 * @param depth
 * @param searchFile
 * @return
 * @throws SmbException
 */

private static InfiniteFile searchFileShare(SourcePojo source, String searchFile) throws Exception {
    // Made this synchronized to work around what looks like deadlock issue in code
    // This is undesirable and should be fixed once the underlying bug has been fixed
    // (note in practice this is only an issue for multiple threads going to the same domain)
    InfiniteFile f;
    synchronized (FileHarvester.class) {
        try {
            if (null != source.getProcessingPipeline()) { // new style...
                SourcePipelinePojo firstElement = source.getProcessingPipeline().iterator().next();
                source.setFileConfig(firstElement.file);
                source.setUrl(firstElement.file.getUrl());
            } //TESTED
            if (source.getUrl().startsWith("inf://")) { // Infinit.e share/custom object
                NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(
                        source.getCommunityIds().iterator().next().toString(), source.getOwnerId().toString(),
                        null);
                f = InfiniteFile.create(source.getUrl(), auth);

                if (f.isDirectory()) {
                    InfiniteFile subs[] = f.listFiles();
                    for (InfiniteFile sub : subs) {
                        if (sub.isDirectory()) { // (can only nest once)
                            InfiniteFile subs2[] = sub.listFiles();
                            for (InfiniteFile sub2 : subs2) {
                                if (sub2.getUrlString().equals(searchFile)) {
                                    return sub2;
                                } //TOTEST
                            }
                        } //(end loop ove sub-dirs)
                        else if (sub.getUrlString().equals(searchFile)) {
                            return sub;
                        } //TOTEST
                    } //(end loop over dirs)

                } //TOTEST

            } //TODO (INF-2122): TOTEST
            else if (source.getFileConfig() == null || source.getFileConfig().password == null
                    || source.getFileConfig().username == null) {
                f = InfiniteFile.create(searchFile);
            } else {
                if (source.getFileConfig().domain == null) {
                    source.getFileConfig().domain = "";
                }
                NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(source.getFileConfig().domain,
                        source.getFileConfig().username, source.getFileConfig().password);
                f = InfiniteFile.create(searchFile, auth);
            }
        } //TESTED
        catch (Exception e) {

            int nIndex = searchFile.lastIndexOf("/");
            searchFile = searchFile.substring(0, nIndex); // (ie not including the /)
            f = searchFileShare(source, searchFile);
            if (f.isDirectory()) {
                throw new MalformedURLException(searchFile + " is directory.");
            }
        } //TESTED         
        return f;
    }
    // (End INF-1406 sync bug, see above explanation)
}