Example usage for org.apache.commons.httpclient HttpException getMessage

List of usage examples for org.apache.commons.httpclient HttpException getMessage

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.apache.ambari.view.slider.rest.client.AmbariHttpClient.java

public Map<String, String> getConfiguration(AmbariClusterInfo cluster, String configType, String configTag) {
    if (cluster != null && configType != null && configTag != null) {
        try {/*  ww w  .  j ava  2  s. c o m*/
            JsonElement jsonElement = doGetJson("/api/v1/clusters/" + cluster.getName()
                    + "/configurations?type=" + configType + "&tag=" + configTag);
            if (jsonElement != null) {
                JsonObject jsonObject = jsonElement.getAsJsonObject();
                JsonArray configsArray = jsonObject.get("items").getAsJsonArray();
                if (configsArray.size() > 0) {
                    JsonObject propertiesObj = configsArray.get(0).getAsJsonObject().get("properties")
                            .getAsJsonObject();
                    Map<String, String> properties = new HashMap<String, String>();
                    for (Map.Entry<String, JsonElement> entry : propertiesObj.entrySet()) {
                        if (entry.getValue().isJsonPrimitive()) {
                            properties.put(entry.getKey(), entry.getValue().getAsString());
                        }
                    }
                    return properties;
                }
            }
        } catch (HttpException e) {
            logger.warn("Unable to determine Ambari clusters", e);
            throw createRuntimeException(e);
        } catch (IOException e) {
            logger.warn("Unable to determine Ambari clusters", e);
            throw new RuntimeException(e.getMessage(), e);
        }
    }
    return null;
}

From source file:org.apache.ambari.view.slider.rest.client.AmbariHttpClient.java

@Override
public AmbariService getService(AmbariClusterInfo cluster, String serviceId) {
    if (cluster != null && serviceId != null) {
        try {/*ww w  .j  a  v  a 2  s  .  co m*/
            JsonElement jsonElement = doGetJson("/api/v1/clusters/" + cluster.getName() + "/services/"
                    + serviceId + "?fields=ServiceInfo,components/host_components/HostRoles");
            if (jsonElement == null) {
                return null;
            }
            JsonObject jsonObject = jsonElement.getAsJsonObject();
            AmbariService svc = new AmbariService();
            JsonObject serviceInfoJsonObject = jsonObject.get("ServiceInfo").getAsJsonObject();
            svc.setId(serviceInfoJsonObject.get("service_name").getAsString());
            svc.setStarted("STARTED".equals(serviceInfoJsonObject.get("state").getAsString()));
            svc.setMaintenanceMode(!"OFF".equals(serviceInfoJsonObject.get("maintenance_state").getAsString()));
            Map<String, List<AmbariHostComponent>> componentsToHostComponentsMap = new HashMap<String, List<AmbariHostComponent>>();
            for (JsonElement ce : jsonObject.get("components").getAsJsonArray()) {
                String componentName = ce.getAsJsonObject().get("ServiceComponentInfo").getAsJsonObject()
                        .get("component_name").getAsString();
                List<AmbariHostComponent> hcList = new ArrayList<AmbariHostComponent>();
                componentsToHostComponentsMap.put(componentName, hcList);
                JsonArray hcJsonArray = ce.getAsJsonObject().get("host_components").getAsJsonArray();
                for (JsonElement hce : hcJsonArray) {
                    AmbariHostComponent hc = new AmbariHostComponent();
                    JsonObject hcJsonObject = hce.getAsJsonObject().get("HostRoles").getAsJsonObject();
                    hc.setHostName(hcJsonObject.get("host_name").getAsString());
                    hc.setStarted("STARTED".equals(hcJsonObject.get("state").getAsString()));
                    hc.setName(hcJsonObject.get("component_name").getAsString());
                    hcList.add(hc);
                }
            }
            svc.setComponentsToHostComponentsMap(componentsToHostComponentsMap);
            return svc;
        } catch (HttpException e) {
            logger.warn("Unable to determine Ambari clusters", e);
            throw createRuntimeException(e);
        } catch (IOException e) {
            logger.warn("Unable to determine Ambari clusters", e);
            throw new RuntimeException(e.getMessage(), e);
        }
    }
    return null;
}

