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:net.neurowork.cenatic.centraldir.workers.XMLRestWorker.java

private void buscarOrganizacion(String token) {
    Organizacion organizacion = null;/* www.ja  v  a  2 s.com*/
    if (logger.isDebugEnabled())
        logger.debug("Buscando Organizaciones para Satelite: " + satelite);

    HttpClient httpclient = getHttpClient();

    GetMethod get = new GetMethod(restUrl.getOrganizacionUrl());
    get.addRequestHeader("Accept", "application/xml");
    NameValuePair tokenParam = new NameValuePair("token", token);
    int id = 0;
    //      if(satelite.getLastOrgId() != null) 
    //         id = satelite.getLastOrgId();

    int leap = idLeap;

    while (true) {
        id = id + 1;

        if (logger.isTraceEnabled()) {
            logger.trace("Buscando Organizacion con id: " + id + " en el Satelite: " + satelite);
        }

        NameValuePair passwordParam = new NameValuePair("id", String.valueOf(id));
        NameValuePair[] params = new NameValuePair[] { tokenParam, passwordParam };

        get.setQueryString(params);
        String queryString = get.getQueryString();

        int statusCode;
        try {
            if (logger.isTraceEnabled()) {
                logger.trace("Query String: " + queryString);
            }

            statusCode = httpclient.executeMethod(get);
            if (statusCode != HttpStatus.SC_OK) {
                logger.error("Method failed: " + get.getStatusLine());
            } else {
                String xmlString = get.getResponseBodyAsString();
                if (logger.isInfoEnabled()) {
                    logger.info("Xml Received.");
                }

                String xmlHash = constructXmlHash(xmlString);

                organizacion = organizacionService.findByHash(xmlHash);
                if (organizacion == null) {
                    organizacion = parseOrganizacion(xmlString);
                    if (organizacion == null) {
                        leap--;
                        if (leap <= 0) {
                            logger.info("Se lleg al fin de las Organizaciones. Saliendo del Satelite: "
                                    + satelite);
                            break;
                        } else {
                            logger.info("Leap: " + leap);
                        }
                    } else {
                        if (organizacion.getSatelites() == null) {
                            organizacion.setSatelites(new HashSet<OrganizacionSatelite>());
                        }
                        boolean sateliteFound = false;
                        for (OrganizacionSatelite sat : organizacion.getSatelites()) {
                            if (sat.getSatelite().getName().equals(satelite.getName())) {
                                sateliteFound = true;
                                break;
                            }
                        }
                        if (!sateliteFound) {
                            OrganizacionSatelite newSat = new OrganizacionSatelite();
                            newSat.setSatelite(satelite);
                            newSat.setOrganizacion(organizacion);
                            organizacion.getSatelites().add(newSat);
                        }

                        organizacion.setXmlHash(xmlHash);
                        organizacionService.saveOrganization(organizacion);

                        int numEmpresas = 0;
                        if (satelite.getNumEmpresas() != null) {
                            numEmpresas = satelite.getNumEmpresas();
                        }
                        numEmpresas++;

                        Date now = new Date();
                        satelite.setNumEmpresas(numEmpresas);
                        satelite.setLastRetrieval(new Timestamp(now.getTime()));
                        satelite.setLastOrgId(id);
                        sateliteService.saveSatelite(satelite);
                    }
                } else {
                    if (logger.isInfoEnabled()) {
                        logger.info("Organizacion with id: " + id + " already in centraldir");
                    }
                }
            }
        } catch (HttpException e) {
            logger.error(e.getMessage());
        } catch (IOException e) {
            logger.error(e.getMessage());
        } catch (ParserConfigurationException e) {
            logger.error(e.getMessage());
        } catch (SAXException e) {
            logger.error(e.getMessage());
        } catch (ServiceException e) {
            logger.error(e.getMessage());
        } catch (NoSuchAlgorithmException e) {
            logger.error(e.getMessage());
        } finally {
            get.releaseConnection();
        }
    }

}

From source file:fr.cls.atoll.motu.processor.wps.StringList.java

