Example usage for java.math BigInteger TEN

List of usage examples for java.math BigInteger TEN

Introduction

In this page you can find the example usage for java.math BigInteger TEN.

Prototype

BigInteger TEN

To view the source code for java.math BigInteger TEN.

Click Source Link

Document

The BigInteger constant ten.

Usage

From source file:com.github.jrrdev.mantisbtsync.core.jobs.projects.ProjectsReadersTest.java

public JobExecution getJobExecution() {
    if (jobExecution == null) {
        final Map<String, JobParameter> map = new HashMap<String, JobParameter>();
        map.put("mantis.username", new JobParameter("toto"));
        map.put("mantis.password", new JobParameter("passwd"));

        final JobParameters jobParams = new JobParameters(map);
        jobExecution = MetaDataInstanceFactory.createJobExecution("testJob", 1L, 1L, jobParams);

        jobExecution.getExecutionContext().put("mantis.acess_level", BigInteger.TEN);
        jobExecution.getExecutionContext().put("mantis.loop.project_id", BigInteger.ONE);
    }//from ww w. j av a  2  s  .c  om

    return jobExecution;
}

From source file:org.ovirt.api.metamodel.tests.JsonWriterTest.java

/**
 * Checks that integer longer than long are written correctly.
 *///from  w w  w .j a v a  2 s  .  c o  m
@Test
public void testVeryLong() {
    BigInteger memory = BigInteger.TEN.multiply(BigInteger.valueOf(Long.MAX_VALUE));
    V4Vm object = vm().memory(memory).build();
    assertEquals("{'memory':92233720368547758070}", objectToJson(object));
}

From source file:org.trnltk.numeral.DigitsToTextConverter.java

private String convertNaturalNumberToWords(BigInteger naturalNumber) {
    Validate.isTrue(naturalNumber.compareTo(ZERO) >= 0);
    Validate.isTrue(naturalNumber.compareTo(MAX_NATURAL_NUMBER_SUPPORTED) <= 0, "Given number " + naturalNumber
            + " is larger than maximum supported natural number " + MAX_NATURAL_NUMBER_SUPPORTED);

    StringBuilder result = new StringBuilder();

    if (naturalNumber.compareTo(BigInteger.TEN) < 0) {
        result.append(NUMERAL_SYMBOL_NAMES.get(naturalNumber.intValue()));

    } else if (naturalNumber.compareTo(ONE_HUNDRED) < 0) {
        final BigInteger tensDigit = naturalNumber.divide(TEN);
        final BigInteger onesDigit = naturalNumber.mod(TEN);
        final String strTensDigit = TENS_MULTIPLES_NAMES.get(tensDigit.intValue());
        final String strOnesDigit = onesDigit.compareTo(ZERO) > 0 ? convertNaturalNumberToWords(onesDigit)
                : StringUtils.EMPTY;//  w  w  w. jav a2s  .  co  m
        result.append(strTensDigit).append(" ").append(strOnesDigit);

    } else if (naturalNumber.compareTo(ONE_THOUSAND) < 0) {
        final BigInteger hundredsDigit = naturalNumber.divide(ONE_HUNDRED);
        final BigInteger rest = naturalNumber.mod(ONE_HUNDRED);
        final String strHundredsDigit;
        if (hundredsDigit.equals(ZERO)) {
            strHundredsDigit = StringUtils.EMPTY;
        } else if (hundredsDigit.equals(ONE)) {
            strHundredsDigit = StringUtils.EMPTY;
        } else {
            strHundredsDigit = convertNaturalNumberToWords(hundredsDigit);
        }

        final String restStr = rest.compareTo(ZERO) > 0 ? convertNaturalNumberToWords(rest) : StringUtils.EMPTY;

        result.append(strHundredsDigit).append(" ").append(HUNDRED_NAME).append(" ").append(restStr);

    } else {
        int mostSignificantGroupBase = this.findMostSignificantGroupBase(naturalNumber);
        for (int i = mostSignificantGroupBase / 3; i > 0; i--) {
            int groupNumber = this.getNthGroupNumber(naturalNumber, i);
            //noinspection StatementWithEmptyBody
            if (groupNumber == 0) {
                // don't write 'sifir milyon'
            } else if (groupNumber == 1 && i == 1) {
                // don't write 'bir bin', but write 'bir milyon'(below)
                result.append(" ").append(THOUSAND_NAME);
            } else {
                final String strGroupNumber = this.convertNaturalNumberToWords(BigInteger.valueOf(groupNumber));
                result.append(" ").append(strGroupNumber).append(" ").append(THOUSAND_POWER_NAMES.get(i));
            }

            result = new StringBuilder(result.toString().trim());
        }

        final BigInteger lastGroupNumber = naturalNumber.mod(ONE_THOUSAND);
        if (lastGroupNumber.compareTo(ZERO) > 0)
            result.append(" ").append(convertNaturalNumberToWords(lastGroupNumber));
    }

    return result.toString().trim();
}

