Java tutorial
/* * Copyright (c) 2010-2011, Martijn Brinkers, Djigzo. * * This file is part of Djigzo email encryption. * * Djigzo is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License * version 3, 19 November 2007 as published by the Free Software * Foundation. * * Djigzo is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public * License along with Djigzo. If not, see <http://www.gnu.org/licenses/> * * Additional permission under GNU AGPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or * combining it with aspectjrt.jar, aspectjweaver.jar, tyrex-1.0.3.jar, * freemarker.jar, dom4j.jar, mx4j-jmx.jar, mx4j-tools.jar, * spice-classman-1.0.jar, spice-loggerstore-0.5.jar, spice-salt-0.8.jar, * spice-xmlpolicy-1.0.jar, saaj-api-1.3.jar, saaj-impl-1.3.jar, * wsdl4j-1.6.1.jar (or modified versions of these libraries), * containing parts covered by the terms of Eclipse Public License, * tyrex license, freemarker license, dom4j license, mx4j license, * Spice Software License, Common Development and Distribution License * (CDDL), Common Public License (CPL) the licensors of this Program grant * you additional permission to convey the resulting work. */ package mitm.common.security.ca.handlers.comodo; import java.io.IOException; import java.io.InputStream; import java.io.LineNumberReader; import java.io.StringReader; import mitm.common.net.HTTPMethodExecutor; import mitm.common.net.HTTPMethodExecutor.ResponseHandler; import mitm.common.scheduler.TaskScheduler; import mitm.common.util.Check; import mitm.common.util.SizeLimitedInputStream; import mitm.common.util.SizeUtils; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.CharEncoding; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Used to automatic authorize a certificate using Comodo's EPKI * * @author Martijn Brinkers * */ public class AutoAuthorize { private final static Logger logger = LoggerFactory.getLogger(AutoAuthorize.class); /* * Maximum allowed response size returned from a call to the Comodo service */ private final static int MAX_HTTP_RESPONSE_SIZE = 5 * SizeUtils.KB; /* * Tier account username (max 64 chars) */ private String loginName; /* * Tier account password. */ private String loginPassword; /* * The order number to retrieve. */ private String orderNumber; /* * The connection settings */ private final ComodoConnectionSettings connectionSettings; /* * True if an error occurred. */ private boolean error; /* * The status code */ private CustomClientStatusCode errorCode; /* * The error message if error is true */ private String errorMessage; private ResponseHandler responseHandler = new ResponseHandler() { @Override public void handleResponse(int statusCode, HttpMethod httpMethod, TaskScheduler watchdog) throws IOException, HttpException { AutoAuthorize.this.handleResponse(statusCode, httpMethod); } }; public AutoAuthorize(ComodoConnectionSettings connectionSettings) { Check.notNull(connectionSettings, "connectionSettings"); Check.notNull(connectionSettings.getAutoAuthorizeURL(), "url"); this.connectionSettings = connectionSettings; } private void handleResponse(int statusCode, HttpMethod httpMethod) throws IOException { if (statusCode != HttpStatus.SC_OK) { throw new IOException("Error Authorize. Message: " + httpMethod.getStatusLine()); } InputStream input = httpMethod.getResponseBodyAsStream(); if (input == null) { throw new IOException("Response body is null."); } /* * we want to set a max on the number of bytes to download. We do not want a rogue server to return 1GB. */ InputStream limitInput = new SizeLimitedInputStream(input, MAX_HTTP_RESPONSE_SIZE); String response = IOUtils.toString(limitInput, CharEncoding.US_ASCII); if (logger.isDebugEnabled()) { logger.debug("Response:\r\n" + response); } LineNumberReader lineReader = new LineNumberReader(new StringReader(response)); String statusParameter = lineReader.readLine(); errorCode = CustomClientStatusCode.fromCode(statusParameter); if (errorCode.getID() < CustomClientStatusCode.SUCCESSFUL.getID()) { error = true; errorMessage = lineReader.readLine(); } else { error = false; } } private void reset() { error = false; errorCode = null; errorMessage = null; } /** * Authorizes the certificate with the given orderNummer. * @return true if successful, false if an error occurs * @throws CustomClientCertException */ public boolean authorize() throws CustomClientCertException { reset(); if (StringUtils.isEmpty(loginName)) { throw new CustomClientCertException("loginName must be specified."); } if (StringUtils.isEmpty(loginPassword)) { throw new CustomClientCertException("loginPassword must be specified."); } if (StringUtils.isEmpty(orderNumber)) { throw new CustomClientCertException("orderNumber must be specified."); } PostMethod postMethod = new PostMethod(connectionSettings.getAutoAuthorizeURL()); NameValuePair[] data = { new NameValuePair("loginName", loginName), new NameValuePair("loginPassword", loginPassword), new NameValuePair("orderNumber", orderNumber) }; postMethod.setRequestBody(data); HTTPMethodExecutor executor = new HTTPMethodExecutor(connectionSettings.getTotalTimeout(), connectionSettings.getProxyInjector()); executor.setConnectTimeout(connectionSettings.getConnectTimeout()); executor.setReadTimeout(connectionSettings.getReadTimeout()); try { executor.executeMethod(postMethod, responseHandler); } catch (IOException e) { throw new CustomClientCertException(e); } return !error; } public String getLoginName() { return loginName; } public void setLoginName(String loginName) { this.loginName = loginName; } public String getLoginPassword() { return loginPassword; } public void setLoginPassword(String loginPassword) { this.loginPassword = loginPassword; } public String getOrderNumber() { return orderNumber; } public void setOrderNumber(String orderNumber) { this.orderNumber = orderNumber; } public boolean isError() { return error; } public CustomClientStatusCode getErrorCode() { return errorCode; } public String getErrorMessage() { return errorMessage; } }