Example usage for javax.xml.datatype DatatypeConfigurationException printStackTrace

List of usage examples for javax.xml.datatype DatatypeConfigurationException printStackTrace

Introduction

In this page you can find the example usage for javax.xml.datatype DatatypeConfigurationException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:de.fischer.thotti.core.runner.NDRunner.java

private TestSuiteResult generatedTestResult(List<NDTestResult> resultList) throws RunnerException {
    if (null == resultList) {
        throw new NullPointerException();
    }/*from   w  w w . ja va  2s  .c o m*/

    DatatypeFactory datatypeFac = null;

    try {
        datatypeFac = DatatypeFactory.newInstance();
    } catch (DatatypeConfigurationException e) {
        throw new RunnerException("Failed to instanciate datatype factory.", e);
    }

    de.fischer.thotti.core.resources.ndtest.ObjectFactory factory = new de.fischer.thotti.core.resources.ndtest.ObjectFactory();

    de.fischer.thotti.core.resources.ndresult.ObjectFactory factory2 = new de.fischer.thotti.core.resources.ndresult.ObjectFactory();

    TestSuiteResult suiteResult = factory2.createTestSuiteResult();

    for (NDTestResult result : resultList) {
        NonDistributedTestResultType ndResult = factory2.createNonDistributedTestResultType();

        Duration execTime = datatypeFac.newDuration(result.getExecutionTime());
        XMLGregorianCalendar startTime = datatypeFac.newXMLGregorianCalendar(result.getStartTime());
        ndResult.setTestID(result.getTestId());
        ndResult.setExitCode(BigInteger.valueOf(result.getExitCode()));
        ndResult.setJvmArgsID(result.getJVMArgsID());
        ndResult.setJvmArgs(result.getJvmArgs());
        ndResult.setExecutionTimeMS(execTime);
        ndResult.setStartedAt(startTime);
        ndResult.setParamGrpID(result.getParamGrpID());

        try {
            ndResult.setMahoutVersion(org.apache.mahout.Version.versionFromResource());
        } catch (IOException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        }
        suiteResult.getNonDistributedTestResults().add(ndResult);
    }

    suiteResult.setUuid(generateResultUUID());
    return suiteResult;
}

From source file:org.fenixedu.treasury.services.integration.erp.ERPExporter.java

private Payment convertToSAFTPaymentDocument(SettlementNote document,
        Map<String, oecd.standardauditfile_tax.pt_1.Customer> baseCustomers,
        Map<String, oecd.standardauditfile_tax.pt_1.Product> productMap) {
    Payment payment = new Payment();

    // Find the Customer in BaseCustomers
    oecd.standardauditfile_tax.pt_1.Customer customer = null;

    if (baseCustomers.containsKey(document.getDebtAccount().getCustomer().getCode())) {
        customer = baseCustomers.get(document.getDebtAccount().getCustomer().getCode());
    } else {// w  ww.  j  a  v a2  s.  c o m
        // If not found, create a new one and add it to baseCustomers
        customer = convertCustomerToSAFTCustomer(document.getDebtAccount().getCustomer());
        baseCustomers.put(customer.getCustomerID(), customer);
    }

    // MovementDate
    DatatypeFactory dataTypeFactory;
    try {
        dataTypeFactory = DatatypeFactory.newInstance();
        DateTime documentDate = document.getDocumentDate();

        // SystemEntryDate
        payment.setSystemEntryDate(convertToXMLDateTime(dataTypeFactory, documentDate));

        payment.setTransactionDate(convertToXMLDateTime(dataTypeFactory, documentDate));

        // DocumentNumber
        payment.setPaymentRefNo(document.getUiDocumentNumber());

        // CustomerID
        payment.setCustomerID(document.getDebtAccount().getCustomer().getCode());

        // DocumentStatus
        /*
         * Deve ser preenchido com: ?N? ? Normal; Texto 1 ?T? ? Por conta de
         * terceiros; ?A? ? Documento anulado.
         */
        SourceDocuments.Payments.Payment.DocumentStatus status = new SourceDocuments.Payments.Payment.DocumentStatus();
        if (document.isAnnulled()) {
            status.setPaymentStatus("A");
        } else {
            status.setPaymentStatus("N");
        }
        status.setPaymentStatusDate(payment.getSystemEntryDate());
        // status.setReason("");
        // Utilizador responsvel pelo estado atual do docu-mento.
        status.setSourceID(document.getVersioningUpdatedBy());
        // Deve ser preenchido com:
        // 'P' - Documento produzido na aplicacao;
        if (Boolean.TRUE.equals(document.getDocumentNumberSeries().getSeries().getExternSeries())
                || Boolean.TRUE.equals(document.getDocumentNumberSeries().getSeries().getLegacy())) {
            status.setSourcePayment(SAFTPTSourcePayment.I);
        } else {
            status.setSourcePayment(SAFTPTSourcePayment.P);
        }

        payment.setDocumentStatus(status);

        //Check if is Rehimbursement/Payment
        if (Constants.isPositive(document.getTotalPayedAmount())) {
            //PaymentMethods
            for (PaymentEntry paymentEntry : document.getPaymentEntriesSet()) {
                PaymentMethod method = new PaymentMethod();
                method.setPaymentAmount(paymentEntry.getPayedAmount().setScale(2, RoundingMode.HALF_EVEN));
                method.setPaymentDate(payment.getTransactionDate());
                method.setPaymentMechanism(convertToSAFTPaymentMechanism(paymentEntry.getPaymentMethod()));
                payment.getPaymentMethod().add(method);
            }
            payment.setSettlementType(SAFTPTSettlementType.NL);
        } else if (Constants.isPositive(document.getTotalReimbursementAmount())) {
            //Reimbursments
            for (ReimbursementEntry reimbursmentEntry : document.getReimbursementEntriesSet()) {
                PaymentMethod method = new PaymentMethod();
                method.setPaymentAmount(
                        reimbursmentEntry.getReimbursedAmount().setScale(2, RoundingMode.HALF_EVEN));
                method.setPaymentDate(payment.getTransactionDate());
                method.setPaymentMechanism(convertToSAFTPaymentMechanism(reimbursmentEntry.getPaymentMethod()));
                payment.getPaymentMethod().add(method);
                payment.setSettlementType(SAFTPTSettlementType.NR);
            }
        } else {
            payment.setSettlementType(SAFTPTSettlementType.NN);
        }

        payment.setSourceID(document.getVersioningCreator());

        // DocumentTotals
        SourceDocuments.Payments.Payment.DocumentTotals docTotals = new SourceDocuments.Payments.Payment.DocumentTotals();

        //Lines
        BigInteger i = BigInteger.ONE;
        for (SettlementEntry settlementEntry : document.getSettlemetEntriesSet()) {
            SourceDocuments.Payments.Payment.Line line = new SourceDocuments.Payments.Payment.Line();
            line.setLineNumber(i);
            //SourceDocument
            SourceDocumentID sourceDocument = new SourceDocumentID();
            sourceDocument.setLineNumber(BigInteger.valueOf(settlementEntry.getInvoiceEntry().getEntryOrder()));
            sourceDocument.setOriginatingON(
                    settlementEntry.getInvoiceEntry().getFinantialDocument().getUiDocumentNumber());
            sourceDocument.setInvoiceDate(convertToXMLDateTime(dataTypeFactory,
                    settlementEntry.getInvoiceEntry().getFinantialDocument().getDocumentDate()));
            sourceDocument.setDescription(settlementEntry.getDescription());
            line.getSourceDocumentID().add(sourceDocument);
            //SettlementAmount
            line.setSettlementAmount(BigDecimal.ZERO);
            if (settlementEntry.getInvoiceEntry().isDebitNoteEntry()) {
                line.setDebitAmount(settlementEntry.getTotalAmount());
            } else if (settlementEntry.getInvoiceEntry().isCreditNoteEntry()) {
                line.setCreditAmount(settlementEntry.getTotalAmount());
            }
            payment.getLine().add(line);
            i = i.add(BigInteger.ONE);
        }
        docTotals.setGrossTotal(document.getTotalAmount().setScale(2, RoundingMode.HALF_EVEN));
        docTotals.setNetTotal(document.getTotalAmount().setScale(2, RoundingMode.HALF_EVEN));
        docTotals.setTaxPayable(BigDecimal.ZERO.setScale(2, RoundingMode.HALF_EVEN));
        payment.setDocumentTotals(docTotals);

        // Period
        /*
         * Per?odo contabil?stico (Period) . . . . . . . . . . Deve ser
         * indicado o n?mero do m?s do per?odo de tributa??o, de ?1? a ?12?,
         * contado desde a data do in?cio. Pode ainda ser preenchido com
         * ?13?, ?14?, ?15? ou ?16? para movimentos efectuados no ?ltimo m?s
         * do per?odo de tributa??o, relacionados com o apuramento do
         * resultado. Ex.: movimentos de apuramentos de invent?rios,
         * deprecia??es, ajustamentos ou apuramentos de resultados.
         */
        payment.setPeriod(document.getDocumentDate().getMonthOfYear());

        // SourceID
        /*
         * C?digo do utilizador que registou o movimento (SourceID).
         */
        payment.setSourceID(document.getVersioningCreator());

    } catch (DatatypeConfigurationException e) {

        e.printStackTrace();
    }

    return payment;
}

