001/* 002 * acme4j - Java ACME client 003 * 004 * Copyright (C) 2016 Richard "Shred" Körber 005 * http://acme4j.shredzone.org 006 * 007 * Licensed under the Apache License, Version 2.0 (the "License"); 008 * you may not use this file except in compliance with the License. 009 * 010 * This program is distributed in the hope that it will be useful, 011 * but WITHOUT ANY WARRANTY; without even the implied warranty of 012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 013 */ 014package org.shredzone.acme4j; 015 016import java.net.HttpURLConnection; 017import java.net.URI; 018import java.net.URL; 019import java.util.ArrayList; 020import java.util.List; 021 022import org.shredzone.acme4j.connector.Connection; 023import org.shredzone.acme4j.connector.Resource; 024import org.shredzone.acme4j.exception.AcmeConflictException; 025import org.shredzone.acme4j.exception.AcmeException; 026import org.shredzone.acme4j.toolbox.JSONBuilder; 027import org.slf4j.Logger; 028import org.slf4j.LoggerFactory; 029 030/** 031 * A builder for a new account registration. 032 */ 033public class RegistrationBuilder { 034 private static final Logger LOG = LoggerFactory.getLogger(RegistrationBuilder.class); 035 036 private List<URI> contacts = new ArrayList<>(); 037 038 /** 039 * Add a contact URI to the list of contacts. 040 * 041 * @param contact 042 * Contact URI 043 * @return itself 044 */ 045 public RegistrationBuilder addContact(URI contact) { 046 contacts.add(contact); 047 return this; 048 } 049 050 /** 051 * Add a contact address to the list of contacts. 052 * <p> 053 * This is a convenience call for {@link #addContact(URI)}. 054 * 055 * @param contact 056 * Contact URI as string 057 * @throws IllegalArgumentException 058 * if there is a syntax error in the URI string 059 * @return itself 060 */ 061 public RegistrationBuilder addContact(String contact) { 062 addContact(URI.create(contact)); 063 return this; 064 } 065 066 /** 067 * Creates a new account. 068 * 069 * @param session 070 * {@link Session} to be used for registration 071 * @return {@link Registration} referring to the new account 072 * @throws AcmeConflictException 073 * if there is already an account for the connection's key pair. 074 * {@link AcmeConflictException#getLocation()} contains the registration's 075 * location URI. 076 */ 077 public Registration create(Session session) throws AcmeException { 078 LOG.debug("create"); 079 080 try (Connection conn = session.provider().connect()) { 081 JSONBuilder claims = new JSONBuilder(); 082 claims.putResource(Resource.NEW_REG); 083 if (!contacts.isEmpty()) { 084 claims.put("contact", contacts); 085 } 086 087 conn.sendSignedRequest(session.resourceUrl(Resource.NEW_REG), claims, session); 088 conn.accept(HttpURLConnection.HTTP_CREATED); 089 090 URL location = conn.getLocation(); 091 URI tos = conn.getLinkAsURI("terms-of-service"); 092 093 return new Registration(session, location, tos); 094 } 095 } 096 097}