Example usage for java.net URISyntaxException toString

List of usage examples for java.net URISyntaxException toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:se.lu.nateko.edca.svc.DescribeFeatureType.java

/**
 * Method run in a separate worker thread when GetCapabilities.execute() is called.
 * Takes the server info from the ServerConnection supplied and stores it as a URI.
 * @param srvs An array of ServerConnection objects from which to form the URI. May only contain 1.
 *///from   www.ja v  a  2 s.  co  m
@Override
protected DescribeFeatureType doInBackground(ServerConnection... srvs) {
    Log.d(TAG, "doInBackground(ServerConnection...) called.");

    /* Try to form an URI from the supplied ServerConnection info. */
    if (srvs[0] == null) // Cannot connect unless there is an active connection.
        return this;
    String uriString = srvs[0].getAddress()
            + "/wfs?service=wfs&version=1.1.0&request=DescribeFeatureType&typeName=" + mLayerName;
    try {
        mServerURI = new URI(uriString);
    } catch (URISyntaxException e) {
        Log.e(TAG, e.getMessage() + ": " + uriString);
    }

    /* If there is already a layer stored with this name; clear its data to make room for the new DescribeFeatureType result. */
    mService.getSQLhelper().getSQLiteDB().execSQL("DROP TABLE IF EXISTS " + LocalSQLDBhelper.TABLE_FIELD_PREFIX
            + Utilities.dropColons(mLayerName, Utilities.RETURN_LAST));
    mService.getSQLhelper().createFieldTable(mLayerName);
    GeoHelper.deleteGeographyLayer(mLayerName);

    try { // Get or wait for exclusive access to the HttpClient.
        mHttpClient = mService.getHttpClient();
    } catch (InterruptedException e) {
        Log.w(TAG, "Thread " + Thread.currentThread().getId() + ": " + e.toString());
    }

    mHasResponse = describeFeatureTypeRequest(); // Make the DescribeFeatureType request to the server and record the success state.
    mService.unlockHttpClient(); // Release the lock on the HttpClient, allowing new connections to be made.

    Log.v(TAG, "DescribeFeatureType request succeeded: " + String.valueOf(mHasResponse));
    if (mHasResponse) {
        /* Update the database and set a new active layer. */
        mService.setActiveLayer(mService.generateGeographyLayer(mLayerName));
        mService.deactivateLayers();
        mService.getSQLhelper().updateData(LocalSQLDBhelper.TABLE_LAYER, mLayerRowId,
                LocalSQLDBhelper.KEY_LAYER_ID, new String[] { LocalSQLDBhelper.KEY_LAYER_USEMODE },
                new String[] { String
                        .valueOf(LocalSQLDBhelper.LAYER_MODE_ACTIVE * LocalSQLDBhelper.LAYER_MODE_DISPLAY) });
    }
    return this;
}

From source file:org.protocoderrunner.apprunner.api.PNetwork.java

@ProtocoderScript
@APIMethod(description = "Connect to a websocket server", example = "")
@APIParam(params = { "uri", "function(status, data)" })
public WebSocketClient connectWebsocket(String uri, final connectWebsocketCB callbackfn) {

    Draft d = new Draft_17();

    WebSocketClient webSocketClient = null;
    try {/* ww  w.  j a  v  a  2 s .c om*/
        webSocketClient = new WebSocketClient(new URI(uri), d) {

            @Override
            public void onOpen(ServerHandshake arg0) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        callbackfn.event("onOpen", "");
                    }
                });
                //Log.d(TAG, "onOpen");
            }

            @Override
            public void onMessage(final String arg0) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        callbackfn.event("onMessage", arg0);
                    }
                });

                //Log.d(TAG, "onMessage client");

            }

            @Override
            public void onError(Exception arg0) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        callbackfn.event("onError", "");

                    }
                });

                //Log.d(TAG, "onError");

            }

            @Override
            public void onClose(int arg0, String arg1, boolean arg2) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        callbackfn.event("onClose", "");
                    }
                });

                //Log.d(TAG, "onClose");

            }
        };
        webSocketClient.connect();

    } catch (URISyntaxException e) {
        Log.d(TAG, "error");

        callbackfn.event("error ", e.toString());
        e.printStackTrace();
    }

    return webSocketClient;
}