public static ProcessDescriptions getDescribeProcess() {

    UserBase user = new UserBase();

    user.setLogin("xxx");
    user.setPwd("xxx");
    user.setAuthenticationMode(AuthenticationMode.CAS);

    AuthenticationHolder.setUser(user);/*from   w  w w . j av a 2s .c  o m*/

    //String href = "http://localhost:8080/atoll-motuservlet/services";
    String href = "http://atoll-dev.cls.fr:30080/mis-gateway-servlet/ogc";
    InputStream in = null;
    Map<String, String> headers = new HashMap<String, String>();
    try {
        in = Organizer.getUriAsInputStream("DescribeAll.xml");
        in = WPSUtils.post(HttpUtils.STREAM, href, in, headers);
        // byte b[] = new byte[1024];
        //
        // int bytesRead = 0;
        // if (in.markSupported()) {
        // in.mark(bytesRead);
        // }
        //
        // while ((bytesRead = in.read(b)) != -1) {
        // String nextLine = new String(b, 0, bytesRead);
        // System.out.println(nextLine);
        // }
        //            
        // if (in.markSupported()) {
        // in.reset();
        // }

    } catch (HttpException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MotuException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    ProcessDescriptions processDescriptions = null;

    if (in == null) {
        return processDescriptions;
    }

    try {
        JAXBContext jc = JAXBContext.newInstance(MotuWPSProcess.WPS100_SHEMA_PACK_NAME);
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        processDescriptions = (ProcessDescriptions) unmarshaller.unmarshal(in);
    } catch (Exception e) {
        // throw new MotuException("Error in GetDescribeProcess", e);
        System.out.println(e.getMessage());
    }

    if (processDescriptions == null) {
        // throw new
        // MotuException("Unable to load WPS Process Descriptions (processDescriptions is null)");
        System.out.println("Unable to load WPS Process Descriptions (processDescriptions is null)");
        return processDescriptions;
    }

    List<ProcessDescriptionType> processDescriptionList = processDescriptions.getProcessDescription();

    for (ProcessDescriptionType processDescriptionType : processDescriptionList) {
        // JAXBElement<String> element = new JAXBElement<String>(new QName("Test"), String.class, "tre");
        System.out.println("===================");
        System.out.println(processDescriptionType.getIdentifier().getValue());
        System.out.println("===================");
        List<InputDescriptionType> inputDescriptionTypeList = processDescriptionType.getDataInputs().getInput();
        for (InputDescriptionType inputDescriptionType : inputDescriptionTypeList) {
            Object inputData = null;
            String fieldName = "";
            if (inputDescriptionType.getLiteralData() != null) {
                inputData = inputDescriptionType.getLiteralData();
                // JAXBElement<InputDescriptionType> element = inputDescriptionType;
            }
            if (inputDescriptionType.getComplexData() != null) {
                inputData = inputDescriptionType.getComplexData();
            }
            if (inputDescriptionType.getBoundingBoxData() != null) {
                inputData = inputDescriptionType.getBoundingBoxData();
            }
            try {
                Field[] fields = DescriptionType.class.getDeclaredFields();
                for (Field field : fields) {
                    System.out.println(field.getName());

                }
                System.out.println(DescriptionType.class.getDeclaredField("identifier")
                        .getAnnotation(XmlElement.class).toString());
                System.out.println(inputDescriptionType.getIdentifier().getCodeSpace());
            } catch (SecurityException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (NoSuchFieldException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            System.out.print(inputDescriptionType.getIdentifier().getValue());
            System.out.print(" class is '");
            System.out.println(inputData.getClass().getName());
            System.out.print("', XmlElement is '");
            try {
                System.out.print(InputDescriptionType.class.getDeclaredField("complexData")
                        .getAnnotation(XmlElement.class).toString());
                // System.out.print(InputDescriptionType.class.getDeclaredField("complexData").getAnnotation(XmlElement.class).name());
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("'");
        }

    }

    return processDescriptions;
}

From source file:it.geosolutions.httpproxy.HTTPProxy.java

/**
 * Executes the {@link HttpMethod} passed in and sends the proxy response back to the client via the given {@link HttpServletResponse}
 * //from  www . ja va 2  s.c o  m
 * @param httpMethodProxyRequest An object representing the proxy request to be made
 * @param httpServletResponse An object by which we can send the proxied response back to the client
 * @param digest
 * @throws IOException Can be thrown by the {@link HttpClient}.executeMethod
 * @throws ServletException Can be thrown to indicate that another error has occurred
 */
private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse, String user, String password, ProxyInfo proxyInfo)
        throws IOException, ServletException {

    if (user != null && password != null) {
        UsernamePasswordCredentials upc = new UsernamePasswordCredentials(user, password);
        httpClient.getState().setCredentials(AuthScope.ANY, upc);
    }

    httpMethodProxyRequest.setFollowRedirects(false);

    InputStream inputStreamServerResponse = null;
    ByteArrayOutputStream baos = null;

    try {

        // //////////////////////////
        // Execute the request
        // //////////////////////////

        int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest);

        onRemoteResponse(httpMethodProxyRequest);

        // ////////////////////////////////////////////////////////////////////////////////
        // Check if the proxy response is a redirect
        // The following code is adapted from
        // org.tigris.noodle.filters.CheckForRedirect
        // Hooray for open source software
        // ////////////////////////////////////////////////////////////////////////////////

        if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */
                && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) {

            String stringStatusCode = Integer.toString(intProxyResponseCode);
            String stringLocation = httpMethodProxyRequest.getResponseHeader(Utils.LOCATION_HEADER).getValue();

            if (stringLocation == null) {
                throw new ServletException("Recieved status code: " + stringStatusCode + " but no "
                        + Utils.LOCATION_HEADER + " header was found in the response");
            }

            // /////////////////////////////////////////////
            // Modify the redirect to go to this proxy
            // servlet rather that the proxied host
            // /////////////////////////////////////////////

            String stringMyHostName = httpServletRequest.getServerName();

            if (httpServletRequest.getServerPort() != 80) {
                stringMyHostName += ":" + httpServletRequest.getServerPort();
            }

            stringMyHostName += httpServletRequest.getContextPath();
            httpServletResponse.sendRedirect(stringLocation.replace(
                    Utils.getProxyHostAndPort(proxyInfo) + proxyInfo.getProxyPath(), stringMyHostName));

            return;

        } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) {

            // ///////////////////////////////////////////////////////////////
            // 304 needs special handling. See:
            // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
            // We get a 304 whenever passed an 'If-Modified-Since'
            // header and the data on disk has not changed; server
            // responds w/ a 304 saying I'm not going to send the
            // body because the file has not changed.
            // ///////////////////////////////////////////////////////////////

            httpServletResponse.setIntHeader(Utils.CONTENT_LENGTH_HEADER_NAME, 0);
            httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);

            return;
        }

        // /////////////////////////////////////////////
        // Pass the response code back to the client
        // /////////////////////////////////////////////

        httpServletResponse.setStatus(intProxyResponseCode);

        // /////////////////////////////////////////////
        // Pass response headers back to the client
        // /////////////////////////////////////////////

        Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();

        for (Header header : headerArrayResponse) {

            // /////////////////////////
            // Skip GZIP Responses
            // /////////////////////////

            if (header.getName().equalsIgnoreCase(Utils.HTTP_HEADER_ACCEPT_ENCODING)
                    && header.getValue().toLowerCase().contains("gzip"))
                continue;
            else if (header.getName().equalsIgnoreCase(Utils.HTTP_HEADER_CONTENT_ENCODING)
                    && header.getValue().toLowerCase().contains("gzip"))
                continue;
            else if (header.getName().equalsIgnoreCase(Utils.HTTP_HEADER_TRANSFER_ENCODING))
                continue;
            //                else if (header.getName().equalsIgnoreCase(Utils.HTTP_HEADER_WWW_AUTHENTICATE))
            //                    continue;                
            else
                httpServletResponse.setHeader(header.getName(), header.getValue());
        }

        // ///////////////////////////////////
        // Send the content to the client
        // ///////////////////////////////////

        inputStreamServerResponse = httpMethodProxyRequest.getResponseBodyAsStream();

        if (inputStreamServerResponse != null) {
            byte[] b = new byte[proxyConfig.getDefaultStreamByteSize()];

            baos = new ByteArrayOutputStream(b.length);

            int read = 0;
            while ((read = inputStreamServerResponse.read(b)) > 0) {
                baos.write(b, 0, read);
                baos.flush();
            }

            baos.writeTo(httpServletResponse.getOutputStream());
        }

    } catch (HttpException e) {
        if (LOGGER.isLoggable(Level.SEVERE))
            LOGGER.log(Level.SEVERE, "Error executing HTTP method ", e);
    } finally {
        try {
            if (inputStreamServerResponse != null)
                inputStreamServerResponse.close();
        } catch (IOException e) {
            if (LOGGER.isLoggable(Level.SEVERE))
                LOGGER.log(Level.SEVERE, "Error closing request input stream ", e);
            throw new ServletException(e.getMessage());
        }

        try {
            if (baos != null) {
                baos.flush();
                baos.close();
            }
        } catch (IOException e) {
            if (LOGGER.isLoggable(Level.SEVERE))
                LOGGER.log(Level.SEVERE, "Error closing response stream ", e);
            throw new ServletException(e.getMessage());
        }

        httpMethodProxyRequest.releaseConnection();
    }
}

