Example usage for javax.xml.datatype DatatypeFactory newInstance

List of usage examples for javax.xml.datatype DatatypeFactory newInstance

Introduction

In this page you can find the example usage for javax.xml.datatype DatatypeFactory newInstance.

Prototype

public static DatatypeFactory newInstance() throws DatatypeConfigurationException 

Source Link

Document

Obtain a new instance of a DatatypeFactory .

Usage

From source file:ee.ria.xroad.confproxy.commandline.ConfProxyUtilGenerateAnchor.java

/**
 * Generates an achor xml file based on the provided proxy configuration
 * properties and writes it to the provided output stream.
 * @param conf configuration proxy properties instance
 * @param instanceIdentifier instance identifier of the resulting anchor
 * @param out the output stream for writing the generated xml
 * @throws Exception if xml generation fails
 *//*from ww  w  .  j  a v a 2  s .  co m*/
private void generateAnchorXml(final ConfProxyProperties conf, final String instanceIdentifier,
        final OutputStream out) throws Exception {
    JAXBContext jaxbCtx = JAXBContext.newInstance(ObjectFactory.class);
    Marshaller marshaller = jaxbCtx.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

    ObjectFactory factory = new ObjectFactory();
    ConfigurationSourceType sourceType = factory.createConfigurationSourceType();
    sourceType.setDownloadURL(conf.getConfigurationProxyURL() + "/" + OutputBuilder.SIGNED_DIRECTORY_NAME);
    for (byte[] cert : conf.getVerificationCerts()) {
        sourceType.getVerificationCert().add(cert);
    }
    ConfigurationAnchorType anchorType = factory.createConfigurationAnchorType();
    anchorType.setInstanceIdentifier(instanceIdentifier);
    GregorianCalendar gcal = new GregorianCalendar();
    gcal.setTimeZone(TimeZone.getTimeZone("UTC"));
    XMLGregorianCalendar xgcal = DatatypeFactory.newInstance().newXMLGregorianCalendar(gcal);
    anchorType.setGeneratedAt(xgcal);
    anchorType.getSource().add(sourceType);
    JAXBElement<ConfigurationAnchorType> root = factory.createConfigurationAnchor(anchorType);

    marshaller.marshal(root, out);
}

From source file:in.gov.uidai.core.aua.client.KYCClient.java