From source file:org.ovirt.api.metamodel.tests.XmlWriterTest.java

/**
 * Checks that integer longer than long are written correctly.
 *///from   w w  w  .j  a  va  2  s  . c o m
@Test
public void testVeryLong() {
    BigInteger memory = BigInteger.TEN.multiply(BigInteger.valueOf(Long.MAX_VALUE));
    V4Vm object = vm().memory(memory).build();
    assertEquals("<vm><memory>92233720368547758070</memory></vm>", objectToXml(object));
}

From source file:io.instacount.client.InstacountClientTest.java

@Test
public void testShardedCounterHappyPath() throws InstacountClientException {
    try {//  w ww.j  a v  a2  s . c  o m
        final String counterName = UUID.randomUUID().toString();
        {
            /////////
            // Create the Counter
            final CreateShardedCounterInput createCounterInput = new CreateShardedCounterInput(counterName);
            final CreateShardedCounterResponse createdCounterResponse = this.client
                    .createShardedCounter(createCounterInput);
            this.doBasicAssertions(createdCounterResponse, 201);
        }
        {
            /////////
            // Get the Counter
            final GetShardedCounterResponse createdShardedCounterResponse = this.client
                    .getShardedCounter(counterName);
            this.doBasicAssertions(createdShardedCounterResponse, 200);
            this.doShardedCounterAssertions(createdShardedCounterResponse.getShardedCounter(), counterName,
                    Optional.<String>absent(), 3, CounterStatus.AVAILABLE);
        }
        {
            ////////////
            // Increment the Counter by 1
            final IncrementShardedCounterResponse incrementShardedCounterResponse = client
                    .incrementShardedCounter(counterName);
            this.doBasicAssertions(incrementShardedCounterResponse, 201);
        }
        {
            ////////////
            // Increment the Counter by 10
            final IncrementShardedCounterResponse incrementShardedCounterResponse2 = client
                    .incrementShardedCounter(counterName,
                            new IncrementShardedCounterInput(BigInteger.TEN, false));
            this.doBasicAssertions(incrementShardedCounterResponse2, 201);
        }
        {
            ////////////
            // Decrement the Counter by 1
            final DecrementShardedCounterResponse decrementShardedCounterResponse = client
                    .decrementShardedCounter(counterName);
            this.doBasicAssertions(decrementShardedCounterResponse, 201);
        }
        {
            ////////////
            // Decrement the Counter by 10
            final DecrementShardedCounterResponse decrementShardedCounterResponse2 = client
                    .decrementShardedCounter(counterName,
                            new DecrementShardedCounterInput(BigInteger.TEN, false));
            this.doBasicAssertions(decrementShardedCounterResponse2, 201);
        }
        {
            ////////////
            // Get the Counter

            final GetShardedCounterResponse response = client.getShardedCounter(counterName);
            assertThat(response.getHttpResponseCode(), is(200));

            this.doShardedCounterAssertions(response.getShardedCounter(), counterName,
                    Optional.<String>absent(), 3, CounterStatus.AVAILABLE);

            assertThat(response.getShardedCounter().getCount(), is(BigInteger.ZERO));
        }
    } catch (InstacountClientException e) {
        assertThat(e.getErrors().getHttpResponseCode(), is(400));
        throw e;
    }
}

From source file:com.github.jrrdev.mantisbtsync.core.jobs.projects.ProjectsReadersTest.java

/**
 * Test the reader for the table mantis_user_table.
 *
 * @throws Exception//www . java 2 s .c o m
 *          Technical Exception
 */
@Test
public void testProjectUsersReader() throws Exception {
    final AccountData[] expected = new AccountData[] {
            new AccountData(BigInteger.ONE, "user_1", "user_real_1", "toto1@foo.fr"),
            new AccountData(BigInteger.valueOf(2), "user_2", "user_real_2", "toto2@foo.fr") };

    Mockito.when(clientStub.mc_project_get_users("toto", "passwd", BigInteger.ONE, BigInteger.TEN))
            .thenReturn(expected);

    projectUsersReader.setClientStub(clientStub);

    for (int i = 0; i <= expected.length; i++) {
        final AccountData item = projectUsersReader.read();
        if (i < expected.length) {
            assertNotNull(item);
            assertEquals(expected[i].getId(), item.getId());
            assertEquals(expected[i].getName(), item.getName());
            assertEquals(expected[i].getReal_name(), item.getReal_name());
            assertEquals(expected[i].getEmail(), item.getEmail());
        } else {
            assertNull(item);
        }
    }
}

