Example usage for org.joda.time DateTime now

List of usage examples for org.joda.time DateTime now

Introduction

In this page you can find the example usage for org.joda.time DateTime now.

Prototype

public static DateTime now() 

Source Link

Document

Obtains a DateTime set to the current system millisecond time using ISOChronology in the default time zone.

Usage

From source file:ch.bfh.ti.ictm.iam.stiam.aa.authority.AttributeService.java

License:MIT License

/**
 * Method inherited from HttpServlet. Handles POST-requests, tries to
 * extract extended SAML attribute queries from the request and return
 * appropriate responses.//  w  w w  .ja v  a2  s .  c om
 *
 * @param req The request-instance obtained from the container
 * @param res The response-instance obtained from the container
 * @throws ServletException
 * @throws IOException
 */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    logger.info("Request received!");
    final DateTime receptionTime = DateTime.now();

    //////////////////// Decode raw request
    logger.debug("Trying to decode raw request...");
    final MessageContext messageContext = new BasicSAMLMessageContext();
    messageContext.setInboundMessageTransport(new HttpServletRequestAdapter(req));
    final BaseSAMLMessageDecoder messageDecoder;
    if (config.getBinding() == StiamConfiguration.Binding.HTTP_POST) {
        logger.debug("Using HTTPPostDecoder for decoding...");
        messageDecoder = new HTTPPostDecoder();
    } else {
        logger.debug("Using HTTPSOAP11Decoder for decoding...");
        messageDecoder = new HTTPSOAP11Decoder();
    }

    try {
        messageDecoder.decode(messageContext);
    } catch (MessageDecodingException | SecurityException | IllegalArgumentException ex) {
        sendSAMLError(res, 400, "Decoding failed: " + ex.getMessage(), "", "", new String[] {
                ResponseBuilder.STATUS_CODE_REQUESTER, ResponseBuilder.STATUS_CODE_REQUEST_DENIED });
        return;
    }
    logger.debug("Decoding succeeded!");

    //////////////////// Read out attribute-query
    logger.debug("Trying to read AttributeQuery...");
    AttributeQuery attributeQuery = null;
    try {
        if (config.getBinding() == StiamConfiguration.Binding.HTTP_POST) {
            attributeQuery = (AttributeQuery) messageContext.getInboundMessage();
        } else {
            final Envelope soapEnvelope = (Envelope) messageContext.getInboundMessage();
            final List<XMLObject> bodyElements = soapEnvelope.getBody().getUnknownXMLObjects();

            for (XMLObject element : bodyElements) {
                if (element instanceof AttributeQuery) {
                    attributeQuery = (AttributeQuery) element;
                }
            }
        }
    } catch (ClassCastException ex) {
        sendSAMLError(res, 400, "AttributeQuery could not be read!", "", "", new String[] {
                ResponseBuilder.STATUS_CODE_REQUESTER, ResponseBuilder.STATUS_CODE_REQUEST_DENIED });
        return;
    }

    if (attributeQuery == null) {
        sendSAMLError(res, 400, "No AttributeQuery found!", "", "", new String[] {
                ResponseBuilder.STATUS_CODE_REQUESTER, ResponseBuilder.STATUS_CODE_REQUEST_DENIED });
        return;
    }

    logger.debug("Sucessfully read AttributeQuery!");

    //////////////////// Try to read out QueryID, Issuer and NameID of the query
    logger.debug("Reading QueryID, Issuer and NameID of the query...");
    final String queryID;
    final String queryIssuer;
    final String nameID;
    try {
        queryID = attributeQuery.getID();
        queryIssuer = attributeQuery.getIssuer().getValue();
        nameID = attributeQuery.getSubject().getNameID().getValue();
    } catch (Exception ex) {
        sendSAMLError(res, 400, "Unable to read essential attributes of the query!", "", "", new String[] {
                ResponseBuilder.STATUS_CODE_REQUESTER, ResponseBuilder.STATUS_CODE_REQUEST_DENIED });
        return;
    }
    logger.debug("Query with ID '{}' received from issuer '{}' for subject '{}'.", queryID, queryIssuer,
            nameID);

    //////////////////// Verify signature of the attribute query
    if (config.verifyQuerySignature()) {
        logger.debug("Trying to verify signature of the attribute query...");
        if (!verifySignature(attributeQuery.getSignature(), attributeQuery.getIssuer().getValue().toString())) {
            sendSAMLError(res, 400, "Signature validation failed!", queryIssuer, queryID, new String[] {
                    ResponseBuilder.STATUS_CODE_REQUESTER, ResponseBuilder.STATUS_CODE_REQUEST_DENIED });
            return;
        }
        logger.debug("Signature verified successfully!");
    }

    //////////////////// Check if subject is eligible...
    logger.debug("Checking subject eligibility...");
    if (!eligibilityChecker.isEligible(nameID)) {
        sendSAMLError(res, 400, "Subject not eligible!", queryIssuer, queryID, new String[] {
                ResponseBuilder.STATUS_CODE_RESPONDER, ResponseBuilder.STATUS_CODE_UNKNOWN_PRINCIPAL });
        return;
    }
    logger.debug("Subject is eligible, continueing");

    //////////////////// Verify if we have extensions and if they contain an authentication statement
    if (config.verifyAuthnStatement()) {
        logger.debug("Trying to verify embedded Authn-Assertion...");

        logger.debug("Reading out assertion...");
        final AuthnStatement authnStatement;
        final Assertion assertion;
        final String assertionNameID;
        try {
            // Note: this code only works for the very limited assumption that we only have one
            // extension in the query (which is to be assumed to be an Assertion) and that this
            // in turn contains exactly one AuthnStatement. For other than PoC-code, this must be
            // implemented properly...
            assertion = (Assertion) attributeQuery.getExtensions().getUnknownXMLObjects().get(0);
            assertionNameID = assertion.getSubject().getNameID().getValue();
            authnStatement = (AuthnStatement) assertion.getStatements().get(0);
            if (authnStatement == null) {
                sendSAMLError(res, 400, "Unable to read embedded authentication statement!", queryIssuer,
                        queryID, new String[] { ResponseBuilder.STATUS_CODE_REQUESTER,
                                ResponseBuilder.STATUS_CODE_NO_AUTHN_CONTEXT });
                return;
            }
        } catch (Exception ex) {
            sendSAMLError(res, 400, "Unable to read embedded authentication statement!", queryIssuer, queryID,
                    new String[] { ResponseBuilder.STATUS_CODE_REQUESTER,
                            ResponseBuilder.STATUS_CODE_NO_AUTHN_CONTEXT });
            return;
        }
        logger.debug("Successfully read assertion!");

        //////////////////// Compare NameID of authentication assertion to attribute query
        logger.debug("Ensuring that NameIDs match...");
        if (!assertionNameID.equals(nameID)) {
            sendSAMLError(res, 400, "NameID of assertion does not match NameID of attribute query!",
                    queryIssuer, queryID, new String[] { ResponseBuilder.STATUS_CODE_REQUESTER,
                            ResponseBuilder.STATUS_CODE_NO_AUTHN_CONTEXT });
            return;
        }
        logger.debug("NameIDs are equal!");

        //////////////////// Verify signature of the assertion
        if (config.verifyAuthnSignature()) {
            logger.debug("Trying to validate signature of authentication statement...");
            if (!verifySignature(assertion.getSignature(), assertion.getIssuer().getValue().toString())) {
                sendSAMLError(res, 400, "Signature validation failed!", queryIssuer, queryID, new String[] {
                        ResponseBuilder.STATUS_CODE_REQUESTER, ResponseBuilder.STATUS_CODE_NO_AUTHN_CONTEXT });
                return;
            }
            logger.debug("Signature verified successfully!");
        }

        //////////////////// Verify NotBefore / NotOnOrAfter in the Conditions of the authentication statement
        if (config.verifyAuthnTimespan()) {
            logger.debug("Trying to validate authentication-timespan...");
            if (receptionTime.isBefore(assertion.getConditions().getNotBefore())
                    || receptionTime.isEqual(assertion.getConditions().getNotOnOrAfter())
                    || receptionTime.isAfter(assertion.getConditions().getNotOnOrAfter())) {
                sendSAMLError(res, 400, "Received statement is not in authentication-timespan!", queryIssuer,
                        queryID, new String[] { ResponseBuilder.STATUS_CODE_REQUESTER,
                                ResponseBuilder.STATUS_CODE_NO_AUTHN_CONTEXT });
                return;
            }
            logger.debug("Authentication-timespan verifed!");
        }

        logger.debug("Authn-Assertion found and validated!");
    }

    //////////////////// Read out attributes
    logger.debug("Reading Attributes...");
    final HashMap<String, Attribute> attributes = new HashMap<>(10);
    for (org.opensaml.saml2.core.Attribute attr : attributeQuery.getAttributes()) {
        attributes.put(attr.getName(), new Attribute(attr));
    }
    if (attributes.isEmpty()) {
        sendSAMLError(res, 400, "No attributes found in query!", queryIssuer, queryID, new String[] {
                ResponseBuilder.STATUS_CODE_REQUESTER, ResponseBuilder.STATUS_CODE_REQUEST_DENIED });
        return;
    }
    logger.debug("Found {} attributes in query", attributes.size());

    for (Attribute attr : attributes.values()) {
        logger.debug("Attribute: {}", attr);
    }

    //////////////////// Query attributes in directory
    logger.debug("Retrieving attributes from directory...");
    try {
        final String[] attributeNames = new String[attributes.size()];
        int i = 0;
        for (String name : attributes.keySet()) {
            attributeNames[i] = name;
            i++;
        }
        final Map<String, String> fetchedAttributes = directory.fetchAttributes(nameID, attributeNames);

        for (String name : attributeNames) {
            attributes.get(name).setValue(fetchedAttributes.get(name));
            logger.debug("Got value: {}", attributes.get(name));
        }
    } catch (NameIDNotFoundException ex) {
        sendSAMLError(res, 400, "Subject not found!", queryIssuer, queryID, new String[] {
                ResponseBuilder.STATUS_CODE_RESPONDER, ResponseBuilder.STATUS_CODE_UNKNOWN_PRINCIPAL });
        return;
    } catch (DirectoryException ex) {
        sendError(res, 500, "Error while fetching Attributes in directory: " + ex.getMessage());
        return;
    }
    logger.debug("Attributes retrieved!");

    //////////////////// Return attribute assertion
    logger.debug("Sending response...");
    try {
        logger.debug("Building attribute response...");
        final AttributeResponseBuilder builder = new AttributeResponseBuilder(queryIssuer, queryID, nameID,
                attributes.values());
        if (config.getBinding() == StiamConfiguration.Binding.HTTP_POST) {
            res.setStatus(200);
            res.setContentType("text/html");

            final PrintWriter pw = res.getWriter();
            pw.println("<!DOCTYPE html>");
            pw.println("<html><head>\n<meta charset=\"utf-8\"/>\n<title>SAMLResponse</title>\n</head>");
            pw.println("<body onload=\"function () { document.forms[0].submit(); }\">");
            pw.println("<form method=\"post\" action=\"" + queryIssuer + "\">");
            pw.println("<input type=\"hidden\" name=\"SAMLResponse\" value=\""
                    + URLEncoder.encode(builder.buildBase64(), "UTF-8") + "\"/>");
            pw.println("</form>");
            pw.println("</body>\n</html>");
        } else {
            res.setStatus(200);
            res.setContentType("text/xml;charset=UTF-8");

            final PrintWriter pw = res.getWriter();
            pw.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            pw.print(
                    "<soap11:Envelope xmlns:soap11=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap11:Body>");
            pw.print(builder.build().substring(38)); // FIXME ugly substring-hack
            pw.print("</soap11:Body></soap11:Envelope>");
        }
    } catch (ConfigurationException | NoSuchAlgorithmException | KeyStoreException | CertificateException
            | UnrecoverableEntryException | SecurityException | MarshallingException | SignatureException
            | XMLParserException | TransformerException ex) {
        sendError(res, 500, "Error while building attribute response: " + ex.getMessage());
        return;
    }

    logger.info("Request handled!");
}