From source file:davmail.caldav.CaldavConnection.java

/**
 * Append calendar inbox object to Caldav response.
 *
 * @param response  Caldav response// w  w w . j a v a  2  s  .  com
 * @param request   Caldav request
 * @param subFolder inbox folder path relative to request path
 * @throws IOException on error
 */
public void appendInbox(CaldavResponse response, CaldavRequest request, String subFolder) throws IOException {
    String ctag = "0";
    String etag = "0";
    String folderPath = request.getFolderPath(subFolder);
    // do not try to access inbox on shared calendar
    if (!session.isSharedFolder(folderPath)) {
        try {
            ExchangeSession.Folder folder = session.getFolder(folderPath);
            ctag = base64Encode(folder.ctag);
            etag = base64Encode(folder.etag);
        } catch (HttpException e) {
            // unauthorized access, probably an inbox on shared calendar
            DavGatewayTray.debug(new BundleMessage("LOG_ACCESS_FORBIDDEN", folderPath, e.getMessage()));
        }
    }
    response.startResponse(encodePath(request, request.getPath(subFolder)));
    response.startPropstat();

    if (request.hasProperty("resourcetype")) {
        response.appendProperty("D:resourcetype",
                "<D:collection/>" + "<C:schedule-inbox xmlns:C=\"urn:ietf:params:xml:ns:caldav\"/>");
    }
    if (request.hasProperty("getcontenttype")) {
        response.appendProperty("D:getcontenttype", "text/calendar; component=vevent");
    }
    if (request.hasProperty("getctag")) {
        response.appendProperty("CS:getctag", "CS=\"http://calendarserver.org/ns/\"", ctag);
    }
    if (request.hasProperty("getetag")) {
        response.appendProperty("D:getetag", etag);
    }
    if (request.hasProperty("displayname")) {
        response.appendProperty("D:displayname", "inbox");
    }
    response.endPropStatOK();
    response.endResponse();
}