From source file:org.tdmx.lib.zone.service.ChannelAuthorizationServiceRepositoryUnitTest.java

@Test
public void testModify() throws Exception {
    ChannelAuthorization ca = data.getDomains().get(0).getAuths().get(0);
    ChannelAuthorization storedCA = channelAuthorizationService.findByChannel(zone,
            ca.getDomain().getDomainName(), ca.getOrigin(), ca.getDestination());
    assertNotNull(storedCA);// ww  w  .  j a v a  2 s  .c  o  m
    storedCA.getUndeliveredBuffer().setHighMarkBytes(BigInteger.TEN);
    storedCA.getUndeliveredBuffer().setLowMarkBytes(BigInteger.ONE);
    storedCA.getUnsentBuffer().setHighMarkBytes(BigInteger.TEN);
    storedCA.getUnsentBuffer().setLowMarkBytes(BigInteger.ONE);
    channelAuthorizationService.createOrUpdate(storedCA);

    ChannelAuthorization modifiedCA = channelAuthorizationService.findByChannel(zone,
            ca.getDomain().getDomainName(), ca.getOrigin(), ca.getDestination());
    assertNotNull(modifiedCA);
    assertEquals(storedCA.getUndeliveredBuffer().getHighMarkBytes(),
            modifiedCA.getUndeliveredBuffer().getHighMarkBytes());
    assertEquals(storedCA.getUndeliveredBuffer().getLowMarkBytes(),
            modifiedCA.getUndeliveredBuffer().getLowMarkBytes());
    assertEquals(storedCA.getUnsentBuffer().getHighMarkBytes(),
            modifiedCA.getUnsentBuffer().getHighMarkBytes());
    assertEquals(storedCA.getUnsentBuffer().getLowMarkBytes(), modifiedCA.getUnsentBuffer().getLowMarkBytes());

}

From source file:net.pms.util.Rational.java

/**
 * Returns an instance that represents the value of {@code value}.
 *
 * @param value the value./* w  w w  . ja v a  2 s  .  c  o m*/
 * @return An instance that represents the value of {@code value}.
 */
@Nullable
public static Rational valueOf(@Nullable BigDecimal value) {
    if (value == null) {
        return null;
    }
    BigInteger numerator;
    BigInteger denominator;
    if (value.signum() == 0) {
        return ZERO;
    }
    if (BigDecimal.ONE.equals(value)) {
        return ONE;
    }
    if (value.scale() > 0) {
        BigInteger unscaled = value.unscaledValue();
        BigInteger tmpDenominator = BigInteger.TEN.pow(value.scale());
        BigInteger tmpGreatestCommonDivisor = unscaled.gcd(tmpDenominator);
        numerator = unscaled.divide(tmpGreatestCommonDivisor);
        denominator = tmpDenominator.divide(tmpGreatestCommonDivisor);
    } else {
        numerator = value.toBigIntegerExact();
        denominator = BigInteger.ONE;
    }
    return new Rational(numerator, denominator, BigInteger.ONE, numerator, denominator);
}

From source file:org.sinekartads.integration.cms.SignCMSonAlfresco.java

