List of usage examples for org.apache.commons.httpclient HttpException HttpException
public HttpException(String message)
From source file:com.mindquarry.desktop.util.HttpUtilities.java
public static InputStream getContentAsXML(String login, String pwd, String address) throws NotAuthorizedException, MalformedURLException { try {/*from w w w . java 2s . com*/ HttpClient client = createHttpClient(login, pwd, address); GetMethod get = createAndExecuteGetMethod(address, client); InputStream result = null; if (get.getStatusCode() == 200) { result = get.getResponseBodyAsStream(); } else if (get.getStatusCode() == 401) { throw new NotAuthorizedException(AUTH_REFUSED, address, login, pwd); } else { throw new HttpException(I18N.get("Unknown connection error. Status code ") //$NON-NLS-1$ + get.getStatusCode()); } return result; } catch (NotAuthorizedException e) { throw e; } catch (MalformedURLException e) { throw e; } catch (Exception e) { throw new RuntimeException(e.toString(), e); } }
From source file:com.wfreitas.camelsoap.util.ClientWsdlLoader.java
public InputStream load(String url) throws Exception { GetMethod httpGetMethod;/*from w w w .ja v a2 s . c om*/ if (url.startsWith("file")) { return new URL(url).openStream(); } // Authentication is not being overridden on the method. It needs // to be present on the supplied HttpClient instance! httpGetMethod = new GetMethod(url); httpGetMethod.setDoAuthentication(true); try { int result = httpClient.executeMethod(httpGetMethod); if (result != HttpStatus.SC_OK) { if (result < 200 || result > 299) { throw new HttpException( "Received status code '" + result + "' on WSDL HTTP (GET) request: '" + url + "'."); } else { logger.warn("Received status code '" + result + "' on WSDL HTTP (GET) request: '" + url + "'."); } } return new ByteArrayInputStream(httpGetMethod.getResponseBody()); } finally { httpGetMethod.releaseConnection(); } }
From source file:de.juwimm.cms.http.HttpClientWrapper.java
/** * /*from ww w . j ava2s . c om*/ * @param testUrlString * destination * @param userName * for authentication at testUrlString NOT for proxy * @param password * for authentication at testUrlString NOT for proxy * @throws HttpException */ public void testAndConfigureConnection(String testUrlString, String userName, String password) throws HttpException { URL testURL = null; try { testURL = new URL(testUrlString); } catch (MalformedURLException exe1) { throw new HttpException( HttpMessages.getString("HttpClientWrapper.testConnectionFailed", testUrlString, "\n")); } DlgUsernamePassword dlg = new DlgUsernamePassword(); if ((getHttpProxyUser() == null || "".equalsIgnoreCase(getHttpProxyUser())) && getHttpProxyPassword() == null || "".equalsIgnoreCase(getHttpProxyPassword())) { dlg.getTxtUsername().setText(System.getProperty("user.name")); } else { dlg.getTxtUsername().setText(getHttpProxyUser()); } dlg.getTxtPassword().setText(getHttpProxyPassword()); // dlg.getTxtNTDomain().setText(httpProxyNTDomain); // try no auth, base auth, ntlm auth with user giving username and // password until successful while (true) { try { testAndConfigureConnectionTryInvoke(testURL, userName, password); // save password only if connect successful saveProperties(dlg.getCboSave().isSelected()); break; } catch (URIException exe) { // http-Error-Code: 407 = Proxy Authentication Required if (exe.getReasonCode() == 407) { // ask user for user and password dlg.setVisible(true); if (dlg.isCanceled()) { throw new HttpException( HttpMessages.getString("HttpClientWrapper.noProxyWhereNeededExeption")); } setHttpProxyUser(dlg.getTxtUsername().getText()); setHttpProxyPassword(String.copyValueOf(dlg.getTxtPassword().getPassword())); // httpProxyNTDomain = dlg.getTxtNTDomain().getText(); } else { throw new HttpException(HttpMessages.getString("HttpClientWrapper.testConnectionFailed", testURL.getHost(), exe.getMessage())); } } } log.debug("finished test"); }
From source file:de.mpg.imeji.presentation.util.LoginHelper.java
/** * Get handle of System administrator of eSciDoc instance. * //from ww w . j a v a2 s .c om * @return */ // public static String loginSystemAdmin() // { // String handle = null; // try // { // handle = login(PropertyReader.getProperty("framework.admin.username"), // PropertyReader.getProperty("framework.admin.password")); // } // catch (Exception e) // { // sessionBean = (SessionBean)BeanHelper.getSessionBean(SessionBean.class); // BeanHelper // .info(sessionBean.getLabel("error") + ", wrong administrator user. Check config file or FW: " + e); // logger.error("Error escidoc admin login", e); // } // return handle; // } public static String login(String userName, String password) throws Exception { String frameworkUrl = PropertyReader.getProperty("escidoc.framework_access.framework.url"); StringTokenizer tokens = new StringTokenizer(frameworkUrl, "//"); tokens.nextToken(); StringTokenizer hostPort = new StringTokenizer(tokens.nextToken(), ":"); String host = hostPort.nextToken(); int port = 80; if (hostPort.hasMoreTokens()) { port = Integer.parseInt(hostPort.nextToken()); } HttpClient client = new HttpClient(); client.getHttpConnectionManager().closeIdleConnections(1000); client.getHostConfiguration().setHost(host, port, "http"); client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); PostMethod login = new PostMethod(frameworkUrl + "/aa/j_spring_security_check"); login.addParameter("j_username", userName); login.addParameter("j_password", password); try { client.executeMethod(login); } catch (Exception e) { throw new RuntimeException("Error login in " + frameworkUrl + " status: " + login.getStatusCode() + " - " + login.getStatusText()); } login.releaseConnection(); CookieSpec cookiespec = CookiePolicy.getDefaultSpec(); Cookie[] logoncookies = cookiespec.match(host, port, "/", false, client.getState().getCookies()); Cookie sessionCookie = logoncookies[0]; PostMethod postMethod = new PostMethod("/aa/login"); postMethod.addParameter("target", frameworkUrl); client.getState().addCookie(sessionCookie); client.executeMethod(postMethod); if (HttpServletResponse.SC_SEE_OTHER != postMethod.getStatusCode()) { throw new HttpException("Wrong status code: " + postMethod.getStatusCode()); } String userHandle = null; Header headers[] = postMethod.getResponseHeaders(); for (int i = 0; i < headers.length; ++i) { if ("Location".equals(headers[i].getName())) { String location = headers[i].getValue(); int index = location.indexOf('='); userHandle = new String(Base64.decode(location.substring(index + 1, location.length()))); } } if (userHandle == null) { throw new ServiceException("User not logged in."); } return userHandle; }
From source file:de.mpg.mpdl.inge.util.AdminHelper.java
/** * Logs in the given user with the given password. * /*from w w w . j a va 2 s . com*/ * @param userid The id of the user to log in. * @param password The password of the user to log in. * @return The handle for the logged in user. * @throws HttpException * @throws IOException * @throws ServiceException * @throws URISyntaxException */ public static String loginUser(String userid, String password) throws HttpException, IOException, ServiceException, URISyntaxException { String frameworkUrl = PropertyReader.getLoginUrl(); int delim1 = frameworkUrl.indexOf("//"); int delim2 = frameworkUrl.indexOf(":", delim1); String host; int port; if (delim2 > 0) { host = frameworkUrl.substring(delim1 + 2, delim2); port = Integer.parseInt(frameworkUrl.substring(delim2 + 1)); } else { host = frameworkUrl.substring(delim1 + 2); port = 80; } HttpClient client = new HttpClient(); client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); PostMethod login = new PostMethod(frameworkUrl + "/aa/j_spring_security_check"); login.addParameter("j_username", userid); login.addParameter("j_password", password); ProxyHelper.executeMethod(client, login); login.releaseConnection(); CookieSpec cookiespec = CookiePolicy.getDefaultSpec(); Cookie[] logoncookies = cookiespec.match(host, port, "/", false, client.getState().getCookies()); Cookie sessionCookie = logoncookies[0]; PostMethod postMethod = new PostMethod(frameworkUrl + "/aa/login"); postMethod.addParameter("target", frameworkUrl); client.getState().addCookie(sessionCookie); ProxyHelper.executeMethod(client, postMethod); if (HttpServletResponse.SC_SEE_OTHER != postMethod.getStatusCode()) { throw new HttpException("Wrong status code: " + login.getStatusCode()); } String userHandle = null; Header headers[] = postMethod.getResponseHeaders(); for (int i = 0; i < headers.length; ++i) { if ("Location".equals(headers[i].getName())) { String location = headers[i].getValue(); int index = location.indexOf('='); userHandle = new String( Base64.getDecoder().decode(location.substring(index + 1, location.length()))); // System.out.println("location: "+location); // System.out.println("handle: "+userHandle); } } if (userHandle == null) { throw new ServiceException("User not logged in."); } return userHandle; }
From source file:de.mpg.escidoc.services.framework.AdminHelper.java
/** * Logs in the given user with the given password. * //w w w. j a v a 2 s . co m * @param userid The id of the user to log in. * @param password The password of the user to log in. * @return The handle for the logged in user. * @throws HttpException * @throws IOException * @throws ServiceException * @throws URISyntaxException */ public static String loginUser(String userid, String password) throws HttpException, IOException, ServiceException, URISyntaxException { String frameworkUrl = ServiceLocator.getLoginUrl(); int delim1 = frameworkUrl.indexOf("//"); int delim2 = frameworkUrl.indexOf(":", delim1); String host; int port; if (delim2 > 0) { host = frameworkUrl.substring(delim1 + 2, delim2); port = Integer.parseInt(frameworkUrl.substring(delim2 + 1)); } else { host = frameworkUrl.substring(delim1 + 2); port = 80; } HttpClient client = new HttpClient(); client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); PostMethod login = new PostMethod(frameworkUrl + "/aa/j_spring_security_check"); login.addParameter("j_username", userid); login.addParameter("j_password", password); ProxyHelper.executeMethod(client, login); login.releaseConnection(); CookieSpec cookiespec = CookiePolicy.getDefaultSpec(); Cookie[] logoncookies = cookiespec.match(host, port, "/", false, client.getState().getCookies()); Cookie sessionCookie = logoncookies[0]; PostMethod postMethod = new PostMethod(frameworkUrl + "/aa/login"); postMethod.addParameter("target", frameworkUrl); client.getState().addCookie(sessionCookie); ProxyHelper.executeMethod(client, postMethod); if (HttpServletResponse.SC_SEE_OTHER != postMethod.getStatusCode()) { throw new HttpException("Wrong status code: " + login.getStatusCode()); } String userHandle = null; Header headers[] = postMethod.getResponseHeaders(); for (int i = 0; i < headers.length; ++i) { if ("Location".equals(headers[i].getName())) { String location = headers[i].getValue(); int index = location.indexOf('='); userHandle = new String(Base64.decode(location.substring(index + 1, location.length()))); //System.out.println("location: "+location); //System.out.println("handle: "+userHandle); } } if (userHandle == null) { throw new ServiceException("User not logged in."); } return userHandle; }
From source file:com.sos.VirtualFileSystem.WebDAV.SOSVfsWebDAVOutputStream.java
/** * * \brief put//from ww w . j ava2 s . c o m * * \details * * @throws HttpException, IOException */ public void put() throws HttpException, IOException { resource.putMethod(this.toByteArray()); if (resource.exists() == false) { String msg = String.format("%1$s: %2$s", resource.getPath(), resource.getStatusMessage()); throw new HttpException(msg); } }
From source file:com.linkedin.pinot.common.utils.FileUploadUtils.java
public static int sendFile(final String host, final String port, final String path, final String fileName, final InputStream inputStream, final long lengthInBytes, SendFileMethod httpMethod) { EntityEnclosingMethod method = null; try {/* www . ja v a2s.c o m*/ method = httpMethod.forUri("http://" + host + ":" + port + "/" + path); Part[] parts = { new FilePart(fileName, new PartSource() { @Override public long getLength() { return lengthInBytes; } @Override public String getFileName() { return "fileName"; } @Override public InputStream createInputStream() throws IOException { return new BufferedInputStream(inputStream); } }) }; method.setRequestEntity(new MultipartRequestEntity(parts, new HttpMethodParams())); FILE_UPLOAD_HTTP_CLIENT.executeMethod(method); if (method.getStatusCode() >= 400) { String errorString = "POST Status Code: " + method.getStatusCode() + "\n"; if (method.getResponseHeader("Error") != null) { errorString += "ServletException: " + method.getResponseHeader("Error").getValue(); } throw new HttpException(errorString); } return method.getStatusCode(); } catch (Exception e) { LOGGER.error("Caught exception while sending file: {}", fileName, e); Utils.rethrowException(e); throw new AssertionError("Should not reach this"); } finally { if (method != null) { method.releaseConnection(); } } }
From source file:com.releasequeue.server.ReleaseQueueServer.java
private Object postJsonRequest(URL url, JSONObject payload) throws IOException { HttpPost request = new HttpPost(url.toString()); setAuthHeader(request);//from w ww . j a v a 2s . c om CloseableHttpClient httpClient = HttpClients.createDefault(); try { StringWriter data = new StringWriter(); payload.writeJSONString(data); StringEntity params = new StringEntity(data.toString()); request.addHeader("content-type", "application/json"); request.setEntity(params); HttpResponse response = httpClient.execute(request); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode >= 400) { throw new HttpException(statusLine.getReasonPhrase()); } String json_string = EntityUtils.toString(response.getEntity()); JSONParser parser = new JSONParser(); return parser.parse(json_string); } catch (ParseException pe) { throw new RuntimeException("Failed to parse json responce", pe); } finally { httpClient.getConnectionManager().shutdown(); } }
From source file:net.sf.j2ep.requesthandlers.RequestHandlerBase.java
/** * Will write the proxy specific headers such as Via and x-forwarded-for. * //from w ww . j a va 2 s. c om * @param method Method to write the headers to * @param request The incoming request, will need to get virtual host. * @throws HttpException */ private void setProxySpecificHeaders(HttpMethod method, HttpServletRequest request) throws HttpException { String serverHostName = "jEasyExtensibleProxy"; try { serverHostName = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { log.error("Couldn't get the hostname needed for headers x-forwarded-server and Via", e); } String originalVia = request.getHeader("via"); StringBuffer via = new StringBuffer(""); if (originalVia != null) { if (originalVia.indexOf(serverHostName) != -1) { log.error("This proxy has already handled the request, will abort."); throw new HttpException("Request has a cyclic dependency on this proxy."); } via.append(originalVia).append(", "); } via.append(request.getProtocol()).append(" ").append(serverHostName); method.setRequestHeader("via", via.toString()); method.setRequestHeader("x-forwarded-for", request.getRemoteAddr()); method.setRequestHeader("x-forwarded-host", request.getServerName()); method.setRequestHeader("x-forwarded-server", serverHostName); method.setRequestHeader("accept-encoding", ""); }