From source file:ch.bfh.ti.ictm.iam.stiam.aa.util.saml.ExtendedAttributeQueryBuilder.java

License:MIT License

/**
 * Builds a complete, extended SAML attribute query with included
 * authentication statement, both of them signed, serialized to String.
 * Overrides the method from MessageBuilder.
 *
 * @return Serialized extended attribute query as String
 * @throws ConfigurationException//  w  w w  .  j av a2s .c o m
 * @throws NoSuchAlgorithmException
 * @throws IOException
 * @throws FileNotFoundException
 * @throws KeyStoreException
 * @throws CertificateException
 * @throws UnrecoverableEntryException
 * @throws SecurityException
 * @throws MarshallingException
 * @throws SignatureException
 * @throws TransformerException
 * @throws XMLParserException
 */
@Override
public String build() throws ConfigurationException, NoSuchAlgorithmException, IOException, KeyStoreException,
        CertificateException, UnrecoverableEntryException, SecurityException, MarshallingException,
        SignatureException, XMLParserException, TransformerException {
    logger.debug("Starting generation of extended attribute query...");

    //////////////////// Perform initial setup
    DefaultBootstrap.bootstrap();
    final SecureRandomIdentifierGenerator idGenerator = new SecureRandomIdentifierGenerator();

    final DateTime queryTime = DateTime.now();
    final DateTime authnIssueTime = queryTime.minusMinutes(4);
    final DateTime authnNotBeforeTime = queryTime.minusMinutes(5);
    final DateTime authnNotAfterTime = queryTime.plusMinutes(5);

    //////////////////// The outer AttributeQuery
    final AttributeQuery query = (AttributeQuery) buildXMLObject(AttributeQuery.DEFAULT_ELEMENT_NAME);
    query.setID(idGenerator.generateIdentifier());
    query.setVersion(SAMLVersion.VERSION_20);
    query.setIssueInstant(queryTime);
    query.setSubject(null);
    query.setDestination(config.getSAMLDestination());

    // Issuer of the AttributeQuery
    final Issuer queryIssuer = (Issuer) buildXMLObject(Issuer.DEFAULT_ELEMENT_NAME);
    queryIssuer.setValue(config.getSAMLIssuer());
    query.setIssuer(queryIssuer);

    // Subject of the AttributeQuery
    final Subject querySubject = (Subject) buildXMLObject(Subject.DEFAULT_ELEMENT_NAME);
    query.setSubject(querySubject);

    // --> NameID of the Subject
    NameID queryNameID = (NameID) buildXMLObject(NameID.DEFAULT_ELEMENT_NAME);
    queryNameID.setFormat(config.getSAMLNameIDFormat());
    queryNameID.setValue(config.getSAMLNameID());
    querySubject.setNameID(queryNameID);

    // Attributes of the AttributeQuery
    for (String[] attr : attributes) {
        Attribute attribute = (Attribute) buildXMLObject(Attribute.DEFAULT_ELEMENT_NAME);
        attribute.setName(attr[0]);
        if (attr.length >= 2) {
            attribute.setNameFormat(attr[1]);
        }
        if (attr.length >= 3) {
            attribute.setFriendlyName(attr[2]);
        }
        query.getAttributes().add(attribute);
    }

    //////////////////// The Assertion added to the Extensions of the above query
    Assertion assertion = (Assertion) buildXMLObject(Assertion.DEFAULT_ELEMENT_NAME);
    assertion.setID(idGenerator.generateIdentifier());
    assertion.setVersion(SAMLVersion.VERSION_20);
    assertion.setIssueInstant(authnIssueTime);

    // --> Issuer of the Assertion
    Issuer assertionIssuer = (Issuer) buildXMLObject(Issuer.DEFAULT_ELEMENT_NAME);
    assertionIssuer.setValue(config.getSAMLIssuer());
    assertion.setIssuer(assertionIssuer);

    // --> Subject of the Assertion
    Subject assertionSubject = (Subject) buildXMLObject(Subject.DEFAULT_ELEMENT_NAME);
    assertion.setSubject(assertionSubject);

    // --> -->  NameID for the Subject of the Assertion
    NameID assertionNameID = (NameID) buildXMLObject(NameID.DEFAULT_ELEMENT_NAME);
    assertionNameID.setFormat(config.getSAMLNameIDFormat());
    assertionNameID.setValue(config.getSAMLNameID());
    assertionSubject.setNameID(assertionNameID);

    // --> -->  SubjectConfirmation for the Subject of the Assertion
    SubjectConfirmation assertionSubjectConfirmation = (SubjectConfirmation) buildXMLObject(
            SubjectConfirmation.DEFAULT_ELEMENT_NAME);
    assertionSubjectConfirmation.setMethod(config.getSAMLSubjectConfirmationMethod());
    assertionSubject.getSubjectConfirmations().add(assertionSubjectConfirmation);

    // --> Conditions for the Assertion
    Conditions conditions = (Conditions) buildXMLObject(Conditions.DEFAULT_ELEMENT_NAME);
    conditions.setNotBefore(authnNotBeforeTime);
    conditions.setNotOnOrAfter(authnNotAfterTime);
    assertion.setConditions(conditions);

    // --> --> AudienceRestriction for the Conditions
    AudienceRestriction audienceRestriction = (AudienceRestriction) buildXMLObject(
            AudienceRestriction.DEFAULT_ELEMENT_NAME);
    conditions.getAudienceRestrictions().add(audienceRestriction);

    // --> --> --> Audience for the AudienceRestriction
    Audience audience = (Audience) buildXMLObject(Audience.DEFAULT_ELEMENT_NAME);
    audience.setAudienceURI(config.getSAMLIssuer());
    audienceRestriction.getAudiences().add(audience);

    // --> AuthnStatement for the Assertion
    AuthnStatement authnStatement = (AuthnStatement) buildXMLObject(AuthnStatement.DEFAULT_ELEMENT_NAME);
    authnStatement.setAuthnInstant(authnIssueTime);
    assertion.getAuthnStatements().add(authnStatement);

    // -->-->  AuthnContext for the AuthnStatement
    AuthnContext authnContext = (AuthnContext) buildXMLObject(AuthnContext.DEFAULT_ELEMENT_NAME);
    authnStatement.setAuthnContext(authnContext);

    // --> -->-->  AuthnContextClassRef for AuthnContext
    AuthnContextClassRef authnContextClassRef = (AuthnContextClassRef) buildXMLObject(
            AuthnContextClassRef.DEFAULT_ELEMENT_NAME);
    authnContextClassRef.setAuthnContextClassRef(config.getSAMLAssuranceLevel());
    authnContext.setAuthnContextClassRef(authnContextClassRef);

    //////////////////// Sign the assertion and add it to the query
    Credential signingCredential = StiamConfiguration.getInstance().getSignatureCredential();
    Signature assertionSignature = (Signature) buildXMLObject(Signature.DEFAULT_ELEMENT_NAME);
    assertionSignature.setSigningCredential(signingCredential);
    SecurityHelper.prepareSignatureParams(assertionSignature, signingCredential, null, null);
    assertion.setSignature(assertionSignature);
    Configuration.getMarshallerFactory().getMarshaller(assertion).marshall(assertion);
    Signer.signObject(assertionSignature);

    // Extensions of the AttributeQuery
    // Manually build the correct QName, otherwise "md"-namespace gets marshalled...
    // see https://groups.google.com/forum/#!topic/opensaml-users/FFCQ48uqw3o for details.
    QName name = new QName(SAMLConstants.SAML20P_NS, Extensions.LOCAL_NAME, SAMLConstants.SAML20P_PREFIX);
    Extensions extensions = (Extensions) Configuration.getBuilderFactory().getBuilder(name).buildObject(name);
    extensions.getUnknownXMLObjects().add(assertion);
    query.setExtensions(extensions);

    //////////////////// Sign the query
    Signature querySignature = (Signature) buildXMLObject(Signature.DEFAULT_ELEMENT_NAME);
    querySignature.setSigningCredential(signingCredential);
    SecurityHelper.prepareSignatureParams(querySignature, signingCredential, null, null);
    query.setSignature(querySignature);
    Configuration.getMarshallerFactory().getMarshaller(query).marshall(query);
    Signer.signObject(querySignature);

    logger.debug("Extended attribute query generated!");
    return marshallToString(query);
}