From source file:org.apache.hadoop.metrics2.sink.RollingFileSystemSink.java

/**
 * Return the supplied file system for testing or otherwise get a new file
 * system./*from   w w  w. ja  v  a2  s .  c  o m*/
 *
 * @return the file system to use
 * @throws MetricsException thrown if the file system could not be retrieved
 */
private FileSystem getFileSystem() throws MetricsException {
    FileSystem fs = null;

    if (suppliedFilesystem != null) {
        fs = suppliedFilesystem;
    } else {
        try {
            fs = FileSystem.get(new URI(basePath.toString()), conf);
        } catch (URISyntaxException ex) {
            throw new MetricsException(
                    "The supplied filesystem base path URI" + " is not a valid URI: " + basePath.toString(),
                    ex);
        } catch (IOException ex) {
            throw new MetricsException(
                    "Error connecting to file system: " + basePath + " [" + ex.toString() + "]", ex);
        }
    }

    return fs;
}

From source file:org.eclipse.smila.connectivity.framework.crawler.web.http.HttpResponse.java

/**
 * Gets the HTTP method.//from   w w  w . j  a  v a 2 s. c o  m
 * 
 * @return the HTTP method
 * 
 * @throws IOException
 *           Signals that an I/O exception has occurred.
 * @throws URISyntaxException
 *           URISyntaxException
 */
private HttpMethodBase getHttpMethod() throws IOException, URISyntaxException {
    URI uri;
    try {
        uri = new URI(_urlString);
    } catch (URISyntaxException exception) {
        uri = new URI(URIUtil.encodePathQuery(_urlString));
    }
    final List<HtmlFormAuthentication> authentications = _http._authentication.getHtmlFormAuthentications();
    for (HtmlFormAuthentication auth : authentications) {
        if (auth.getCredentialDomain().equals(uri.toString())) {
            // get login page in order to set required cookies
            final GetMethod getMethod = new GetMethod(uri.toString());
            setHttpParameters(_http, getMethod);
            try {
                final int result = Http.getClient().executeMethod(getMethod);
                LOG.debug("Response status code from login page: " + result);
            } catch (ProtocolException exception) {
                if (LOG.isErrorEnabled()) {
                    LOG.error(exception);
                }
                throw new IOException(exception.toString());
            } finally {
                getMethod.releaseConnection();
            }
            // remove used authentication from the list
            authentications.remove(auth);
            // prepare authentication method
            return getAuthenticationMethod(auth);
        }
    }
    try {
        return new GetMethod(uri.toString());
    } catch (IllegalArgumentException exception) {
        throw new IOException("Can't get method. " + exception.getMessage());
    }
}

From source file:com.lgallardo.youtorrentcontroller.JSONParser.java