From source file:org.fenixedu.treasury.services.integration.erp.ERPExporter.java

private WorkDocument convertToSAFTWorkDocument(Invoice document,
        Map<String, oecd.standardauditfile_tax.pt_1.Customer> baseCustomers,
        Map<String, oecd.standardauditfile_tax.pt_1.Product> baseProducts) {
    WorkDocument workDocument = new WorkDocument();

    // Find the Customer in BaseCustomers
    oecd.standardauditfile_tax.pt_1.Customer customer = null;

    if (baseCustomers.containsKey(document.getDebtAccount().getCustomer().getCode())) {
        customer = baseCustomers.get(document.getDebtAccount().getCustomer().getCode());
    } else {//www  . j  a v a2s .  c  o  m
        // If not found, create a new one and add it to baseCustomers
        customer = convertCustomerToSAFTCustomer(document.getDebtAccount().getCustomer());
        baseCustomers.put(customer.getCustomerID(), customer);
    }

    //check the PayorDebtAccount
    if (document.getPayorDebtAccount() != null) {
        if (baseCustomers.containsKey(document.getPayorDebtAccount().getCustomer().getCode())) {
            //do nothing
        } else {
            // If not found, create a new one and add it to baseCustomers
            oecd.standardauditfile_tax.pt_1.Customer payorCustomer = convertCustomerToSAFTCustomer(
                    document.getPayorDebtAccount().getCustomer());
            baseCustomers.put(payorCustomer.getCustomerID(), payorCustomer);
        }
    }

    // MovementDate
    DatatypeFactory dataTypeFactory;
    try {
        dataTypeFactory = DatatypeFactory.newInstance();
        DateTime documentDate = document.getDocumentDate();

        // SystemEntryDate
        workDocument.setSystemEntryDate(convertToXMLDateTime(dataTypeFactory, documentDate));

        workDocument.setWorkDate(convertToXMLDateTime(dataTypeFactory, documentDate));

        // DocumentNumber
        workDocument.setDocumentNumber(document.getUiDocumentNumber());

        // CustomerID
        workDocument.setCustomerID(document.getDebtAccount().getCustomer().getCode());

        //PayorID
        if (document.getPayorDebtAccount() != null) {
            workDocument.setPayorCustomerID(document.getPayorDebtAccount().getCustomer().getCode());
        }

        // DocumentStatus
        /*
         * Deve ser preenchido com: ?N? ? Normal; Texto 1 ?T? ? Por conta de
         * terceiros; ?A? ? Documento anulado.
         */
        SourceDocuments.WorkingDocuments.WorkDocument.DocumentStatus status = new SourceDocuments.WorkingDocuments.WorkDocument.DocumentStatus();
        if (document.isAnnulled()) {
            status.setWorkStatus("A");
        } else {
            status.setWorkStatus("N");
        }

        status.setWorkStatusDate(workDocument.getSystemEntryDate());
        // status.setReason("");
        // Utilizador responsvel pelo estado atual do docu-mento.
        status.setSourceID(document.getVersioningUpdatedBy());
        // Deve ser preenchido com:
        // 'P' - Documento produzido na aplicacao;
        if (Boolean.TRUE.equals(document.getDocumentNumberSeries().getSeries().getExternSeries())) {
            status.setSourceBilling(SAFTPTSourceBilling.I);
        } else {
            status.setSourceBilling(SAFTPTSourceBilling.P);
        }

        workDocument.setDocumentStatus(status);

        // DocumentTotals
        SourceDocuments.WorkingDocuments.WorkDocument.DocumentTotals docTotals = new SourceDocuments.WorkingDocuments.WorkDocument.DocumentTotals();
        docTotals.setGrossTotal(document.getTotalAmount().setScale(2, RoundingMode.HALF_EVEN));
        docTotals.setNetTotal(document.getTotalNetAmount().setScale(2, RoundingMode.HALF_EVEN));
        docTotals.setTaxPayable(document.getTotalAmount().subtract(document.getTotalNetAmount()).setScale(2,
                RoundingMode.HALF_EVEN));
        workDocument.setDocumentTotals(docTotals);

        // WorkType
        /*
         * Deve ser preenchido com: Texto 2 "DC"  Documentos emitidos que
         * sejam suscetiveis de apresentacao ao cliente para conferencia de
         * entrega de mercadorias ou da prestacao de servicos. "FC"  Fatura
         * de consignacao nos termos do artigo 38 do codigo do IVA.
         */
        workDocument.setWorkType("DC");

        // Period
        /*
         * Per?odo contabil?stico (Period) . . . . . . . . . . Deve ser
         * indicado o n?mero do m?s do per?odo de tributa??o, de ?1? a ?12?,
         * contado desde a data do in?cio. Pode ainda ser preenchido com
         * ?13?, ?14?, ?15? ou ?16? para movimentos efectuados no ?ltimo m?s
         * do per?odo de tributa??o, relacionados com o apuramento do
         * resultado. Ex.: movimentos de apuramentos de invent?rios,
         * deprecia??es, ajustamentos ou apuramentos de resultados.
         */
        workDocument.setPeriod(document.getDocumentDate().getMonthOfYear());

        // SourceID
        /*
         * C?digo do utilizador que registou o movimento (SourceID).
         */
        workDocument.setSourceID(document.getVersioningCreator());

    } catch (DatatypeConfigurationException e) {

        e.printStackTrace();
    }

    List<oecd.standardauditfile_tax.pt_1.SourceDocuments.WorkingDocuments.WorkDocument.Line> productLines = workDocument
            .getLine();

    // Process individual
    BigInteger i = BigInteger.ONE;
    for (FinantialDocumentEntry docLine : document.getFinantialDocumentEntriesSet()) {
        InvoiceEntry orderNoteLine = (InvoiceEntry) docLine;
        oecd.standardauditfile_tax.pt_1.SourceDocuments.WorkingDocuments.WorkDocument.Line line = convertToSAFTWorkDocumentLine(
                orderNoteLine, baseProducts);

        // LineNumber
        line.setLineNumber(i);

        // Add to productLines
        i = i.add(BigInteger.ONE);
        productLines.add(line);
    }

    return workDocument;
}

