Example usage for java.util Date getMinutes

List of usage examples for java.util Date getMinutes

Introduction

In this page you can find the example usage for java.util Date getMinutes.

Prototype

@Deprecated
public int getMinutes() 

Source Link

Document

Returns the number of minutes past the hour represented by this date, as interpreted in the local time zone.

Usage

From source file:pa_SymposiumPlanner.RuleML2008ChallengeChair.java

public void answerQuery() {
    try {//ww w .  j a v  a2s .c o m
        address = PAConfiguration.getAddress();
        port = PAConfiguration.getPort(instantiation);
        poslAddress = PAConfiguration.getPOSL(instantiation, topic);
        rdfAddress = PAConfiguration.getRDFTaxonomy(instantiation);
        messageEndpoint = PAConfiguration.getEndpointName(instantiation, topic);
    } catch (BadConfigurationException e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
        System.exit(0);
    }

    try {
        System.out.println("5 Publicty Chair Servlet");
        String message = "";

        SAXReader reader = new SAXReader();
        message = reader.read(new File("D:\\RuleMLMessage.xml")).asXML();

        String[] varOrder = getVariableOrder(message);
        System.out.println("Received Message: " + message);

        // BackwardReasoner br = new BackwardReasoner();
        // Iterator solit =null;
        // DefiniteClause dc = null;
        // SymbolTable.reset();

        POSLParser pp = new POSLParser();
        // String contents = "c(a).\nc(b).\nc(c).";

        Date t1 = new GregorianCalendar().getTime();
        System.out.println(t1.getHours() + ":" + t1.getMinutes());
        // append time to contents

        System.out.println("day: " + t1.getDay());
        System.out.println("day: " + t1.getYear());
        System.out.println("day: " + t1.getMonth());

        // time
        String time = "time(" + t1.getHours() + ":integer).";
        System.out.println(time);

        String url = poslAddress;

        // String url = "http://www.jdrew.org/oojdrew/test.posl";
        String contents = "";

        // day of the week
        int day = t1.getDay();
        boolean weekday = true;

        if (day == 0 || day == 6) {
            weekday = false;
        }

        String dayOfWeek;

        if (weekday) {
            dayOfWeek = "day(weekday).";
        } else {
            dayOfWeek = "day(weekend).";
        }
        // full date
        Calendar cal = new GregorianCalendar();

        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        int day2 = cal.get(Calendar.DAY_OF_MONTH);

        String date;

        String day3 = "" + day2;

        if (day2 == 1 || day2 == 2 || day2 == 3 || day2 == 4 || day2 == 5 || day2 == 6 || day2 == 7 || day2 == 8
                || day2 == 9) {

            day3 = "0" + day2;
        }

        if (month == 10 || month == 11 || month == 12)
            date = "" + year + month + day3;
        else
            date = "" + year + "0" + month + day3;

        date = "date(" + date + ":integer).";

        System.out.println(date);

        //         String url2 = rdfAddress;
        //         HttpClient client2 = new HttpClient();
        //         GetMethod method2 = new GetMethod(url2);
        //         method2.setFollowRedirects(true);
        //         String typestr = "";
        //         // Execute the GET method
        //         int statusCode2 = client2.executeMethod(method2);
        //         if (statusCode2 != -1) {
        //            typestr = method2.getResponseBodyAsString();
        //         }
        //         System.out.println("Types: " + typestr);
        //         Types.reset();
        //         RDFSParser.parseRDFSString(typestr);

        try {
            HttpClient client = new HttpClient();
            GetMethod method = new GetMethod(url);
            method.setFollowRedirects(true);

            // Execute the GET method
            int statusCode = client.executeMethod(method);
            if (statusCode != -1) {
                contents = method.getResponseBodyAsString();
            }
        }

        catch (Exception e) {
            e.printStackTrace();
        }
        contents = contents + "\n" + time;
        contents = contents + "\n" + dayOfWeek;
        contents = contents + "\n" + date;

        BackwardReasoner br = new BackwardReasoner();
        Iterator solit = null;
        DefiniteClause dc = null;
        SymbolTable.reset();

        pp.parseDefiniteClauses(contents);

        br.loadClauses(pp.iterator());
        System.out.println("TEST");
        Iterator it = pp.iterator();
        while (it.hasNext()) {
            DefiniteClause d = (DefiniteClause) it.next();
            System.out.println("Loaded clause: " + d.toPOSLString());
        }

        br = new BackwardReasoner(br.clauses, br.oids);

        MessageParser m = new MessageParser(message);
        Element atom = null;

        try {
            atom = m.parseForContent();
        } catch (Exception e) {

            System.out.println("Invalid Message");
            // out.flush();
        }

        QueryBuilder q = new QueryBuilder(atom);
        String query = q.generateDoc();
        System.out.println("ABOUT TO INPUT THIS QUERY:" + query);
        RuleMLParser qp = new RuleMLParser();

        try {

            dc = qp.parseRuleMLQuery(query);

        }

        catch (Exception e) {
            System.out.println("Invalid Query");
            // out.flush();
        }

        // solit = br.iterativeDepthFirstSolutionIterator(dc);

        solit = br.iterativeDepthFirstSolutionIterator(dc);

        int varSize = 0;

        while (solit.hasNext()) {

            Vector data = new Vector();

            BackwardReasoner.GoalList gl = (BackwardReasoner.GoalList) solit.next();
            Hashtable varbind = gl.varBindings;

            //            javax.swing.tree.DefaultMutableTreeNode root = br.toTree();
            //            root.setAllowsChildren(true);
            //
            //            javax.swing.tree.DefaultTreeModel dtm = new DefaultTreeModel(
            //                  root);

            int i = 0;
            Object[][] rowdata = new Object[varbind.size()][2];
            varSize = varbind.size();

            Enumeration e = varbind.keys();
            while (e.hasMoreElements()) {
                Object k = e.nextElement();
                Object val = varbind.get(k);
                String ks = (String) k;
                rowdata[i][0] = ks;
                rowdata[i][1] = val;
                i++;
            }

            data.addElement(rowdata);
            String[] messages = new String[data.size()];
            MessageGenerator g = new MessageGenerator(data, varSize, messageEndpoint, m.getId(),
                    m.getProtocol(), m.getRel(), varOrder);
            messages = g.Messages2();

            String appender = "";

            URL sender = new URL(address + ":" + port);
            HttpMessage msg = new HttpMessage(sender);
            Properties props = new Properties();

            for (int i1 = 0; i1 < data.size(); i1++) {
                System.out.println(i1 + ")" + messages[i1].toString());
                props.put("text", messages[i1].toString());
                //               InputStream in = msg.sendGetMessage(props);
            }
            System.out.println("NEXT MESSAGE");
        }

        MessageGenerator g = new MessageGenerator(null, varSize, messageEndpoint, m.getId(), m.getProtocol(),
                m.getRel());
        URL sender = new URL(address + ":" + port);
        HttpMessage msg = new HttpMessage(sender);
        Properties props = new Properties();
        String finalMessage = g.finalMessage(query);
        System.out.println("******************\n" + finalMessage);
        props.put("text", finalMessage);
        //         InputStream in = msg.sendGetMessage(props);
        System.out.println("Stop_Communication");
    } catch (Exception e) {
        System.out.println("ERROR has occured : " + e.toString());

    }
}

