Example usage for java.util Date getYear

List of usage examples for java.util Date getYear

Introduction

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

Prototype

@Deprecated
public int getYear() 

Source Link

Document

Returns a value that is the result of subtracting 1900 from the year that contains or begins with the instant in time represented by this Date object, as interpreted in the local time zone.

Usage

From source file:org.openmrs.module.DeIdentifiedPatientDataExportModule.api.impl.DeIdentifiedExportServiceImpl.java

private Patient setPatientDOB(Date date, Patient patient) {
    int year = date.getYear() + 1900;
    int age = patient.getAge();
    if (age > 60) { //If patient age above 60 years then randomize the year also
        year = randBetween(1990, 2010);//from w w  w  . j a  v  a2  s. c om
    }
    int dayOfMonth = randBetween(1, 31);
    int month = randBetween(0, 11);
    Date d = new Date(year - 1900, month, dayOfMonth); //Random date
    patient.setBirthdate(d);
    return patient;
}

From source file:ca.oson.json.gson.functional.DefaultTypeAdaptersTest.java

@SuppressWarnings("deprecation")
public void testDateDeserializationWithPattern() throws Exception {
    String pattern = "yyyy-MM-dd";
    //Gson gson = new GsonBuilder().setDateFormat(DateFormat.FULL).setDateFormat(pattern).create();
    Date now = new Date(1315806903103L);
    String json = oson.setDateFormat(pattern).toJson(now);
    Date extracted = oson.fromJson(json, Date.class);
    assertEquals(now.getYear(), extracted.getYear());
    assertEquals(now.getMonth(), extracted.getMonth());
    assertEquals(now.getDay(), extracted.getDay());
}

From source file:pa_SymposiumPlanner.ECAI2012ProgramChair.java

