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:charts.Chart.java

public static int FindPathwayPosition(Vector pathways, String pathway) {
    if (!pathways.contains(pathway)) {
        return (-1);//nao contem
    }/*from  w  w w  .  jav  a2s . com*/
    for (int p = 0; p < pathways.size(); p++) {
        if (((String) pathways.get(p)).equalsIgnoreCase(pathway)) {
            return (p);
        }
    }
    return (-1);
}

From source file:eionet.gdem.utils.InputFile.java

/**
 * Get Host credentials from database. There could be restriction for accessing files in different servers. Username and
 * password are saved in the T_HOST table for these cases.
 *
 * @param host URL.//w ww .jav a  2s.c  om
 */
private void getHostCredentials(String host) {
    try {

        Vector v = hostDao.getHosts(host);

        if (v == null) {
            return;
        }
        if (v.size() > 0) {
            Hashtable h = (Hashtable) v.get(0);
            String user = (String) h.get("user_name");
            String pwd = (String) h.get("pwd");
            this.ticket = Utils.getEncodedAuthentication(user, pwd);

        }

    } catch (Exception e) {
        LOGGER.error("Error getting host data from the DB " + e.toString());
        LOGGER.error("Conversion proceeded");
    }
}

From source file:edu.ku.brc.specify.config.FixDBAfterLogin.java

/**
 * //from w  w w  .jav  a  2  s  .  co  m
 */
public static void fixGTPTreeDefParents() {
    int fixed = 0;
    String updateSQL = "UPDATE geologictimeperiodtreedefitem SET ParentItemID=? WHERE GeologicTimePeriodTreeDefItemID=?";

    Connection conn = DBConnection.getInstance().getConnection();
    PreparedStatement pStmt = null;
    try {
        pStmt = conn.prepareStatement(updateSQL);

        Vector<Integer> gtpTreeDefIds = BasicSQLUtils.queryForInts(
                "SELECT GeologicTimePeriodTreeDefID FROM geologictimeperiodtreedef ORDER BY GeologicTimePeriodTreeDefID");
        for (Integer defId : gtpTreeDefIds) {
            String sql = String.format(
                    "SELECT COUNT(*) FROM geologictimeperiodtreedefitem WHERE ParentItemID IS NULL AND GeologicTimePeriodTreeDefID=%d",
                    defId);
            if (BasicSQLUtils.getCount(sql) == 1)
                continue;

            sql = String.format(
                    "SELECT GeologicTimePeriodTreeDefItemID FROM geologictimeperiodtreedefitem WHERE GeologicTimePeriodTreeDefID=%d ORDER BY RankID",
                    defId);
            Vector<Integer> gtpTreeDefItemIds = BasicSQLUtils.queryForInts(sql);
            Vector<Integer> parentIds = new Vector<Integer>();
            parentIds.add(-1);

            for (int i = 1; i < gtpTreeDefItemIds.size(); ++i) {
                parentIds.add(gtpTreeDefItemIds.get(i - 1));
            }

            fixed = 0;
            for (int i = 1; i < gtpTreeDefItemIds.size(); ++i) {
                log.debug(String.format("Node: %d  -> Parent: %d", gtpTreeDefItemIds.get(i), parentIds.get(i)));
                pStmt.setInt(1, parentIds.get(i));
                pStmt.setInt(2, gtpTreeDefItemIds.get(i));
                int rv = pStmt.executeUpdate();
                if (rv != 1) {
                    log.error("Error updating GTP TreeDef Item PArent");
                }
                fixed++;
            }
            log.debug(String.format("Fixed %d/%d", fixed, gtpTreeDefItemIds.size() - 1));
        }

    } catch (Exception ex) {
        ex.printStackTrace();

    } finally {
        try {
            if (pStmt != null)
                pStmt.close();
        } catch (SQLException e) {
        }
    }
}

From source file:gsn.http.A3DWebServiceImpl.java

