Example usage for javax.xml.bind DatatypeConverter parseBase64Binary

List of usage examples for javax.xml.bind DatatypeConverter parseBase64Binary

Introduction

In this page you can find the example usage for javax.xml.bind DatatypeConverter parseBase64Binary.

Prototype

public static byte[] parseBase64Binary(String lexicalXSDBase64Binary) 

Source Link

Document

Converts the string argument into an array of bytes.

Usage

From source file:fi.csc.emrex.smp.ThymeController.java

@RequestMapping(value = "/onReturn", method = RequestMethod.POST)
public String onReturnelmo(@ModelAttribute ElmoData request, Model model,
        @CookieValue(value = "elmoSessionId") String sessionIdCookie,
        @CookieValue(value = "chosenNCP") String chosenNCP,
        //@CookieValue(value = "chosenCert") String chosenCert,
        HttpServletRequest httpRequest) throws Exception {
    String sessionId = request.getSessionId();
    String elmo = request.getElmo();

    Person person = (Person) context.getSession().getAttribute("shibPerson");

    if (person == null) {
        ShibbolethHeaderHandler headerHandler = new ShibbolethHeaderHandler(httpRequest);
        log.debug(headerHandler.stringifyHeader());
        person = headerHandler.generatePerson();
        context.getSession().setAttribute("shibPerson", person);
    }/*from ww  w . j  av a 2s .c  o  m*/

    String source = "SMP";
    String personalLogLine = generatePersonalLogLine(httpRequest, person, source);
    log.info(request.getReturnCode());
    if (!"NCP_OK".equalsIgnoreCase(request.getReturnCode())) {
        log.error("NCP not OK");
        if ("NCP_NO_RESULTS".equalsIgnoreCase(request.getReturnCode())) {
            model.addAttribute("message", "No courses found on NCP.");
            log.error("No courses found on NCP.");
        }
        if ("NCP_CANCEL".equalsIgnoreCase(request.getReturnCode())) {
            model.addAttribute("message", "User cancelled transfer on NCP.");
            log.error("User cancelled transfer on NCP.");
        }
        if ("NCP_ERROR".equalsIgnoreCase(request.getReturnCode())) {
            model.addAttribute("message", "Error on NCP.");
            log.error("Error on NCP.");
        }
        return abort(model);
    }
    log.info("NCP OK!");
    if (elmo == null || elmo.isEmpty()) {
        PersonalLogger.log(personalLogLine + "\tfailed");
        log.error("ELMO-xml empy or null.");
        return abort(model);
    }
    String ncpPubKey = this.getCertificate(chosenNCP);
    final String decodedXml;
    final boolean verifySignatureResult;
    try {
        final byte[] bytes = DatatypeConverter.parseBase64Binary(elmo);
        decodedXml = GzipUtil.gzipDecompress(bytes);
        verifySignatureResult = signatureVerifier.verifySignatureWithDecodedData(ncpPubKey, decodedXml,
                StandardCharsets.UTF_8);

        log.info("Verify signature result: {}", verifySignatureResult);
        log.info("providedSessionId: {}", sessionId);

        FiSmpApplication.verifySessionId(sessionId, sessionIdCookie);
    } catch (Exception e) {
        log.error("Session verification failed", e);
        model.addAttribute("error", "Session verification failed");
        PersonalLogger.log(personalLogLine + "\tfailed");
        return "error";
    }
    try {
        if (!verifySignatureResult) {
            log.error("NCP signature check failed");
            model.addAttribute("error", "NCP signature check failed");
            PersonalLogger.log(personalLogLine + "\tfailed");
            return "error";
        }
    } catch (Exception e) {
        log.error("NCP verification failed", e);
        model.addAttribute("error", "NCP verification failed");
        PersonalLogger.log(personalLogLine + "\tfailed");
        return "error";
    }

    log.info("Returned elmo XML " + decodedXml);
    context.getSession().setAttribute("elmoxmlstring", decodedXml);
    ElmoParser parser = ElmoParser.elmoParser(decodedXml);
    try {
        byte[] pdf = parser.getAttachedPDF();
        context.getSession().setAttribute("pdf", pdf);
    } catch (Exception e) {
        log.error("EMREX transcript missing.");
        model.addAttribute("error", "EMREX transcript missing.");
        PersonalLogger.log(personalLogLine + "\tfailed");
        return "error";
    }
    model.addAttribute("elmoXml", decodedXml);

    Document document;
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    //Get the DOM Builder
    DocumentBuilder builder;
    if (person != null) {
        List<VerifiedReport> results = new ArrayList<>();
        try {

            builder = factory.newDocumentBuilder();
            StringReader sr = new StringReader(decodedXml);
            final InputSource inputSource = new InputSource();
            inputSource.setEncoding(StandardCharsets.UTF_8.name());
            inputSource.setCharacterStream(sr);
            //person.setFirstName("test"); person.setLastName("user");
            //person.setHomeOrganizationName("test institution");
            //Load and Parse the XML document
            //document contains the complete XML as a Tree.
            document = builder.parse(inputSource);
            NodeList reports = document.getElementsByTagName("report");
            for (int i = 0; i < reports.getLength(); i++) {
                VerifiedReport vr = new VerifiedReport();
                Element report = (Element) reports.item(i);
                vr.setReport(nodeToString(report));
                Person elmoPerson = getUserFromElmoReport((Element) report.getParentNode());

                if (elmoPerson != null) {
                    VerificationReply verification = VerificationReply.verify(person, elmoPerson,
                            verificationThreshold);
                    log.info("Verification messages: " + verification.getMessages());
                    log.info("VerScore: " + verification.getScore());

                    vr.setVerification(verification);

                } else {
                    vr.addMessage("Elmo learner missing");
                    //TODO fix this
                }
                results.add(vr);
            }
            context.getSession().setAttribute("reports", results);
            model.addAttribute("reports", results);

        } catch (ParserConfigurationException | IOException | SAXException ex) {
            log.error("Error in report verification", ex);
            model.addAttribute("error", ex.getMessage());
            PersonalLogger.log(personalLogLine + "\tfailed");
            return "error";
        }
    } else {
        model.addAttribute("error", "HAKA login missing");
        PersonalLogger.log(personalLogLine + "\tfailed");
        return "error";
    }
    PersonalLogger.log(personalLogLine + "\tokay");
    return "review";
}

