Skip to main content
Skip table of contents

Automated list import with sample java code

JAVA
package de.retarus.webexpress.list.autoimport.test.customer;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.SocketFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpClientError;
import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.params.HttpConnectionParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;
import org.apache.commons.lang.CharEncoding;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang.time.StopWatch;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.PropertyConfigurator;
/**
 * Remark: commons-codec-1.3.jar required
 */
public class CustomerJavaAutoImportExample {
  private static final Log log =
      LogFactory.getLog(CustomerJavaAutoImportExam - ple.class);
  public CustomerJavaAutoImportExample() {}
  public void importList() {
    try {
      File f1 = new File("FILE"); // xls, csv or txt
      Protocol easyhttps =
          new protocol("https", new EasySSLProtocolSock - etFactory(), 443);
      Protocol.registerProtocol("https", easyhttps);
      HttpClient httpClient = new HttpClient();
      // set timeout
      int timeout = (int) (DateUtils.MILLIS_PER_SECOND * 120);
      HttpConnectionManager httpConnectionManager =
          httpClient.getHttpConnectionManager();
      HttpConnectionManagerParams httpConnectionManagerParams =
          httpCon - nectionManager.getParams();
      httpConnectionManagerParams.setConnectionTimeout(
          timeout); // CON-NECTION-TIMEOUT
      httpConnectionManagerParams.setSoTimeout(timeout); // READ_TIMEOUT
      PostMethod post = new PostMethod(
          "https://webexpress.retarus.com/PicoPortal/autoLogin/listIm-port/");
      final String charSet = CharEncoding.UTF_8;
      Part[] parts = {
          //
          //
          new StringPart("j_username", "YOUR_USERID"), //
          new StringPart("j_password", "YOUR_PASSWORD", charSet), //
          new StringPart(
              "dlu_targetuser", "TARGET_USERID", char - Set), // optional
          new StringPart("dlu_listname", "LISTNAME", charSet), //
          new StringPart("dlu_listcomment", "LISTCOMMENT", charSet),
          new StringPart("dlu_visibility", "user", charSet), // user vs. company
          new StringPart("dlu_defaultcountrycode", "+49", charSet), //
          new StringPart("dlu_firstrowcolumnnames", "on", charSet), // optional
          new StringPart("dlu_charset", "ISO-8859-1", charSet), // op-tional
          new StringPart(
              "dlu_type", "distributionlist", charSet), // distributionlist
          // vs. blacklist
          new FilePart("dlu_file", f1) //
      };
      DefaultHttpMethodRetryHandler retryHandler =
          new DefaultHttp - MethodRetryHandler(0, false);
      HttpMethodParams httpMethodParams = post.getParams();
      httpMethodParams.setParameter(
          HttpMethodParams.RETRY_HANDLER, retry - Handler);
      post.setRequestEntity(
          new MultipartRequestEntity(parts, httpMethod - Params));
      int httpRc = httpClient.executeMethod(post);
      // READ RESPONSE
      StringBuffer responseText = new StringBuffer();
      final InputStream in = post.getResponseBodyAsStream();
      int ch = 0;
      while ((ch = in.read()) >= 0) {
        responseText.append((char) ch);
      }
      log.info("HTTP-response-code: " + httpRc);
      log.info("RESPONSE:\n" + responseText);
      if (httpRc == HttpStatus.SC_OK) {
        log.info("Upload successful.");
      } else {
        log.error("Upload FAILED.");
      }
    } catch (Throwable t) {
      log.error("", t);
    }
  }
  /**
   * @param args
   */
  public static void main(String[] args) {
    PropertyConfigurator.configure("PATH/log4j.properties");
    log.info("STARTED...");
    StopWatch sw = new StopWatch();
    sw.start();
    CustomerJavaAutoImportExample javaAutoImport =
        new CustomerJavaAutoImportEx - ample();
    javaAutoImport.importList();
    sw.stop();
    log.info("... STOPPED [" + sw.getTime() + "ms]");
  }
  /**
   * <p>
   * EasyX509TrustManager unlike default {@link X509TrustManager} accepts
   * self-signed certificates.
   * </p>
   * <p>
   * This trust manager SHOULD NOT be used for productive systems due to
   * security reasons, unless it is a conscious decision and you are perfectly
   * aware of security implications of accepting self-signed certificates
   * </p>
   *
   * @author <a href="mailto:adrian.sutton@ephox.com">Adrian Sutton</a>
   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
   * <p>
   * DISCLAIMER: HttpClient developers DO NOT actively support this component.
   * The component is provided as a reference material, which may be
   * inappropriate for use without additional customization.
   * </p>
   */
  static class EasyX509TrustManager implements X509TrustManager {
    private X509TrustManager standardTrustManager = null;
    /** Log object for this class. */
    private static final Log log =
        LogFactory.getLog(EasyX509TrustManager.class);
    /**
     * Constructor for EasyX509TrustManager.
     */
    public EasyX509TrustManager(KeyStore keystore)
        throws NoSuchAlgorithmException, KeyStoreExcep - tion {
      super();
      TrustManagerFactory factory = TrustManagerFactory.getInstance(
          TrustManagerFactory.getDefaultAlgorithm());
      factory.init(keystore);
      TrustManager[] trustmanagers = factory.getTrustManagers();
      if (trustmanagers.length == 0) {
        throw new NoSuchAlgorithmException("no trust manager found");
      }
      this.standardTrustManager = (X509TrustManager) trustmanagers[0];
    }
    /**
     * @see
     *     javax.net.ssl.X509TrustManager#checkClientTrusted(X509Certifi-cate[],String
     * authType)
     */
    public void checkClientTrusted(X509Certificate[] certificates,
        String authType) throws CertificateException {
      standardTrustManager.checkClientTrusted(certificates, authType);
    }
    /**
     * @see
     *     javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certifi-cate[],String
     * authType)
     */
    public void checkServerTrusted(X509Certificate[] certificates,
        String authType) throws CertificateException {
      if ((certificates != null) && log.isDebugEnabled()) {
        log.debug("Server certificate chain:");
        for (int i = 0; i < certificates.length; i++) {
          log.debug("X509Certificate[" + i + "]=" + certifi - cates[i]);
        }
      }
      if ((certificates != null) && (certificates.length == 1)) {
        certificates[0].checkValidity();
      } else {
        standardTrustManager.checkServerTrusted(certificates, authType);
      }
    }
    /**
     * @see javax.net.ssl.X509TrustManager#getAcceptedIssuers()
     */
    public X509Certificate[] getAcceptedIssuers() {
      return this.standardTrustManager.getAcceptedIssuers();
    }
  }
  /**
   * <p>
   * EasySSLProtocolSocketFactory can be used to creats SSL {@link Socket}s that
   * accept self-signed certificates.
   * </p>
   * <p>
   * This socket factory SHOULD NOT be used for productive systems due to
   * security reasons, unless it is a conscious decision and you are perfectly
   * aware of security implications of accepting self-signed certificates
   * </p>
   * <p>
   * Example of using custom protocol socket factory for a specific host:
   *
   * <pre>
   * protocol easyhttps = new protocol(&quot;https&quot;, new
   * EasySSLProtocolSocketFac-tory(),443);
   *
   * HttpClient client = new HttpClient();
   * client.getHostConfiguration().setHost(&quot;localhost&quot;, 443,
   * easyhttps);
   * // use relative url only
   * GetMethod httpget = new GetMethod(&quot;/&quot;);
   * client.executeMethod(httpget);
   * </pre>
   *
   * </p>
   * <p>
   * Example of using custom protocol socket factory per default instead of the
   * stand-ard one:
   *
   * <pre>
   * protocol easyhttps = new protocol(&quot;https&quot;, new
   * EasySSLProtocolSocketFac-tory(),443);
   * protocol.registerProtocol(&quot;https&quot;, easyhttps);
   *
   * HttpClient client = new HttpClient();
   * GetMethod httpget = new GetMethod(&quot;https://localhost/&quot;);
   * client.executeMethod(httpget);
   * </pre>
   *
   * </p>
   */
  static class EasySSLProtocolSocketFactory implements protocolSocketFactory {
    // ~ Static fields/initializers
    // -------------------------------------------------------------------------------------
    /** Log object for this class. */
    private static final Log LOG =
        LogFactory.getLog(EasySSLProtocolSocketFactory.class);
    // ~ Instance fields
    // ------------------------------------------------------------------------------------------------
    private SSLContext sslcontext = null;
    // ~ Constructors
    // ---------------------------------------------------------------------------------------------------
    /**
     * Constructor for EasySSLProtocolSocketFactory.
     */
    public EasySSLProtocolSocketFactory() {
      super();
    }
    // ~ Methods
    // --------------------------------------------------------------------------------------------------------
    /**
     * @see
     *     SecureProtocolSocketFactory#cre-ateSocket(java.lang.String,int,java.net.InetAddress,int)
     */
    public Socket createSocket(String host, int port, InetAddress clientHost,
        int clientPort) throws IOException, UnknownHostException {
      return getSSLContext().getSocketFactory().createSocket(
          host, port, clientHost, clientPort);
    }
    /**
     * Attempts to get a new socket connection to the given host within the
     * given time limit. <p> To circumvent the limitations of older JREs that do
     * not support connect timeout a controller thread is executed. The
     * controller thread attempts to create a new socket within the given limit
     * of time. If socket constructor does not re-turn until the timeout
     * expires, the controller terminates and throws an
     * {@link ConnectTimeoutException}
     * </p>
     *
     * @param host
     * the host name/IP
     * @param port
     * the port on the host
     * @param localAddress
     * the local host name/IP to bind the socket to
     * @param localPort
     * the port on the local machine
     * @param params
     * {@link HttpConnectionParams Http connection parameters}
     * @return Socket a new socket
     * @throws IOException
     * if an I/O error occurs while creating the socket
     * @throws UnknownHostException
     * if the IP address of the host cannot be determined
     * @throws ConnectTimeoutException
     * DOCUMENT ME!
     * @throws IllegalArgumentException
     * DOCUMENT ME!
     */
    public Socket createSocket(final String host, final int port,
        final InetAddress localAddress, final int localPort,
        final HttpConnectionParams params)
        throws IOException, UnknownHostException, ConnectTimeoutException {
      if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null");
      }
      int timeout = params.getConnectionTimeout();
      SocketFactory socketfactory = getSSLContext().getSocketFactory();
      if (timeout == 0) {
        return socketfactory.createSocket(host, port, localAddress, localPort);
      } else {
        Socket socket = socketfactory.createSocket();
        SocketAddress localaddr =
            new InetSocketAddress(localAd - dress, localPort);
        SocketAddress remoteaddr = new InetSocketAddress(host, port);
        socket.bind(localaddr);
        socket.connect(remoteaddr, timeout);
        return socket;
      }
    }
    /**
     * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int)
     */
    public Socket createSocket(String host, int port)
        throws IOException, UnknownHostException {
      return getSSLContext().getSocketFactory().createSocket(host, port);
    }
    /**
     * @see
     *     SecureProtocolSocketFactory#cre-ateSocket(java.net.Socket,java.lang.String,int,boolean)
     */
    public Socket createSocket(Socket socket, String host, int port,
        boolean autoClose) throws IOException, UnknownHostException {
      return getSSLContext().getSocketFactory().createSocket(
          socket, host, port, autoClose);
    }
    /*
     * (non-Javadoc)
     * @see java.lang.Object#equals(java.lang.Object)
     */
    public boolean equals(Object obj) {
      return ((obj != null)
          && obj.getClass().equals(EasySSLProtocolSocketFactory.class));
    }
    /*
     * (non-Javadoc)
     * @see java.lang.Object#hashCode()
     */
    public int hashCode() {
      return EasySSLProtocolSocketFactory.class.hashCode();
    }
    private static SSLContext createEasySSLContext() {
      try {
        SSLContext context = SSLContext.getInstance("SSL");
        context.init(
            null, new TrustManager[] {new EasyX509Trust - Manager(null)}, null);
        return context;
      } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        throw new HttpClientError(e.toString());
      }
    }
    private SSLContext getSSLContext() {
      if (this.sslcontext == null) {
        this.sslcontext = createEasySSLContext();
      }
      return this.sslcontext;
    }
  }
}
JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.