Example usage for java.util Hashtable size

List of usage examples for java.util Hashtable size

Introduction

In this page you can find the example usage for java.util Hashtable size.

Prototype

public synchronized int size() 

Source Link

Document

Returns the number of keys in this hashtable.

Usage

From source file:edu.ku.brc.af.ui.weblink.WebLinkButton.java

/**
 * @return//from  w  w w  . j ava 2  s.c o m
 */
private CustomDialog createPromptDlg(final Hashtable<String, String> backupHash) {
    if (webLinkDef != null) {
        // Start by getting the data needed to build the URL
        // so first see if we need to prompt for data.

        int promptCnt = webLinkDef.getPromptCount();
        if (promptCnt > 0 || backupHash.size() > 0) {
            textFieldHash.clear();

            promptCnt += backupHash != null ? backupHash.size() : 0;

            String rowDef = createDuplicateJGoodiesDef("p", "4px", promptCnt); //$NON-NLS-1$ //$NON-NLS-2$
            PanelBuilder pb = new PanelBuilder(new FormLayout("p,2px,f:p:g", rowDef)); //$NON-NLS-1$
            CellConstraints cc = new CellConstraints();

            DocumentAdaptor dla = new DocumentAdaptor() {
                @Override
                protected void changed(DocumentEvent e) {
                    super.changed(e);
                    boolean enableOK = true;
                    for (JTextField tf : textFieldHash.values()) {
                        if (tf.getText().length() == 0) {
                            enableOK = false;
                            break;
                        }
                    }
                    promptDialog.getOkBtn().setEnabled(enableOK);
                }

            };

            int y = 1;
            for (WebLinkDefArg arg : webLinkDef.getArgs()) {
                if (arg.isPrompt() && valueHash.get(arg.getName()) == null) {
                    JTextField txtField = createTextField(15);
                    txtField.getDocument().addDocumentListener(dla);
                    textFieldHash.put(arg.getName(), txtField);
                    String label = arg.getTitle();
                    if (StringUtils.isEmpty(label)) {
                        label = arg.getName();
                    }
                    pb.add(createFormLabel(label), cc.xy(1, y));
                    pb.add(txtField, cc.xy(3, y));
                    y += 2;
                }
            }

            if (backupHash != null) {
                for (String name : backupHash.keySet()) {
                    JTextField txtField = createTextField(15);
                    txtField.getDocument().addDocumentListener(dla);
                    textFieldHash.put(name, txtField);
                    pb.add(createLabel(backupHash.get(name), SwingConstants.RIGHT), cc.xy(1, y));
                    pb.add(txtField, cc.xy(3, y));
                    y += 2;
                }
            }

            pb.setDefaultDialogBorder();

            return new CustomDialog((Frame) getTopWindow(), getResourceString("WBLK_PROMPT_DATA"), true,
                    CustomDialog.OKCANCELHELP, pb.getPanel());
        }
    }
    return null;
}

From source file:org.socraticgrid.displaydataaggregator.DisplayDataAggregatorImpl.java

private String checkDataSource(String msgType) throws Exception {
    Hashtable<String, String> sourceTable = new Hashtable<String, String>();
    ServiceError dataSourceError = getDataSources(sourceTable);
    if (dataSourceError != null) {
        throw new Exception("Error retrieving data sources.");
    }/*  w w  w . j  a  v a  2  s . c  om*/
    if (sourceTable.size() == 0) {
        throw new Exception("No data sources defined.");
    }
    String dataSourceUrl = sourceTable.get(msgType);
    if (dataSourceUrl == null) {
        throw new Exception("Requested data source is not configured: " + msgType);
    }
    return dataSourceUrl;
}

From source file:ucar.unidata.data.storm.AtcfStormDataSource.java

/**
 * _more_/*w  w  w  .ja v a  2  s . co  m*/
 *
 * @param stormInfo _more_
 * @param waysToUse _more_
 * @param observationWay _more_
 *
 * @return _more_
 *
 * @throws Exception _more_
 */