public String kycTrans(Auth auth, String kua, boolean isRcReceived, String ksaLicense, Uses usesElement,
        String customXML) {//from w w  w  .j a v a2 s .c o m
    setAsaLicenseKey(ksaLicense);

    String raType = "";
    if (usesElement.getBt().contains("FIR") || usesElement.getBt().contains("FMR")) {
        raType += "F";
    }
    if (usesElement.getBt().contains("IIR")) {
        raType += "I";
    }
    if (usesElement.getOtp().toString().contains("Y")) {
        raType += "O";
    }
    if (raType.isEmpty())
        raType = "F";

    String rcType = "N";
    if (isRcReceived) {
        rcType = "Y";
    }

    try {
        String signedXML = generateSignedAuthXML(auth);
        byte[] codedAuthXML = signedXML.getBytes();
        Kyc kyc = new Kyc();
        kyc.setRa(RaType.valueOf(raType));
        kyc.setRc(YesNoType.valueOf(rcType));
        kyc.setMec(YesNoType.valueOf(mecType));
        kyc.setLr(YesNoType.valueOf(lrType));
        kyc.setDe(YesNoType.valueOf(deType));

        //         kyc.setVer("1.0");
        kyc.setVer(ver);

        if (ver.equals("2.0")) {
            kyc.setPfr(YesNoType.valueOf(pfr));

        }
        XMLGregorianCalendar calendar = DatatypeFactory.newInstance()
                .newXMLGregorianCalendar((GregorianCalendar) GregorianCalendar.getInstance());
        //kyc.setTs(PidCreator.pidTs.getTs());
        //System.out.println("KYC"+PidCreator.pidTs.getTs());
        //if(PidCreator.pidTs != null ){
        if (PidCreator.threadLocalPidTs.get() != null) {
            //kyc.setTs(PidCreator.pidTs.getTs());
            kyc.setTs(PidCreator.threadLocalPidTs.get().getTs());
        } else {
            SimpleDateFormat dateFormat = new SimpleDateFormat(ISO_8601_DATE_FORMAT);
            //Date convertedDate = dateFormat.parse(PidCreator.pidBuilderTs.getTs());
            Date convertedDate = dateFormat.parse(PidCreator.threadLocalPidBuilderTs.get().getTs());
            //System.out.println("convertedDate.toString()== "+convertedDate.toString());
            GregorianCalendar gc = (GregorianCalendar) GregorianCalendar.getInstance();
            gc.setTime(convertedDate);
            kyc.setTs(DatatypeFactory.newInstance().newXMLGregorianCalendar(gc));
        }
        kyc.setRad(codedAuthXML);

        String kycSignedXML;
        if (StringUtils.isBlank(System.getenv("USE_CUSTOM_KYC_XML"))) {
            kycSignedXML = generateSignedKycXML(kyc);
            System.out.println(kycSignedXML);
        } else {
            String customKYCXML = customXML;
            Document kycDOM = XMLUtilities.getDomObject(customKYCXML);
            XMLUtilities.addRarNode(kycDOM, codedAuthXML);
            String updatedCustomKYCXML = XMLUtilities.getString(kycDOM);
            System.out.println(updatedCustomKYCXML);
            kycSignedXML = generateSignedKycXML(updatedCustomKYCXML);
        }

        String uriString = kycServerURI.toString() + (kycServerURI.toString().endsWith("/") ? "" : "/") + kua
                + "/" + auth.getUid().charAt(0) + "/" + auth.getUid().charAt(1) + SLASH + ksaLicense;

        String responseXML = HttpClientHelper.postAndGetResponse(uriString, kycSignedXML);

        System.out.println("\nresp \n" + responseXML);

        Resp resp1 = (Resp) XMLUtilities.parseXML(Resp.class, responseXML);
        if (resp1.getStatus().equalsIgnoreCase("-1")) {
            if (resp1.getKycRes().length == 0) {
                throw new Exception("KYC response xml retured a status of -1, no content found.");
            }
        }
        byte[] kycRes = resp1.getKycRes();
        String xml = "";
        if (resp1.getStatus().equalsIgnoreCase("0")) {
            xml = new String(dataDecryptor.decrypt(kycRes));
            //            xml = new String(kycRes); // if private key not present 
        } else {
            xml = new String(kycRes);
        }
        System.out.println(" \n xml \n  " + xml);
        if (StringUtils.isBlank(System.getenv("SKIP_RESP_SIG_VERIFY"))) {
            if (dataDecryptor.verify(xml)) {
                return xml;
            } else {
                throw new Exception("KYC response xml signature verification failed.");
            }
        } else {
            return xml;
        }

    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Exception during KYC transaction " + e.getMessage(), e);
    }
}