public void postCommand(String command, String hash) throws JSONParserStatusCodeException {

    String key = "hash";

    String urlContentType = "application/x-www-form-urlencoded";

    String boundary = null;//from   w w  w  .j a v a 2s  . co  m

    StringBuilder fileContent = null;

    HttpResponse httpResponse;
    DefaultHttpClient httpclient;

    String url = "";

    //        Log.d("Debug", "JSONParser - command: " + command);

    if ("start".equals(command) || "startSelected".equals(command)) {
        url = url + "gui/?action=start&hash=" + hash;
    }

    if ("pause".equals(command) || "pauseSelected".equals(command)) {
        url = url + "gui/?action=pause&hash=" + hash;
    }

    if ("stop".equals(command) || "stopSelected".equals(command)) {
        url = url + "gui/?action=stop&hash=" + hash;
        Log.d("Debug", "Stoping torrent " + hash);
    }

    if ("delete".equals(command) || "deleteSelected".equals(command)) {
        url = url + "gui/?action=remove&hash=" + hash.replace("|", "&hash=");
        key = "hashes";
    }

    if ("deleteDrive".equals(command) || "deleteDriveSelected".equals(command)) {
        url = url + "gui/?action=removedata&hash=" + hash.replace("|", "&hash=");
        key = "hashes";
    }

    if ("addTorrent".equals(command)) {

        URI hash_uri = null;

        try {
            hash_uri = new URI(hash);
            hash = hash_uri.toString();

            //                Log.d("Debug","Torrent URL: "+ hash);

        } catch (URISyntaxException e) {
            Log.e("Debug", "URISyntaxException: " + e.toString());
        }

        url = url + "gui/?action=add-url&s=" + hash;
        //            key = "urls";
    }

    if ("addTorrentFile".equals(command)) {
        url = url + "gui/?action=add-file";
        key = "urls";

        boundary = "-----------------------" + (new Date()).getTime();

        urlContentType = "multipart/form-data; boundary=" + boundary;
        //            urlContentType = "multipart/form-data";

    }

    //        if ("pauseall".equals(command)) {
    //            url = "command/pauseall";
    //        }
    //
    //        if ("pauseAll".equals(command)) {
    //            url = "command/pauseAll";
    //        }
    //
    //
    //        if ("resumeall".equals(command)) {
    //            url = "command/resumeall";
    //        }
    //
    //        if ("resumeAll".equals(command)) {
    //            url = "command/resumeAll";
    //        }

    if ("increasePrio".equals(command)) {
        url = url + "gui/?action=queueup&hash=" + hash.replace("|", "&hash=");
        key = "hashes";
    }

    if ("decreasePrio".equals(command)) {
        url = url + "gui/?action=queuedown&hash=" + hash.replace("|", "&hash=");
        key = "hashes";

    }

    if ("maxPrio".equals(command)) {
        url = url + "gui/?action=queuetop&hash=" + hash.replace("|", "&hash=");
        key = "hashes";
    }

    if ("minPrio".equals(command)) {
        url = url + "gui/?action=queuebottom&hash=" + hash.replace("|", "&hash=");
        key = "hashes";

    }

    if ("setQBittorrentPrefefrences".equals(command)) {
        url = "command/setPreferences";
        key = "json";
    }

    if ("recheckSelected".equals(command)) {
        url = url + "gui/?action=recheck&hash=" + hash.replace("|", "&hash=");
    }

    //        if ("toggleFirstLastPiecePrio".equals(command)) {
    //            url = "command/toggleFirstLastPiecePrio";
    //            key = "hashes";
    //
    //        }
    //
    //        if ("toggleSequentialDownload".equals(command)) {
    //            url = "command/toggleSequentialDownload";
    //            key = "hashes";
    //
    //        }

    // if server is publish in a subfolder, fix url
    if (subfolder != null && !subfolder.equals("")) {
        url = subfolder + "/" + url;
    }

    HttpParams httpParameters = new BasicHttpParams();

    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used.
    int timeoutConnection = connection_timeout * 1000;

    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = data_timeout * 1000;

    // Set http parameters
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    HttpProtocolParams.setUserAgent(httpParameters, "youTorrent Controller");
    HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8);

    // Making HTTP request
    HttpHost targetHost = new HttpHost(this.hostname, this.port, this.protocol);

    // httpclient = new DefaultHttpClient();
    httpclient = getNewHttpClient();

    // Set http parameters
    httpclient.setParams(httpParameters);

    try {

        AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());

        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password);

        httpclient.getCredentialsProvider().setCredentials(authScope, credentials);

        url = protocol + "://" + hostname + ":" + port + "/" + url + "&token=" + token;

        //            Log.d("Debug", "JSONParser - url: " + url);

        HttpPost httpget = new HttpPost(url);

        if ("addTorrent".equals(command)) {
            URI hash_uri = new URI(hash);
            hash = hash_uri.toString();
        }

        // In order to pass the has we must set the pair name value
        BasicNameValuePair bnvp = new BasicNameValuePair(key, hash);

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(bnvp);

        httpget.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

        // Set content type and urls
        if ("increasePrio".equals(command) || "decreasePrio".equals(command) || "maxPrio".equals(command)) {
            httpget.setHeader("Content-Type", urlContentType);

        }

        // Set cookie
        if (this.cookie != null) {
            httpget.setHeader("Cookie", this.cookie);
        }

        // Set content type and urls
        if ("addTorrentFile".equals(command)) {

            //                Log.d("Debug", "JSONParser - urlContentType: " +  urlContentType);
            //                Log.d("Debug", "JSONParser - hash: " +  Uri.decode(URLEncoder.encode(hash, "UTF-8")));
            //                Log.d("Debug", "JSONParser - hash: " +  hash);

            httpget.setHeader("Content-Type", urlContentType);

            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

            // Add boundary
            builder.setBoundary(boundary);

            // Add torrent file as binary
            File file = new File(hash);
            // FileBody fileBody = new FileBody(file);
            // builder.addPart("file", fileBody);

            builder.addBinaryBody("torrent_file", file, ContentType.DEFAULT_BINARY, null);
            //                builder.addBinaryBody("upfile", file, ContentType.create(urlContentType), hash);

            // Build entity
            HttpEntity entity = builder.build();

            // Set entity to http post
            httpget.setEntity(entity);

        }

        httpResponse = httpclient.execute(targetHost, httpget);

        StatusLine statusLine = httpResponse.getStatusLine();

        int mStatusCode = statusLine.getStatusCode();

        if (mStatusCode != 200) {
            httpclient.getConnectionManager().shutdown();
            throw new JSONParserStatusCodeException(mStatusCode);
        }

        HttpEntity httpEntity = httpResponse.getEntity();

        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {

    } catch (ClientProtocolException e) {
        Log.e("Debug", "Client: " + e.toString());
        e.printStackTrace();
    } catch (IOException e) {
        Log.e("Debug", "IO: " + e.toString());
        // e.printStackTrace();
        httpclient.getConnectionManager().shutdown();
        throw new JSONParserStatusCodeException(TIMEOUT_ERROR);
    } catch (JSONParserStatusCodeException e) {
        httpclient.getConnectionManager().shutdown();
        throw new JSONParserStatusCodeException(e.getCode());
    } catch (Exception e) {
        Log.e("Debug", "Generic: " + e.toString());
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }

}