From source file:org.fenixedu.treasury.services.integration.erp.ERPExporter.java

private oecd.standardauditfile_tax.pt_1.SourceDocuments.WorkingDocuments.WorkDocument.Line convertToSAFTWorkDocumentLine(
        InvoiceEntry entry, Map<String, oecd.standardauditfile_tax.pt_1.Product> baseProducts) {
    oecd.standardauditfile_tax.pt_1.Product currentProduct = null;

    Product product = entry.getProduct();

    if (product.getCode() != null && baseProducts.containsKey(product.getCode())) {
        currentProduct = baseProducts.get(product.getCode());
    } else {//from www. j  a  v  a 2s  . c om
        currentProduct = convertProductToSAFTProduct(product);
        baseProducts.put(currentProduct.getProductCode(), currentProduct);
    }
    XMLGregorianCalendar documentDateCalendar = null;
    try {
        DatatypeFactory dataTypeFactory = DatatypeFactory.newInstance();
        DateTime documentDate = entry.getFinantialDocument().getDocumentDate();
        documentDateCalendar = convertToXMLDateTime(dataTypeFactory, documentDate);
    } catch (DatatypeConfigurationException e) {

        e.printStackTrace();
    }

    oecd.standardauditfile_tax.pt_1.SourceDocuments.WorkingDocuments.WorkDocument.Line line = new oecd.standardauditfile_tax.pt_1.SourceDocuments.WorkingDocuments.WorkDocument.Line();

    if (entry.isCreditNoteEntry()) {
        line.setCreditAmount(entry.getAmount().setScale(2, RoundingMode.HALF_EVEN));
    } else if (entry.isDebitNoteEntry()) {
        line.setDebitAmount(entry.getAmount().setScale(2, RoundingMode.HALF_EVEN));
    }

    // Description
    line.setDescription(entry.getDescription());
    List<OrderReferences> orderReferences = line.getOrderReferences();

    //Add the references on the document creditEntries <-> debitEntries
    if (entry.isCreditNoteEntry()) {
        CreditEntry creditEntry = (CreditEntry) entry;
        if (creditEntry.getDebitEntry() != null) {
            OrderReferences reference = new OrderReferences();
            reference
                    .setOriginatingON(creditEntry.getDebitEntry().getFinantialDocument().getUiDocumentNumber());
            reference.setOrderDate(documentDateCalendar);
            orderReferences.add(reference);
        }

    } else if (entry.isDebitNoteEntry()) {
        //            DebitEntry debitEntry = (DebitEntry) entry;
        //            for (CreditEntry creditEntry : debitEntry.getCreditEntriesSet()) {
        //                OrderReferences reference = new OrderReferences();
        //                reference.setOriginatingON(creditEntry.getFinantialDocument().getUiDocumentNumber());
        //                reference.setOrderDate(documentDateCalendar);
        //                orderReferences.add(reference);
        //            }
    }

    // ProductCode
    line.setProductCode(currentProduct.getProductCode());

    // ProductDescription
    line.setProductDescription(currentProduct.getProductDescription());

    // Quantity
    line.setQuantity(entry.getQuantity());

    // SettlementAmount
    line.setSettlementAmount(BigDecimal.ZERO);

    // Tax
    line.setTax(getSAFTWorkingDocumentsTax(product, entry.getVat()));

    line.setTaxPointDate(documentDateCalendar);

    // TaxExemptionReason
    /*
     * Motivo da isen??o de imposto (TaxExemptionReason). Campo de
     * preenchimento obrigat?rio, quando os campos percentagem da taxa de
     * imposto (TaxPercentage) ou montante do imposto (TaxAmount) s?o iguais
     * a zero. Deve ser referido o preceito legal aplic?vel. . . . . . . . .
     * . Texto 60
     */
    if (line.getTax().getTaxPercentage() == BigDecimal.ZERO) {
        Vat vat = entry.getVat();

        if (vat.getVatExemptionReason() != null) {
            line.setTaxExemptionReason(
                    vat.getVatExemptionReason().getCode() + "-" + vat.getVatExemptionReason().getName());
        } else {
            // HACK : DEFAULT
            // line.setTaxExemptionReason(VatExemptionReason.M1().getCode()
            // + "-" + VatExemptionReason.M1().getDescription());
        }
    }

    // UnitOfMeasure
    line.setUnitOfMeasure(product.getUnitOfMeasure().getContent());
    // UnitPrice
    line.setUnitPrice(entry.getAmount().setScale(2, RoundingMode.HALF_EVEN));

    return line;
}