From source file:org.apache.ambari.view.slider.rest.client.SliderAppMasterClient.java

public SliderAppMasterData getAppMasterData() {
    try {/*from ww w . j a v a2  s.c  o  m*/
        String html = doGet("");
        if (html != null) {
            int from = html.lastIndexOf("<ul>");
            int to = html.lastIndexOf("</ul>");
            if (from < to && from > -1) {
                SliderAppMasterData data = new SliderAppMasterData();
                String content = html.substring(from, to);
                content = content.replaceAll("<[^>]*>", "\r\n");
                String[] splits = content.split("\r\n");
                for (int i = 0; i < splits.length; i++) {
                    String split = splits[i].trim();
                    if ("classpath:org.apache.slider.registry".equals(split)) {
                        data.registryUrl = splits[i + 1].trim();
                    } else if ("classpath:org.apache.http.UI".equals(split)) {
                        data.uiUrl = splits[i + 1].trim();
                    } else if ("classpath:org.apache.slider.management".equals(split)) {
                        data.managementUrl = splits[i + 1].trim();
                    } else if ("classpath:org.apache.slider.publisher".equals(split)) {
                        data.publisherUrl = splits[i + 1].trim();
                    }
                }
                return data;
            }
        }
    } catch (HttpException e) {
        logger.warn("Unable to determine Ambari clusters", e);
        throw new RuntimeException(e.getMessage(), e);
    } catch (IOException e) {
        logger.warn("Unable to determine Ambari clusters", e);
        throw new RuntimeException(e.getMessage(), e);
    }
    return null;
}

From source file:org.apache.cloudstack.region.RegionsApiUtil.java

/**
 * Makes an api call using region service end_point, api command and params
 * @param region/* w ww.j av a2 s.c  om*/
 * @param command
 * @param params
 * @return True, if api is successful
 */
protected static boolean makeAPICall(Region region, String command, List<NameValuePair> params) {
    try {
        String apiParams = buildParams(command, params);
        String url = buildUrl(apiParams, region);
        HttpClient client = new HttpClient();
        HttpMethod method = new GetMethod(url);
        if (client.executeMethod(method) == 200) {
            return true;
        } else {
            return false;
        }
    } catch (HttpException e) {
        s_logger.error(e.getMessage());
        return false;
    } catch (IOException e) {
        s_logger.error(e.getMessage());
        return false;
    }
}

From source file:org.apache.cocoon.components.source.impl.WebDAVSource.java

/**
 * Initialize the SWCL WebdavResource.// ww  w  . j  a  va 2 s .c o m
 * <p>
 * The action argument specifies a set of properties to load during initialization.
 * Its value is one of WebdavResource.NOACTION, WebdavResource.NAME,
 * WebdavResource.BASIC, WebdavResource.DEFAULT, WebdavResource.ALL.
 * Similarly the depth argument specifies the depth header of the PROPFIND
 * method that is executed upon initialization.
 * </p>
 * <p>
 * The different methods of this Source implementation call this method to
 * initialize the resource using their minimal action and depth requirements.
 * For instance the WebDAVSource.getMimeType() method requires WebdavResource.BASIC
 * properties and a search depth of 0 is sufficient.
 * </p>
 * <p>
 * However it may be that a later call (eg. WebDAVSource.getChildren()) requires more
 * information. In that case the WebdavResource would have to make another call to the Server.
 * It would be more efficient if previous initialization had been done using depth 1 instead.
 * In order give the user more control over this the WebDAVSource can be passed a minimal
 * action and depth using cocoon:webdav-depth and cocoon:webdav-action query string parameters.
 * By default the mimimum action is WebdavResource.BASIC (which loads all the following basic
 * webdav properties: DAV:displayname, DAV:getcontentlength, DAV:getcontenttype DAV:resourcetype,
 * DAV:getlastmodified and DAV:lockdiscovery). The default minimum depth is 1.
 * </p>
 *
 * @param action  the set of propterties the WebdavResource should load.
 * @param depth  the webdav depth.
 * @throws SourceException
 * @throws SourceNotFoundException
 */