From source file:com.cloudera.recordbreaker.analyzer.FSAnalyzer.java

public FileSystem getFS() {
    String uriStr = getConfigProperty("fsuri");
    if (uriStr == null) {
        return null;
    }//from   w w  w . j a v a 2 s. com
    try {
        URI uri = new URI(uriStr);
        FileSystem result = FileSystem.get(uri, new Configuration());
        return result;
    } catch (IOException iex) {
        LOG.error(iex.toString());
        return null;
    } catch (URISyntaxException use) {
        LOG.error(use.toString());
        return null;
    }
}

From source file:org.apache.axis2.description.WSDL20ToAxisServiceBuilder.java

private Description readInTheWSDLFile(Document document) throws WSDLException {
    WSDLReader reader = DOMWSDLFactory.newInstance().newWSDLReader();
    if (customWSDLResolver != null) {
        reader.setURIResolver(customWSDLResolver);
    }// ww  w  .java  2  s .  c o m
    // This turns on WSDL validation which is set off by default.
    reader.setFeature(WSDLReader.FEATURE_VALIDATION, true);
    WSDLSource wsdlSource = reader.createWSDLSource();
    wsdlSource.setSource(document.getDocumentElement());
    String uri = getBaseUri();
    if (uri != null && !"".equals(uri)) {
        try {
            wsdlSource.setBaseURI(new URI(uri));
        } catch (URISyntaxException e) {
            File f = new File(uri);
            if (f.exists()) {
                wsdlSource.setBaseURI(f.toURI());
            } else {
                log.error(e.toString(), e);
            }
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Reading 2.0 WSDL with wsdl uri = " + wsdlURI);
        log.trace("  the stack at this point is: " + stackToString());
    }
    return reader.readWSDL(wsdlSource);
}

From source file:org.apache.cloudstack.secondarystorage.SecondaryStorageManagerImpl.java

@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
    if (s_logger.isInfoEnabled()) {
        s_logger.info("Start configuring secondary storage vm manager : " + name);
    }//  w  w  w  .  j a v a2 s  .  co m

    Map<String, String> configs = _configDao.getConfiguration("management-server", params);

    _secStorageVmMtuSize = NumbersUtil.parseInt(configs.get("secstorage.vm.mtu.size"), DEFAULT_SS_VM_MTUSIZE);
    String useServiceVM = _configDao.getValue("secondary.storage.vm");
    boolean _useServiceVM = false;
    if ("true".equalsIgnoreCase(useServiceVM)) {
        _useServiceVM = true;
    }

    String sslcopy = _configDao.getValue("secstorage.encrypt.copy");
    if ("true".equalsIgnoreCase(sslcopy)) {
        _useSSlCopy = true;
    }

    //default to HTTP in case of missing domain
    String ssvmUrlDomain = _configDao.getValue("secstorage.ssl.cert.domain");
    if (_useSSlCopy && (ssvmUrlDomain == null || ssvmUrlDomain.isEmpty())) {
        s_logger.warn("Empty secondary storage url domain, explicitly disabling SSL");
        _useSSlCopy = false;
    }

    _allowedInternalSites = _configDao.getValue("secstorage.allowed.internal.sites");

    String value = configs.get("secstorage.capacityscan.interval");
    _capacityScanInterval = NumbersUtil.parseLong(value, DEFAULT_CAPACITY_SCAN_INTERVAL);

    _instance = configs.get("instance.name");
    if (_instance == null) {
        _instance = "DEFAULT";
    }

    Map<String, String> agentMgrConfigs = _configDao.getConfiguration("AgentManager", params);

    value = agentMgrConfigs.get("port");
    _mgmtPort = NumbersUtil.parseInt(value, 8250);

    _listener = new SecondaryStorageListener(this);
    _agentMgr.registerForHostEvents(_listener, true, false, true);

    _itMgr.registerGuru(VirtualMachine.Type.SecondaryStorageVm, this);

    //check if there is a default service offering configured
    String ssvmSrvcOffIdStr = configs.get(Config.SecondaryStorageServiceOffering.key());
    if (ssvmSrvcOffIdStr != null) {
        _serviceOffering = _offeringDao.findByUuid(ssvmSrvcOffIdStr);
        if (_serviceOffering == null) {
            try {
                _serviceOffering = _offeringDao.findById(Long.parseLong(ssvmSrvcOffIdStr));
            } catch (NumberFormatException ex) {
                s_logger.debug("The system service offering specified by global config is not id, but uuid="
                        + ssvmSrvcOffIdStr + " for secondary storage vm");
            }
        }
        if (_serviceOffering == null) {
            s_logger.warn("Can't find system service offering specified by global config, uuid="
                    + ssvmSrvcOffIdStr + " for secondary storage vm");
        }
    }

    if (_serviceOffering == null || !_serviceOffering.getSystemUse()) {
        int ramSize = NumbersUtil.parseInt(_configDao.getValue("ssvm.ram.size"), DEFAULT_SS_VM_RAMSIZE);
        int cpuFreq = NumbersUtil.parseInt(_configDao.getValue("ssvm.cpu.mhz"), DEFAULT_SS_VM_CPUMHZ);
        List<ServiceOfferingVO> offerings = _offeringDao.createSystemServiceOfferings(
                "System Offering For Secondary Storage VM", ServiceOffering.ssvmDefaultOffUniqueName, 1,
                ramSize, cpuFreq, null, null, false, null, Storage.ProvisioningType.THIN, true, null, true,
                VirtualMachine.Type.SecondaryStorageVm, true);
        // this can sometimes happen, if DB is manually or programmatically manipulated
        if (offerings == null || offerings.size() < 2) {
            String msg = "Data integrity problem : System Offering For Secondary Storage VM has been removed?";
            s_logger.error(msg);
            throw new ConfigurationException(msg);
        }
    }

    if (_useServiceVM) {
        _loadScanner = new SystemVmLoadScanner<Long>(this);
        _loadScanner.initScan(STARTUP_DELAY, _capacityScanInterval);
    }

    _httpProxy = configs.get(Config.SecStorageProxy.key());
    if (_httpProxy != null) {
        boolean valid = true;
        String errMsg = null;
        try {
            URI uri = new URI(_httpProxy);
            if (!"http".equalsIgnoreCase(uri.getScheme())) {
                errMsg = "Only support http proxy";
                valid = false;
            } else if (uri.getHost() == null) {
                errMsg = "host can not be null";
                valid = false;
            } else if (uri.getPort() == -1) {
                _httpProxy = _httpProxy + ":3128";
            }
        } catch (URISyntaxException e) {
            errMsg = e.toString();
        } finally {
            if (!valid) {
                s_logger.debug("ssvm http proxy " + _httpProxy + " is invalid: " + errMsg);
                throw new ConfigurationException("ssvm http proxy " + _httpProxy + "is invalid: " + errMsg);
            }
        }
    }
    if (s_logger.isInfoEnabled()) {
        s_logger.info("Secondary storage vm Manager is configured.");
    }
    _resourceMgr.registerResourceStateAdapter(this.getClass().getSimpleName(), this);
    return true;
}

