Java tutorial
/* * * Copyright (c) 2016 by Alex Shpurov. All rights reserved. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.rcn.controller; import com.rcn.core.Tuple; import com.rcn.domain.CodeName; import com.rcn.repository.ResourceRepository; import com.rcn.service.CertificateService; import com.rcn.web.app.RcnUserDetail; import org.apache.commons.lang3.ArrayUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.*; import java.util.stream.IntStream; import static com.rcn.core.Tuple.initMap; import static com.rcn.repository.ResourceRepository.*; /** * Created by alex on 3/26/2016. */ @Controller public class ResourceController { @Autowired private ResourceRepository resourceRepository; @Autowired private MessageSource messageSource; @Autowired private CertificateService certificateService; private static final Logger log = LoggerFactory.getLogger(ResourceController.class); final public static Map<String, String> ResoureMapping = initMap(Tuple.of("ca", TYPE_CA), Tuple.of("resource", TYPE_Resource), Tuple.of("token", TYPE_Token)); private final Character[] PinAlphabet = ArrayUtils.toObject("123456789BCDFHJKLMNPRSTVXZ".toCharArray()); private final int PinLength = 16; @RequestMapping(value = "/resources", method = RequestMethod.GET) public String resources(@RequestParam(value = "t", required = false) Optional<String> resourceType, Model model) { model.addAttribute("resourceType", resourceType.orElseGet(() -> "")); return "resources"; } @RequestMapping(value = "/properties", method = RequestMethod.GET) public String properties(@RequestParam("rid") String rid, Model model) { return "properties"; } @RequestMapping(value = "/create-certificate", method = RequestMethod.GET) public String createCert(Authentication principal, Model model) { RcnUserDetail user = (RcnUserDetail) principal.getPrincipal(); Long targetUserId = user.getTargetUser().getId(); List<CodeName> codeValues = resourceRepository.caList(user.getId(), targetUserId); model.addAttribute("caList", codeValues); return "create-certificate"; } @RequestMapping(value = "/create-certificate", method = RequestMethod.POST) public String createCertPost(@RequestParam("resourceType") String resourceType, @RequestParam("certName") String certName, @RequestParam("validDays") int validDays, @RequestParam("certDesc") String certDesc, @RequestParam("certType") String certType, @RequestParam("taPemCert") String taPemCert, @RequestParam("taPkcs10") String taPkcs10, @RequestParam("ca") String ca, @RequestParam("caPassword") String caPassword, @RequestParam("password1") String password1, @RequestParam("password2") String password2, Authentication principal, Model model) { Optional<String> optError = !password1.equals(password2) ? Optional.of(l("password.does.not.match")) : Optional.empty(); if (!optError.isPresent()) { try { String type = ResoureMapping.computeIfAbsent(resourceType, a -> { throw new IllegalArgumentException("could not map a resource key:" + a); }); RcnUserDetail user = (RcnUserDetail) principal.getPrincipal(); Long targetUserId = user.getTargetUser().getId(); Optional<String> caCert = ca.trim().length() > 0 ? Optional.ofNullable( resourceRepository.certById(targetUserId, user.getId(), Long.valueOf(ca))) : Optional.empty(); Optional<String> clientCert = Optional.ofNullable("certImport".equals(certType) ? taPemCert : null); Optional<String> pkcs10Req = Optional .ofNullable("certGeneratePkcs10".equals(certType) ? taPkcs10 : null); String cnName = certName.startsWith("cn=") ? certName : "cn=" + certName; String certPem = clientCert.orElseGet(() -> certificateService.generateCert(cnName, password1, validDays, caCert, caPassword, TYPE_CA.equals(type), pkcs10Req)); Long resourceId = resourceRepository.createResource(targetUserId, type, certName, certDesc); certificateService.storeCert(resourceId, certPem, password1); } catch (Exception e) { log.error("createCertPost", e); optError = Optional.of(e.getMessage()); } } optError.ifPresent(e -> model.addAttribute("error", e)); return optError.map(a -> "create-certificate").orElse("redirect:/resources"); } @RequestMapping(value = "/license-key", method = RequestMethod.GET) public String licenseKey(Model model) { return "license-key"; } @RequestMapping(value = "/license-key", method = RequestMethod.POST) public String licenseKeyPost(@RequestParam("name") String name, @RequestParam("validFor") Integer validFor, @RequestParam("keyExpires") Integer keyExpires, @RequestParam("activationsNumber") Integer activationsNumber, @RequestParam("customKey") String customKey, @RequestParam("key") Long key, @RequestParam("val") String val, @RequestParam(name = "resourceGroup", required = false) boolean resourceGroup, @RequestParam(name = "customNumber", required = false) boolean customNumber, Authentication principal, Model model) { RcnUserDetail user = (RcnUserDetail) principal.getPrincipal(); Long targetUserId = user.getTargetUser().getId(); try { String lk = customNumber ? IntStream.range(0, 1).mapToObj(a -> customKey.toUpperCase()).filter(a -> a.length() == 16) .filter(a -> resourceRepository.containsKey(a) == null).findFirst() .orElseThrow(() -> new IllegalArgumentException(l("invalid.custom.number"))) : IntStream.range(0, 10).mapToObj(a -> generateLicenseKey()) .filter(a -> resourceRepository.containsKey(a) == null).findFirst() .orElseThrow(() -> new IllegalArgumentException(l("cant.generate.license.key"))); Long id = resourceRepository.createLicenseKey(targetUserId, name, lk, validFor, keyExpires, activationsNumber); if (resourceGroup) { resourceRepository.licenseKeyToResourceGroup(targetUserId, id, key); } } catch (IllegalArgumentException e) { model.addAttribute("error", e.getMessage()); } return "license-key"; } @RequestMapping(value = "/pkcs12", method = RequestMethod.GET) public String pkcs12() { return "pkcs12"; } @RequestMapping(value = "/pkcs12/{file_name}", method = RequestMethod.POST) public void pkcs12Post(@PathVariable("file_name") String fileName, @RequestParam("rid") Long rid, @RequestParam("password") String password, Authentication principal, Model model, HttpServletResponse response) throws IOException { RcnUserDetail user = (RcnUserDetail) principal.getPrincipal(); Long targetUserId = user.getTargetUser().getId(); String cert = resourceRepository.certById(targetUserId, targetUserId, rid); try { byte[] content = certificateService.toPkcs12(cert, password); response.setContentType("application/octet-stream"); response.getOutputStream().write(content); response.flushBuffer(); } catch (Exception e) { model.addAttribute("error", e.getMessage()); } } private String generateLicenseKey() { Random randomGenerator = new Random(System.currentTimeMillis()); return IntStream.range(0, PinLength).mapToObj(a -> PinAlphabet[randomGenerator.nextInt(PinAlphabet.length)]) .reduce(new StringBuilder(), (a, b) -> a.append(b), (a, b) -> a.append(b)).toString(); } private String l(String s) { Locale locale = LocaleContextHolder.getLocale(); return messageSource.getMessage(s, null, s, locale); } }