@Test
public void test() throws Exception {
    if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
        Security.addProvider(new BouncyCastleProvider());
    }//from   ww w .  j a va 2 s.co m

    SignNOApplet applet = new SignNOApplet();
    try {

        // Main options
        boolean applyMark = true;
        boolean useFakeSmartCard = true;
        String driver;
        String scPin;
        if (useFakeSmartCard) {
            driver = "fake";
            scPin = "123";
        } else {
            driver = "libbit4ipki.so";
            scPin = "18071971";
        }

        // Test products
        String[] aliases;
        String alias;
        X509Certificate certificate;
        X509Certificate[] certificateChain;
        byte[] fingerPrint;
        byte[] digitalSignature;

        // Communication unities
        DocumentDTO[] documents;
        String jsonResp;
        SkdsDocumentDetailsResponse detailsResp;
        SkdsPreSignResponse preSignResp;
        SkdsPostSignResponse postSignResp;
        AppletResponseDTO appletResponse;
        SignatureDTO emptySignatureDTO;
        SignatureDTO chainSignatureDTO;
        SignatureDTO digestSignatureDTO;
        SignatureDTO signedSignatureDTO;
        SignatureDTO finalizedSignatureDTO;
        VerifyDTO verifyDTO;

        // Init the applet
        try {
            AppletRequestDTO req = new AppletRequestDTO();
            req.setDriver(driver);
            appletResponse = applet.selectDriver(req);
        } catch (Exception e) {
            tracer.error("error during the applet initialization", e);
            throw e;
        }

        // Login with the smartCard
        try {
            AppletRequestDTO req = new AppletRequestDTO();
            req.setDriver(driver);
            req.setPin(scPin);
            appletResponse = applet.login(req);
            aliases = (String[]) JSONUtils.deserializeJSON(String[].class, extractJSON(appletResponse));
        } catch (Exception e) {
            tracer.error("error during the applet login", e);
            throw e;
        }

        // Choose the signing alias
        StringBuilder buf = new StringBuilder();
        for (String a : aliases) {
            buf.append(a).append(" ");
        }
        alias = aliases[0];
        tracer.info(String.format("available aliases:   %s", buf));
        tracer.info(String.format("signing alias:       %s", alias));

        // Load the certificate chain from the applet
        try {
            AppletRequestDTO req = new AppletRequestDTO();
            req.setDriver(driver);
            req.setPin(scPin);
            req.setAlias(alias);
            appletResponse = applet.selectCertificate(req);
            certificate = (X509Certificate) X509Utils.rawX509CertificateFromHex(extractJSON(appletResponse));
            tracer.info(String.format("certificate:         %s", certificate));
            certificateChain = new X509Certificate[] { certificate };
        } catch (Exception e) {
            tracer.error("error during the certificate selection", e);
            throw e;
        }

        // FindRefByName
        String sourceRef = null;
        try {
            SkdsFindRefByNameRequest req = new SkdsFindRefByNameRequest();
            req.setName(SOURCE_NAME);
            SkdsFindRefByNameResponse findResp = postJsonRequest(req, SkdsFindRefByNameResponse.class);
            if (ResultCode.valueOf(findResp.getResultCode()) == ResultCode.SUCCESS) {
                sourceRef = findResp.getNodeRef();
            } else {
                throw new Exception(findResp.getMessage());
            }
        } catch (Exception e) {
            tracer.error("error during the pre sign phase", e);
            throw e;
        }

        // DocumentDetails
        try {
            //            String sourceRef = getNodeRefId("pippo.txt");
            SkdsDocumentDetailsRequest req = new SkdsDocumentDetailsRequest();
            req.setNodeRefs(new String[] { sourceRef });
            //            req.setNodeRefs ( new String[] {SOURCE_REF} );
            detailsResp = postJsonRequest(req, SkdsDocumentDetailsResponse.class);
            if (ResultCode.valueOf(detailsResp.getResultCode()) == ResultCode.SUCCESS) {
                documents = detailsResp.documentsFromBase64();
            } else {
                throw new Exception(detailsResp.getMessage());
            }
            String fileName = documents[0].getBaseDocument().getFileName();
            if (applyMark) {
                documents[0].setDestName(fileName + ".p7m.tsd");
            } else {
                documents[0].setDestName(fileName + ".p7m");
            }
        } catch (Exception e) {
            tracer.error("error during the pre sign phase", e);
            throw e;
        }

        // empty signature - initialized with the SHA256withRSA and RSA algorithms
        emptySignatureDTO = new SignatureDTO();
        emptySignatureDTO.setSignAlgorithm(conf.getSignatureAlgorithm().getName());
        emptySignatureDTO.setDigestAlgorithm(conf.getDigestAlgorithm().getName());
        emptySignatureDTO.signCategoryToString(SignCategory.CMS);

        // Add to the empty signature the timeStamp request if needed
        TimeStampRequestDTO tsRequestDTO = new TimeStampRequestDTO();
        if (applyMark) {
            tsRequestDTO.timestampDispositionToString(SignDisposition.TimeStamp.ENVELOPING);
            tsRequestDTO.messageImprintAlgorithmToString(DigestAlgorithm.SHA256);
            tsRequestDTO.nounceToString(BigInteger.TEN);
            tsRequestDTO.setTsUrl("http://ca.signfiles.com/TSAServer.aspx");
        }
        emptySignatureDTO.setTimeStampRequest(tsRequestDTO);

        // chain signature - contains the certificate chain
        chainSignatureDTO = TemplateUtils.Instantiation.clone(emptySignatureDTO);
        chainSignatureDTO.certificateChainToHex(certificateChain);
        documents[0].setSignatures(new SignatureDTO[] { chainSignatureDTO });

        // PreSign phase - join the content with the certificate chain and evaluate the digest
        try {
            SkdsPreSignRequest req = new SkdsPreSignRequest();
            req.documentsToBase64(documents);
            preSignResp = postJsonRequest(req, SkdsPreSignResponse.class);
            if (ResultCode.valueOf(preSignResp.getResultCode()) == ResultCode.SUCCESS) {
                documents = preSignResp.documentsFromBase64();
                digestSignatureDTO = documents[0].getSignatures()[0];
            } else {
                throw new Exception(preSignResp.getMessage());
            }
        } catch (Exception e) {
            tracer.error("error during the pre sign phase", e);
            throw e;
        }

        // signed signature - sign the digest with the smartCard to obtain the digitalSignature
        try {
            fingerPrint = digestSignatureDTO.getDigest().fingerPrintFromHex();
            tracer.info(String.format("fingerPrint:         %s", HexUtils.encodeHex(fingerPrint)));
            AppletRequestDTO req = new AppletRequestDTO();
            req.setDriver(driver);
            req.setPin(scPin);
            req.setAlias(alias);
            req.setHexDigest(HexUtils.encodeHex(fingerPrint));
            appletResponse = applet.signDigest(req);
            digitalSignature = HexUtils.decodeHex((String) extractJSON(appletResponse));
            tracer.info(String.format("digitalSignature:    %s", HexUtils.encodeHex(digitalSignature)));
            signedSignatureDTO = TemplateUtils.Instantiation.clone(digestSignatureDTO);
            signedSignatureDTO.digitalSignatureToHex(digitalSignature);
            documents[0].getSignatures()[0] = signedSignatureDTO;
        } catch (Exception e) {
            tracer.error("error during the digital signature evaluation", e);
            throw e;
        }

        // PostSign phase - add the digitalSignature to the envelope and store the result into the JCLResultDTO
        try {
            SkdsPostSignRequest req = new SkdsPostSignRequest();
            req.documentsToBase64(documents);
            postSignResp = postJsonRequest(req, SkdsPostSignResponse.class);
            if (ResultCode.valueOf(postSignResp.getResultCode()) == ResultCode.SUCCESS) {
                documents = postSignResp.documentsFromBase64();
                finalizedSignatureDTO = documents[0].getSignatures()[0];
            } else {
                throw new Exception(postSignResp.getMessage());
            }
        } catch (Exception e) {
            tracer.error("error during the envelope generation", e);
            throw e;
        }

        //         // Verify phase - load the envelope content and verify the nested signature 
        //         try {
        //            jsonResp = signatureService.verify ( envelopeHex, null, null, VerifyResult.VALID.name() );
        //            verifyDTO = extractResult ( VerifyDTO.class, jsonResp );
        //         } catch(Exception e) {
        //            tracer.error("error during the envelope verification", e);
        //            throw e;
        //         }
        //         
        //         // finalized signature - enveloped signed and eventually marked, not modifiable anymore
        //         try {
        //            verifyResult = (VerifyInfo) converter.toVerifyInfo( verifyDTO );
        //         } catch(Exception e) {
        //            tracer.error("unable to obtain the verifyInfo from the DTO", e);
        //            throw e;
        //         }
        //         
        //         try {
        //            for(VerifiedSignature < ?, ?, VerifyResult, ?> verifiedSignature : verifyResult.getSignatures() ) {
        //               tracer.info(String.format ( "signature validity:  %s", verifiedSignature.getVerifyResult().name() ));
        //               tracer.info(String.format ( "signature type:      %s", verifiedSignature.getSignType().name() ));
        //               tracer.info(String.format ( "disposition:         %s", verifiedSignature.getDisposition().name() ));
        //               tracer.info(String.format ( "digest algorithm:    %s", verifiedSignature.getDigest().getAlgorithm().name() ));
        //               tracer.info(String.format ( "finger print:        %s", HexUtils.encodeHex(verifiedSignature.getDigest().getFingerPrint()) ));
        //               tracer.info(String.format ( "counter signature:   %s", verifiedSignature.isCounterSignature() ));
        //               tracer.info(String.format ( "signature algorithm: %s", verifiedSignature.getSignAlgorithm().name() ));
        //               tracer.info(String.format ( "digital signature:   %s", HexUtils.encodeHex(verifiedSignature.getDigitalSignature()) ));
        //               tracer.info(String.format ( "reason:              %s", verifiedSignature.getReason() ));
        //               tracer.info(String.format ( "signing location:    %s", verifiedSignature.getLocation() ));
        //               tracer.info(String.format ( "signing time:        %s", formatDate(verifiedSignature.getSigningTime()) ));
        //               tracer.info(String.format ( "\n "));
        //               tracer.info(String.format ( "signing certificate chain: "));
        //               for ( X509Certificate cert : verifiedSignature.getRawX509Certificates() ) {
        //                  showCertificate(cert);
        //               }
        //               if ( verifiedSignature.getTimeStamps() != null ) {
        //                  tracer.info(String.format ( "\n "));
        //                  tracer.info(String.format ( "timestamps: "));
        //                  for ( TimeStampInfo mark : verifiedSignature.getTimeStamps() ) {
        //                     tracer.info(String.format ( "timestamp validity:  %s", mark.getVerifyResult().name() ));
        //                     tracer.info(String.format ( "timestamp authority: %s", mark.getTsaName() ));
        //                     tracer.info(String.format ( "timestamp authority: %s", mark.getTsaName() ));
        //                     tracer.info(String.format ( "message imprint alg: %s", mark.getMessageInprintInfo().getAlgorithm().name() ));
        //                     tracer.info(String.format ( "message imprint:     %s", HexUtils.encodeHex(mark.getMessageInprintInfo().getFingerPrint()) ));
        //                     tracer.info(String.format ( "digest algorithm:    %s", mark.getDigestAlgorithm().name() ));
        //                     tracer.info(String.format ( "digital signature:   %s", HexUtils.encodeHex(mark.getDigitalSignature()) ));
        //                     tracer.info(String.format ( "signature algorithm: %s", mark.getSignAlgorithm().name() ));
        //                     tracer.info(String.format ( "timestamp certificate: "));
        //                     for ( X509Certificate cert : mark.getRawX509Certificates() ) {
        //                        showCertificate(cert);
        //                     }
        //                  }
        //               }
        //            }
        //         } catch(Exception e) {
        //            tracer.error("unable to print the verify results", e);
        //            throw e;
        //         }
        //         
    } finally {
        applet.close();
    }
}