From source file:org.mumod.util.HttpManager.java

public InputStream requestData(String url, String httpMethod, ArrayList<NameValuePair> params, int loop)
        throws IOException, MustardException, AuthException {

    URI uri;//from  w  ww  . j ava  2  s.  co  m

    try {
        uri = new URI(url);
    } catch (URISyntaxException e) {
        throw new IOException("Invalid URL.");
    }
    if (MustardApplication.DEBUG)
        Log.d("HTTPManager", "Requesting " + uri);
    HttpUriRequest method;

    if (POST.equals(httpMethod)) {
        HttpPost post = new HttpPost(uri);
        if (params != null)
            post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
        method = post;
    } else if (DELETE.equals(httpMethod)) {
        method = new HttpDelete(uri);
    } else {
        method = new HttpGet(uri);
    }

    if (mHeaders != null) {
        Iterator<String> headKeys = mHeaders.keySet().iterator();
        while (headKeys.hasNext()) {
            String key = headKeys.next();
            method.setHeader(key, mHeaders.get(key));
        }
    }
    if (consumer != null) {
        try {
            consumer.sign(method);
        } catch (OAuthMessageSignerException e) {

        } catch (OAuthExpectationFailedException e) {

        } catch (OAuthCommunicationException e) {

        }
    }

    HttpResponse response;
    try {
        response = mClient.execute(method);
    } catch (ClientProtocolException e) {
        throw new IOException("HTTP protocol error.");
    }

    int statusCode = response.getStatusLine().getStatusCode();
    //      Log.d("HttpManager", url + " >> " + statusCode);
    if (statusCode == 401) {
        throw new AuthException(401, "Unauthorized");
    } else if (statusCode == 400 || statusCode == 403 || statusCode == 406) {
        try {
            JSONObject json = null;
            try {
                json = new JSONObject(StreamUtil.toString(response.getEntity().getContent()));
            } catch (JSONException e) {
                throw new MustardException(998, "Non json response: " + e.toString());
            }
            throw new MustardException(statusCode, json.getString("error"));
        } catch (IllegalStateException e) {
            throw new IOException("Could not parse error response.");
        } catch (JSONException e) {
            throw new IOException("Could not parse error response.");
        }
    } else if (statusCode == 404) {
        // User/Group or page not found
        throw new MustardException(404, "Not found: " + url);
    } else if ((statusCode == 301 || statusCode == 302 || statusCode == 303) && GET.equals(httpMethod)
            && loop < 3) {
        //         Log.v("HttpManager", "Got : " + statusCode);
        Header hLocation = response.getLastHeader("Location");
        if (hLocation != null) {
            Log.v("HttpManager", "Got : " + hLocation.getValue());
            return requestData(hLocation.getValue(), httpMethod, params, loop + 1);
        } else
            throw new MustardException(statusCode, "Too many redirect: " + url);
    } else if (statusCode != 200) {
        throw new MustardException(999, "Unmanaged response code: " + statusCode);
    }

    return response.getEntity().getContent();
}