From source file:eionet.util.Util.java

/**
 * A method for calculating and formatting the current date and time into a String for a log.
 *///from  w ww.jav a2s.c o  m

public static String logTime() {

    Date date = new Date();
    String month = String.valueOf(date.getMonth());
    month = (month.length() < 2) ? ("0" + month) : month;
    String day = String.valueOf(date.getDate());
    day = (day.length() < 2) ? ("0" + day) : day;
    String hours = String.valueOf(date.getHours());
    hours = (hours.length() < 2) ? ("0" + hours) : hours;
    String minutes = String.valueOf(date.getMinutes());
    minutes = (minutes.length() < 2) ? ("0" + minutes) : minutes;
    String seconds = String.valueOf(date.getSeconds());
    seconds = (seconds.length() < 2) ? ("0" + seconds) : seconds;

    String time = "[" + month;
    time = time + "/" + day;
    time = time + " " + hours;
    time = time + ":" + minutes;
    time = time + ":" + seconds;
    time = time + "] ";

    return time;
}

From source file:com.edgenius.wiki.blogsync.WordpressProxy.java

/**
 * Return "date_create_gmt" time is gmt, but timezone is wrong - it is local timezone. 
 * Here will correct timezone and return date in local timezone.
 * @param date/*ww  w .j  a v  a  2 s.  c  o m*/
 * @return
 */