private void answerQuery() {
    try {/*from   w  ww  .  jav  a2  s.  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("Programming 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);

        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());

        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;

        int i11 = 0;
        while (solit.hasNext()) {
            System.out.println("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA:" + (i11++));

            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());

    }

}

From source file:pa_SymposiumPlanner.ECAI2012ProgramChair.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/* w ww .j a  v  a2s . c om*/
        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("Programming 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);

        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());

        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:pa_SymposiumPlanner.RuleML2008ChallengeChair.java

public void answerQuery() {
    try {/*w  w  w .  j  av a 2 s  .co 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:org.akaza.openclinica.control.managestudy.UpdateStudySubjectServlet.java

/**
 * Processes 'confirm' request, validate the study subject object
 *
 * @param sub/*from  w w w.j  av a  2  s .  c  om*/
 * @throws Exception
 */
private void confirm(StudyGroupDAO sgdao) throws Exception {
    HashMap manualErrors = new HashMap();
    ArrayList classes = (ArrayList) session.getAttribute("groups");
    SubjectBean subject = (SubjectBean) session.getAttribute("subject");
    StudySubjectBean studySub = (StudySubjectBean) session.getAttribute("studySub");
    FormDiscrepancyNotes discNotes = (FormDiscrepancyNotes) session
            .getAttribute(AddNewSubjectServlet.FORM_DISCREPANCY_NOTES_NAME);
    DiscrepancyValidator v = new DiscrepancyValidator(request, discNotes);
    FormProcessor fp = new FormProcessor(request);
    java.util.Date enrollDate = studySub.getEnrollmentDate();

    // Update: allow data entry person role to edit subject on study level (https://jira.openclinica.com/browse/OC-8620)
    if (ub.isSysAdmin() || currentRole.isManageStudy() || currentRole.isInvestigator()
            || currentRole.isResearchAssistant()
            || currentStudy.getParentStudyId() > 0 && currentRole.isResearchAssistant2()) {

        v.addValidation("label", Validator.NO_BLANKS);
        v.addValidation("label", Validator.DOES_NOT_CONTAIN_HTML_LESSTHAN_GREATERTHAN_ELEMENTS);

        v.addValidation("secondaryLabel", Validator.DOES_NOT_CONTAIN_HTML_LESSTHAN_GREATERTHAN_ELEMENTS);

        String eDateString = fp.getString("enrollmentDate");
        if (!StringUtil.isBlank(eDateString)) {
            v.addValidation("enrollmentDate", Validator.IS_A_DATE);
            v.alwaysExecuteLastValidation("enrollmentDate");
        } else {
            Validator.addError(manualErrors, "enrollmentDate", resexception.getString("field_not_blank"));
        }

        if (currentStudy.getStudyParameterConfig().getPersonIdShownOnCRF().equals("true")) {
            v.addValidation("uniqueIdentifier", Validator.LENGTH_NUMERIC_COMPARISON,
                    NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO, 255);
            v.alwaysExecuteLastValidation("uniqueIdentifier");
        }

        String personId = fp.getString("uniqueIdentifier");
        if (personId.contains("<") || personId.contains(">")) {
            v.addValidation("uniqueIdentifier", Validator.DOES_NOT_CONTAIN_HTML_LESSTHAN_GREATERTHAN_ELEMENTS);
        }

        // more study subject id validations
        if (!StringUtil.isBlank(fp.getString("label"))) {
            StudySubjectDAO ssdao = new StudySubjectDAO(sm.getDataSource());

            StudySubjectBean sub1 = (StudySubjectBean) ssdao.findAnotherBySameLabel(
                    fp.getString("label").trim(), currentStudy.getId(), studySub.getId());

            // JRWS>> Also look for labels in the child studies
            if (sub1.getId() == 0) {
                sub1 = (StudySubjectBean) ssdao.findAnotherBySameLabelInSites(fp.getString("label").trim(),
                        currentStudy.getId(), studySub.getId());
            }

            if (sub1.getId() > 0) {
                Validator.addError(manualErrors, "label",
                        resexception.getString("subject_ID_used_by_another_choose_unique"));
            }
        }

        studySub.setLabel(fp.getString("label"));
        studySub.setSecondaryLabel(fp.getString("secondaryLabel"));

        try {
            local_df.setLenient(false);
            if (!StringUtil.isBlank(eDateString)) {
                enrollDate = local_df.parse(eDateString);
            } else {
                enrollDate = null;
            }
        } catch (ParseException fe) {
            logger.warn("Enrollment Date cannot be parsed.");
        }
        studySub.setEnrollmentDate(enrollDate);

        subject.setGender(fp.getString("gender").charAt(0));

        // uniqueIdentifier must be unique in the system
        if (currentStudy.getStudyParameterConfig().getSubjectPersonIdRequired().equals("required")
                || currentStudy.getStudyParameterConfig().getSubjectPersonIdRequired().equals("optional")) {

            String uniqueIdentifier = fp.getString("uniqueIdentifier");
            if (currentStudy.getStudyParameterConfig().getSubjectPersonIdRequired().equals("required")
                    && (uniqueIdentifier == null || uniqueIdentifier.isEmpty())) {
                Validator.addError(manualErrors, "uniqueIdentifier", resexception.getString("field_not_blank"));

            }
            if (uniqueIdentifier != null && !uniqueIdentifier.isEmpty()) {

                if (uniqueIdentifier.length() > 255) {
                    String descr = resexception.getString("input_provided_is_not")
                            + NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO.getDescription() + " 255 "
                            + resword.getString("characters_long") + ".";
                    Validator.addError(manualErrors, "uniqueIdentifier", descr);

                }
                SubjectDAO sdao = new SubjectDAO(sm.getDataSource());
                SubjectBean sub1 = (SubjectBean) sdao.findAnotherByIdentifier(uniqueIdentifier,
                        subject.getId());
                if (sub1.getId() > 0) {
                    Validator.addError(manualErrors, "uniqueIdentifier",
                            resexception.getString("person_ID_used_by_another_choose_unique"));
                }
                SubjectBean subjectWithSameId = sdao.findByUniqueIdentifier(uniqueIdentifier);
                if (subjectWithSameId.isActive() && subjectWithSameId.getId() != subject.getId()) {
                    Validator.addError(manualErrors, "uniqueIdentifier",
                            resexception.getString("another_assigned_this_ID_choose_unique"));

                }
            }
            subject.setUniqueIdentifier(uniqueIdentifier);
        }

        if (currentStudy.getStudyParameterConfig().getCollectDob().equals("1")) {
            if (!StringUtil.isBlank(fp.getString(UpdateSubjectServlet.DATE_DOB))) {
                v.addValidation(UpdateSubjectServlet.DATE_DOB, Validator.IS_A_DATE);
                v.alwaysExecuteLastValidation(UpdateSubjectServlet.DATE_DOB);
            } else if (StringUtil.isBlank(fp.getString(UpdateSubjectServlet.DATE_DOB))
                    && subject.getDateOfBirth() != null) {
                Validator.addError(manualErrors, UpdateSubjectServlet.DATE_DOB,
                        resexception.getString("field_not_blank"));
            }
            if (fp.getDate(UpdateSubjectServlet.DATE_DOB) != null) {
                subject.setDateOfBirth(fp.getDate(UpdateSubjectServlet.DATE_DOB));
                String converted_date = local_df.format(subject.getDateOfBirth());
                request.setAttribute(UpdateSubjectServlet.DATE_DOB_TO_SAVE, converted_date);
            }

        } else if (currentStudy.getStudyParameterConfig().getCollectDob().equals("2")) {
            if (!StringUtils.isBlank(fp.getString(UpdateSubjectServlet.DATE_DOB))) {

                // if DOB was not updated (and originally entered as a full day, post it as is
                String submitted_date = fp.getString(UpdateSubjectServlet.DATE_DOB);

                boolean isTheSameDate = false;
                try {
                    Date fakeDOB = yformat.parse(submitted_date);
                    if (subject.getDateOfBirth() != null) {
                        if (subject.getDateOfBirth().getYear() == (fakeDOB.getYear())) {
                            isTheSameDate = true;
                            String converted_date = yformat.format(subject.getDateOfBirth());
                            request.setAttribute(UpdateSubjectServlet.DATE_DOB_TO_SAVE, converted_date);
                        }
                    }
                } catch (ParseException pe) {
                    logger.error("update subject: cannot convert date " + submitted_date);
                }

                if (!isTheSameDate) {

                    v.addValidation(UpdateSubjectServlet.DATE_DOB, Validator.IS_AN_INTEGER);
                    v.alwaysExecuteLastValidation(UpdateSubjectServlet.DATE_DOB);
                    v.addValidation(UpdateSubjectServlet.DATE_DOB, Validator.COMPARES_TO_STATIC_VALUE,
                            NumericComparisonOperator.GREATER_THAN_OR_EQUAL_TO, 1000);

                    // get today's year
                    Date today = new Date();
                    Calendar c = Calendar.getInstance();
                    c.setTime(today);
                    int currentYear = c.get(Calendar.YEAR);
                    v.addValidation(UpdateSubjectServlet.DATE_DOB, Validator.COMPARES_TO_STATIC_VALUE,
                            NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO, currentYear);
                    int yob = fp.getInt(UpdateSubjectServlet.DATE_DOB);
                    Date fakeDate = new Date(yob);
                    String dobString = yformat.format(fakeDate);
                    try {

                        Date fakeDOB = yformat.parse(dobString);
                        if (yob != 0) {
                            subject.setDateOfBirth(fakeDOB);
                        }
                        request.setAttribute(UpdateSubjectServlet.DATE_DOB_TO_SAVE, yob);
                    } catch (ParseException pe) {
                        logger.debug("Parse exception happened.");
                        Validator.addError(manualErrors, UpdateSubjectServlet.DATE_DOB,
                                resexception.getString("please_enter_a_valid_year_birth"));
                    }
                }
                request.setAttribute(UpdateSubjectServlet.DATE_DOB,
                        fp.getString(UpdateSubjectServlet.DATE_DOB));

            } else {
                Validator.addError(manualErrors, UpdateSubjectServlet.DATE_DOB,
                        resexception.getString("field_not_blank"));
            }
        }

        if (!StringUtil.isBlank(fp.getString("gender"))) {
            subject.setGender(fp.getString("gender").charAt(0));
        } else {
            if (currentStudy.getStudyParameterConfig().getGenderRequired().equals("true")
                    && subject.getGender() == ' ') {
                Validator.addError(manualErrors, "gender", resexception.getString("field_not_blank"));
            }
            subject.setGender(' ');
        }

        errors = v.validate();
        addMultipleErrors(manualErrors);

        // below added tbh 092007, fix for YY vs YYYY formatting
        String enrollDateStr = enrollDate != null ? local_df.format(enrollDate) : "";

        session.setAttribute("enrollDateStr", enrollDateStr);
        // above added tbh 092007
        session.setAttribute("studySub", studySub);
        session.setAttribute("subject", subject);

        if (!classes.isEmpty()) {
            for (int i = 0; i < classes.size(); i++) {
                StudyGroupClassBean sgc = (StudyGroupClassBean) classes.get(i);
                int groupId = fp.getInt("studyGroupId" + i);
                String notes = fp.getString("notes" + i);
                v.addValidation("notes" + i, Validator.LENGTH_NUMERIC_COMPARISON,
                        NumericComparisonOperator.LESS_THAN_OR_EQUAL_TO, 255);
                sgc.setStudyGroupId(groupId);
                sgc.setGroupNotes(notes);
                if (groupId > 0) {
                    StudyGroupBean sgb = (StudyGroupBean) sgdao.findByPK(groupId);
                    sgc.setStudyGroupName(sgb.getName());
                }
            }
        }

        session.setAttribute("groups", classes);
        if (!errors.isEmpty()) {
            logger.info("has errors");
            if (StringUtil.isBlank(studySub.getLabel())) {
                addPageMessage(respage.getString("must_enter_subject_ID_for_identifying")
                        + respage.getString("this_may_be_external_ID_number")
                        + respage.getString("you_may_enter_study_subject_ID_listed")
                        + respage.getString("study_subject_ID_should_not_contain_protected_information"));
            } else {
                StudySubjectDAO subdao = new StudySubjectDAO(sm.getDataSource());
                StudySubjectBean sub1 = (StudySubjectBean) subdao.findAnotherBySameLabel(studySub.getLabel(),
                        studySub.getStudyId(), studySub.getId());
                if (sub1.getId() > 0) {
                    addPageMessage(resexception.getString("subject_ID_used_by_another_choose_unique"));
                }
            }
            setLocalDOB(subject);
            if (currentStudy.getStudyParameterConfig().getCollectDob().equals("2"))
                request.setAttribute("localBirthDate", "");
            request.setAttribute("formMessages", errors);
            forwardPage(Page.UPDATE_STUDY_SUBJECT);

        } else {
            forwardPage(Page.UPDATE_STUDY_SUBJECT_CONFIRM);
        }
    }

}

From source file:pa_SymposiumPlanner.RuleML2008ChallengeChair.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//from   ww  w. jav a 2 s . com
        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:graph.module.DateParseModule.java

@SuppressWarnings("deprecation")
private DAGNode parseDate(SimpleDateFormat sdf, String dateStr) {
    try {//  w  w  w.  ja  v  a2  s .  c o m
        ParsePosition position = new ParsePosition(0);
        Date date = sdf.parse(dateStr, position);
        if (position.getIndex() != dateStr.length()) {
            // Throw an exception or whatever else you want to do
            return null;
        }
        String pattern = sdf.toPattern();

        StringBuilder buffer = new StringBuilder();
        boolean addFurther = false;
        int brackets = 0;
        if (addFurther || pattern.contains("d")) {
            addFurther = true;
            buffer.append("(" + CommonConcepts.DAYFN.getID() + " '" + date.getDate() + " ");
            brackets++;
        }
        if (addFurther || pattern.contains("M")) {
            addFurther = true;
            buffer.append("(" + CommonConcepts.MONTHFN.getID() + " " + MONTH_FORMATTER.format(date) + " ");
            brackets++;
        }
        if (pattern.contains("y")) {
            buffer.append("(" + CommonConcepts.YEARFN.getID() + " '" + (date.getYear() + 1900));
            brackets++;
        } else if (addFurther)
            buffer.append(CommonConcepts.THE_YEAR.getID());
        for (int i = 0; i < brackets; i++)
            buffer.append(")");
        return (DAGNode) dag_.findOrCreateNode(buffer.toString(), null);
    } catch (Exception e) {
    }
    return null;
}

From source file:org.opencastproject.capture.impl.SchedulerImpl.java

/**
 * Parses an date to build a cron-like time string.
 * /*from   w  w w  .j  a v  a  2s  . c  o  m*/
 * @param date
 *          The {@code Date} you want returned in a cronstring.
 * @return A cron-like scheduling string in a {@code CronExpression} object.
 * @throws ParseException
 */
public static CronExpression getCronString(Date date) throws ParseException {
    // TODO: Remove the deprecated calls here.
    StringBuilder sb = new StringBuilder();
    sb.append(date.getSeconds() + " ");
    sb.append(date.getMinutes() + " ");
    sb.append(date.getHours() + " ");
    sb.append(date.getDate() + " ");
    sb.append(date.getMonth() + 1 + " "); // Note: Java numbers months from 0-11, Quartz uses 1-12. Sigh.
    sb.append("? ");
    sb.append(date.getYear() + 1900); // Yay java.
    return new CronExpression(sb.toString());
}

From source file:palamarchuk.smartlife.app.RegisterActivity.java

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DATE_PICKER:
        Date date = new Date();
        return new DatePickerDialog(this, R.style.AppTheme, new DatePickerDialog.OnDateSetListener() {
            @Override/*from w  w w  . jav  a  2 s. c o  m*/
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

                SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
                SimpleDateFormat toServer = new SimpleDateFormat("yyyy-MM-dd");

                Calendar calendar = new GregorianCalendar(year, monthOfYear, dayOfMonth);

                birthDateToServer = toServer.format(calendar.getTime());
                birthDate.setText(sdf.format(calendar.getTime()));
            }
        }, date.getYear() + 1900, date.getMonth(), date.getDate());
    }
    return null;
}