From source file:ch.bfh.ti.ictm.iam.stiam.aa.util.saml.ResponseBuilder.java

License:MIT License

/**
 * Default constructor, allowing subclasses to have constructors with
 * different parameters/*  w  w w.  j  a va2  s.  co m*/
 */
private ResponseBuilder() {
    this.destination = "";
    this.inResponseTo = "";
    this.statusCodes = new String[] { STATUS_CODE_SUCCESS };
    issueInstant = DateTime.now();
}

From source file:ch.bfh.ti.ictm.iam.stiam.aa.util.saml.ResponseBuilder.java

License:MIT License

/**
 * Initialises a builder for status responses with the given status codes.
 *
 * @param destination The recipient of the response
 * @param inResponseTo ID from the requesting extended responseAttribute
 * query/*from  w  ww  .  j  a v  a2s  .  co  m*/
 * @param statusCodes An array of statuscodes to include in the response
 * @throws org.opensaml.xml.ConfigurationException
 * @throws java.security.NoSuchAlgorithmException
 */
public ResponseBuilder(String destination, String inResponseTo, String[] statusCodes)
        throws ConfigurationException, NoSuchAlgorithmException {
    this.destination = destination;
    this.inResponseTo = inResponseTo;
    this.statusCodes = statusCodes;

    DefaultBootstrap.bootstrap();
    issueInstant = DateTime.now();
}