public String[] getSensorLocation(String sensor) {

    VSensorConfig sensorConfig = Mappings.getVSensorConfig(sensor);
    Vector<String> sensorLocation = new Vector<String>();
    for (KeyValue df : sensorConfig.getAddressing())
        sensorLocation/*  w ww.j a v  a2s  . co  m*/
                .add(StringEscapeUtils.escapeXml(df.getKey().toString()) + "=" + df.getValue().toString());

    String v_sensorLocation[] = new String[sensorLocation.size()];
    for (int i = 0; i < sensorLocation.size(); i++)
        v_sensorLocation[i] = sensorLocation.get(i);

    return v_sensorLocation;

}

From source file:com.linkedin.databus.core.TestDbusEventBufferAppendEvents.java

@Test
/**//  w  w  w .j  av a2 s  .com
 * verify that changes to the buffer (appendEvent, endEvent, clear) after the buffer is closed
 * are ignored (and rolled back)
 * we do this by creating buffer (or loading from mmap files from the previous run), adding one window,
 * then doing append, close , append/endEvents (which should throw an exception)
 * then loading again and verifying that it has our events
 */
public void testAppendEventsWithCloseInMiddle() throws Exception {
    final Logger log = Logger.getLogger("TestDbusEventBuffer.testAppendEventsWithCloseInMiddle");
    log.setLevel(Level.DEBUG);
    log.info("starting");

    // mmap dir
    File mmapDir = initMmapDir("/tmp/tmp_mmapDir");

    DbusEventBuffer.StaticConfig config = getConfig(1200, 500, 100, 500, AllocationPolicy.MMAPPED_MEMORY,
            mmapDir.getAbsolutePath(), true);
    DbusEventBuffer dbusBuf = new DbusEventBuffer(config);

    DbusEventBufferReflector bufferReflector = new DbusEventBufferReflector(dbusBuf);
    // BufferPositionParser parser = dbusBuf.getBufferPositionParser();
    log.info("append initial events");
    DbusEventGenerator generator = new DbusEventGenerator();
    Vector<DbusEvent> events = new Vector<DbusEvent>();
    generator.generateEvents(12, 2, 120, 39, events);

    // add first window with 2 events
    dbusBuf.start(-1);
    int i = 0;

    addOneEvent(events.get(i++), dbusBuf, EventType.START);
    addOneEvent(events.get(i++), dbusBuf, EventType.END);
    checkEventsInBuffer(bufferReflector, 3); // 2 + 1(EOW)

    // add first event of the second window
    addOneEvent(events.get(i++), dbusBuf, EventType.START);
    checkEventsInBuffer(bufferReflector, 3); // 2 + 1(EOW)

    // now close the buffer
    dbusBuf.closeBuffer(true);
    checkEventsInBuffer(bufferReflector, 3); // 2 + 1(EOW)

    // now add the end
    try {
        addOneEvent(events.get(i), dbusBuf, EventType.END);
    } catch (Throwable ex) {
        log.info("Got e: ", ex);
    }
    checkEventsInBuffer(bufferReflector, 3); // 2 + 1(EOW)

    // create new buffer
    dbusBuf = new DbusEventBuffer(config); // should load from mmap
    bufferReflector = new DbusEventBufferReflector(dbusBuf);
    checkEventsInBuffer(bufferReflector, 3); // 2 + 1(EOW)

    addOneEvent(events.get(i++), dbusBuf, EventType.START);
    addOneEvent(events.get(i++), dbusBuf, EventType.END);
    checkEventsInBuffer(bufferReflector, 6); // 4 + 2(EOW)

    // add two more events but don't do endEvents
    addOneEvent(events.get(i++), dbusBuf, EventType.START);
    addOneEvent(events.get(i++), dbusBuf, EventType.REG); // no endEvents()
    // now close the buffer
    dbusBuf.closeBuffer(true);
    dbusBuf.closeBuffer(true); // should be ok (WARN in the logs)
    checkEventsInBuffer(bufferReflector, 6); // 4 + 2(EOW)

    // call endEvents(on a closed buffer);
    try {
        dbusBuf.endEvents(events.get(i - 1).sequence());
    } catch (Throwable ex) {
        log.info("Got e2: ", ex);
    }
    checkEventsInBuffer(bufferReflector, 6); // 4 + 2(EOW)

    // create new buffer
    dbusBuf = new DbusEventBuffer(config); // should load from mmap
    bufferReflector = new DbusEventBufferReflector(dbusBuf);
    checkEventsInBuffer(bufferReflector, 6); // 4 + 2(EOW)

    addOneEvent(events.get(i++), dbusBuf, EventType.START);
    addOneEvent(events.get(i++), dbusBuf, EventType.END);
    checkEventsInBuffer(bufferReflector, 9); // 6 + 3(EOW)

    // add two more events but don't do endEvents
    addOneEvent(events.get(i++), dbusBuf, EventType.START);
    addOneEvent(events.get(i++), dbusBuf, EventType.REG); // no endEvents()
    // now close the buffer
    dbusBuf.closeBuffer(true);
    checkEventsInBuffer(bufferReflector, 9); // 6 + 3(EOW)

    // call endEvents(on a closed buffer);
    try {
        dbusBuf.clear(); //should fail
    } catch (Throwable ex) {
        log.info("Got e3: ", ex);
    }
    checkEventsInBuffer(bufferReflector, 9); // 6 + 3(EOW)

    // make sure it is still valid
    dbusBuf = new DbusEventBuffer(config); // should load from mmap
    bufferReflector = new DbusEventBufferReflector(dbusBuf);
    checkEventsInBuffer(bufferReflector, 9); // 6 + 3(EOW)

}