public StormTrackCollection getTrackCollectionInner(StormInfo stormInfo, Hashtable<String, Boolean> waysToUse,
        Way observationWay) throws Exception {
    if (localTracks != null) {
        return localTracks;
    }

    long t1 = System.currentTimeMillis();
    StormTrackCollection tracks = new StormTrackCollection();

    String trackFile;
    boolean justObs = (waysToUse != null) && (waysToUse.size() == 1)
            && (waysToUse.get(Way.OBSERVATION.toString()) != null);
    int nowYear = new GregorianCalendar(DateUtil.TIMEZONE_GMT).get(Calendar.YEAR);
    int stormYear = getYear(stormInfo.getStartTime());
    //If its the current year then its in the aid_public dir
    String aSubDir = ((stormYear == nowYear) ? "aid_public" : ("archive/" + stormYear));
    String bSubDir = ((stormYear == nowYear) ? "btk" : ("archive/" + stormYear));
    if (!justObs) {
        trackFile = getFullPath(aSubDir + "/" + PREFIX_ANALYSIS + stormInfo.getBasin().toLowerCase()
                + stormInfo.getNumber() + stormYear + ".dat.gz");
        //What we think might be in the archive might actually be the last year
        //and they haven't moved it into the archive
        try {
            readTracks(stormInfo, tracks, trackFile, waysToUse, true);
        } catch (BadDataException bde) {
            if (!aSubDir.equals("aid_public")) {
                try {
                    trackFile = getFullPath("aid_public/" + PREFIX_ANALYSIS + stormInfo.getBasin().toLowerCase()
                            + stormInfo.getNumber() + stormYear + ".dat.gz");
                    readTracks(stormInfo, tracks, trackFile, waysToUse, true);
                } catch (BadDataException bde2) {
                    System.err.println("Failed reading 'A' file for storm:" + stormInfo + " file:" + trackFile);
                }
            }
            //                System.err.println("Failed reading 'A' file for storm:" + stormInfo+" file:" + trackFile);
        }
    }
    //Now  read the b"est file
    trackFile = getFullPath(bSubDir + "/" + PREFIX_BEST + stormInfo.getBasin().toLowerCase()
            + stormInfo.getNumber() + stormYear + ".dat.gz");
    try {
        readTracks(stormInfo, tracks, trackFile, null, true);
    } catch (BadDataException bde) {
        if (!bSubDir.equals("btk")) {
            try {
                trackFile = getFullPath("btk/" + PREFIX_BEST + stormInfo.getBasin().toLowerCase()
                        + stormInfo.getNumber() + stormYear + ".dat.gz");
                readTracks(stormInfo, tracks, trackFile, null, true);
            } catch (BadDataException bde2) {
                System.err.println("Failed reading 'B' file for storm:" + stormInfo + " file:" + trackFile);
            }

        }
        //            System.err.println("Failed reading 'B' file for storm:" + stormInfo+" file:" + trackFile);
    }
    long t2 = System.currentTimeMillis();
    //        System.err.println("time: " + (t2 - t1));

    return tracks;
}

From source file:edu.wisc.ssec.mcidasv.data.cyclone.AtcfStormDataSource.java

/**
 * _more_//www.j av a2  s . c  om
 * 
 * @param stormInfo
 *            _more_
 * @param waysToUse
 *            _more_
 * @param observationWay
 *            _more_
 * 
 * @return _more_
 * 
 * @throws Exception
 *             _more_
 */
public StormTrackCollection getTrackCollectionInner(StormInfo stormInfo, Hashtable<String, Boolean> waysToUse,
        Way observationWay) throws Exception {
    if (localTracks != null) {
        return localTracks;
    }

    long t1 = System.currentTimeMillis();
    StormTrackCollection tracks = new StormTrackCollection();

    String trackFile;
    boolean justObs = (waysToUse != null) && (waysToUse.size() == 1)
            && (waysToUse.get(Way.OBSERVATION.toString()) != null);
    int nowYear = new GregorianCalendar(DateUtil.TIMEZONE_GMT).get(Calendar.YEAR);
    int stormYear = getYear(stormInfo.getStartTime());
    // If its the current year then its in the aid_public dir
    String aSubDir = ((stormYear == nowYear) ? "aid_public" : ("archive/" + stormYear));
    String bSubDir = ((stormYear == nowYear) ? "btk" : ("archive/" + stormYear));
    if (!justObs) {
        trackFile = getFullPath(aSubDir + "/" + PREFIX_ANALYSIS + stormInfo.getBasin().toLowerCase()
                + stormInfo.getNumber() + stormYear + ".dat.gz");
        // What we think might be in the archive might actually be the last
        // year
        // and they haven't moved it into the archive
        try {
            readTracks(stormInfo, tracks, trackFile, waysToUse, true);
        } catch (BadDataException bde) {
            if (!aSubDir.equals("aid_public")) {
                try {
                    trackFile = getFullPath("aid_public/" + PREFIX_ANALYSIS + stormInfo.getBasin().toLowerCase()
                            + stormInfo.getNumber() + stormYear + ".dat.gz");
                    readTracks(stormInfo, tracks, trackFile, waysToUse, true);
                } catch (BadDataException bde2) {
                    System.err.println("Failed reading 'A' file for storm:" + stormInfo + " file:" + trackFile);
                }
            }
            // System.err.println("Failed reading 'A' file for storm:" +
            // stormInfo+" file:" + trackFile);
        }
    }
    // Now read the b"est file
    trackFile = getFullPath(bSubDir + "/" + PREFIX_BEST + stormInfo.getBasin().toLowerCase()
            + stormInfo.getNumber() + stormYear + ".dat.gz");
    try {
        readTracks(stormInfo, tracks, trackFile, null, true);
    } catch (BadDataException bde) {
        if (!bSubDir.equals("btk")) {
            try {
                trackFile = getFullPath("btk/" + PREFIX_BEST + stormInfo.getBasin().toLowerCase()
                        + stormInfo.getNumber() + stormYear + ".dat.gz");
                readTracks(stormInfo, tracks, trackFile, null, true);
            } catch (BadDataException bde2) {
                System.err.println("Failed reading 'B' file for storm:" + stormInfo + " file:" + trackFile);
            }

        }
        // System.err.println("Failed reading 'B' file for storm:" +
        // stormInfo+" file:" + trackFile);
    }
    long t2 = System.currentTimeMillis();
    // System.err.println("time: " + (t2 - t1));

    return tracks;
}