From source file:ch.bfh.ti.soed.hs16.srs.yellow.controllers.JPARealDataAccessor.java

License:Open Source License

private void generateFakeData() {
    Building building = this.makeBuilding("GEO1");
    Building building1 = this.makeBuilding("NAT2");
    Building building2 = this.makeBuilding("ROLEX3");
    Building building3 = this.makeBuilding("ID4");
    Building building4 = this.makeBuilding("TRN5");
    Equipment equipment = this.makeEquipment("TV");
    Equipment equipment1 = this.makeEquipment("Panoramic view");
    Equipment equipment2 = this.makeEquipment("Douche");
    Equipment equipment3 = this.makeEquipment("Projector");
    Equipment equipment4 = this.makeEquipment("Embedded PC");
    Customer customer = this.makeCustomer("nt4245", "rwutth9428*/&");
    Customer customer1 = this.makeCustomer("test", "twztuzrw85478&/(");
    Customer customer2 = this.makeCustomer("test1", "rwut428*/&");
    Customer customer3 = this.makeCustomer("test2", "fkdsnmfks428*/&");
    Customer customer4 = this.makeCustomer("test3", "rwutt(()7778*/&");
    Room room = this.makeRoom("N1", 15);
    Room room1 = this.makeRoom("N2", 10);
    Room room2 = this.makeRoom("N3", 12);
    Room room3 = this.makeRoom("N4", 13);
    Room room4 = this.makeRoom("N5", 16);
    Booking booking = this.makeBooking(customer, room, DateTime.now(), new DateTime(2017, 6, 2, 5, 17));
    Booking booking1 = this.makeBooking(customer1, room1, DateTime.now(), new DateTime(2017, 6, 2, 5, 13));
    Booking booking2 = this.makeBooking(customer, room, DateTime.now(), new DateTime(2017, 6, 2, 4, 17));
}