private Date fixInputTimezone(Date date) {
    if (date == null)
        return new Date();//???

    Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
    cal.set(Calendar.YEAR, date.getYear() + 1900);
    cal.set(Calendar.MONTH, date.getMonth());
    cal.set(Calendar.DATE, date.getDate());
    cal.set(Calendar.HOUR_OF_DAY, date.getHours());
    cal.set(Calendar.MINUTE, date.getMinutes());
    cal.set(Calendar.SECOND, date.getSeconds());

    Calendar local = Calendar.getInstance(TimeZone.getDefault());
    local.setTimeInMillis(cal.getTimeInMillis());
    return local.getTime();
}

From source file:pa_SymposiumPlanner.RuleML2008ChallengeChair.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//from   w  w  w . j av  a2s  .c o  m
        address = PAConfiguration.getAddress();
        port = PAConfiguration.getPort(instantiation);
        poslAddress = PAConfiguration.getPOSL(instantiation, topic);
        rdfAddress = PAConfiguration.getRDFTaxonomy(instantiation);
        messageEndpoint = PAConfiguration.getEndpointName(instantiation, topic);
    } catch (BadConfigurationException e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
        System.exit(0);
    }
    response.setContentType("text/html; charset=UTF-8");
    PrintWriter out = response.getWriter();

    try {
        System.out.println("5 Publicty Chair Servlet");
        System.out.println(response.toString());

        BufferedReader brd = request.getReader();

        String input = "";
        String message = "";

        while (!input.equals("</RuleML>")) {

            input = brd.readLine();

            message = message + input;
        }
        String[] varOrder = getVariableOrder(message);
        System.out.println("Received Message: " + message);

        // BackwardReasoner br = new BackwardReasoner();
        // Iterator solit =null;
        // DefiniteClause dc = null;
        // SymbolTable.reset();

        POSLParser pp = new POSLParser();
        // String contents = "c(a).\nc(b).\nc(c).";

        Date t1 = new GregorianCalendar().getTime();
        System.out.println(t1.getHours() + ":" + t1.getMinutes());
        // append time to contents

        System.out.println("day: " + t1.getDay());
        System.out.println("day: " + t1.getYear());
        System.out.println("day: " + t1.getMonth());

        // time
        String time = "time(" + t1.getHours() + ":integer).";
        System.out.println(time);

        String url = poslAddress;

        // String url = "http://www.jdrew.org/oojdrew/test.posl";
        String contents = "";

        // day of the week
        int day = t1.getDay();
        boolean weekday = true;

        if (day == 0 || day == 6) {
            weekday = false;
        }

        String dayOfWeek;

        if (weekday) {
            dayOfWeek = "day(weekday).";
        } else {
            dayOfWeek = "day(weekend).";
        }
        // full date
        Calendar cal = new GregorianCalendar();

        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        int day2 = cal.get(Calendar.DAY_OF_MONTH);

        String date;

        String day3 = "" + day2;

        if (day2 == 1 || day2 == 2 || day2 == 3 || day2 == 4 || day2 == 5 || day2 == 6 || day2 == 7 || day2 == 8
                || day2 == 9) {

            day3 = "0" + day2;
        }

        if (month == 10 || month == 11 || month == 12)
            date = "" + year + month + day3;
        else
            date = "" + year + "0" + month + day3;

        date = "date(" + date + ":integer).";

        System.out.println(date);

        String url2 = rdfAddress;
        HttpClient client2 = new HttpClient();
        GetMethod method2 = new GetMethod(url2);
        method2.setFollowRedirects(true);
        String typestr = "";
        // Execute the GET method
        int statusCode2 = client2.executeMethod(method2);
        if (statusCode2 != -1) {
            typestr = method2.getResponseBodyAsString();
        }
        System.out.println("Types: " + typestr);
        Types.reset();
        RDFSParser.parseRDFSString(typestr);

        try {
            HttpClient client = new HttpClient();
            GetMethod method = new GetMethod(url);
            method.setFollowRedirects(true);

            // Execute the GET method
            int statusCode = client.executeMethod(method);
            if (statusCode != -1) {
                contents = method.getResponseBodyAsString();
            }
        }

        catch (Exception e) {
            e.printStackTrace();
        }
        contents = contents + "\n" + time;
        contents = contents + "\n" + dayOfWeek;
        contents = contents + "\n" + date;

        BackwardReasoner br = new BackwardReasoner();
        Iterator solit = null;
        DefiniteClause dc = null;
        SymbolTable.reset();

        pp.parseDefiniteClauses(contents);

        br.loadClauses(pp.iterator());
        System.out.println("TEST");
        Iterator it = pp.iterator();
        while (it.hasNext()) {
            DefiniteClause d = (DefiniteClause) it.next();
            System.out.println("Loaded clause: " + d.toPOSLString());
        }

        br = new BackwardReasoner(br.clauses, br.oids);

        MessageParser m = new MessageParser(message);
        Element atom = null;

        try {

            atom = m.parseForContent();

        } catch (Exception e) {

            System.out.println("Invalid Message");
            // out.flush();

        }

        QueryBuilder q = new QueryBuilder(atom);
        String query = q.generateDoc();
        System.out.println("ABOUT TO INPUT THIS QUERY:" + query);
        RuleMLParser qp = new RuleMLParser();

        try {

            dc = qp.parseRuleMLQuery(query);

        }

        catch (Exception e) {
            System.out.println("Invalid Query");
            // out.flush();
        }

        // solit = br.iterativeDepthFirstSolutionIterator(dc);

        solit = br.iterativeDepthFirstSolutionIterator(dc);

        int varSize = 0;

        while (solit.hasNext()) {

            Vector data = new Vector();

            BackwardReasoner.GoalList gl = (BackwardReasoner.GoalList) solit.next();

            Hashtable varbind = gl.varBindings;
            javax.swing.tree.DefaultMutableTreeNode root = br.toTree();
            root.setAllowsChildren(true);

            javax.swing.tree.DefaultTreeModel dtm = new DefaultTreeModel(root);

            int i = 0;
            Object[][] rowdata = new Object[varbind.size()][2];
            varSize = varbind.size();

            Enumeration e = varbind.keys();
            while (e.hasMoreElements()) {
                Object k = e.nextElement();
                Object val = varbind.get(k);
                String ks = (String) k;
                rowdata[i][0] = ks;
                rowdata[i][1] = val;
                i++;
            }

            data.addElement(rowdata);
            String[] messages = new String[data.size()];

            MessageGenerator g = new MessageGenerator(data, varSize, messageEndpoint, m.getId(),
                    m.getProtocol(), m.getRel(), varOrder);
            messages = g.Messages2();

            String appender = "";

            URL sender = new URL(address + ":" + port);
            HttpMessage msg = new HttpMessage(sender);
            Properties props = new Properties();

            for (int i1 = 0; i1 < data.size(); i1++) {
                System.out.println(i1 + ")" + messages[i1].toString());
                props.put("text", messages[i1].toString());
                InputStream in = msg.sendGetMessage(props);
            }
            System.out.println("NEXT MESSAGE");
        }

        MessageGenerator g = new MessageGenerator(null, varSize, messageEndpoint, m.getId(), m.getProtocol(),
                m.getRel());

        URL sender = new URL(address + ":" + port);
        HttpMessage msg = new HttpMessage(sender);
        Properties props = new Properties();

        String finalMessage = g.finalMessage(query);

        System.out.println(finalMessage);

        props.put("text", finalMessage);
        InputStream in = msg.sendGetMessage(props);

        System.out.println("Stop_Communication");

    } catch (Exception e) {
        System.out.println("ERROR has occured : " + e.toString());

    }
    out.close();
}