From source file:oscar.oscarReport.ClinicalReports.PageUtil.RunClinicalReportAction.java

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws IOException, ServletException {

    String numeratorId = request.getParameter("numerator");
    String denominatorId = request.getParameter("denominator");

    MiscUtils.getLogger().debug("numerator " + numeratorId + " denominator " + denominatorId);
    ClinicalReportManager reports = ClinicalReportManager.getInstance();

    Denominator d = reports.getDenominatorById(denominatorId);
    if (d.hasReplaceableValues()) {
        String[] denomReplaceKeys = d.getReplaceableKeys();
        Hashtable h = new Hashtable();
        String keyValue;// www . java  2  s  .co m
        if (denomReplaceKeys != null) {
            for (int i = 0; i < denomReplaceKeys.length; i++) {
                String[] keyValues = request.getParameterValues("denominator_" + denomReplaceKeys[i]);
                if (keyValues == null) {
                    keyValue = "";
                }
                if (keyValues.length == 1) {
                    h.put(denomReplaceKeys[i], keyValues[0]);
                } else {
                    for (int idx = 0; idx < keyValues.length; ++idx) {
                        h.put(denomReplaceKeys[i] + String.valueOf(idx), keyValues[idx]);
                    }
                }
            }
        }
        MiscUtils.getLogger().debug("setting replaceable values with a size of " + h.size());
        d.setReplaceableValues(h);
    }

    Numerator n = reports.getNumeratorById(numeratorId);
    MiscUtils.getLogger().debug("n" + n + " " + n.hasReplaceableValues());
    if (n.hasReplaceableValues()) {
        String[] denomReplaceKeys = n.getReplaceableKeys();
        Hashtable h = new Hashtable();
        String keyValue;
        if (denomReplaceKeys != null) {
            for (int i = 0; i < denomReplaceKeys.length; i++) {
                MiscUtils.getLogger().debug("The sought after key would be "
                        + request.getParameterValues("numerator_" + denomReplaceKeys[i]));
                String[] keyValues = request.getParameterValues("numerator_" + denomReplaceKeys[i]);
                if (keyValues == null) {
                    keyValue = "";
                }
                if (keyValues.length == 1) {
                    h.put(denomReplaceKeys[i], keyValues[0]);
                    request.setAttribute("numerator_" + denomReplaceKeys[i],
                            request.getParameter("numerator_" + denomReplaceKeys[i]));
                } else {
                    for (int idx = 0; idx < keyValues.length; ++idx) {
                        h.put(denomReplaceKeys[i] + String.valueOf(idx), keyValues[idx]);
                    }
                }
            }
        }
        MiscUtils.getLogger().debug("setting replaceable values with a size of " + h.size());
        n.setReplaceableValues(h);
    }

    List<KeyValue> extraVal = null;
    for (Object params : request.getParameterMap().keySet()) {
        String requestParam = (String) params;
        if (requestParam.startsWith("report_measurement") && !request.getParameter(requestParam).equals("-1")) {
            if (extraVal == null) {
                extraVal = new LinkedList();
            }
            KeyValue kv = new org.apache.commons.collections.keyvalue.DefaultKeyValue(requestParam,
                    request.getParameter(requestParam));
            extraVal.add(kv);
            request.setAttribute(requestParam, request.getParameter(requestParam));

        }
    }

    request.setAttribute("showfields", request.getParameterValues("showfields"));

    //Need to change the out put fields here On the JSP use an getDisplay MEthod that checks for instance of.

    ReportEvaluator re = new ReportEvaluator();
    re.evaluate(d, n, extraVal);

    int num = re.getNumeratorCount();
    int denom = re.getDenominatorCount();
    MiscUtils.getLogger().debug("num " + num + " denom " + denom);
    float percentage = re.getPercentage();

    ArrayList arrList = (ArrayList) request.getSession().getAttribute("ClinicalReports");
    if (arrList == null) {
        arrList = new ArrayList();
    }
    arrList.add(re);
    request.getSession().setAttribute("ClinicalReports", arrList);

    request.setAttribute("extraValues", extraVal);
    request.setAttribute("name", re.getName());
    request.setAttribute("numerator", Integer.toString(num));
    request.setAttribute("denominator", Integer.toString(denom));
    request.setAttribute("numeratorId", numeratorId);
    request.setAttribute("denominatorId", denominatorId);
    request.setAttribute("percentage", Integer.toString(new Float(percentage).intValue()));
    request.setAttribute("csv", re.getCSV());
    request.setAttribute("list", re.getReportResultList());
    request.setAttribute("outputfields", n.getOutputFields());
    return mapping.findForward("success");
}