From source file:ch.css.workingdiary.service.UserService.java

License:Open Source License

public Optional<Map<String, String>> getAccessToken(final User user) {
    final DateTime now = DateTime.now();
    final HmacSHA512Signer signer = new HmacSHA512Signer(tokenSecret);
    final JsonWebToken token = JsonWebToken.builder().header(JsonWebTokenHeader.HS512())
            .claim(JsonWebTokenClaim.builder().param("principal", user.getUsername())
                    .param("userId", user.getId()).issuedAt(now).expiration(now.plusHours(1)).build())
            .build();// w  w  w.j ava 2  s.co m
    final String signedToken = signer.sign(token);
    return Optional.of(singletonMap("accessToken", signedToken));
}

From source file:ch.fihlon.moodini.business.token.control.TokenService.java

License:Open Source License

private String generateToken(@NotNull final User user) {
    final HmacSHA512Signer signer = new HmacSHA512Signer(tokenSecret);
    final JsonWebToken token = JsonWebToken.builder().header(JsonWebTokenHeader.HS512())
            .claim(JsonWebTokenClaim.builder().subject(user.getUserId().toString()).issuedAt(DateTime.now())
                    .expiration(DateTime.now().plusHours(12)).build())
            .build();/* w w  w. j av a  2 s .co  m*/

    return signer.sign(token);
}