From source file:de.nmichael.efa.Daten.java

public static void printEfaInfos(boolean efaInfos, boolean pluginInfos, boolean javaInfos, boolean hostInfos,
        boolean jarInfos) {
    Vector infos = getEfaInfos(efaInfos, pluginInfos, javaInfos, hostInfos, jarInfos);
    for (int i = 0; infos != null && i < infos.size(); i++) {
        Logger.log(Logger.INFO, Logger.MSG_INFO_CONFIGURATION, (String) infos.get(i));
    }/* ww w  .  ja  v a 2  s .  c o m*/
}

From source file:com.mytalentfolio.h_daforum.CconnectToServer.java

/**
 * {@code connect} is for forming the secure connection between server and
 * android, sending and receiving of the data.
 * //from w  w  w .  jav a  2s  . c  om
 * @param arg0
 *            data which is to be sent to server.
 * 
 * @return data in string format, received from the server.
 */
public String connect(String... arg0) {

    int nrOfDataToSendToServer = arg0.length;
    nrOfDataToSendToServer = nrOfDataToSendToServer - 1;
    boolean valid = false;
    String dataFromServer = "unverified", serverPublicKeySigStr, serverDataSig;

    try {
        //Creating the server certificate
        Certificate serverCertificate = getServerCertificate();

        KeyStore keyStore = getKeyStore(serverCertificate);

        TrustManagerFactory tmf = getTrustManager(keyStore);

        SSLContext sslContext = getSSLContext(tmf);

        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        HttpsURLConnection urlConnection = getURLConnection(sslContext, hostnameVerifier);

        // Converting the data into JSONObject
        JSONObject obj = new JSONObject();
        for (int i = 0; i <= nrOfDataToSendToServer; i++) {
            obj.put("param" + i, arg0[i]);
        }

        // Converting the JSONObject into string
        String dataToSend = obj.toString();

        KeyPairGenerator keyGen = getKeyPairGenerator();

        KeyPair keyPair = keyGen.generateKeyPair();
        //Public key for verifying the digital signature
        PublicKey clientPublicKeySig = keyPair.getPublic();
        //Private key for signing the data
        PrivateKey clientPrivateKeySig = keyPair.getPrivate();

        // Get signed data
        String sigData = getDataSig(clientPrivateKeySig, dataToSend);

        // Creating URL Format
        String urlData = URLEncoder.encode("clientPublicKeySig", "UTF-8") + "=" + URLEncoder
                .encode(Base64.encodeToString(clientPublicKeySig.getEncoded(), Base64.DEFAULT), "UTF-8");
        urlData += "&" + URLEncoder.encode("clientData", "UTF-8") + "="
                + URLEncoder.encode(dataToSend, "UTF-8");
        urlData += "&" + URLEncoder.encode("clientDataSig", "UTF-8") + "="
                + URLEncoder.encode(sigData, "UTF-8");

        // Sending the data to the server
        OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
        wr.write(urlData);
        wr.flush();
        wr.close();

        // Receiving the data from server
        BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line = null;

        // Read Server Response
        while ((line = reader.readLine()) != null) {
            // Append server response in string
            sb.append(line + "\n");
            // sb.append(line);
        }
        String text = sb.toString();
        reader.close();

        // Extracting the data, public key and signature received from
        // server
        Vector<String> storeExtractedValues = new Vector<String>();

        storeExtractedValues = extractDataFromJson(text, "data");
        dataFromServer = storeExtractedValues.get(0);

        storeExtractedValues = extractDataFromJson(text, "serverPublicKeySig");
        serverPublicKeySigStr = storeExtractedValues.get(0);

        storeExtractedValues = extractDataFromJson(text, "serverDataSig");
        serverDataSig = storeExtractedValues.get(0);

        // Converting the Server Public key format to Java compatible from
        PublicKey serverPublicKeySig = getServerPublicKey(serverPublicKeySigStr);

        // Verify the received data
        valid = getDataValidity(serverPublicKeySig, dataFromServer, serverDataSig);

        // Disconnect the url connection
        urlConnection.disconnect();

        if (dataFromServer.equalsIgnoreCase("unverified")) {
            CExceptionHandling.ExceptionState = ExceptionSet.SENT_DATA_UNVERIFIED;
            return "-1";
        } else if (valid == false) {
            CExceptionHandling.ExceptionState = ExceptionSet.RECEIVED_DATA_UNVERIFIED;
            return "-1";
        } else {
            return dataFromServer;
        }

    } catch (Exception e) {
        CExceptionHandling.ExceptionMsg = e.getMessage();

        if (e.toString().equals("java.net.SocketException: Network unreachable")) {
            CExceptionHandling.ExceptionState = ExceptionSet.NO_DATA_CONNECTION;
        } else if (e.toString().equals(
                "java.net.SocketTimeoutException: failed to connect to /10.0.2.2 (port 443) after 10000ms")) {
            CExceptionHandling.ExceptionState = ExceptionSet.CONNECTION_TIMEOUT;
        } else {
            CExceptionHandling.ExceptionState = ExceptionSet.OTHER_EXCEPTIONS;
        }
        return "-1";
    }

}