From source file:com.att.android.arodatacollector.utils.AROCollectorUtils.java

/**
 * Gets the default ARO trace folder name in the HH:MM:SS:DD:MM:YY format.
 * //from  ww w .j  a va  2 s  .  c om
 * @return The default ARO trace folder name.
 */
public String getDefaultTraceFolderName() {
    final Date systemDate = new Date();
    final Calendar now = Calendar.getInstance();
    final int currenthours = systemDate.getHours();
    final int currentminutes = systemDate.getMinutes();
    final int currentseconds = systemDate.getSeconds();
    final int currentdate = now.get(Calendar.DATE); // java calendar
    int currentmonth = now.get(Calendar.MONTH); // As Jan is defined as 0 in
    currentmonth = currentmonth + 1;
    if (currentmonth >= 13) // As Jan is defined as 0 in java calendar
        currentmonth = 1;
    String currentMonth = Integer.toString(currentmonth);
    String currentDate = Integer.toString(currentdate);
    String currentHours = Integer.toString(currenthours);
    String currentMinutes = Integer.toString(currentminutes);
    String currentSeconds = Integer.toString(currentseconds - 1);

    if (currentmonth < 10) {
        currentMonth = "";
        currentMonth = "0" + currentmonth;
    }
    if (currentdate < 10) {
        currentDate = "";
        currentDate = "0" + currentdate;
    }

    if (currenthours < 10) {
        currentHours = "";
        currentHours = "0" + currenthours;
    }
    if (currentminutes < 10) {
        currentMinutes = "";
        currentMinutes = "0" + currentminutes;
    }
    if (currentseconds < 10) {
        currentSeconds = "";
        currentSeconds = "0" + currentseconds;
    }
    final String folderName = now.get(Calendar.YEAR) + "-" + currentMonth + "-" + currentDate + "-"
            + currentHours + "-" + currentMinutes + "-" + currentSeconds;

    return folderName;
}