From source file:ch.ge.ve.offlineadmin.controller.BallotDecryptionController.java

License:Open Source License

private void saveCleartextBallots(List<String> decryptedBallots) {
    try {//from w  w  w .ja v a2  s  .co  m
        File selectedDirectory = selectDirectory();
        final String ballotsFilename = propertyConfigurationService.getConfigValue(BALLOTS_FILENAME);

        Path cleartextBallotsFilename = Paths.get(selectedDirectory.toString(),
                outputFilesPattern.injectParams(ballotsFilename, DateTime.now()));
        Files.write(cleartextBallotsFilename, decryptedBallots);

        byte[] cleartextBallotsFileHash;
        try (InputStream cleartextBallotsInputStream = Files.newInputStream(cleartextBallotsFilename,
                StandardOpenOption.READ)) {
            cleartextBallotsFileHash = streamHasher.threadSafeComputeHash(cleartextBallotsInputStream);
        }
        consoleOutputController
                .logOnScreen(String.format(resources.getString("ballot_decryption.output_file_hash"),
                        DatatypeConverter.printHexBinary(cleartextBallotsFileHash)));

        consoleOutputController.logOnScreen(
                String.format(resources.getString("ballot_decryption.file_saved"), cleartextBallotsFilename));
    } catch (ProcessInterruptedException | IOException | PropertyConfigurationException e) {
        consoleOutputController.logOnScreen(resources.getString("ballot_decryption.process_interrupted"),
                LogLevel.WARN);
        LOGGER.warn(PROCESS_INTERRUPTED_MESSAGE, e);
    }
}