From source file:com.kibana.multitenancy.plugin.acl.DynamicACLFilter.java

private String getUser(RestRequest request) {

    //Sushant:Getting user in case of Basic Authentication
    String username = "";
    //Sushant:Scenario when user Authenticated at Proxy level itself
    String proxyAuthUser = (String) ObjectUtils.defaultIfNull(request.header(proxyUserHeader), "");
    //Sushant: Scenario when user Authenticated at Proxy level itself

    String basicAuthorizationHeader = StringUtils.defaultIfBlank(request.header("Authorization"), "");
    if (StringUtils.isNotEmpty(basicAuthorizationHeader)) {
        String decodedBasicHeader = new String(
                DatatypeConverter.parseBase64Binary(basicAuthorizationHeader.split(" ")[1]),
                StandardCharsets.US_ASCII);
        final String[] decodedBasicHeaderParts = decodedBasicHeader.split(":");
        username = decodedBasicHeaderParts[0];
        decodedBasicHeader = null;/*ww w  .  j  a  v a  2  s . c  om*/
        basicAuthorizationHeader = null;
        logger.debug("User '{}' is authenticated", username);
    }
    return username;

}

From source file:com.github.stephanarts.cas.ticket.registry.RegistryClient.java

/**
 * Get a ticket from the ticketregistry.
 *
 * @return Ticket Objects/*w  w w .  ja  va  2  s .  c  om*/
 *
 * @throws JSONRPCException Throws JSONRPCException containing any error.
 */
public final Collection<Ticket> getTickets() throws JSONRPCException {

    JSONObject params = new JSONObject();
    JSONObject result;
    JSONArray resultTickets;

    Ticket ticket;
    ArrayList<Ticket> tickets = new ArrayList<Ticket>();

    result = this.call("cas.getTickets", params);

    if (result.has("tickets")) {
        logger.debug("Number of Tickets: " + result.getJSONArray("tickets").length());
        resultTickets = result.getJSONArray("tickets");
        for (int i = 0; i < resultTickets.length(); ++i) {
            try {
                String serializedTicket = resultTickets.getString(i);
                ByteArrayInputStream bi = new ByteArrayInputStream(
                        DatatypeConverter.parseBase64Binary(serializedTicket));
                ObjectInputStream si = new ObjectInputStream(bi);

                ticket = (Ticket) si.readObject();

                tickets.add(ticket);
            } catch (final Exception e) {
                throw new JSONRPCException(-32501, "Could not decode Ticket");
            }
        }
    }

    return tickets;
}

From source file:gov.ca.cwds.rest.util.jni.CmsPKCompressor.java

public String compressBase64ToHex(String base64) throws IOException {
    return DatatypeConverter.printHexBinary(compressBytes(DatatypeConverter.parseBase64Binary(base64)))
            .toLowerCase();//from  w w  w .  java2 s .c  o  m
}

From source file:org.openmrs.module.muzimabiometrics.api.impl.MuzimaFingerprintServiceImpl.java

private NTemplate createTemplate(String fingerPrintTemplateString) {
    byte[] templateBuffer = DatatypeConverter.parseBase64Binary(fingerPrintTemplateString);//Base64.decode(fingerPrintTemplateString);
    return new NTemplate(new NBuffer(templateBuffer));
}

From source file:org.openiot.gsn.http.rest.RestStreamHanlder.java

/**
 *
 * @param request//from  ww w  . j a v  a2 s. c om
 * @return [username,password] or null if unable to retrieve these pieces of information.
 */