From source file:Index.RegisterUserServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  ww  w  . j av a 2 s  . com*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    PrintWriter out = response.getWriter();

    try {
        String errorMessage;

        if (request.getParameter("user") != null && request.getParameter("password") != null
                && request.getParameter("email") != null && request.getParameter("passwordConfirmation") != null
                && request.getParameter("name") != null && request.getParameter("address") != null
                && request.getParameter("lastName") != null && request.getParameter("dateBorn") != null) {

            String user = request.getParameter("user");
            String password = request.getParameter("password");
            String passwordConfirmation = request.getParameter("passwordConfirmation");
            String email = request.getParameter("email");
            String name = request.getParameter("name");
            String address = request.getParameter("address");
            String lastName = request.getParameter("lastName");
            String dateBorn = request.getParameter("dateBorn");

            if (user.equalsIgnoreCase("") || password.equalsIgnoreCase("")
                    || passwordConfirmation.equalsIgnoreCase("") || email.equalsIgnoreCase("")
                    || name.equalsIgnoreCase("")) {

                errorMessage = "Ingrese todos los datos.";
                request.setAttribute("error", errorMessage);
                request.setAttribute("funcionalidad", "Registro");

                request.getRequestDispatcher("/Login.jsp").forward(request, response);
            } else {
                if (password.equals(passwordConfirmation)) {
                    QuickOrderWebService webService = new QuickOrderWebService();
                    ControllerInterface port = webService.getQuickOrderWebServicePort();
                    webservice.Cliente listCli = port.infoCliente(user);

                    if (listCli != null && listCli.getApellido() != null) {

                        errorMessage = "Ya existe un usuario con ese nickname";
                        request.setAttribute("error", errorMessage);
                        request.setAttribute("funcionalidad", "Registro");
                        request.getRequestDispatcher("/Login.jsp").forward(request, response);
                    } else {
                        webservice.Cliente usr = new webservice.Cliente();
                        usr.setNickname(user);
                        usr.setNombre(name);
                        usr.setEmail(email);
                        usr.setDireccion(address);
                        usr.setImagen(user + ".jpg");
                        usr.setApellido(lastName);

                        //PORCEDIMIENTO PARA ENCRIPTAR LA CLAVE INGRESADA CUANDO INICIA SESIN UN USUARIO.
                        String encriptMD5 = DigestUtils.md5Hex(password);
                        password = "md5:" + encriptMD5;

                        usr.setPassword(password);
                        Date dt;
                        try {
                            dt = new Date(dateBorn);
                        } catch (Exception ex) {
                            dt = Date.from(Instant.now());
                        }

                        GregorianCalendar c = new GregorianCalendar();
                        c.setTime(dt);
                        XMLGregorianCalendar date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
                        usr.setFechaNac(date2);

                        String result = port.registrarCliente(usr);

                        if (result.equals("")) {
                            request.setAttribute("error", null);
                            request.setAttribute("funcionalidad", "Imagen");
                            request.getSession().setAttribute("userName", user);
                        } else {
                            request.setAttribute("error", "Surgio un error al registrar el cliente");
                            request.setAttribute("funcionalidad", "Registro");
                        }
                        request.getRequestDispatcher("/Login.jsp").forward(request, response);
                    }
                } else {
                    errorMessage = "Las contraseas no cohinciden";
                    request.setAttribute("error", errorMessage);
                    request.setAttribute("funcionalidad", "Registro");
                    request.getRequestDispatcher("/Login.jsp").forward(request, response);
                }

            }
        } else {
            errorMessage = "Error al realizar el registro.";
            request.setAttribute("error", errorMessage);
            request.setAttribute("funcionalidad", "Registro");
            request.getRequestDispatcher("/Login.jsp").forward(request, response);
        }
    } catch (Exception ex) {
        out.print("Error en proceso de registro: " + ex.getMessage());
    } finally {
        out.close();
    }
}

From source file:it.cnr.icar.eric.server.persistence.rdb.RegistryDAO.java