From source file:ch.ge.ve.offlineadmin.controller.KeyGenerationController.java

License:Open Source License

private void saveKeys(SecretKey secretKey, X509Certificate certificate, KeyStore store, char[] password)
        throws ProcessInterruptedException, PropertyConfigurationException {
    File selectedDirectory = fileUtils.getDirectory(resources.getString("key_generation.dir_chooser.title"),
            fileUtils.getUserHome());//from w ww .  jav  a2 s.  c  o  m

    if (selectedDirectory == null) {
        throw new ProcessInterruptedException("Directory selection cancelled");
    }

    OutputFilesPattern outputFilesPattern = new OutputFilesPattern();

    final DateTime now = DateTime.now();

    final String keysFolder = outputFilesPattern
            .injectParams(propertyConfigurationService.getConfigValue("keys_folder"), now);
    Path keyFolderPath = Paths.get(selectedDirectory.toString(), keysFolder);

    if (!keyFolderPath.toFile().mkdir()) {
        consoleOutputController.logOnScreen(
                String.format(resources.getString("already.existing_dir"), keyFolderPath), LogLevel.WARN);
    }

    String ctrlP12Filename = keyFolderPath + "/" + outputFilesPattern
            .injectParams(propertyConfigurationService.getConfigValue(CERT_PRIVATE_KEY_FILENAME), now);
    String ctrlDerFilename = keyFolderPath + "/" + outputFilesPattern
            .injectParams(propertyConfigurationService.getConfigValue(CERT_PUBLIC_KEY_FILENAME), now);
    String integrityKeyFilename = keyFolderPath + "/" + outputFilesPattern
            .injectParams(propertyConfigurationService.getConfigValue(INTEGRITY_KEY_FILENAME), now);

    keySavedMessage = resources.getString("key_generation.key_saved");

    storePrivateKey(store, password, ctrlP12Filename);
    storeCertificate(certificate, ctrlDerFilename);
    computePublicKeyHash(propertyConfigurationService, ctrlDerFilename);
    saveIntegrityKey(secretKey, integrityKeyFilename);
}

From source file:ch.opentrainingcenter.client.views.dialoge.SearchDialog.java

License:Open Source License

private void update() {
    Display.getDefault().asyncExec(new Runnable() {

        @Override//from w ww .  j  a  va  2  s . c o  m
        public void run() {
            final CriteriaContainer container = CriteriaFactory.createCriteriaContainer();
            // damit es meter werden * 1000
            container.addCriteria(CriteriaFactory.createDistanceCriteria(scale.getSelection() * 1000));
            container.addCriteria(CriteriaFactory.createNoteCriteria(beschreibungSearch.getText()));
            final Set<Sport> sports = new HashSet<>();
            if (runButton.getSelection()) {
                sports.add(Sport.RUNNING);
            }
            if (bikeButton.getSelection()) {
                sports.add(Sport.BIKING);
            }
            if (otherButton.getSelection()) {
                sports.add(Sport.OTHER);
            }
            container.addCriteria(CriteriaFactory.createSportCriteria(sports));
            container.addCriteria(CriteriaFactory.createStreckeCriteria(referenzTrainingId));
            final long start = DateTime.now().getMillis();

            final List<ITraining> result = new ArrayList<>();
            for (final ITraining training : trainings) {
                if (container.matches(training)) {
                    result.add(training);
                }
            }
            LOGGER.info(String.format("Filter trainings dauerte %s [ms]", DateTime.now().getMillis() - start)); //$NON-NLS-1$
            if (viewer != null) {
                viewer.setInput(result);
            }
            updateButton();
        }

    });
    scaleLabel.setText(String.format("%s %s", scale.getSelection(), Messages.SearchDialog_COMMON_KM)); //$NON-NLS-1$
}