From source file:davmail.caldav.CaldavConnection.java

/**
 * Send inbox response for request./*from   w ww . ja  va 2 s  .c o m*/
 *
 * @param request Caldav request
 * @throws IOException on error
 */
public void sendInbox(CaldavRequest request) throws IOException {
    CaldavResponse response = new CaldavResponse(HttpStatus.SC_MULTI_STATUS);
    response.startMultistatus();
    appendInbox(response, request, null);
    // do not try to access inbox on shared calendar
    if (!session.isSharedFolder(request.getFolderPath(null)) && request.getDepth() == 1
            && !request.isLightning()) {
        try {
            DavGatewayTray.debug(new BundleMessage("LOG_SEARCHING_CALENDAR_MESSAGES"));
            List<ExchangeSession.Event> events = session.getEventMessages(request.getFolderPath());
            DavGatewayTray.debug(new BundleMessage("LOG_FOUND_CALENDAR_MESSAGES", events.size()));
            appendEventsResponses(response, request, events);
        } catch (HttpException e) {
            // unauthorized access, probably an inbox on shared calendar
            DavGatewayTray
                    .debug(new BundleMessage("LOG_ACCESS_FORBIDDEN", request.getFolderPath(), e.getMessage()));
        }
    }
    response.endMultistatus();
    response.close();
}

From source file:de.sub.goobi.metadaten.Metadaten.java

/**
 * Show OCR result./*from w ww . j  a  v a 2s. co m*/
 */
public void showOcrResult() {
    String myOcrUrl = getOcrBasisUrl(this.imageNumber);
    HttpClient client = new HttpClient();
    GetMethod method = new GetMethod(myOcrUrl);
    try {
        int statusCode = client.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            this.ocrResult = "HttpStatus nicht ok";
            return;
        }
        this.ocrResult = method.getResponseBodyAsString();
    } catch (HttpException e) {
        this.ocrResult = "Fatal protocol violation: " + e.getMessage();
    } catch (IOException e) {
        this.ocrResult = "Fatal transport error: " + e.getMessage();
    } finally {
        method.releaseConnection();
    }
}

From source file:net.sourceforge.tagsea.instrumentation.network.RegisterWithProgress.java