protected void loadObject(Object obj, ResultSet rs) throws RegistryException {
    try {/*from   ww  w.jav  a  2  s  .  c  o m*/
        if (!(obj instanceof RegistryType)) {
            throw new RegistryException(ServerResourceBundle.getInstance()
                    .getString("message.RegistryTypeExpected", new Object[] { obj }));
        }

        RegistryType ebRegistryType = (RegistryType) obj;
        super.loadObject(obj, rs);

        String catalogingSyncLatencyString = rs.getString("catalogingSyncLatency");
        Duration catalogingSyncLatency = DatatypeFactory.newInstance().newDuration(catalogingSyncLatencyString);
        ebRegistryType.setCatalogingLatency(catalogingSyncLatency);

        String conformanceProfile = rs.getString("conformanceProfile");
        ebRegistryType.setConformanceProfile(conformanceProfile);

        String operator = rs.getString("operator");
        ebRegistryType.setOperator(operator);

        String replicationSyncLatencyString = rs.getString("replicationSyncLatency");
        Duration replicationSyncLatency = DatatypeFactory.newInstance()
                .newDuration(replicationSyncLatencyString);
        ebRegistryType.setReplicationSyncLatency(replicationSyncLatency);

        String specificationVersion = rs.getString("specificationVersion");
        ebRegistryType.setSpecificationVersion(specificationVersion);

    } catch (SQLException e) {
        log.error(ServerResourceBundle.getInstance().getString("message.CaughtException1"), e);
        throw new RegistryException(e);
    } catch (DatatypeConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:eu.prestoprime.p4gui.connection.AccessConnection.java

public static List<Event> getEvents(P4Service service, String id) {
    final String PREMIS_NS = "http://www.loc.gov/standards/premis/v1";

    DIP dip = AccessConnection.getDIP(service, id);
    NodeList eventNodes = ((Document) dip.getContent()).getDocumentElement().getElementsByTagNameNS(PREMIS_NS,
            "event");
    logger.debug("Found " + eventNodes.getLength() + " PREMIS events...");

    List<Event> events = new ArrayList<>();
    for (int i = 0; i < eventNodes.getLength(); i++) {
        Node eventNode = eventNodes.item(i);
        do {// w w w.j av a  2  s. com
            if (eventNode instanceof Element) {
                Node typeNode = ((Element) eventNode).getElementsByTagNameNS(PREMIS_NS, "eventType").item(0);
                Node dateTimeNode = ((Element) eventNode).getElementsByTagNameNS(PREMIS_NS, "eventDateTime")
                        .item(0);
                Node detailNode = ((Element) eventNode).getElementsByTagNameNS(PREMIS_NS, "eventDetail")
                        .item(0);

                String type = typeNode.getTextContent();
                Calendar dateTime;
                try {
                    dateTime = DatatypeFactory.newInstance()
                            .newXMLGregorianCalendar(dateTimeNode.getTextContent()).toGregorianCalendar();
                } catch (Exception e) {
                    dateTime = new GregorianCalendar();
                }
                String detail = detailNode.getTextContent();

                logger.debug("Found event " + type + "...");

                Event event = new Event(type, dateTime, detail);
                events.add(event);
            }
        } while ((eventNode = eventNode.getNextSibling()) != null);
    }
    return events;
}

From source file:eu.prestoprime.p4gui.connection.WorkflowConnection.java

public static JobList getMyJobs(P4Service service) {
    JobList jobList = new JobList();
    try {//from  ww  w  .  j a v a  2 s .  co  m
        String path = service.getURL() + "/wf/myjobs";
        P4HttpClient client = new P4HttpClient(service.getUserID());
        HttpRequestBase request = new HttpGet(path);
        HttpEntity entity = client.executeRequest(request).getEntity();
        if (entity != null) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
            String line;
            while ((line = reader.readLine()) != null) {
                String[] fields = line.split("\\t");
                jobList.addJob(jobList.new Job(fields[0], // jobID
                        StatusType.valueOf(fields[1].toUpperCase()), // status
                        fields[2], // wfID
                        fields[3].equals("") ? null
                                : DatatypeFactory.newInstance().newXMLGregorianCalendar(fields[3]), // startup
                        fields[4].equals("") ? 0L : Long.parseLong(fields[4]), // duration
                        Integer.parseInt(fields[5]), // totalSteps
                        Integer.parseInt(fields[6]), // lastCompletedStep
                        fields.length < 8 ? null : fields[7])); // lastCompletedService
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return jobList;
}

From source file:com.epam.catgenome.manager.externaldb.bindings.ExternalDBBindingTest.java

private Object createParam(Class type)
        throws IllegalAccessException, InvocationTargetException, InstantiationException {
    Object param;/*from   w  w w. ja  v a  2s .c  o m*/
    if (type == String.class) {
        param = "test";
    } else if (type == Integer.class || type == Integer.TYPE) {
        param = RandomUtils.nextInt();
    } else if (type == Long.class || type == Long.TYPE) {
        param = RandomUtils.nextLong();
    } else if (type == Float.class || type == Float.TYPE) {
        param = RandomUtils.nextFloat();
    } else if (type == Double.class || type == Double.TYPE) {
        param = RandomUtils.nextDouble();
    } else if (type == Boolean.class || type == Boolean.TYPE) {
        param = RandomUtils.nextBoolean();
    } else if (type == BigInteger.class) {
        param = new BigInteger(TEST_BIGINTEGER);
    } else if (type == List.class) {
        param = new ArrayList<>();
    } else if (type == XMLGregorianCalendar.class) {
        try {
            param = DatatypeFactory.newInstance().newXMLGregorianCalendar();
        } catch (DatatypeConfigurationException e) {
            throw new IllegalArgumentException(e.getMessage(), e);
        }
    } else {
        Constructor[] constructors = type.getConstructors();
        param = constructors[0].newInstance();
    }

    return param;
}

From source file:com.fusesource.example.camel.process.camel.ProcessorRouteBuilderTest.java

@Test
@DirtiesContext/*w  w w .  j  av  a2  s  .c  om*/
public void testDuplicates() throws Exception {
    context.start();

    DatatypeFactory dtf = DatatypeFactory.newInstance();

    output.setExpectedMessageCount(1);

    RecordType recordType = new RecordType();
    recordType.setId("1");
    recordType.setDate(dtf.newXMLGregorianCalendar(new GregorianCalendar()));
    recordType.setDescription("Record number: 1");

    trigger.sendBody(recordType);

    trigger.sendBody(recordType);

    output.assertIsSatisfied();
}

From source file:be.fedict.eid.tsl.TrustService.java

TrustService(TSPServiceType tspService) {
    this.tspService = tspService;
    this.objectFactory = new ObjectFactory();
    try {/*from  w ww.  j av  a2 s . co  m*/
        this.datatypeFactory = DatatypeFactory.newInstance();
    } catch (DatatypeConfigurationException e) {
        throw new RuntimeException("datatype config error: " + e.getMessage(), e);
    }
    this.eccObjectFactory = new be.fedict.eid.tsl.jaxb.ecc.ObjectFactory();
    this.xadesObjectFactory = new be.fedict.eid.tsl.jaxb.xades.ObjectFactory();
}

From source file:eu.europa.ec.fisheries.uvms.rules.service.bean.RulesMessageServiceBeanTest.java

@Before
@SneakyThrows/*from   w  ww .  j a  va 2  s.  co m*/
public void before() {

    SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");

    date = sdf.parse("31-08-1982 10:20:56");

    idType = new IDType();
    idType.setValue("value");
    idType.setSchemeID("schemeId");

    codeType = new CodeType();
    codeType.setValue("value");

    delimitedPeriod = new DelimitedPeriod();
    MeasureType durationMeasure = new MeasureType();
    durationMeasure.setUnitCode("unitCode");
    durationMeasure.setValue(new BigDecimal(10));
    delimitedPeriod.setDurationMeasure(durationMeasure);

    GregorianCalendar c = new GregorianCalendar();
    c.setTime(date);

    dateTimeType = new DateTimeType();
    dateTimeType.setDateTime(DatatypeFactory.newInstance().newXMLGregorianCalendar(c));
    delimitedPeriod.setStartDateTime(dateTimeType);
    delimitedPeriod.setEndDateTime(dateTimeType);

    faQueryParameterList = new ArrayList<>();
    FAQueryParameter faQueryParameter = new FAQueryParameter();
    faQueryParameter.setTypeCode(codeType);
    faQueryParameter.setValueCode(codeType);
    faQueryParameter.setValueDateTime(dateTimeType);
    faQueryParameter.setValueID(idType);
    faQueryParameterList.add(faQueryParameter);

    faQuery = new FAQuery();
    faQuery.setID(idType);
    faQuery.setSimpleFAQueryParameters(faQueryParameterList);
    faQuery.setSpecifiedDelimitedPeriod(delimitedPeriod);
    faQuery.setSubmittedDateTime(dateTimeType);
    faQuery.setTypeCode(codeType);

    FLUXFAQueryMessage message = new FLUXFAQueryMessage();
    message.setFAQuery(faQuery);

    fluxfaQueryMessage = new FLUXFAQueryMessage();
    fluxfaQueryMessage.setFAQuery(faQuery);

}