From source file:com.globalsight.connector.mindtouch.MindTouchCreateJobHandler.java

@ActionHandler(action = "connect", formClass = "")
public void prepareConnect(HttpServletRequest p_request, HttpServletResponse p_response, Object form)
        throws Exception {
    String mtcId = p_request.getParameter("mtcId");
    MindTouchConnector mtc = MindTouchManager.getMindTouchConnectorById(Long.parseLong(mtcId));
    p_request.setAttribute("mindtouchConnector", mtc);

    List<GlobalSightLocale> trgServerLocaleList = new ArrayList<GlobalSightLocale>();
    HashSet<String> trgServerLocales = new HashSet<String>();
    List<MindTouchConnectorTargetServer> targetServers = MindTouchManager
            .getAllTargetServers(Long.parseLong(mtcId));
    for (MindTouchConnectorTargetServer trgServer : targetServers) {
        trgServerLocales.add(trgServer.getTargetLocale().toLowerCase());
    }//www  .  java 2s  .  c o  m
    Vector allLocales = new Vector();
    try {
        allLocales = ServerProxy.getLocaleManager().getAvailableLocales();
        for (int i = 0; i < allLocales.size(); i++) {
            GlobalSightLocale gsl = (GlobalSightLocale) allLocales.get(i);
            if (trgServerLocales.contains(gsl.toString().toLowerCase())) {
                trgServerLocaleList.add(gsl);
            }
        }
    } catch (Exception e) {
        logger.error(e);
    }
    p_request.setAttribute("allAvailableLocales", allLocales);
    p_request.setAttribute("targetServerLocales", trgServerLocaleList);
}

From source file:com.globalsight.everest.webapp.applet.admin.customer.FileSystemApplet.java

/**
 * Prepare the info for the upload process and zip all the files.
 *//*from  w w  w.ja v  a 2  s  .  c  o  m*/