From source file:org.fenixedu.treasury.services.integration.erp.ERPExporter.java

private Header createSAFTHeader(DateTime startDate, DateTime endDate, FinantialInstitution finantialInstitution,
        String auditVersion) {/*  ww w . j a  v  a 2  s  . co  m*/

    Header header = new Header();
    DatatypeFactory dataTypeFactory;
    try {

        dataTypeFactory = DatatypeFactory.newInstance();

        // AuditFileVersion
        header.setAuditFileVersion(auditVersion);

        // BusinessName - Nome da Empresa
        header.setBusinessName(finantialInstitution.getCompanyName());
        header.setCompanyName(finantialInstitution.getName());

        // CompanyAddress
        AddressStructurePT companyAddress = null;
        //TODOJN Locale por resolver
        companyAddress = convertAddressToAddressPT(finantialInstitution.getAddress(),
                finantialInstitution.getZipCode(),
                finantialInstitution.getMunicipality() != null
                        ? finantialInstitution.getMunicipality().getLocalizedName(new Locale("pt"))
                        : "---",
                finantialInstitution.getAddress());
        header.setCompanyAddress(companyAddress);

        // CompanyID
        /*
         * Obtem -se pela concatena??o da conservat?ria do registo comercial
         * com o n?mero do registo comercial, separados pelo car?cter
         * espa?o. Nos casos em que n?o existe o registo comercial, deve ser
         * indicado o NIF.
         */
        header.setCompanyID(finantialInstitution.getComercialRegistrationCode());

        // CurrencyCode
        /*
         * 1.11 * C?digo de moeda (CurrencyCode) . . . . . . . Preencher com
         * ?EUR?
         */
        header.setCurrencyCode(finantialInstitution.getCurrency().getCode());

        // DateCreated
        DateTime now = new DateTime();
        header.setDateCreated(convertToXMLDateTime(dataTypeFactory, now));

        // Email
        // header.setEmail(StringUtils.EMPTY);

        // EndDate
        header.setEndDate(convertToXMLDateTime(dataTypeFactory, endDate));

        // Fax
        // header.setFax(StringUtils.EMPTY);

        // FiscalYear
        /*
         * Utilizar as regras do c?digo do IRC, no caso de per?odos
         * contabil?sticos n?o coincidentes com o ano civil. (Ex: per?odo de
         * tributa??o de 01 -10 -2008 a 30 -09 -2009 corresponde FiscalYear
         * 2008). Inteiro 4
         */
        header.setFiscalYear(endDate.getYear());

        // Ir obter a data do ?ltimo
        // documento(por causa de submeter em janeiro, documentos de
        // dezembro)

        // HeaderComment
        // header.setHeaderComment(org.apache.commons.lang.StringUtils.EMPTY);

        // ProductCompanyTaxID
        // Preencher com o NIF da entidade produtora do software
        header.setProductCompanyTaxID(SaftConfig.PRODUCT_COMPANY_TAX_ID());

        // ProductID
        /*
         * 1.16 * Nome do produto (ProductID). . . . . . . . . . . Nome do
         * produto que gera o SAF -T (PT) . . . . . . . . . . . Deve ser
         * indicado o nome comercial do software e o da empresa produtora no
         * formato ?Nome produto/nome empresa?.
         */
        header.setProductID(SaftConfig.PRODUCT_ID());

        // Product Version
        header.setProductVersion(SaftConfig.PRODUCT_VERSION());

        // SoftwareCertificateNumber
        header.setSoftwareCertificateNumber(BigInteger.valueOf(SaftConfig.SOFTWARE_CERTIFICATE_NUMBER()));

        // StartDate
        header.setStartDate(dataTypeFactory.newXMLGregorianCalendarDate(startDate.getYear(),
                startDate.getMonthOfYear(), startDate.getDayOfMonth(), DatatypeConstants.FIELD_UNDEFINED));

        // TaxAccountingBasis
        /*
         * Deve ser preenchido com: contabilidade; facturao; ?I? ? dados
         * integrados de factura??o e contabilidade; ?S? ? autofactura??o;
         * ?P? ? dados parciais de factura??o
         */
        header.setTaxAccountingBasis("P");

        // TaxEntity
        /*
         * Identifica??o do estabelecimento (TaxEntity) No caso do ficheiro
         * de factura??o dever? ser especificado a que estabelecimento diz
         * respeito o ficheiro produzido, se aplic?vel, caso contr?rio,
         * dever? ser preenchido com a especifica??o ?Global?. No caso do
         * ficheiro de contabilidade ou integrado, este campo dever? ser
         * preenchido com a especifica??o ?Sede?. Texto 20
         */
        header.setTaxEntity("Global");

        // TaxRegistrationNumber
        /*
         * N?mero de identifica??o fiscal da empresa
         * (TaxRegistrationNumber). Preencher com o NIF portugu?s sem
         * espa?os e sem qualquer prefixo do pa?s. Inteiro 9
         */
        try {
            header.setTaxRegistrationNumber(Integer.parseInt(finantialInstitution.getFiscalNumber()));
        } catch (Exception ex) {
            throw new RuntimeException("Invalid Fiscal Number.");
        }

        // header.setTelephone(finantialInstitution.get);

        // header.setWebsite(finantialInstitution.getEmailContact());

        return header;
    } catch (DatatypeConfigurationException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:org.fsl.roms.service.action.RoadCheckServiceAction.java

private boolean validateInitiateRequiredFields(RequestContext context, boolean checkMVFields) {
    RoadCheckInitiateView roadCheckInitiateView = (RoadCheckInitiateView) context.getFlowScope()
            .get("initiateView");
    boolean error = false;
    Calendar calendar = Calendar.getInstance();
    Date currentDate = calendar.getTime();

    if (StringUtils.isBlank(roadCheckInitiateView.getActivityType())) {
        addErrorMessageWithParameter(context, "RequiredFields", "Road Check Activity");
        error = true;//from w  w  w .  ja v a2s  .co  m
    }

    // if(StringUtils.isBlank(roadCheckInitiateView.getOperationName())){
    if (roadCheckInitiateView.getActivityType().equalsIgnoreCase("S")
            && (roadCheckInitiateView.getRoadOperationBO() == null
                    || roadCheckInitiateView.getRoadOperationBO().getRoadOperationId() == null)) {
        addErrorMessageWithParameter(context, "RequiredFields", "Operation Name");
        error = true;
    }

    // if(StringUtils.isBlank(roadCheckInitiateView.getOffencePlace())){
    if (roadCheckInitiateView.getOffencePlace() == null
            || roadCheckInitiateView.getOffencePlace().getArteryId() == null) {
        addErrorMessageWithParameter(context, "RequiredFields", "Place of Offence");
        error = true;
    }
    if (roadCheckInitiateView.getOffenceDate() == null) {
        addErrorMessageWithParameter(context, "RequiredFields", "Offence Date");
        error = true;
    } else {

        XMLGregorianCalendar today = null;
        // Date convertedDate = null;

        // SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm a");
        /* try { convertedDate = dateFormat.parse(StringUtil.getCurrentDateString()); } catch (ParseException e1) {
         * // TODO Auto-generated catch block e1.printStackTrace(); } */
        // convertedDate = dateFormat.getCalendar().getTime();

        try {
            today = DateUtils.getXMLGregorianCalendar(currentDate);
        } catch (DatatypeConfigurationException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        // System.err.println("The date " + offDate);

        if (roadCheckInitiateView.getOffenceDate().after(currentDate)) {
            addErrorMessageText(context, "Offence Date cannot be after Today's Date and Time");
            error = true;
        }
        boolean offDateError = false;
        Date startDate = null;
        Date endDate = null;

        if (roadCheckInitiateView.getActivityType().equalsIgnoreCase("S")) {

            if (roadCheckInitiateView.getRoadOperationBO() != null
                    && roadCheckInitiateView.getRoadOperationBO().getRoadOperationId() != null) {

                Date offDate = roadCheckInitiateView.getRoadOperationBO().getStatusId()
                        .equalsIgnoreCase(Constants.Status.ROAD_OPERATION_STARTED)
                                ? returnDateTimeInMinutesOnlyDateType(roadCheckInitiateView.getOffenceDate())
                                : returnDateTimeInMinutesOnlyDateType(roadCheckInitiateView.getOffenceDate());

                if (roadCheckInitiateView.getRoadOperationBO().getActualStartDate() != null) {

                    startDate = roadCheckInitiateView.getRoadOperationBO().getStatusId()
                            .equalsIgnoreCase(Constants.Status.ROAD_OPERATION_STARTED)
                                    ? returnDateTimeInMinutesOnlyDateType(
                                            roadCheckInitiateView.getRoadOperationBO().getActualStartDate())
                                    : returnDateTimeInMinutesOnlyDateType(
                                            roadCheckInitiateView.getRoadOperationBO().getActualStartDate());

                    if (offDate.compareTo(startDate) < 0) {
                        offDateError = true;
                    }
                } else {
                    if (startDate == null) {
                        startDate = roadCheckInitiateView.getRoadOperationBO().getStatusId()
                                .equalsIgnoreCase(Constants.Status.ROAD_OPERATION_STARTED)
                                        ? returnDateOnlyDateType(roadCheckInitiateView.getRoadOperationBO()
                                                .getScheduledStartDate())
                                        : returnDateTimeInMinutesOnlyDateType(roadCheckInitiateView
                                                .getRoadOperationBO().getScheduledStartDate());
                    }
                    if (offDate.compareTo(startDate) < 0) {
                        offDateError = true;
                    }
                }

                if (roadCheckInitiateView.getRoadOperationBO().getActualEndDate() != null) {
                    endDate = roadCheckInitiateView.getRoadOperationBO().getStatusId()
                            .equalsIgnoreCase(Constants.Status.ROAD_OPERATION_STARTED)
                                    ? returnDateOnlyDateType(
                                            roadCheckInitiateView.getRoadOperationBO().getActualEndDate())
                                    : returnDateTimeInMinutesOnlyDateType(
                                            roadCheckInitiateView.getRoadOperationBO().getActualEndDate());

                    if (offDate.compareTo(endDate) > 0) {
                        offDateError = true;
                    }
                } else {
                    if (endDate == null) {

                        Calendar calRoadEndDate = Calendar.getInstance();
                        calRoadEndDate
                                .setTime(roadCheckInitiateView.getRoadOperationBO().getScheduledEndDate());
                        calRoadEndDate.set(Calendar.HOUR_OF_DAY, 23);
                        calRoadEndDate.set(Calendar.MINUTE, 59);
                        calRoadEndDate.set(Calendar.SECOND, 59);
                        endDate = roadCheckInitiateView.getRoadOperationBO().getStatusId()
                                .equalsIgnoreCase(Constants.Status.ROAD_OPERATION_STARTED)
                                        ? returnDateTimeInMinutesOnlyDateType(calRoadEndDate.getTime())
                                        : returnDateTimeInMinutesOnlyDateType(roadCheckInitiateView
                                                .getRoadOperationBO().getScheduledEndDate());
                    }
                    if (offDate.compareTo(endDate) > 0) {
                        offDateError = true;
                    }
                }
            }

            if (offDateError == true) {
                try {
                    error = true;
                    if (startDate.compareTo(endDate) == 0) {
                        addErrorMessageText(context,
                                "Offence Date must be " + DateUtils.getFormattedUtilDate(startDate) + " for "
                                        + roadCheckInitiateView.getRoadOperationBO().getOperationName());
                    } else {
                        //addErrorMessageText(context, "Offence Date must be between " + DateUtils.getFormattedUtilDate(startDate) + " and " + DateUtils.getFormattedUtilDate(endDate) + " for " + roadCheckInitiateView.getRoadOperationBO().getOperationName());
                        addErrorMessageText(context,
                                "Offence Date must be between "
                                        + (roadCheckInitiateView.getRoadOperationBO().getStatusId()
                                                .equalsIgnoreCase(Constants.Status.ROAD_OPERATION_STARTED)
                                                        ? DateUtils.getFormattedUtilLongDate(startDate)
                                                        : DateUtils.getFormattedUtilLongDate(startDate))
                                        + " and "
                                        + (roadCheckInitiateView.getRoadOperationBO().getStatusId()
                                                .equalsIgnoreCase(Constants.Status.ROAD_OPERATION_STARTED)
                                                        ? DateUtils.getFormattedUtilLongDate(endDate)
                                                        : DateUtils.getFormattedUtilLongDate(endDate))
                                        + " for "
                                        + roadCheckInitiateView.getRoadOperationBO().getOperationName());
                    }
                } catch (Exception e) {
                    logger.error("Road Check", e);
                }
            }
        }

    }

    // if(StringUtils.isBlank(roadCheckInitiateView.getInspector())){
    if (roadCheckInitiateView.getTaStaffBO() == null
            || StringUtils.isBlank(roadCheckInitiateView.getTaStaffBO().getStaffId())) {
        addErrorMessageWithParameter(context, "RequiredFields", "Inspector");
        error = true;
    }

    if (StringUtils.isBlank(roadCheckInitiateView.getRoleObserved())) {
        addErrorMessageWithParameter(context, "RequiredFields", "Role Observed");
        error = true;
    } else if ("T".equalsIgnoreCase(roadCheckInitiateView.getRoleObserved())
            && StringUtils.isBlank(roadCheckInitiateView.getOtherRoleId())) {
        addErrorMessageWithParameter(context, "RequiredFields", "Other Role Observed");
        error = true;

    }

    //global address validation - kpowell

    boolean errorFoundInAddress = validateAddress(context, roadCheckInitiateView.getAddressView());

    if (errorFoundInAddress) {
        error = true;
    }

    /* if(StringUtils.isBlank(roadCheckInitiateView.getMobilePhoneNo()) &&
     * StringUtils.isBlank(roadCheckInitiateView.getHomePhoneNo()) &&
     * StringUtils.isBlank(roadCheckInitiateView.getWorkPhoneNo())){ addErrorMessageWithParameter(context,
     * "RequiredFields", "At least one Contact Number"); error=true; } */

    // Validate Phone numbers
    logger.info("Mobile Phone " + roadCheckInitiateView.getMobilePhoneNo());
    if (!StringUtils.isBlank(roadCheckInitiateView.getMobilePhoneNo())
            && !roadCheckInitiateView.getMobilePhoneNo().equals("(___)___-____")) {
        if (!PhoneNumberUtil.validateAllPhoneNumbers(roadCheckInitiateView.getMobilePhoneNo())) {
            addErrorMessageText(context, "Mobile Contact Number is not valid. E.g.(555)555-5555");
            error = true;
        }
    }
    if (!StringUtils.isBlank(roadCheckInitiateView.getHomePhoneNo())
            && !roadCheckInitiateView.getHomePhoneNo().equals("(___)___-____")) {
        if (!PhoneNumberUtil.validateAllPhoneNumbers(roadCheckInitiateView.getHomePhoneNo())) {
            addErrorMessageText(context, "Home Contact Number is not valid. E.g.(555)555-5555");
            error = true;
        }
    }
    if (!StringUtils.isBlank(roadCheckInitiateView.getWorkPhoneNo())
            && !roadCheckInitiateView.getWorkPhoneNo().equals("(___)___-____")) {
        if (!PhoneNumberUtil.validateAllPhoneNumbers(roadCheckInitiateView.getWorkPhoneNo())) {
            addErrorMessageText(context, "Work Contact Number is not valid. E.g.(555)555-5555");
            error = true;
        }
    }

    if (StringUtils.isBlank(roadCheckInitiateView.getPlateRegNo())) {
        addErrorMessageWithParameter(context, "RequiredFields", "Plate No.");
        error = true;
    }

    if (roadCheckInitiateView.isDisableMotorVehicleFields() == false && checkMVFields == true) {

        //         if (StringUtils.isBlank(roadCheckInitiateView.getChassisNo())) {
        //            addErrorMessageWithParameter(context, "RequiredFields", "Chassis No.");
        //            error = true;
        //         }

        //         if (StringUtils.isBlank(roadCheckInitiateView.getEngineNo())) {
        //            addErrorMessageWithParameter(context, "RequiredFields", "Engine No.");
        //            error = true;
        //         }

        if (StringUtils.isBlank(roadCheckInitiateView.getMakeDescription())) {
            addErrorMessageWithParameter(context, "RequiredFields", "Make");
            error = true;
        }

        if (StringUtils.isBlank(roadCheckInitiateView.getModel())) {
            addErrorMessageWithParameter(context, "RequiredFields", "Model");
            error = true;
        }

        if (StringUtils.isBlank(roadCheckInitiateView.getType())) {
            addErrorMessageWithParameter(context, "RequiredFields", "Type");
            error = true;
        }

        if (StringUtils.isBlank(roadCheckInitiateView.getColour())) {
            addErrorMessageWithParameter(context, "RequiredFields", "Colour");
            error = true;
        }

        if (roadCheckInitiateView.getYear() == null) {
            addErrorMessageWithParameter(context, "RequiredFields", "Year");
            error = true;
        } else {
            // validate MV year
            int firstYear = 1800;
            int lastYear = Calendar.getInstance().get(Calendar.YEAR) + 1;
            // System.err.println("lastYear: " + lastYear);
            if (roadCheckInitiateView.getYear().intValue() < firstYear
                    || roadCheckInitiateView.getYear().intValue() > lastYear) {
                addErrorMessage(context, "InvalidYear");
                error = true;
            }
        }

    }

    if (checkMVFields == true) {
        if (roadCheckInitiateView.isBadgeQuery()) {
            if (StringUtils.isBlank(roadCheckInitiateView.getBadgeNo())) {
                addErrorMessageWithParameter(context, "RequiredFields", "Badge #");
                error = true;
            }
        }

        if (roadCheckInitiateView.isDlQuery()) {
            if (StringUtils.isBlank(roadCheckInitiateView.getDlNo())) {
                addErrorMessageWithParameter(context, "RequiredFields", "Driver Licence #");
                error = true;
            }
        }

        //         if (roadCheckInitiateView.isRoadLicQuery()) {
        //            if (StringUtils.isBlank(roadCheckInitiateView.getRoadLicNo())) {
        //               addErrorMessageWithParameter(context, "RequiredFields", "Road Licence #");
        //               error = true;
        //            }
        //         }
    }
    return error;
}

From source file:org.mitre.stix.examples.CIQIdentity.java

/**
 * @param args/*from w  w  w .  j  av a2s  .c  om*/
 * @throws DatatypeConfigurationException
 * @throws JAXBException
 * @throws ParserConfigurationException
 */
@SuppressWarnings("serial")
public static void main(String[] args) {

    try {
        // Get time for now.
        XMLGregorianCalendar now = DatatypeFactory.newInstance()
                .newXMLGregorianCalendar(new GregorianCalendar(TimeZone.getTimeZone("UTC")));

        ContactNumbers contactNumbers = new ContactNumbers()
                .withContactNumbers(new ContactNumbers.ContactNumber().withContactNumberElements(
                        new ContactNumbers.ContactNumber.ContactNumberElement().withValue("555-555-5555"),
                        new ContactNumbers.ContactNumber.ContactNumberElement().withValue("555-555-5556")));

        ElectronicAddressIdentifiers electronicAddressIdentifiers = new ElectronicAddressIdentifiers()
                .withElectronicAddressIdentifiers(new ElectronicAddressIdentifiers.ElectronicAddressIdentifier()
                        .withValue("jsmith@example.com"));

        FreeTextLines freeTextLines = new FreeTextLines()
                .withFreeTextLines(new FreeTextLines.FreeTextLine().withValue("Demonstrating Free Text!"));

        PartyNameType partyName = new PartyNameType()
                .withNameLines(new NameLine().withValue("Foo"), new NameLine().withValue("Bar"))
                .withPersonNames(new PersonName().withNameElements(
                        new oasis.names.tc.ciq.xnl._3.PersonNameType.NameElement().withValue("John Smith")),
                        new PersonName()
                                .withNameElements(new oasis.names.tc.ciq.xnl._3.PersonNameType.NameElement()
                                        .withValue("Jill Smith")))
                .withOrganisationNames(new OrganisationName().withNameElements(
                        new oasis.names.tc.ciq.xnl._3.OrganisationNameType.NameElement().withValue("Foo Inc.")),
                        new OrganisationName().withNameElements(
                                new oasis.names.tc.ciq.xnl._3.OrganisationNameType.NameElement()
                                        .withValue("Bar Corp.")));

        STIXCIQIdentity30Type specification = new STIXCIQIdentity30Type().withContactNumbers(contactNumbers)
                .withElectronicAddressIdentifiers(electronicAddressIdentifiers).withFreeTextLines(freeTextLines)
                .withPartyName(partyName);

        CIQIdentity30InstanceType identity = new CIQIdentity30InstanceType().withSpecification(specification);

        InformationSourceType producer = new InformationSourceType()
                .withDescriptions(new StructuredTextType()
                        .withValue("An indicator containing a File observable with an associated hash"))
                .withTime(new TimeType().withProducedTime(new DateTimeWithPrecisionType(now, null)))
                .withIdentity(identity);

        FileObjectType fileObject = new FileObjectType().withHashes(new HashListType(new ArrayList<HashType>() {
            {
                add(new HashType().withType(new HashNameVocab10().withValue("MD5")).withSimpleHashValue(
                        new SimpleHashValueType().withValue("4EC0027BEF4D7E1786A04D021FA8A67F")));
            }
        }));

        ObjectType obj = new ObjectType().withProperties(fileObject)
                .withId(new QName("http://example.com/", "file-" + UUID.randomUUID().toString(), "example"));

        Observable observable = new Observable().withId(
                new QName("http://example.com/", "observable-" + UUID.randomUUID().toString(), "example"));

        observable.setObject(obj);

        final Indicator indicator = new Indicator()
                .withId(new QName("http://example.com/", "indicator-" + UUID.randomUUID().toString(),
                        "example"))
                .withTimestamp(now).withTitle("File Hash Example")
                .withDescriptions(new StructuredTextType()
                        .withValue("An indicator containing a File observable with an associated hash"))
                .withProducer(producer).withObservable(observable);

        IndicatorsType indicators = new IndicatorsType(new ArrayList<IndicatorBaseType>() {
            {
                add(indicator);
            }
        });

        STIXHeaderType header = new STIXHeaderType()
                .withDescriptions(new StructuredTextType().withValue("Example"));

        STIXPackage stixPackage = new STIXPackage().withSTIXHeader(header).withIndicators(indicators)
                .withVersion("1.2").withTimestamp(now)
                .withId(new QName("http://example.com/", "package-" + UUID.randomUUID().toString(), "example"));

        System.out.println(stixPackage.toXMLString(true));

        System.out.println(StringUtils.repeat("-", 120));

        System.out.println("Validates: " + stixPackage.validate());

        System.out.println(StringUtils.repeat("-", 120));

        System.out.println(STIXPackage.fromXMLString(stixPackage.toXMLString()).toXMLString(true));

    } catch (DatatypeConfigurationException e) {
        throw new RuntimeException(e);
    } catch (SAXException e) {
        e.printStackTrace();
    }
}

From source file:org.mitre.stix.examples.CreationToolMetadata.java

public static void main(String[] args) {

    try {/*from  w  w w. j av  a2  s .c  o m*/
        // Get time for now.
        XMLGregorianCalendar now = DatatypeFactory.newInstance()
                .newXMLGregorianCalendar(new GregorianCalendar(TimeZone.getTimeZone("UTC")));

        STIXHeaderType header = new STIXHeaderType()
                .withDescriptions(new StructuredTextType().withValue("Example"))
                .withInformationSource(new InformationSourceType()
                        .withTools(new ToolsInformationType().withTools(new ToolInformationType()
                                .withName("org.mitre.stix.examples.CreationToolMetadata")
                                .withVendor("The MITRE Corporation"))));

        STIXPackage stixPackage = new STIXPackage().withSTIXHeader(header).withVersion("1.2").withTimestamp(now)
                .withId(new QName("http://example.com/", "package-" + UUID.randomUUID().toString(), "example"));

        System.out.println(stixPackage.toXMLString(true));

        System.out.println(StringUtils.repeat("-", 120));

        System.out.println("Validates: " + stixPackage.validate());

    } catch (DatatypeConfigurationException e) {
        throw new RuntimeException(e);
    } catch (SAXException e) {
        e.printStackTrace();
    }
}

From source file:org.mitre.stix.examples.IndicatorHash.java

@SuppressWarnings("serial")
public static void main(String[] args) {

    try {//from  w  w w. ja v a  2 s .  c o  m
        // Get time for now.
        XMLGregorianCalendar now = DatatypeFactory.newInstance()
                .newXMLGregorianCalendar(new GregorianCalendar(TimeZone.getTimeZone("UTC")));

        FileObjectType fileObject = new FileObjectType().withHashes(new HashListType(new ArrayList<HashType>() {
            {
                add(new HashType().withType(new HashNameVocab10().withValue("MD5")).withSimpleHashValue(
                        new SimpleHashValueType().withValue("4EC0027BEF4D7E1786A04D021FA8A67F")));
            }
        }));

        ObjectType obj = new ObjectType().withProperties(fileObject)
                .withId(new QName("http://example.com/", "file-" + UUID.randomUUID().toString(), "example"));

        Observable observable = new Observable().withId(
                new QName("http://example.com/", "observable-" + UUID.randomUUID().toString(), "example"));

        observable.setObject(obj);

        IdentityType identity = new IdentityType().withName("The MITRE Corporation");

        InformationSourceType producer = new InformationSourceType().withIdentity(identity)
                .withTime(new TimeType().withProducedTime(new DateTimeWithPrecisionType(now, null)));

        final Indicator indicator = new Indicator()
                .withId(new QName("http://example.com/", "indicator-" + UUID.randomUUID().toString(),
                        "example"))
                .withTimestamp(now).withTitle("File Hash Example")
                .withDescriptions(new StructuredTextType()
                        .withValue("An indicator containing a File observable with an associated hash"))
                .withObservable(observable).withProducer(producer);

        IndicatorsType indicators = new IndicatorsType(new ArrayList<IndicatorBaseType>() {
            {
                add(indicator);
            }
        });

        STIXHeaderType stixHeader = new STIXHeaderType()
                .withDescriptions(new StructuredTextType().withValue("Example"));

        STIXPackage stixPackage = new STIXPackage().withSTIXHeader(stixHeader).withIndicators(indicators)
                .withVersion("1.2").withTimestamp(now)
                .withId(new QName("http://example.com/", "package-" + UUID.randomUUID().toString(), "example"));

        System.out.println(stixPackage.toXMLString(true));

        System.out.println(StringUtils.repeat("-", 120));

        System.out.println("Validates: " + stixPackage.validate());

    } catch (DatatypeConfigurationException e) {
        throw new RuntimeException(e);
    } catch (SAXException e) {
        e.printStackTrace();
    }
}

From source file:org.ow2.aspirerfid.beg.capture.CaptureReport.java

private XMLGregorianCalendar getCurrentTime() {
    // get the current time and set the eventTime
    XMLGregorianCalendar currentTime = null;
    try {/*w  w  w  . j av a 2 s  .c  o  m*/
        DatatypeFactory dataFactory = DatatypeFactory.newInstance();
        currentTime = dataFactory.newXMLGregorianCalendar(new GregorianCalendar());
        log.debug("Event Time:" + currentTime.getHour() + ":" + currentTime.getMinute() + ":" + ":"
                + currentTime.getSecond() + "\n");
    } catch (DatatypeConfigurationException e) {
        e.printStackTrace();
    }
    return currentTime;
}