private void initResource(int action, int depth) throws SourceException, SourceNotFoundException {
    try {
        boolean update = false;
        if (action != WebdavResource.NOACTION) {
            if (action > this.action) {
                this.action = action;
                update = true;
            } else {
                action = this.action;
            }
        }
        if (depth > this.depth) {
            this.depth = depth;
            update = true;
        } else {
            depth = this.depth;
        }
        if (this.resource == null) {
            this.resource = new WebdavResource(this.url, action, depth);
        } else if (update) {
            this.resource.setProperties(action, depth);
        }
        if (this.action > WebdavResource.NOACTION) {
            if (this.resource.isCollection()) {
                String path = this.url.getPath();
                if (path.charAt(path.length() - 1) != '/') {
                    this.url.setPath(path + "/");
                }
            }
        }
    } catch (HttpException e) {
        if (e.getReasonCode() == HttpStatus.SC_NOT_FOUND) {
            throw new SourceNotFoundException("Not found: " + getSecureURI(), e);
        }
        if (e.getReasonCode() == HttpStatus.SC_BAD_REQUEST) {
            throw new SourceException("Server doesn't appear to understand WebDAV: " + getSecureURI(), e);
        }
        final String msg = "Could not initialize webdav resource at " + getSecureURI() + ". Server responded "
                + e.getReasonCode() + " (" + e.getReason() + ") - " + e.getMessage();
        throw new SourceException(msg, e);
    } catch (IOException e) {
        throw new SourceException("Could not initialize webdav resource", e);
    }
}

From source file:org.apache.cocoon.components.source.impl.WebDAVSource.java

private void resourcesToSax(WebdavResource[] resources, ContentHandler handler) throws SAXException {
    for (int i = 0; i < resources.length; i++) {
        if (getLogger().isDebugEnabled()) {
            final String message = "RESOURCE: " + resources[i].getDisplayName();
            getLogger().debug(message);//from   ww w  .j a va 2 s  . c o m
        }
        if (resources[i].isCollection()) {
            try {
                WebdavResource[] childs = resources[i].listWebdavResources();
                AttributesImpl attrs = new AttributesImpl();
                attrs.addAttribute(NAMESPACE, COLLECTION_NAME, PREFIX + ":name", "CDATA",
                        resources[i].getDisplayName());
                handler.startElement(NAMESPACE, COLLECTION_NAME, PREFIX + ":" + COLLECTION_NAME, attrs);
                this.resourcesToSax(childs, handler);
                handler.endElement(NAMESPACE, COLLECTION_NAME, PREFIX + ":" + COLLECTION_NAME);
            } catch (HttpException e) {
                if (getLogger().isDebugEnabled()) {
                    final String message = "Unable to get WebDAV children. Server responded "
                            + e.getReasonCode() + " (" + e.getReason() + ") - " + e.getMessage();
                    getLogger().debug(message);
                }
            } catch (SAXException e) {
                if (getLogger().isDebugEnabled()) {
                    final String message = "Unable to get WebDAV children: " + e.getMessage();
                    getLogger().debug(message, e);
                }
            } catch (IOException e) {
                if (getLogger().isDebugEnabled()) {
                    final String message = "Unable to get WebDAV children: " + e.getMessage();
                    getLogger().debug(message, e);
                }
            } catch (Exception e) {
                if (getLogger().isDebugEnabled()) {
                    final String message = "Unable to get WebDAV children: " + e.getMessage();
                    getLogger().debug(message, e);
                }
            }
        } else {
            AttributesImpl attrs = new AttributesImpl();
            attrs.addAttribute(NAMESPACE, "name", PREFIX + ":name", "CDATA", resources[i].getDisplayName());
            handler.startElement(NAMESPACE, RESOURCE_NAME, PREFIX + ":" + RESOURCE_NAME, attrs);
            handler.endElement(NAMESPACE, RESOURCE_NAME, PREFIX + ":" + RESOURCE_NAME);
        }
    }
}