private void performUploadProcess(String servletLocation, String targetLocation, String randID,
        Vector p_outgoingData) {
    try {
        m_progressBar.setValue(10);
        getParentFrame().setCursor(Cursor.WAIT_CURSOR);
        String lineRead = null;
        String result = null;

        Vector outgoingData = new Vector();
        outgoingData.addElement(p_outgoingData);
        outgoingData.addElement(randID);

        Object[] objs = (Object[]) p_outgoingData.get(0);
        int size = objs == null ? 0 : objs.length;
        File[] files = new File[size];
        System.arraycopy(objs, 0, files, 0, size);
        m_progressBar.setValue(20);
        sendZipFile(files, servletLocation, targetLocation);
    } catch (Exception ioe) //IOException, ClassNotFoundException
    {
        System.err.println(ioe);
        AppletHelper.getErrorDlg(ioe.getMessage(), null);
    } finally {
        getParentFrame().setCursor(Cursor.DEFAULT_CURSOR);
    }
}

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

/**
 * @param stats/*from ww w .jav  a2 s  .c  o  m*/
 */
private void appendCollectingStats(final Vector<NameValuePair> stats) {
    final String ALL_YEAR_CATS = "ALL_YEAR_CATS_STAT";
    final String LAST_COL_YEAR_STAT = "LAST_COL_YEAR_STAT";
    //final String LAST_30_DAYS  = "LAST_30DAYS_STAT"; 

    int currentYear = Calendar.getInstance().get(Calendar.YEAR);

    AppPreferences remotePrefs = AppPreferences.getRemote();
    int lastColYear = remotePrefs.getInt(LAST_COL_YEAR_STAT, -1);
    boolean doAllYears = remotePrefs.getBoolean(ALL_YEAR_CATS, true);

    if (lastColYear != currentYear) // override when it is a new year
    {
        doAllYears = true;
    }

    StringBuilder allYearsSB = new StringBuilder();
    StringBuilder last30DaysSB = new StringBuilder();

    for (Object[] colRow : BasicSQLUtils
            .query("SELECT CollectionID,CollectionName,RegNumber FROM collection")) {
        Integer colId = (Integer) colRow[0];
        String colNm = (String) colRow[1];
        String regNum = (String) colRow[2];

        if (doAllYears) {
            String sql = String.format(
                    "SELECT YR,COUNT(YR) FROM (SELECT YEAR(if (CatalogedDate IS NULL, TimestampCreated, CatalogedDate)) AS YR FROM collectionobject WHERE CollectionMemberID = %d) T1 GROUP BY YR ORDER BY YR",
                    colId);
            collectStatsData(colNm, regNum, sql, allYearsSB);
        }

        // Cataloged by Month for current year
        String tmp = "SELECT MN, COUNT(MN) FROM (SELECT MONTH(DT) MN, YEAR(DT) YR FROM (SELECT if (CatalogedDate IS NULL, TimestampCreated, CatalogedDate) AS DT FROM collectionobject WHERE CollectionMemberID = %d) T1 WHERE YEAR(DT) = %d) T2 GROUP BY MN";
        String sql = String.format(tmp, colId, currentYear);
        collectStatsData(colNm, regNum, sql, last30DaysSB);
    }

    if (doAllYears) {
        addEncodedPair(stats, "catbyyr", allYearsSB.toString());
        remotePrefs.putBoolean(ALL_YEAR_CATS, false);
        remotePrefs.putInt(LAST_COL_YEAR_STAT, currentYear);
    }

    addEncodedPair(stats, "catbymn", last30DaysSB.toString());

    // Audit Information 
    Vector<Object[]> instRresults = BasicSQLUtils.query("SELECT Name, RegNumber FROM institution");
    if (instRresults.size() > 0) {
        Object[] instRow = instRresults.get(0);
        String instName = (String) instRow[0];
        String regNum = (String) instRow[1];

        String[] actionStr = { "ins", "upd", "rmv" };
        for (int action = 0; action < 3; action++) {
            StringBuilder auditSB = new StringBuilder();
            String tmp = "SELECT * FROM (SELECT a.TableNum, Count(a.TableNum) as Cnt FROM spauditlog AS a WHERE a.Action = %d GROUP BY a.TableNum) T1 ORDER BY Cnt DESC";
            String sql = String.format(tmp, action);
            collectStatsData(instName, regNum, sql, auditSB);
            addEncodedPair(stats, "audit_" + actionStr[action], auditSB.toString());
        }
    }
}