From source file:module.signature.util.XAdESValidator.java

/**
 * @author joao.antunes@tagus.ist.utl.pt adapted it from {@link #validateXMLSignature(String)}
 * @param streamWithSignature// w w  w .  j av  a2s .  c  o  m
 *            the {@link InputStream} that has the signature content
 * @return true if it's valid, false otherwise
 */
public boolean validateXMLSignature(InputStream streamWithSignature) {
    try {

        // get the  xsd schema

        Validator validator = schemaXSD.newValidator();

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder parser = dbf.newDocumentBuilder();

        ErrorHandler eh = new ErrorHandler() {

            @Override
            public void warning(SAXParseException exception) throws SAXException {
                throw new UnsupportedOperationException("Not supported yet.", exception);
            }

            @Override
            public void error(SAXParseException exception) throws SAXException {
                throw new UnsupportedOperationException("Not supported yet.", exception);
            }

            @Override
            public void fatalError(SAXParseException exception) throws SAXException {
                throw new UnsupportedOperationException("Not supported yet.", exception);
            }
        };

        // parse the document
        parser.setErrorHandler(eh);
        Document document = parser.parse(streamWithSignature);

        // XAdES extension
        NodeList nlObject = document.getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "Object");
        // XMLDSIG
        NodeList nlSignature = document.getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#",
                "Signature");

        if (checkSchema) {
            if (nlObject.getLength() < 1) {
                return false;
            }
            if (nlSignature.getLength() < 1) {
                return false;
            }

            // parse the XML DOM tree againts the XSD schema
            validator.validate(new DOMSource(nlSignature.item(0)));
        }

        if (checkSignature) {
            // Validate Every Signature Element (including CounterSignatures)
            for (int i = 0; i < nlSignature.getLength(); i++) {

                Element signature = (Element) nlSignature.item(i);
                //          String baseURI = fileToValidate.toURL().toString();
                XMLSignature xmlSig = new XMLSignature(signature, null);

                KeyInfo ki = xmlSig.getKeyInfo();

                // If signature contains X509Data
                if (ki.containsX509Data()) {

                    NodeList nlSigningTime = signature.getElementsByTagNameNS(xadesNS, "SigningTime");
                    Date signingDate = null;

                    if (nlSigningTime.item(0) != null) {
                        StringBuilder xmlDate = new StringBuilder(nlSigningTime.item(0).getTextContent())
                                .deleteCharAt(22);
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
                        signingDate = simpleDateFormat.parse(xmlDate.toString());
                    }

                    //verificao OCSP
                    //TODO FENIX-189 joantune: na realidade acho que isto no verifica mesmo a revocao.. a no ser que a keystore indicada seja actualizada regularmente.
                    if (checkRevocation) {
                        //keystore certs cc, raiz estado

                        Security.setProperty("ocsp.enable", "true");
                        //System.setProperty("com.sun.security.enableCRLDP", "true");

                        CertificateFactory cf = CertificateFactory.getInstance("X.509");

                        CertPath certPath = cf
                                .generateCertPath(Collections.singletonList(ki.getX509Certificate()));
                        //             TrustAnchor trustA = new TrustAnchor(ki.getX509Certificate(), null);
                        //             Set trustAnchors = Collections.singleton(trustA);

                        PKIXParameters params = new PKIXParameters(cartaoCidadaoKeyStore);
                        params.setRevocationEnabled(true);

                        // validar o estado na data da assinatura
                        if (nlSigningTime.item(0) != null) {
                            params.setDate(signingDate);
                        }

                        try {
                            CertPathValidator cpValidator = CertPathValidator.getInstance("PKIX");
                            CertPathValidatorResult result = cpValidator.validate(certPath, params);
                            //TODO FENIX-196 probably one would want to send a notification here
                        } catch (CertPathValidatorException ex) {
                            return false;
                        } catch (InvalidAlgorithmParameterException ex) {
                            return false;
                        }
                    }

                    // verifica a validade do certificado no momento da assinatura
                    if (checkValidity) {

                        if (nlSigningTime.item(0) != null) { // continue if there is no SigningTime, if CounterSignature isn't XAdES
                            try {
                                ki.getX509Certificate().checkValidity(signingDate);
                            } catch (CertificateExpiredException ex) {
                                return false;
                            } catch (CertificateNotYetValidException ex) {
                                return false;
                            }
                        }
                    }

                    // validate against Certificate Public Key
                    boolean validSignature = xmlSig.checkSignatureValue(ki.getX509Certificate().getPublicKey());

                    if (!validSignature) {
                        return false;
                    }
                }

                // if signature includes KeyInfo KeyValue, also check against it
                if (ki.containsKeyValue()) {
                    boolean validSignature = xmlSig.checkSignatureValue(ki.getPublicKey());
                    if (!validSignature) {
                        return false;
                    }
                }

                //let's check the SignatureTimeStamp(s) joantune

                NodeList signatureTimeStamps = signature.getElementsByTagNameNS("*", "SignatureTimeStamp");
                Element signatureValue = null;
                if (signatureTimeStamps.getLength() > 0) {
                    signatureValue = (Element) signature.getElementsByTagNameNS("*", "SignatureValue").item(0);
                }
                for (int j = 0; j < signatureTimeStamps.getLength(); j++) {
                    logger.debug("Found a SignatureTimeStamp");
                    Element signatureTimeStamp = (Element) signatureTimeStamps.item(j);
                    //for now we are ignoring the XMLTimeStamp element, let's iterate through all of the EncapsulatedTimeStamp that we find
                    NodeList encapsulatedTimeStamps = signatureTimeStamp.getElementsByTagNameNS("*",
                            "EncapsulatedTimeStamp");
                    for (int k = 0; k < encapsulatedTimeStamps.getLength(); k++) {
                        logger.debug("Found an EncapsulatedTimeStamp");
                        Element encapsulatedTimeStamp = (Element) encapsulatedTimeStamps.item(k);
                        //let's check it
                        // note, we have the timestamptoken, not the whole response, that is, we don't have the status field

                        ASN1Sequence signedTimeStampToken = ASN1Sequence
                                .getInstance(Base64.decode(encapsulatedTimeStamp.getTextContent()));

                        CMSSignedData cmsSignedData = new CMSSignedData(
                                Base64.decode(encapsulatedTimeStamp.getTextContent()));

                        TimeStampToken timeStampToken = new TimeStampToken(cmsSignedData);

                        //let's construct the Request to make sure this is a valid response

                        //let's generate the digest
                        MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
                        byte[] digest = sha1.digest(signatureValue.getTextContent().getBytes("UTF-8"));

                        //let's make sure the digests are the same
                        if (!Arrays.equals(digest,
                                timeStampToken.getTimeStampInfo().getMessageImprintDigest())) {
                            //TODO probably want to send an e-mail if this happens, as it's clearly a sign of tampering
                            //FENIX-196
                            logger.debug("Found a different digest in the timestamp!");
                            return false;
                        }

                        try {
                            //TODO for now we won't use the provided certificates that came with the TST
                            //            X509Store certificateStore = (X509Store) timeStampToken.getCertificates();
                            //            JcaDigestCalculatorProviderBuilder builder = new JcaDigestCalculatorProviderBuilder();
                            //            timeStampToken.validate(tsaCert, "BC");
                            //            timeStampToken.validate(new SignerInformationVerifier(new JcaContentVerifierProviderBuilder()
                            //               .build(tsaCert), builder.build()));
                            timeStampToken.validate(new SignerInformationVerifier(
                                    new JcaContentVerifierProviderBuilder().build(tsaCert),
                                    new BcDigestCalculatorProvider()));
                            //let's just verify that the timestamp was done in the past :) - let's give a tolerance of 5 mins :)
                            Date currentDatePlus5Minutes = new Date();
                            //let's make it go 5 minutes ahead
                            currentDatePlus5Minutes.setMinutes(currentDatePlus5Minutes.getMinutes() + 5);
                            if (!timeStampToken.getTimeStampInfo().getGenTime()
                                    .before(currentDatePlus5Minutes)) {
                                //FENIX-196 probably we want to log this!
                                //what the heck, timestamp is done in the future!! (clocks might be out of sync)
                                logger.warn("Found a timestamp in the future!");
                                return false;
                            }
                            logger.debug("Found a valid TimeStamp!");
                            //as we have no other timestamp elements in this signature, this means all is ok! :) 
                            //(point 5) of g.2.2.16.1.3 on the specs

                        } catch (TSPException exception) {
                            logger.debug("TimeStamp response did not validate", exception);
                            return false;
                        }

                    }
                }
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (ParserConfigurationException ex) {
        Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (SAXException ex) {
        Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (Exception ex) {
        Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    }
    return true;
}

From source file:eionet.util.Util.java

/**
 * A method for formatting the given timestamp into a String for history.
 *
 * @param timestamp Milliseconds since 1 January 1970.
 * @return formatted time as string in the form 2015/04/18 12:43.
 */// w ww. j  a va  2s  .  c om
public static String historyDate(long timestamp) {

    Date date = new Date(timestamp);
    String year = String.valueOf(1900 + date.getYear());
    String month = String.valueOf(date.getMonth() + 1);
    month = (month.length() < 2) ? ("0" + month) : month;
    String day = String.valueOf(date.getDate());
    day = (day.length() < 2) ? ("0" + day) : day;
    String hours = String.valueOf(date.getHours());
    hours = (hours.length() < 2) ? ("0" + hours) : hours;
    String minutes = String.valueOf(date.getMinutes());
    minutes = (minutes.length() < 2) ? ("0" + minutes) : minutes;
    String seconds = String.valueOf(date.getSeconds());
    seconds = (seconds.length() < 2) ? ("0" + seconds) : seconds;

    String time = year;
    time = time + "/" + month;
    time = time + "/" + day;
    time = time + " " + hours;
    time = time + ":" + minutes;

    return time;
}

From source file:com.hp.rest.GenericResource.java

@POST
@Path("/putImage")
@Consumes(MediaType.APPLICATION_JSON)//from  www  . j a  v a2 s.com
public Response putImage(String pData) {

    // pair to object
    ObjectMapper mapper = new ObjectMapper();
    DataInfo data = new DataInfo();
    try {
        //         File jsonFile = new File(jsonFilePath);
        data = mapper.readValue(pData, DataInfo.class);
        //System.out.println(track.getMMaKhachHang());
    } catch (JsonGenerationException e) {
        e.printStackTrace();
    } catch (JsonMappingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    Date today = new Date();

    String name = data.getNhanVien() + "-" + df.format(today) + "-" + today.getHours() + "-"
            + today.getMinutes() + "-" + today.getSeconds() + ".jpg";

    String path = ServletActionContext.getServletContext().getRealPath("/db_customers/");

    //Create new folder
    File file = new File(path + "/" + data.getKhachHang());
    if (!file.exists()) {
        if (file.mkdir()) {
            System.out.println("Directory is created!");
        } else {
            System.out.println("Failed to create directory!");
        }
    }

    System.out.println(path + "/" + data.getKhachHang() + "/" + name);
    //Save
    saveImage(data.getNoiDung(), (path + "/" + data.getKhachHang() + "/" + name));

    //Save in database
    CustomerImageDAO customerImageDAO = new CustomerImageDAOImpl();
    CustomerImage customerImage = new CustomerImage();
    customerImage.setId(name);
    customerImage.setName(name);
    customerImage.setCustomerID(data.getKhachHang());
    customerImage.setStaffID(data.getNhanVien());
    customerImage.setTime(Timestamp.valueOf(df2.format(today)));
    customerImage.setStatus(false);

    boolean status = customerImageDAO.saveOrUpdate(customerImage);

    //save track staff 
    StaffHistoryDAO staffHistoryDAO = new StaffHistoryDAOImpl();
    StaffHistory staffHistory = new StaffHistory();
    staffHistory = staffHistoryDAO.getStaffHistory(data.getKhachHang(), df.format(today));

    if (staffHistory == null) {
        byte[] b = data.getTenKhachHang().getBytes(Charset.forName("UTF-8"));
        String str = new String(b);

        System.out.println(data.getTenKhachHang() + "\n" + str);
        staffHistory = new StaffHistory();
        staffHistory.setStaff(data.getNhanVien());
        staffHistory.setCustomer(data.getKhachHang());
        staffHistory.setCustomerName(str);
        staffHistory.setStartTime(Timestamp.valueOf(df2.format(today)));
        //staffHistory.setNote();

        staffHistoryDAO.saveOrUpdate(staffHistory);
    }

    //            String output = pTrack.toString();
    System.out.println(status + " ____ " + data.getNhanVien() + "___ " + data.getKhachHang());
    return Response.status(200).entity("______ Success").build();
}

From source file:br.ufc.ivela.ejb.impl.CourseBean.java

public String getTimeLeft(Long systemUserId, Long courseId, Long disciplineId) {
    List<UnitContent> allUnitContents = daoCourse.find("select uc from UnitContent uc, Unit u, "
            + "Discipline d where uc.unitId = u.id and u.disciplineId = d.id "
            + "and d.courseId = ? and u.disciplineId = ?", new Object[] { courseId, disciplineId });

    List<Long> finishedUnitContents = daoCourse.find(
            "select f.unitContent from FinishedUnitContent f " + "where f.course = ? and f.systemUser = ?",
            new Object[] { courseId, systemUserId });

    Date date = new Date(70, 1, 1, 0, 0, 0);
    for (UnitContent unitContent : allUnitContents) {
        if (!finishedUnitContents.contains(unitContent.getId())) {
            date = DateUtils.addHours(date, unitContent.getDuration().getHours());
            date = DateUtils.addMinutes(date, unitContent.getDuration().getMinutes());
        }//from  ww w .  ja  v  a2  s . com
    }

    return ((((date.getDay()) * 24) + date.getHours()) != 0
            ? ((date.getDay()) * 24) + date.getHours() + " hora(s) e "
            : "") + date.getMinutes() + " minuto(s)";
}

From source file:br.ufc.ivela.ejb.impl.CourseBean.java

public String getTotalTimeLeft(Long systemUserId, Long courseId) {
    List<UnitContent> allUnitContents = daoCourse.find(
            "select uc from UnitContent uc, Unit u, "
                    + "Discipline d where uc.unitId = u.id and u.disciplineId = d.id " + "and d.courseId = ?",
            new Object[] { courseId });

    List<Long> finishedUnitContents = daoCourse.find(
            "select f.unitContent from FinishedUnitContent f " + "where f.course = ? and f.systemUser = ?",
            new Object[] { courseId, systemUserId });

    Date date = new Date(70, 1, 1, 0, 0, 0);
    for (UnitContent unitContent : allUnitContents) {
        if (!finishedUnitContents.contains(unitContent.getId())) {
            date = DateUtils.addHours(date, unitContent.getDuration().getHours());
            date = DateUtils.addMinutes(date, unitContent.getDuration().getMinutes());
        }//from   w w  w .j  a  v  a  2 s .  c o m
    }

    return ((((date.getDay()) * 24) + date.getHours()) != 0
            ? ((date.getDay()) * 24) + date.getHours() + " hora(s) e "
            : "") + date.getMinutes() + " minuto(s)";
}