private String[] parseAuthorizationHeader(HttpServletRequest request) {
    // Get username/password from the Authorization header
    String authHeader = request.getHeader("Authorization"); // form: BASIC d2VibWFzdGVyOnRyeTJndWVTUw
    if (authHeader != null) {
        String[] ahs = authHeader.split(" ");
        if (ahs.length == 2) {
            String b64UsernamPassword = ahs[1]; // we get: d2VibWFzdGVyOnRyeTJndWVTUw
            String userPass = new String(DatatypeConverter.parseBase64Binary(b64UsernamPassword)); // form: username:passsword
            String[] ups;
            if ((ups = userPass.split(":")).length == 2) {
                return new String[] { ups[0], // username
                        ups[1] // password
                };
            }
        }
    }
    return null;
}

From source file:fr.pasteque.pos.forms.DataLogicSystem.java

/** Load resource from server */
private final byte[] loadResource(String name) throws BasicException {
    ServerLoader loader = new ServerLoader();
    byte[] resource;
    // Check resource from server
    try {//from  w  ww . ja va  2s.c om
        ServerLoader.Response r = loader.read("ResourcesAPI", "get", "label", name);
        if (r.getStatus().equals(ServerLoader.Response.STATUS_OK)) {
            JSONObject o = r.getObjContent();
            String strRes = o.getString("content");
            if (o.getInt("type") == 0) {
                resource = strRes.getBytes();
            } else {
                resource = DatatypeConverter.parseBase64Binary(strRes);
            }
        } else {
            return null;
        }
    } catch (Exception e) {
        e.printStackTrace();
        resource = null;
    }
    return resource;
}

From source file:ddf.catalog.transformer.input.geojson.GeoJsonInputTransformer.java

private Serializable convertValue(Object value, AttributeFormat format) throws ParseException {
    if (value == null) {
        return null;
    }/*from   ww w  .j av  a 2 s.com*/

    switch (format) {
    case BINARY:
        return DatatypeConverter.parseBase64Binary(value.toString());
    case DATE:
        SimpleDateFormat dateFormat = new SimpleDateFormat(ISO_8601_DATE_FORMAT);
        dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        return dateFormat.parse(value.toString());
    case GEOMETRY:
    case STRING:
    case XML:
        return value.toString();
    case BOOLEAN:
        return Boolean.parseBoolean(value.toString());
    case SHORT:
        return Short.parseShort(value.toString());
    case INTEGER:
        return Integer.parseInt(value.toString());
    case LONG:
        return Long.parseLong(value.toString());
    case FLOAT:
        return Float.parseFloat(value.toString());
    case DOUBLE:
        return Double.parseDouble(value.toString());
    default:
        return null;
    }
}

From source file:com.cesnet.pki.DigicertConnector.java

/**
 * downloads and decodes given certificate, updates HashMap of results
 * /*  w ww.ja  v a  2 s  . c  om*/
 * @param certificateId certificate id
 * @param parentId id of parent organization
 * @param apiKey api key to access downloading certificate
 * @throws MalformedURLException if no protocol is specified, or an unknown protocol is found, or spec is null
 * @throws ProtocolException if the method cannot be reset or if the requested method isn't valid for HTTP
 * @throws IllegalArgumentException if Input-buffer size is less or equal zero
 * @throws UnsupportedEncodingException if the named charset is not supported
 * @throws IOException if an I/O error occurs while creating the input stream
 * @throws UnknownServiceException if the protocol does not support input
 * @throws ParseException if the beginning of the specified string cannot be parsed
 * @throws CMSException master exception type for all exceptions caused in OpenCms
 * @throws CertificateException this exception indicates one of a variety of certificate problems
 */
private void decodeCertificate(int orderId, int certificateId, int parentId, String parentName, String apiKey)
        throws MalformedURLException, ProtocolException, IllegalArgumentException, UnsupportedEncodingException,
        IOException, UnknownServiceException, CMSException, ParseException, CertificateException,
        JSONException {

    String certificate = callDigicert("certificate/" + certificateId + "/download/format/p7b", apiKey);

    if (certificate == null) {
        System.out.println("certificate is null");
        System.out.println("orderId:\t" + orderId + "\tcertificateId:\t" + certificateId + "\tparentId:\t"
                + parentId + "\tparentName:\t" + parentName + "\tApiKey:\t" + apiKey);
    } else {

        byte[] source = DatatypeConverter
                .parseBase64Binary(new String(certificate.getBytes(Charset.forName("UTF-8"))));
        CMSSignedData signature = new CMSSignedData(source);
        Store cs = signature.getCertificates();

        ArrayList<X509CertificateHolder> listCertData = new ArrayList(cs.getMatches(null));

        // we want only first certificate
        X509Certificate cert = new JcaX509CertificateConverter().getCertificate(listCertData.get(0));

        CertificateData data = new CertificateData(cert, orderId, parentId, parentName);

        // store found certificate in HashMap
        cache.put(orderId, data);

        if (isCertValidAtDay(cert, referenceDate)) {
            int value = 0;
            if (parentId_has_numOfCerts.get(parentId) != null) {
                value = parentId_has_numOfCerts.get(parentId);
            }
            parentId_has_numOfCerts.put(parentId, value + 1);
        }
    }
}