From source file:org.apache.cocoon.components.source.impl.WebDAVSource.java

/**
 * Get the collection children.//from   w ww . j  a va2  s .c  o m
 *
 * @see org.apache.excalibur.source.TraversableSource#getChildren()
 */
public Collection getChildren() throws SourceException {
    initResource(WebdavResource.BASIC, DepthSupport.DEPTH_1);
    ArrayList children = new ArrayList();
    try {
        WebdavResource[] resources = this.resource.listWebdavResources();
        for (int i = 0; i < resources.length; i++) {
            HttpURL childURL;
            if (this.url instanceof HttpsURL) {
                childURL = new HttpsURL((HttpsURL) this.url, resources[i].getName());
            } else {
                childURL = new HttpURL(this.url, resources[i].getName());
            }
            WebDAVSource src = WebDAVSource.newWebDAVSource(resources[i], childURL, this.protocol, getLogger(),
                    this.eventfactory);
            src.enableLogging(getLogger());
            children.add(src);
        }
    } catch (HttpException e) {
        if (getLogger().isDebugEnabled()) {
            final String message = "Unable to get WebDAV children. Server responded " + e.getReasonCode() + " ("
                    + e.getReason() + ") - " + e.getMessage();
            getLogger().debug(message);
        }
        throw new SourceException("Failed to get WebDAV collection children.", e);
    } catch (SourceException e) {
        throw e;
    } catch (IOException e) {
        throw new SourceException("Failed to get WebDAV collection children.", e);
    }
    return children;
}

From source file:org.apache.cocoon.components.source.impl.WebDAVSource.java

/**
 * Sets a property for a source./*ww  w  .j a v  a 2s  . c o  m*/
 *
 * @param sourceproperty Property of the source
 *
 * @throws SourceException If an exception occurs during this operation
 */
public void setSourceProperty(SourceProperty sourceproperty) throws SourceException {

    initResource(WebdavResource.NOACTION, DepthSupport.DEPTH_0);

    try {
        Node node = null;
        NodeList list = sourceproperty.getValue().getChildNodes();
        for (int i = 0; i < list.getLength(); i++) {
            if ((list.item(i) instanceof Text && !"".equals(list.item(i).getNodeValue()))
                    || list.item(i) instanceof Element) {

                node = list.item(i);
                break;
            }
        }

        Properties format = new Properties();
        format.put(OutputKeys.METHOD, "xml");
        format.put(OutputKeys.OMIT_XML_DECLARATION, "yes");
        String prop = XMLUtils.serializeNode(node, format);

        this.resource.proppatchMethod(new PropertyName(sourceproperty.getNamespace(), sourceproperty.getName()),
                prop, true);

    } catch (HttpException e) {
        final String message = "Unable to set property. Server responded " + e.getReasonCode() + " ("
                + e.getReason() + ") - " + e.getMessage();
        getLogger().debug(message);
        throw new SourceException("Could not set property ", e);
    } catch (Exception e) {
        throw new SourceException("Could not set property ", e);
    }
}

From source file:org.apache.cocoon.transformation.WebDAVTransformer.java