From source file:org.sinekartads.integration.xml.SignXMLonAlfresco.java

@Test
public void test() throws Exception {
    if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
        Security.addProvider(new BouncyCastleProvider());
    }//from   ww  w. j  av a2  s . c om

    SignNOApplet applet = new SignNOApplet();
    try {

        // Main options
        boolean applyMark = false;
        boolean useFakeSmartCard = false;
        String driver;
        String scPin;
        if (useFakeSmartCard) {
            driver = "fake";
            scPin = "123";
        } else {
            driver = "libbit4ipki.so";
            scPin = "18071971";
        }

        // Test products
        String[] aliases;
        String alias;
        X509Certificate certificate;
        X509Certificate[] certificateChain;
        byte[] fingerPrint;
        byte[] digitalSignature;

        // Communication unities
        DocumentDTO[] documents;
        String jsonResp;
        SkdsDocumentDetailsResponse detailsResp;
        SkdsPreSignResponse preSignResp;
        SkdsPostSignResponse postSignResp;
        AppletResponseDTO appletResponse;
        SignatureDTO emptySignatureDTO;
        SignatureDTO chainSignatureDTO;
        SignatureDTO digestSignatureDTO;
        SignatureDTO signedSignatureDTO;
        SignatureDTO finalizedSignatureDTO;
        VerifyDTO verifyDTO;

        // Init the applet
        try {
            AppletRequestDTO req = new AppletRequestDTO();
            req.setDriver(driver);
            appletResponse = applet.selectDriver(req);
        } catch (Exception e) {
            tracer.error("error during the applet initialization", e);
            throw e;
        }

        // Login with the smartCard
        try {
            AppletRequestDTO req = new AppletRequestDTO();
            req.setDriver(driver);
            req.setPin(scPin);
            appletResponse = applet.login(req);
            aliases = (String[]) JSONUtils.deserializeJSON(String[].class, extractJSON(appletResponse));
        } catch (Exception e) {
            tracer.error("error during the applet login", e);
            throw e;
        }

        // Choose the signing alias
        StringBuilder buf = new StringBuilder();
        for (String a : aliases) {
            buf.append(a).append(" ");
        }
        alias = aliases[0];
        tracer.info(String.format("available aliases:   %s", buf));
        tracer.info(String.format("signing alias:       %s", alias));

        // Load the certificate chain from the applet
        try {
            AppletRequestDTO req = new AppletRequestDTO();
            req.setDriver(driver);
            req.setPin(scPin);
            req.setAlias(alias);
            appletResponse = applet.selectCertificate(req);
            certificate = (X509Certificate) X509Utils.rawX509CertificateFromHex(extractJSON(appletResponse));
            tracer.info(String.format("certificate:         %s", certificate));
            certificateChain = new X509Certificate[] { certificate };
        } catch (Exception e) {
            tracer.error("error during the certificate selection", e);
            throw e;
        }

        // FindRefByName
        String sourceRef = null;
        try {
            SkdsFindRefByNameRequest req = new SkdsFindRefByNameRequest();
            req.setName(SOURCE_NAME);
            SkdsFindRefByNameResponse findResp = postJsonRequest(req, SkdsFindRefByNameResponse.class);
            if (ResultCode.valueOf(findResp.getResultCode()) == ResultCode.SUCCESS) {
                sourceRef = findResp.getNodeRef();
            } else {
                throw new Exception(findResp.getMessage());
            }
        } catch (Exception e) {
            tracer.error("error during the pre sign phase", e);
            throw e;
        }

        // DocumentDetails
        try {
            SkdsDocumentDetailsRequest req = new SkdsDocumentDetailsRequest();
            req.setNodeRefs(new String[] { sourceRef });
            detailsResp = postJsonRequest(req, SkdsDocumentDetailsResponse.class);
            if (ResultCode.valueOf(detailsResp.getResultCode()) == ResultCode.SUCCESS) {
                documents = detailsResp.documentsFromBase64();
            } else {
                throw new Exception(detailsResp.getMessage());
            }
            Assert.isTrue(StringUtils.equals(documents[0].getBaseDocument().getMimetype(), "text/xml"));
            String baseName = FilenameUtils.getBaseName(documents[0].getBaseDocument().getFileName());
            if (applyMark) {
                documents[0].setDestName(baseName + "_t.pdf");
            } else {
                documents[0].setDestName(baseName + "_bes.pdf");
            }
        } catch (Exception e) {
            tracer.error("error during the pre sign phase", e);
            throw e;
        }

        // empty signature - initialized with the SHA256withRSA and RSA algorithms
        emptySignatureDTO = new SignatureDTO();
        emptySignatureDTO.setSignAlgorithm(conf.getSignatureAlgorithm().getName());
        emptySignatureDTO.setDigestAlgorithm(conf.getDigestAlgorithm().getName());
        emptySignatureDTO.signCategoryToString(SignCategory.XML);

        // Add to the empty signature the timeStamp request if needed
        TimeStampRequestDTO tsRequestDTO = new TimeStampRequestDTO();
        if (applyMark) {
            tsRequestDTO.timestampDispositionToString(SignDisposition.TimeStamp.ENVELOPING);
            tsRequestDTO.messageImprintAlgorithmToString(DigestAlgorithm.SHA256);
            tsRequestDTO.nounceToString(BigInteger.TEN);
            tsRequestDTO.setTsUrl("http://ca.signfiles.com/TSAServer.aspx");
        }
        emptySignatureDTO.setTimeStampRequest(tsRequestDTO);

        // chain signature - contains the certificate chain
        chainSignatureDTO = TemplateUtils.Instantiation.clone(emptySignatureDTO);
        chainSignatureDTO.certificateChainToHex(certificateChain);
        documents[0].setSignatures(new SignatureDTO[] { chainSignatureDTO });

        // PreSign phase - join the content with the certificate chain and evaluate the digest
        try {
            SkdsPreSignRequest req = new SkdsPreSignRequest();
            req.documentsToBase64(documents);
            preSignResp = postJsonRequest(req, SkdsPreSignResponse.class);
            if (ResultCode.valueOf(preSignResp.getResultCode()) == ResultCode.SUCCESS) {
                documents = preSignResp.documentsFromBase64();
                digestSignatureDTO = documents[0].getSignatures()[0];
            } else {
                throw new Exception(preSignResp.getMessage());
            }
        } catch (Exception e) {
            tracer.error("error during the pre sign phase", e);
            throw e;
        }

        // signed signature - sign the digest with the smartCard to obtain the digitalSignature
        try {
            fingerPrint = digestSignatureDTO.getDigest().fingerPrintFromHex();
            tracer.info(String.format("fingerPrint:         %s", HexUtils.encodeHex(fingerPrint)));
            AppletRequestDTO req = new AppletRequestDTO();
            req.setDriver(driver);
            req.setPin(scPin);
            req.setAlias(alias);
            req.setHexDigest(HexUtils.encodeHex(fingerPrint));
            appletResponse = applet.signDigest(req);
            digitalSignature = HexUtils.decodeHex((String) extractJSON(appletResponse));
            tracer.info(String.format("digitalSignature:    %s", HexUtils.encodeHex(digitalSignature)));
            signedSignatureDTO = TemplateUtils.Instantiation.clone(digestSignatureDTO);
            signedSignatureDTO.digitalSignatureToHex(digitalSignature);
            documents[0].getSignatures()[0] = signedSignatureDTO;
        } catch (Exception e) {
            tracer.error("error during the digital signature evaluation", e);
            throw e;
        }

        // PostSign phase - add the digitalSignature to the envelope and store the result into the JCLResultDTO
        try {
            SkdsPostSignRequest req = new SkdsPostSignRequest();
            req.documentsToBase64(documents);
            postSignResp = postJsonRequest(req, SkdsPostSignResponse.class);
            if (ResultCode.valueOf(postSignResp.getResultCode()) == ResultCode.SUCCESS) {
                documents = postSignResp.documentsFromBase64();
                finalizedSignatureDTO = documents[0].getSignatures()[0];
            } else {
                throw new Exception(postSignResp.getMessage());
            }
        } catch (Exception e) {
            tracer.error("error during the envelope generation", e);
            throw e;
        }

        //         // Verify phase - load the envelope content and verify the nested signature 
        //         try {
        //            jsonResp = signatureService.verify ( envelopeHex, null, null, VerifyResult.VALID.name() );
        //            verifyDTO = extractResult ( VerifyDTO.class, jsonResp );
        //         } catch(Exception e) {
        //            tracer.error("error during the envelope verification", e);
        //            throw e;
        //         }
        //         
        //         // finalized signature - enveloped signed and eventually marked, not modifiable anymore
        //         try {
        //            verifyResult = (VerifyInfo) converter.toVerifyInfo( verifyDTO );
        //         } catch(Exception e) {
        //            tracer.error("unable to obtain the verifyInfo from the DTO", e);
        //            throw e;
        //         }
        //         
        //         try {
        //            for(VerifiedSignature < ?, ?, VerifyResult, ?> verifiedSignature : verifyResult.getSignatures() ) {
        //               tracer.info(String.format ( "signature validity:  %s", verifiedSignature.getVerifyResult().name() ));
        //               tracer.info(String.format ( "signature type:      %s", verifiedSignature.getSignType().name() ));
        //               tracer.info(String.format ( "disposition:         %s", verifiedSignature.getDisposition().name() ));
        //               tracer.info(String.format ( "digest algorithm:    %s", verifiedSignature.getDigest().getAlgorithm().name() ));
        //               tracer.info(String.format ( "finger print:        %s", HexUtils.encodeHex(verifiedSignature.getDigest().getFingerPrint()) ));
        //               tracer.info(String.format ( "counter signature:   %s", verifiedSignature.isCounterSignature() ));
        //               tracer.info(String.format ( "signature algorithm: %s", verifiedSignature.getSignAlgorithm().name() ));
        //               tracer.info(String.format ( "digital signature:   %s", HexUtils.encodeHex(verifiedSignature.getDigitalSignature()) ));
        //               tracer.info(String.format ( "reason:              %s", verifiedSignature.getReason() ));
        //               tracer.info(String.format ( "signing location:    %s", verifiedSignature.getLocation() ));
        //               tracer.info(String.format ( "signing time:        %s", formatDate(verifiedSignature.getSigningTime()) ));
        //               tracer.info(String.format ( "\n "));
        //               tracer.info(String.format ( "signing certificate chain: "));
        //               for ( X509Certificate cert : verifiedSignature.getRawX509Certificates() ) {
        //                  showCertificate(cert);
        //               }
        //               if ( verifiedSignature.getTimeStamps() != null ) {
        //                  tracer.info(String.format ( "\n "));
        //                  tracer.info(String.format ( "timestamps: "));
        //                  for ( TimeStampInfo mark : verifiedSignature.getTimeStamps() ) {
        //                     tracer.info(String.format ( "timestamp validity:  %s", mark.getVerifyResult().name() ));
        //                     tracer.info(String.format ( "timestamp authority: %s", mark.getTsaName() ));
        //                     tracer.info(String.format ( "timestamp authority: %s", mark.getTsaName() ));
        //                     tracer.info(String.format ( "message imprint alg: %s", mark.getMessageInprintInfo().getAlgorithm().name() ));
        //                     tracer.info(String.format ( "message imprint:     %s", HexUtils.encodeHex(mark.getMessageInprintInfo().getFingerPrint()) ));
        //                     tracer.info(String.format ( "digest algorithm:    %s", mark.getDigestAlgorithm().name() ));
        //                     tracer.info(String.format ( "digital signature:   %s", HexUtils.encodeHex(mark.getDigitalSignature()) ));
        //                     tracer.info(String.format ( "signature algorithm: %s", mark.getSignAlgorithm().name() ));
        //                     tracer.info(String.format ( "timestamp certificate: "));
        //                     for ( X509Certificate cert : mark.getRawX509Certificates() ) {
        //                        showCertificate(cert);
        //                     }
        //                  }
        //               }
        //            }
        //         } catch(Exception e) {
        //            tracer.error("unable to print the verify results", e);
        //            throw e;
        //         }

    } finally {
        applet.close();
    }
}