Example usage for java.util Vector get

List of usage examples for java.util Vector get

Introduction

In this page you can find the example usage for java.util Vector get.

Prototype

public synchronized E get(int index) 

Source Link

Document

Returns the element at the specified position in this Vector.

Usage

From source file:com.ibm.xsp.webdav.resource.DAVResourceDomino.java

/**
 * The function checks if a document is read-only for the current user. Step
 * 1: get the user access level, if Reader = ReadOnly, If Editor = ReadWrite
 * if Author = Step 2 Step 2: Get UsernameList for current user and loop
 * through the document to get all items. If a item is an author field, then
 * add it to the list, loop the list to see the access.
 * /*  w  w  w  . j av a 2 s.c om*/
 * @param s
 *            Notessession
 * @param curDoc
 *            Document to evaluate
 * @return true if ReadOnly Access is granted
 */
protected boolean checkReadOnlyAccess(Document curDoc) {

    boolean result = true; // Readonly until proven better
    HashMap<String, String> allAuthors = new HashMap<String, String>();
    Vector<String> v = null;
    @SuppressWarnings("rawtypes")
    Vector allItems = null;
    String unid = null;

    try {
        unid = curDoc.getUniversalID();
        // Step 1 --- Database access
        @SuppressWarnings("unused")
        Session s = DominoProxy.getUserSession();
        Database db = curDoc.getParentDatabase();
        int accessLevel = db.getCurrentAccessLevel();
        LOGGER.info("Starting check access for docunid=" + unid);
        if (accessLevel == ACL.LEVEL_EDITOR || accessLevel == ACL.LEVEL_DESIGNER
                || accessLevel == ACL.LEVEL_MANAGER) {
            result = false; // it is not read only, it can be processed
            // // LOGGER.info("Access level is Editor or better");

        } else if (accessLevel == ACL.LEVEL_AUTHOR) {
            // Step 2 --- Document access
            // //
            // LOGGER.info("Access level is Author, checking local access for:"
            // +
            // DominoProxy.getUserName()+"; effective="+s.getEffectiveUserName());

            allItems = curDoc.getItems();
            Item item;
            for (int i = 0; i < allItems.size(); i++) {
                item = (Item) allItems.get(i);
                if (item != null && item.isAuthors()) {
                    // Record it to the Map
                    @SuppressWarnings("rawtypes")
                    Vector values = item.getValues();
                    if (values != null) {
                        for (int x = 0; x < values.size(); x++) {
                            if (values.get(x) != null) {
                                String curAuthor = (String) values.get(x);
                                // // LOGGER.info("Author found in " +
                                // item.getName() + ": " + curAuthor);
                                allAuthors.put(curAuthor.toLowerCase(), curAuthor.toLowerCase());
                            }
                        }
                    }
                }
                Item itemO = item;
                item = null;
                itemO.recycle();
            }

            // //
            // LOGGER.info("-- Author retrieval completed, now checking usernameslist --");

            // Might not work, if the db is local and consisten acl
            // is not enforced, so we add username and common username
            v = this.getUsernamesList(curDoc);

            if (v == null) {
                // Get Username list has failed, we can't allow editing of
                // the file
                result = true; // READ ONLY
                // // LOGGER.info("getUsernamesList returned NULL");
            } else {
                // Now check the userlist
                for (int i = 0; i < v.size(); i++) {
                    if (v.get(i) != null) {
                        String curName = v.get(i);
                        // // LOGGER.info("Checking access for:" + curName);
                        if (!curName.equals("")) {
                            if (allAuthors.containsKey(curName.toLowerCase())) {
                                result = false; // We can write!
                                // // LOGGER.info("Author access found for "
                                // + curName);
                                break;
                            }
                        }
                    }
                }
            }

        }

    } catch (NotesException e) {
        // // LOGGER.info("ReadOnlyAccess Check failed", e);
        result = true; // It is readonly if the check failed
    }
    // // LOGGER.info("Document "+unid+
    // ((result)?" readonly":" normal access"));
    return result;
}

From source file:edu.ku.brc.af.ui.forms.MultiView.java