private void executeRequest(WebDAVRequestMethod method) throws SAXException {
    try {//from  ww  w  . j  a v  a 2s .  co m
        client.executeMethod(method.getHostConfiguration(), method, m_state);

        super.contentHandler.startPrefixMapping("webdav", NS_URI);

        // start <response>
        AttributesImpl atts = new AttributesImpl();
        atts.addCDATAAttribute(TARGET_ATTR, m_target);
        atts.addCDATAAttribute(METHOD_ATTR, m_method);
        super.contentHandler.startElement(NS_URI, RESPONSE_TAG, NS_PREFIX + RESPONSE_TAG, atts);
        atts.clear();

        // <status>
        atts.addCDATAAttribute(CODE_ATTR, String.valueOf(method.getStatusCode()));
        atts.addCDATAAttribute(MSG_ATTR, method.getStatusText());
        super.contentHandler.startElement(NS_URI, STATUS_TAG, NS_PREFIX + STATUS_TAG, atts);
        atts.clear();
        super.contentHandler.endElement(NS_URI, STATUS_TAG, NS_PREFIX + STATUS_TAG);

        // <header>s
        Header[] headers = method.getResponseHeaders();
        for (int i = 0; i < headers.length; i++) {
            atts.addCDATAAttribute(NAME_ATTR, headers[i].getName());
            atts.addCDATAAttribute(VALUE_ATTR, headers[i].getValue());
            super.contentHandler.startElement(NS_URI, HEADER_TAG, NS_PREFIX + HEADER_TAG, atts);
            atts.clear();
            super.contentHandler.endElement(NS_URI, HEADER_TAG, NS_PREFIX + HEADER_TAG);
        }

        // response <body>
        final InputStream in = method.getResponseBodyAsStream();
        if (in != null) {
            String mimeType = null;
            Header header = method.getResponseHeader("Content-Type");
            if (header != null) {
                mimeType = header.getValue();
                int pos = mimeType.indexOf(';');
                if (pos != -1) {
                    mimeType = mimeType.substring(0, pos);
                }
            }
            if (mimeType != null && mimeType.equals("text/xml")) {
                super.contentHandler.startElement(NS_URI, BODY_TAG, NS_PREFIX + BODY_TAG, atts);
                IncludeXMLConsumer consumer = new IncludeXMLConsumer(super.contentHandler);
                XMLizer xmlizer = null;
                try {
                    xmlizer = (XMLizer) manager.lookup(XMLizer.ROLE);
                    xmlizer.toSAX(in, mimeType, m_target, consumer);
                } catch (ServiceException ce) {
                    throw new SAXException("Missing service dependency: " + XMLizer.ROLE, ce);
                } finally {
                    manager.release(xmlizer);
                }
                super.contentHandler.endElement(NS_URI, BODY_TAG, NS_PREFIX + BODY_TAG);
            }
        }

        // end <response>
        super.contentHandler.endElement(NS_URI, RESPONSE_TAG, NS_PREFIX + RESPONSE_TAG);

        super.contentHandler.endPrefixMapping(NS_URI);
    } catch (HttpException e) {
        throw new SAXException("Error executing WebDAV request." + " Server responded " + e.getReasonCode()
                + " (" + e.getReason() + ") - " + e.getMessage(), e);
    } catch (IOException e) {
        throw new SAXException("Error executing WebDAV request", e);
    }
}

From source file:org.apache.ivy.util.url.HttpClientHandler.java

public URLInfo getURLInfo(URL url, int timeout) {
    HttpMethodBase method = null;// ww w  . ja  va  2s. com
    try {
        if (getRequestMethod() == URLHandler.REQUEST_METHOD_HEAD) {
            method = doHead(url, timeout);
        } else {
            method = doGet(url, timeout);
        }
        if (checkStatusCode(url, method)) {
            return new URLInfo(true, getResponseContentLength(method), getLastModified(method),
                    method.getRequestCharSet());
        }
    } catch (HttpException e) {
        Message.error("HttpClientHandler: " + e.getMessage() + ":" + e.getReasonCode() + "=" + e.getReason()
                + " url=" + url);
    } catch (UnknownHostException e) {
        Message.warn("Host " + e.getMessage() + " not found. url=" + url);
        Message.info("You probably access the destination server through "
                + "a proxy server that is not well configured.");
    } catch (IOException e) {
        Message.error("HttpClientHandler: " + e.getMessage() + " url=" + url);
    } catch (IllegalArgumentException e) {
        // thrown by HttpClient to indicate the URL is not valid, this happens for instance
        // when trying to download a dynamic version (cfr IVY-390)
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
    return UNAVAILABLE;
}