public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
    GetMethod getUidMethod = new GetMethod(NetworkUtilities.REGISTER_SCRIPT);
    getUidMethod.setQueryString(new NameValuePair[] { new NameValuePair("firstName", firstName),
            new NameValuePair("lastName", lastName), new NameValuePair("email", email),
            new NameValuePair("jobFunction", job), new NameValuePair("company", company),
            new NameValuePair("companySize", companySize), new NameValuePair("companyBusiness", fieldOfWork),
            new NameValuePair("anonymous", Boolean.toString(anonymous)) });
    monitor.beginTask("Get User Id", 1);
    HttpClient client = new HttpClient();

    try {//from w w  w . ja v a2  s  . c  o m
        status = client.executeMethod(getUidMethod);

        response = NetworkUtilities.readInputAsString(getUidMethod.getResponseBodyAsStream());
    } catch (HttpException e) {
        //there was a problem with the file upload so throw up
        // an error
        // dialog to inform the user and log the exception
        status = 500;
        response = e.getMessage();
        throw new InvocationTargetException(e, response);
    } catch (IOException e) {
        //there was a problem with the file upload so throw up
        // an error
        // dialog to inform the user and log the exception
        status = 500;
        response = e.getMessage();
        throw new InvocationTargetException(e, response);
    } finally {
        //             release the connection to the server
        getUidMethod.releaseConnection();
    }

    if (status != 200) {
    } else {
        String uidString = response.substring(response.indexOf(":") + 1).trim();
        userID = Integer.parseInt(uidString);
        InstrumentationPreferences.setAnonymous(anonymous);
        InstrumentationPreferences.setAskForRegistration(false);
        InstrumentationPreferences.setCompany(company);
        InstrumentationPreferences.setCompanySize(companySize);
        InstrumentationPreferences.setEmail(email);
        InstrumentationPreferences.setFieldOfWork(fieldOfWork);
        InstrumentationPreferences.setFirstName(firstName);
        InstrumentationPreferences.setJob(job);
        InstrumentationPreferences.setLastName(lastName);
        InstrumentationPreferences.setUID(userID);
        InstrumentationPreferences.setMonitoringEnabled(true);
        InstrumentationPreferences.setUploadInterval(1);
    }

    monitor.worked(1);
    monitor.done();
}

From source file:org.alfresco.web.bean.ajax.PresenceProxyBean.java

/**
 * Perform request/*from  w w w  . j  a v  a2  s. co  m*/
 */
public String getUrlResponse(String requestUrl) {
    String response = "";
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(requestUrl);
    method.setRequestHeader("Accept", "*/*");
    client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
    try {
        int statusCode = client.executeMethod(method);
        if (statusCode == HttpStatus.SC_OK) {
            response = method.getResponseBodyAsString();
        } else {
            response = method.getStatusText();
        }
    } catch (HttpException e) {
        response = e.getMessage();
    } catch (IOException e) {
        response = e.getMessage();
    } finally {
        // Release the connection.
        method.releaseConnection();
    }

    return response;
}

From source file:org.apache.ambari.funtest.server.AmbariHttpWebRequest.java

@SuppressWarnings("deprecation")
private RuntimeException createRuntimeException(HttpException httpException) {
    String message = httpException.getMessage();
    try {//from ww  w .  j  av  a2s  .c o m
        JsonElement jsonElement = new JsonParser()
                .parse(new JsonReader(new StringReader(httpException.getMessage())));
        if (jsonElement != null && jsonElement.getAsJsonObject().has("message")) {
            message = jsonElement.getAsJsonObject().get("message").getAsString();
        }
    } catch (Throwable t) {
    }
    if (httpException.getReasonCode() != HttpStatus.SC_OK) {
        message = httpException.getReasonCode() + " " + httpException.getReason() + ": " + message;
    }
    return new RuntimeException(message, httpException);
}

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

/**
 * Provides the first cluster defined on this Ambari server.
 * /*w  w  w.  jav a2 s .co m*/
 * @return
 */
public AmbariClusterInfo getClusterInfo() {
    try {
        JsonElement jsonElement = doGetJson("/api/v1/clusters");
        if (jsonElement == null) {
            return null;
        }
        JsonObject jsonObject = jsonElement.getAsJsonObject();
        JsonArray clustersArray = jsonObject.get("items").getAsJsonArray();
        if (clustersArray.size() > 0) {
            AmbariClusterInfo cluster = new AmbariClusterInfo();
            JsonObject clusterObj = clustersArray.get(0).getAsJsonObject().get("Clusters").getAsJsonObject();
            cluster.setName(clusterObj.get("cluster_name").getAsString());
            cluster.setVersion(clusterObj.get("version").getAsString());
            return cluster;
        }
    } 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;
}