/**
 * Sets all the resultSetControllers to the proper index.
 *//*w  w  w .  j a v  a  2s . c  o m*/
public void setViewState(final Vector<ViewState> viewStateList, final AltViewIFace.CreationMode mode,
        final int vsInx) {
    if (viewStateList != null && vsInx < viewStateList.size()) {
        ViewState viewState = viewStateList.get(vsInx);

        if (vsInx > -1) {
            int inx = viewState.getInx();
            if (inx > -1) {
                FormViewObj formViewObj = getCurrentViewAsFormViewObj();
                if (formViewObj != null && formViewObj.getRsController() != null) {
                    formViewObj.getRsController().setIndex(inx);
                }
            }
        }

        for (MultiView mv : kids) {
            if (mv.createWithMode == mode) {
                mv.setViewState(viewStateList, mode, vsInx + 1);
            }
        }
    }
}

From source file:webServices.RestServiceImpl.java

@POST
@Path("/endpoint/explore/properties/{host}/{endpoint}/{port}")
@Consumes({ MediaType.TEXT_PLAIN, MediaType.WILDCARD, MediaType.APPLICATION_JSON })
@Produces({ MediaType.TEXT_PLAIN })/*from  w  ww  . ja v a2  s. c  om*/
public String getExploreProperties(String classURI, @PathParam("host") String host,
        @PathParam("endpoint") String endpoint, @PathParam("port") int port)
        throws EndpointCommunicationException {
    Vector<String> results = new Vector<String>();
    String format = classURI + "$";
    results = endpointStore.getExploreProperties(host, endpoint.replaceAll("@@@", "/"), port, classURI);

    if (results != null) {
        for (int i = 0; i < results.size(); i++) {
            format = format.concat(results.get(i));
            format = format.concat("$");
        }
    }

    return format;
}

From source file:eionet.gdem.dcm.business.SchemaManager.java

/**
 * Method creates StylesheetListHolder object, that stores the list of stylesheets both for handcoded and generated. The object
 * stores also user permissions info to manage stylesheets.
 *
 * @param type//from www.  j  a  va2s.  c  o  m
 *            if type==null, then show only handcoded stylesheets. If type==generated, then show only generated stylesheets. If
 *            type==both, then show both handcoded and generated stylesheets
 * @return StylesheetListHolder object holding schema stylesheet and user permission information
 * @throws DCMException in case of database error occurs.
 */
public StylesheetListHolder getSchemas(String type) throws DCMException {

    StylesheetListHolder st = new StylesheetListHolder();
    if (Utils.isNullStr(type)) {
        type = "handcoded";
    }
    Vector hcSchemas;
    List<Schema> schemas;

    try {
        schemas = new ArrayList<Schema>();

        // By default show only handcoded stylesheets
        if (type.equals("handcoded") || type.equals("all")) {
            hcSchemas = schemaDao.getSchemas(null);
            if (hcSchemas == null) {
                hcSchemas = new Vector();
            }

            for (int i = 0; i < hcSchemas.size(); i++) {
                HashMap schema = (HashMap) hcSchemas.get(i);
                Schema sc = new Schema();
                sc.setId((String) schema.get("schema_id"));
                sc.setSchema((String) schema.get("xml_schema"));
                sc.setDescription((String) schema.get("description"));
                sc.setExpireDate(Utils.parseDate((String) schema.get("expire_date"), "yyyy-MM-dd HH:mm:ss"));

                Vector stylesheets = new Vector();
                if (schema.containsKey("stylesheets")) {
                    stylesheets = (Vector) schema.get("stylesheets");
                }

                ArrayList<Stylesheet> stls = new ArrayList<Stylesheet>();
                for (int j = 0; j < stylesheets.size(); j++) {
                    HashMap stylesheet = (HashMap) stylesheets.get(j);
                    Stylesheet stl = new Stylesheet();
                    stl.setConvId((String) stylesheet.get("convert_id"));
                    stl.setType((String) stylesheet.get("content_type_out"));
                    stl.setXsl(Names.XSL_FOLDER + (String) stylesheet.get("xsl"));
                    stl.setXslFileName((String) stylesheet.get("xsl"));
                    stl.setDescription((String) stylesheet.get("description"));
                    stl.setDdConv(false);
                    stls.add(stl);
                }
                if (stls.size() > 0) {
                    sc.setStylesheets(stls);
                    schemas.add(sc);
                }
            }
            if (schemas.size() > 0) {
                st.setHandCodedStylesheets(schemas);
            }
        }

        // if type==all, then show both handcoded and generated stylesheets
        // if type==generated, then show only generated from DD stylesheets
        if (type.equals("generated") || type.equals("all")) {
            // retrieve conversions for DD tables
            schemas = getDDSchemas(true);
            st.setDdStylesheets(schemas);
        }

    } catch (Exception e) {
        LOGGER.error("Error getting schema", e);
        throw new DCMException(BusinessConstants.EXCEPTION_GENERAL);
    }
    return st;

}