From source file:org.socraticgrid.displaydataaggregator.DisplayDataAggregatorImpl.java

/**
 * Return data source list./*from   w  w w .ja v  a2 s  . c  o  m*/
 * 
 * @param getAvailableSourcesRequest
 * @return
 */
public org.socraticgrid.common.dda.GetAvailableSourcesResponseType getAvailableSources(
        org.socraticgrid.common.dda.GetAvailableSourcesRequestType getAvailableSourcesRequest) {
    GetAvailableSourcesResponseType response = new GetAvailableSourcesResponseType();
    Hashtable<String, String> sourceTable = new Hashtable<String, String>();

    try {
        ServiceError dataSourceError = getDataSources(sourceTable);
        if (dataSourceError != null) {
            throw new Exception("Error retrieving data sources.");
        }

        if (sourceTable.size() == 0) {
            throw new Exception("No data sources defined.");
        }

        for (String dataSource : sourceTable.keySet()) {
            response.getReturn().add(dataSource);
        }
    } catch (Exception e) {
        String errorMsg = "Error getting data sources.";
        log.error(errorMsg, e);
        response.getReturn().add(errorMsg + ". " + e.getMessage());
    }

    return response;
}

From source file:pa_SymposiumPlanner.ECAI2012ProgramChair.java

private void answerQuery() {
    try {// ww w  .  j a  va 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("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  w w  . j  a v  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);
    }

    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:org.socraticgrid.displaydataaggregator.DisplayDataAggregatorImpl.java

/**
 * Handle detail data sources requested by a specified user.
 *
 * @param request/*w w  w. ja  va2 s . c  o  m*/
 * @return
 */
public org.socraticgrid.common.dda.GetDetailDataResponseType getDetailDataForUser(
        org.socraticgrid.common.dda.GetDetailDataForUserRequestType request) {
    GetDetailDataResponseType response = new GetDetailDataResponseType();
    Hashtable<String, String> sourceTable = new Hashtable<String, String>();

    try {
        ServiceError dataSourceError = getDataSources(sourceTable);
        if (dataSourceError != null) {
            throw new Exception("Error retrieving data sources.");
        }

        if (sourceTable.size() == 0) {
            throw new Exception("No data sources defined.");
        }

        //Get data source url
        String dataSourceUrl = sourceTable.get(request.getDataSource());
        if (dataSourceUrl == null) {
            throw new Exception("Requested data source is not configured: " + request.getDataSource());
        }

        //Convert userId
        String userId = request.getUserId();
        try {
            UniversalResourceAddressBean beanId = UniversalResourceAddressBeanFactory.getInstance()
                    .createUniversalResourceBean(request.getUserId());
            if (beanId instanceof IdAddressBean) {
                userId = ((IdAddressBean) beanId).getId();
            }
        } catch (Exception e) {
            log.warn("Bad user id: " + userId + ", " + e.getMessage());
        }

        GetComponentDetailDataForUserRequestType componentRequest = new GetComponentDetailDataForUserRequestType();
        componentRequest.setUserId(userId);
        componentRequest.setItemId(request.getItemId());

        DisplayAlertDataUtil alert = new DisplayAlertDataUtil();

        GetComponentDetailDataResponseType componentResponse = alert
                .getComponentDetailDataForUser(DisplayAlertDataUtil.DATA_SOURCE_ALERTS, componentRequest);
        response.setDetailObject(componentResponse.getDetailObject());
        response.getErrorList().addAll(componentResponse.getErrorList());
    } catch (Exception e) {
        String errorMsg = "Error getting detail data.";
        log.error(errorMsg, e);
        ServiceError error = new ServiceError();
        error.setCode(ERROR_CODE);
        error.setText(errorMsg + ". " + e.getMessage());
        response.getErrorList().add(error);
    }

    //Get "read" status as needed
    ServiceError error = addReadStatus(request.getUserId(), response.getDetailObject());
    if (error != null) {
        response.getErrorList().add(error);
    }

    return response;
}

From source file:pa_SymposiumPlanner.RuleML2008ChallengeChair.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/*from  ww w .ja v a  2  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);
    }
    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();
}