From source file:org.mustard.util.HttpManager.java

public InputStream requestData(String url, String httpMethod, ArrayList<NameValuePair> params, int loop)
        throws IOException, MustardException, AuthException {

    URI uri;//  w w w . j  a  v a 2s .c o  m

    try {
        uri = new URI(url);
    } catch (URISyntaxException e) {
        throw new IOException("Invalid URL.");
    }
    if (MustardApplication.DEBUG)
        Log.d("HTTPManager", "Requesting " + uri);
    HttpUriRequest method;

    if (POST.equals(httpMethod)) {
        HttpPost post = new HttpPost(uri);
        if (params != null)
            post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
        method = post;
    } else if (DELETE.equals(httpMethod)) {
        method = new HttpDelete(uri);
    } else {
        method = new HttpGet(uri);
    }

    if (mHeaders != null) {
        Iterator<String> headKeys = mHeaders.keySet().iterator();
        while (headKeys.hasNext()) {
            String key = headKeys.next();
            method.setHeader(key, mHeaders.get(key));
        }
    }
    if (consumer != null) {
        try {
            consumer.sign(method);
        } catch (OAuthMessageSignerException e) {

        } catch (OAuthExpectationFailedException e) {

        } catch (OAuthCommunicationException e) {

        }
    }

    HttpResponse response;
    try {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mContext);
        String accessToken = preferences.getString("oauth2_access_token", "no token specified");
        method.setHeader("Authorization", "Bearer " + accessToken);
        response = mClient.execute(method);
    } catch (ClientProtocolException e) {
        throw new IOException("HTTP protocol error.");
    }

    int statusCode = response.getStatusLine().getStatusCode();
    //      Log.d("HttpManager", url + " >> " + statusCode);
    if (statusCode == 401) {
        throw new AuthException(401, "Unauthorized");
    } else if (statusCode == 403 || statusCode == 406) {
        try {
            JSONObject json = null;
            try {
                json = new JSONObject(StreamUtil.toString(response.getEntity().getContent()));
            } catch (JSONException e) {
                throw new MustardException(998, "Non json response: " + e.toString());
            }
            throw new MustardException(statusCode, json.getString("error"));
        } catch (IllegalStateException e) {
            throw new IOException("Could not parse error response.");
        } catch (JSONException e) {
            throw new IOException("Could not parse error response.");
        }
    } else if (statusCode == 404) {
        // User/Group or page not found
        throw new MustardException(404, "Not found: " + url);
    } else if ((statusCode == 301 || statusCode == 302 || statusCode == 303) && GET.equals(httpMethod)
            && loop < 3) {
        //         Log.v("HttpManager", "Got : " + statusCode);
        Header hLocation = response.getLastHeader("Location");
        if (hLocation != null) {
            Log.v("HttpManager", "Got : " + hLocation.getValue());
            return requestData(hLocation.getValue(), httpMethod, params, loop + 1);
        } else
            throw new MustardException(statusCode, "Too many redirect: " + url);
    } else if (statusCode != 200) {
        throw new MustardException(999, "Unmanaged response code: " + statusCode);
    }

    return response.getEntity().getContent();
}