From source file:org.wise.portal.presentation.web.controllers.ContactWiseController.java

@RequestMapping(method = RequestMethod.POST)
public String onSubmit(@ModelAttribute("contactWISEForm") ContactWISEForm contactWISEForm, BindingResult result,
        HttpServletRequest request) throws Exception {
    contactWISEValidator.validate(contactWISEForm, result);
    checkRecaptcha(request, result);// w  ww.j a va 2  s. com
    getTeacherNameAndSetInForm(contactWISEForm);

    if (result.hasErrors()) {
        return "contact/contactwise";
    }

    // get our user key for the user agent parse site
    String userKey = wiseProperties.getProperty("userAgentParseKey");

    if (userKey != null && !userKey.equals("")) {

        // get the user agent from the request
        String userAgent = request.getParameter("usersystem");

        HttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(userAgentParseURL);

        // add the user_key and user_agent parameters to the POST request
        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        urlParameters.add(new BasicNameValuePair("user_key", userKey));
        urlParameters.add(new BasicNameValuePair("user_agent", userAgent));

        post.setEntity(new UrlEncodedFormEntity(urlParameters));

        try {

            // execute the POST
            HttpResponse response = client.execute(post);

            // read the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer userAgentParseResult = new StringBuffer();
            String line = "";
            while ((line = rd.readLine()) != null) {
                userAgentParseResult.append(line);
            }

            String parseResultString = userAgentParseResult.toString();

            try {

                // get the response as a JSON object
                JSONObject parseResultJSONObject = new JSONObject(parseResultString);

                // get whether the request succeeded
                String parseResult = parseResultJSONObject.getString("result");

                if (parseResult != null && parseResult.equals("success")) {
                    // the request succeeded so we will get the data
                    JSONObject parse = parseResultJSONObject.getJSONObject("parse");

                    // get the operating system and browser values
                    String operatingSystemName = parse.getString("operating_system_name");
                    String operatingSystemVersion = parse.getString("operating_system_version_full");
                    String browserName = parse.getString("browser_name");
                    String browserVersion = parse.getString("browser_version_full");

                    // set the values into the form so that we can use them later when creating the email message
                    contactWISEForm.setOperatingSystemName(operatingSystemName);
                    contactWISEForm.setOperatingSystemVersion(operatingSystemVersion);
                    contactWISEForm.setBrowserName(browserName);
                    contactWISEForm.setBrowserVersion(browserVersion);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //retrieves the contents of the email to be sent
    String[] recipients = getMailRecipients();
    String[] cc = getMailCcs(contactWISEForm);
    String subject = contactWISEForm.getMailSubject();
    String fromEmail = contactWISEForm.getEmail();
    String message = contactWISEForm.getMailMessage();

    //fromEmail will be null if the signed in user is a student
    if (fromEmail == null) {
        /*
         * set the fromEmail to a non null and non empty string otherwise
         * an exception will be thrown
         */
        fromEmail = "null";
    }

    //get the run id
    Long runId = contactWISEForm.getRunId();

    /*
     * if a student is submitting the contactwiseproject form, the runId will
     * be set. if a teacher is submitting the contactwiseproject form, the
     * runId will not be set. this is ok because the teacher is the run
     * owner and their email is already in the cc array
     */
    if (runId != null) {
        Run run = runService.retrieveById(runId);
        Vector<String> runOwnerEmailAddresses = new Vector<String>();
        User runOwner = run.getOwner();
        MutableUserDetails userDetails = runOwner.getUserDetails();
        //get the run owner email address
        String emailAddress = userDetails.getEmailAddress();

        if (emailAddress != null) {
            runOwnerEmailAddresses.add(emailAddress);
        }

        if (!runOwnerEmailAddresses.isEmpty()) {
            //we have run owner email addresses

            for (int x = 0; x < cc.length; x++) {
                if (!runOwnerEmailAddresses.contains(cc[x])) {
                    //add the cc emails to the run owner emails to merge them
                    runOwnerEmailAddresses.add(cc[x]);
                }
            }

            //create a new String array the same size as the runOwnerEmailAddresses
            cc = new String[runOwnerEmailAddresses.size()];

            //put all the email addresses back into the cc array
            for (int x = 0; x < runOwnerEmailAddresses.size(); x++) {
                cc[x] = runOwnerEmailAddresses.get(x);
            }
        }
    }

    //for testing out the email functionality without spamming the groups
    if (DEBUG) {
        cc = new String[1];
        cc[0] = fromEmail;
        recipients[0] = DEBUG_EMAIL;
    }

    //sends the email to the recipients
    mailService.postMail(recipients, subject, message, fromEmail, cc);

    return "contact/contactwiseconfirm";
}

From source file:gskproject.Analyze.java

private void btnPersonGraphActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPersonGraphActionPerformed
    //System.out.println();
    if (tblPersonVise.getSelectedRow() != -1) {
        String username = tablePersonWise.get(tblPersonVise.getSelectedRow()).get(0).toString();
        int userID = dbOps.getUserID(username);
        java.sql.Date from;/*from  w w w .java2 s  . c  o m*/
        java.sql.Date to;
        if (dtPFrom.getDate() == null && dtPTo.getDate() == null) {
            from = null;
            to = null;

        } else if (dtPFrom.getDate() == null) {
            from = null;
            to = new java.sql.Date(dtPTo.getDate().getTime());

        } else if (dtPTo.getDate() == null) {
            from = new java.sql.Date(dtPFrom.getDate().getTime());
            to = null;

        } else {
            from = new java.sql.Date(dtPFrom.getDate().getTime());
            to = new java.sql.Date(dtPTo.getDate().getTime());

        }
        Vector<Vector> eachPersonDates = new Vector<Vector>();

        eachPersonDates = dbOps.getEachPersonObservation(from, to, userID);

        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        JFreeChart chart = null;
        Calendar start = Calendar.getInstance();
        Calendar end = Calendar.getInstance();
        for (Vector<Object> row : eachPersonDates) {
            start.setTime((Date) row.get(1));
            end.setTime((Date) row.get(2));
            dataset.addValue(end.get(Calendar.DAY_OF_YEAR) - start.get(Calendar.DAY_OF_YEAR), "First Aid",
                    row.get(0).toString());
        }
        chart = ChartFactory.createLineChart("All Departments VS All Accident Types", "Observation ID", "Days",
                dataset, PlotOrientation.VERTICAL, false, true, false);
        CategoryPlot p = chart.getCategoryPlot();
        p.setRangeGridlinePaint(Color.BLACK);
        ChartFrame frame = new ChartFrame(username + " Chart", chart);
        frame.setSize(700, 500);
        frame.setVisible(true);
    } else {
        JOptionPane.showMessageDialog(this, "Please select a person using table!");
    }
}

From source file:marytts.tools.dbselection.WikipediaMarkupCleaner.java

/***
 * Using mwdumper extracts pages from a xmlWikiFile and load them in a mysql DB (it loads the
 * tables "locale_text", "locale_page" and "locale_revision", where locale is the corresponding 
 * wikipedia language). Once the tables are loaded, extract/clean text from the pages and create
 * a cleanText table. It also creates a wordList table including frequencies.  
 * @throws Exception// ww w. ja  va  2s.c om
 */
void processWikipediaPages() throws Exception {
    // Load wikipedia pages, extract clean text and  create word list.
    String dateStringIni = "", dateStringEnd = "";
    DateFormat fullDate = new SimpleDateFormat("dd_MM_yyyy_HH:mm:ss");
    Date dateIni = new Date();
    dateStringIni = fullDate.format(dateIni);

    DBHandler wikiToDB = new DBHandler(locale);

    // hashMap for the dictionary, HashMap is faster than TreeMap so the list of words will
    // be kept it in a hashMap. When the process finish the hashMap will be dump in the database.
    HashMap<String, Integer> wordList;

    System.out.println("Creating connection to DB server...");
    wikiToDB.createDBConnection(mysqlHost, mysqlDB, mysqlUser, mysqlPasswd);

    // This loading can take a while
    // create and load TABLES: page, text and revision

    if (loadWikiTables) {
        System.out.println(
                "Creating and loading TABLES: page, text and revision. (The loading can take a while...)");
        wikiToDB.loadPagesWithMWDumper(xmlWikiFile, locale, mysqlHost, mysqlDB, mysqlUser, mysqlPasswd);
    } else {
        // Checking if tables are already created and loaded in the DB
        if (wikiToDB.checkWikipediaTables())
            System.out.println("TABLES " + locale + "_page, " + locale + "_text and " + locale
                    + "_revision already loaded (WARNING USING EXISTING WIKIPEDIA TABLES).");
        else
            throw new Exception("WikipediaMarkupCleaner: ERROR IN TABLES " + locale + "_page, " + locale
                    + "_text and " + locale + "_revision, they are not CREATED/LOADED.");
    }

    System.out.println("\nGetting page IDs");
    String pageId[];
    pageId = wikiToDB.getIds("page_id", locale + "_page");
    System.out.println("Number of page IDs to process: " + pageId.length + "\n");

    // create cleanText TABLE
    if (deleteCleanTextTable) {
        System.out.println("Creating (deleting if already exist) " + locale + "_cleanText TABLE");
        wikiToDB.createWikipediaCleanTextTable();
    } else {
        if (wikiToDB.tableExist(locale + "_cleanText"))
            System.out.println(locale + "_cleanText TABLE already exist (ADDING TO EXISTING cleanText TABLE)");
        else {
            System.out.println("Creating " + locale + "_cleanText TABLE");
            wikiToDB.createWikipediaCleanTextTable();
        }
    }

    System.out.println("Starting Hashtable for wordList.");
    int initialCapacity = 200000;
    wordList = new HashMap<String, Integer>(initialCapacity);

    String text;
    PrintWriter pw = null;
    if (wikiLog != null)
        pw = new PrintWriter(new FileWriter(new File(wikiLog)));

    StringBuilder textId = new StringBuilder();
    int numPagesUsed = 0;

    Vector<String> textList;
    System.out.println("\nStart processing Wikipedia pages.... Start time:" + dateStringIni + "\n");

    for (int i = 0; i < pageId.length; i++) {

        // first filter  
        text = wikiToDB.getTextFromWikiPage(pageId[i], minPageLength, textId, pw);

        if (text != null) {
            textList = removeMarkup(text);
            numPagesUsed++;
            for (int j = 0; j < textList.size(); j++) {
                text = textList.get(j);
                if (text.length() > minTextLength) {
                    // if after cleaning the text is not empty or                 
                    wikiToDB.insertCleanText(text, pageId[i], textId.toString());
                    // insert the words in text in wordlist
                    addWordToHashMap(text, wordList);
                    if (debug)
                        System.out.println("Cleanedpage_id[" + i + "]=" + pageId[i] + "  textList (" + (j + 1)
                                + "/" + textList.size() + ") length=" + text.length() + "  numPagesUsed="
                                + numPagesUsed + "  Wordlist[" + wordList.size() + "] ");

                    if (pw != null)
                        pw.println("CLEANED PAGE page_id[" + i + "]=" + pageId[i] + " textList (" + (j + 1)
                                + "/" + textList.size() + ") length=" + text.length() + " Wordlist["
                                + wordList.size() + "] " + "  NUM_PAGES_USED=" + numPagesUsed + " text:\n\n"
                                + text);
                } else if (pw != null)
                    pw.println("PAGE NOT USED AFTER CLEANING page_id[" + i + "]=" + pageId[i] + " length="
                            + text.length());
            } // for each text in textList
            System.out.println("Cleanedpage_id[" + i + "]=" + pageId[i] + "  numPagesUsed=" + numPagesUsed
                    + "  Wordlist[" + wordList.size() + "] ");
            textList.clear(); // clear the list of text
        }
    }
    Date dateEnd = new Date();
    dateStringEnd = fullDate.format(dateEnd);

    if (pw != null) {
        pw.println("Number of PAGES USED=" + numPagesUsed + " Wordlist[" + wordList.size() + "] "
                + " minPageLength=" + minPageLength + " minTextLength=" + minTextLength + " Start time:"
                + dateStringIni + "  End time:" + dateStringEnd);
        pw.close();
    }

    // save the wordList in the DB
    updateWordList(wikiToDB, wordList);

    wikiToDB.printWordList("./wordlist-freq.txt", "frequency", 0, 0);

    System.out.println("\nNumber of pages used=" + numPagesUsed + " Wordlist[" + wordList.size() + "] "
            + " Start time:" + dateStringIni + "  End time:" + dateStringEnd);

    // Once created the cleantext table delete the wikipedia text, page and revision tables.
    wikiToDB.deleteWikipediaTables();

    wikiToDB.closeDBConnection();

}

From source file:edu.ku.brc.specify.tasks.SystemSetupTask.java

/**
 * //  w ww .  j av  a  2s . c o  m
 */
private void loadUnlockDB(final boolean doJustBtnLabel) {
    Vector<Object[]> rows = query(DBConnection.getInstance().getConnection(),
            "SELECT IsDBClosed, DbClosedBy FROM spversion ORDER BY TimestampCreated DESC");
    if (rows.size() > 0) {
        Object[] row = (Object[]) rows.get(rows.size() - 1);
        Boolean isDBClosed = (Boolean) row[0];
        String dbClosedBy = (String) row[1];

        //log.debug("isDBClosed["+isDBClosed+"]  dbClosedBy["+dbClosedBy+"] ");

        if (!doJustBtnLabel) {
            String updateStr = "UPDATE spversion SET IsDBClosed=%d, DbClosedBy=%s";
            if (isDBClosed == null || !isDBClosed) {
                isDBClosed = true;
                SpecifyUser spUser = AppContextMgr.getInstance().getClassObject(SpecifyUser.class);
                if (spUser == null) {
                    return;
                }
                dbClosedBy = String.format("'%s'", spUser.getName());
            } else {
                isDBClosed = false;
                dbClosedBy = "NULL";
            }

            updateStr = String.format(updateStr, isDBClosed ? 1 : 0, dbClosedBy);
            //log.debug(updateStr);
            int rv = BasicSQLUtils.update(updateStr);
            if (rv == 1) {
                UIRegistry.displayInfoMsgDlgLocalized(isDBClosed ? "SYSSTP_LCK_MSG" : "SYSSTP_UNLCK_MSG");
                setLockBtntitle(isDBClosed);
            }
        } else {
            setLockBtntitle(isDBClosed);
        }
    }
}

From source file:webServices.RestServiceImpl.java

@GET
@Path("/requestMaps")
@Produces({ MediaType.APPLICATION_JSON })
public Response requestMaps(@QueryParam("title") String title, @QueryParam("creator") String creator,
        @QueryParam("license") String license, @QueryParam("theme") String theme,
        @QueryParam("extent") String extent) throws EndpointCommunicationException, JsonProcessingException {

    String mapURL = HTTP + servlet.getServerName() + ":" + servlet.getServerPort() + context.getContextPath()
            + "?mapid=";

    Vector<MyMap> mapResults = new Vector<MyMap>();

    //Reset to default registry values
    endpointStore = new MapEndpointStore();

    //Construct query
    String query = "PREFIX strdf: <http://strdf.di.uoa.gr/ontology#> "
            + "PREFIX geof: <http://www.opengis.net/def/function/geosparql/> "
            + "SELECT ?mapId ?title ?creator ?license ?theme ?description ?geom WHERE { "
            + "?mapId <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <" + MapVocabulary.MAP + ">  . "
            + "?mapId <" + MapVocabulary.HASTITLE + "> ?title . " + "?mapId <" + MapVocabulary.HASCREATOR
            + "> ?creator . " + "?mapId <" + MapVocabulary.HASLICENSE + "> ?license . " + "?mapId <"
            + MapVocabulary.HASTHEME + "> ?theme . " + "?mapId <" + MapVocabulary.HASDESCRIPTION
            + "> ?description . " + "?mapId <" + MapVocabulary.HASGEOMETRY + "> ?geom . ";

    if (title != null) {
        query = query.concat("FILTER regex(?title, \"" + title + "\", \"i\") . ");
    }//  w w w  .j a va  2 s  .c  o m
    if (creator != null) {
        query = query.concat("FILTER regex(?creator, \"" + creator + "\", \"i\") . ");
    }
    if (license != null) {
        query = query.concat("FILTER regex(?license, \"" + license + "\", \"i\") . ");
    }
    if (theme != null) {
        query = query.concat("FILTER regex(?theme, \"" + theme + "\", \"i\") . ");
    }
    if (extent != null) {
        String wkt = extentToWKT(extent);
        System.out.println(wkt);
        query = query.concat("FILTER (strdf:mbbIntersects(?geom, \"" + wkt
                + "\"^^<http://www.opengis.net/ont/geosparql#wktLiteral>)) . ");
    }
    query = query.concat("}");

    //Pose query
    Vector<String> results = endpointStore.searchForMaps(query);

    //Parse results
    for (int i = 0; i < results.size(); i = i + 7) {
        Vector<Distribution> ds = new Vector<Distribution>();
        ds.add(new Distribution("Distribution", "Sextant",
                mapURL.concat(results.get(i).substring(results.get(i).lastIndexOf("/") + 1))));

        MyMap tempMap = new MyMap(
                mapURL.concat(
                        results.get(i).substring(results.get(i).lastIndexOf("/") + 1, results.get(i).length())),
                results.get(i + 1), results.get(i + 2), results.get(i + 3), results.get(i + 4),
                results.get(i + 5), new Extent("Location", results.get(i + 6)
                        .substring(results.get(i + 6).indexOf("POLYGON"), results.get(i + 6).length())),
                ds);
        mapResults.add(tempMap);
    }

    ObjectMapper mapper = new ObjectMapper();

    String output = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(new Maps(mapResults,
            HTTP + servlet.getServerName() + ":" + servlet.getServerPort() + context.getContextPath()));
    output = output.replaceAll("\"context\"", "\"@context\"");
    output = output.replaceAll("\"type\"", "\"@type\"");
    output = output.replaceAll("\"id\"", "\"@id\"");

    return Response.ok().entity(output).header("Access-Control-Allow-Origin", "*")
            .header("Access-Control-Allow-Methods", "GET").build();
}

From source file:CreateNewType.java

private static Vector getDataTypes(Connection con, String typeToCreate) throws SQLException {
    String structName = null, distinctName = null, javaName = null;

    // create a vector of class DataType initialized with
    // the SQL code, the SQL type name, and two null entries
    // for the local type name and the creation parameter(s)

    Vector dataTypes = new Vector();
    dataTypes.add(new DataType(java.sql.Types.BIT, "BIT"));
    dataTypes.add(new DataType(java.sql.Types.TINYINT, "TINYINT"));
    dataTypes.add(new DataType(java.sql.Types.SMALLINT, "SMALLINT"));
    dataTypes.add(new DataType(java.sql.Types.INTEGER, "INTEGER"));
    dataTypes.add(new DataType(java.sql.Types.BIGINT, "BIGINT"));
    dataTypes.add(new DataType(java.sql.Types.FLOAT, "FLOAT"));
    dataTypes.add(new DataType(java.sql.Types.REAL, "REAL"));
    dataTypes.add(new DataType(java.sql.Types.DOUBLE, "DOUBLE"));
    dataTypes.add(new DataType(java.sql.Types.NUMERIC, "NUMERIC"));
    dataTypes.add(new DataType(java.sql.Types.DECIMAL, "DECIMAL"));
    dataTypes.add(new DataType(java.sql.Types.CHAR, "CHAR"));
    dataTypes.add(new DataType(java.sql.Types.VARCHAR, "VARCHAR"));
    dataTypes.add(new DataType(java.sql.Types.LONGVARCHAR, "LONGVARCHAR"));
    dataTypes.add(new DataType(java.sql.Types.DATE, "DATE"));
    dataTypes.add(new DataType(java.sql.Types.TIME, "TIME"));
    dataTypes.add(new DataType(java.sql.Types.TIMESTAMP, "TIMESTAMP"));
    dataTypes.add(new DataType(java.sql.Types.BINARY, "BINARY"));
    dataTypes.add(new DataType(java.sql.Types.VARBINARY, "VARBINARY"));
    dataTypes.add(new DataType(java.sql.Types.LONGVARBINARY, "LONGVARBINARY"));
    dataTypes.add(new DataType(java.sql.Types.NULL, "NULL"));
    dataTypes.add(new DataType(java.sql.Types.OTHER, "OTHER"));
    dataTypes.add(new DataType(java.sql.Types.BLOB, "BLOB"));
    dataTypes.add(new DataType(java.sql.Types.CLOB, "CLOB"));

    DatabaseMetaData dbmd = con.getMetaData();
    ResultSet rs = dbmd.getTypeInfo();
    while (rs.next()) {
        int codeNumber = rs.getInt("DATA_TYPE");
        String dbmsName = rs.getString("TYPE_NAME");
        String createParams = rs.getString("CREATE_PARAMS");

        if (codeNumber == Types.STRUCT && structName == null)
            structName = dbmsName;//from   ww  w  .j a  v  a 2s  .co  m
        else if (codeNumber == Types.DISTINCT && distinctName == null)
            distinctName = dbmsName;
        else if (codeNumber == Types.JAVA_OBJECT && javaName == null)
            javaName = dbmsName;
        else {
            for (int i = 0; i < dataTypes.size(); i++) {
                // find entry that matches the SQL code, 
                // and if local type and params are not already set,
                // set them
                DataType type = (DataType) dataTypes.get(i);
                if (type.getCode() == codeNumber) {
                    type.setLocalTypeAndParams(dbmsName, createParams);
                }
            }
        }
    }

    if (typeToCreate.equals("s")) {
        int[] types = { Types.STRUCT, Types.DISTINCT, Types.JAVA_OBJECT };
        rs = dbmd.getUDTs(null, "%", "%", types);
        while (rs.next()) {
            String typeName = null;
            DataType dataType = null;

            if (dbmd.isCatalogAtStart())
                typeName = rs.getString(1) + dbmd.getCatalogSeparator() + rs.getString(2) + "."
                        + rs.getString(3);
            else
                typeName = rs.getString(2) + "." + rs.getString(3) + dbmd.getCatalogSeparator()
                        + rs.getString(1);

            switch (rs.getInt(5)) {
            case Types.STRUCT:
                dataType = new DataType(Types.STRUCT, typeName);
                dataType.setLocalTypeAndParams(structName, null);
                break;
            case Types.DISTINCT:
                dataType = new DataType(Types.DISTINCT, typeName);
                dataType.setLocalTypeAndParams(distinctName, null);
                break;
            case Types.JAVA_OBJECT:
                dataType = new DataType(Types.JAVA_OBJECT, typeName);
                dataType.setLocalTypeAndParams(javaName, null);
                break;
            }
            dataTypes.add(dataType);
        }
    }

    return dataTypes;
}