Example usage for java.util Vector elementAt

List of usage examples for java.util Vector elementAt

Introduction

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

Prototype

public synchronized E elementAt(int index) 

Source Link

Document

Returns the component at the specified index.

Usage

From source file:com.symbian.driver.remoting.client.TestClient.java

/**
 * Update a test package to be sent to a remote master.
 * //from   ww  w .j  a  va  2s.  co m
 * @param aWorkingFolder
 *            String a working directory
 * @param aTestPackage
 *            String a test package name
 * @param aImage
 *            String a image name
 * @param aPlatsec
 *            true/false ON/OFF
 * 
 * @return the name of the updated test package
 */
public String updatePackage(String aWorkingFolder, String aTestPackage, String aImage, boolean aPlatsec,
        boolean aSysbin, boolean aTestexec, String aTransport, String aRdebug, boolean aTefLite) {
    String lTPUpdatedName = "updated_" + aTestPackage;
    try {
        Zipper lZip = new Zipper();

        File lWorkingFolder = new File(aWorkingFolder);
        File lTestPackageFile = new File(lWorkingFolder, aTestPackage);
        LOGGER.fine("Unzipping " + lTestPackageFile.toString() + "  To: " + lWorkingFolder.toString());

        // enumerate the contained files to be removed after being
        // repackaged
        Enumeration<? extends ZipEntry> lEnumer = (new ZipFile(lTestPackageFile)).entries();
        Vector<String> lUnzippedFileNames = new Vector<String>();

        while (lEnumer.hasMoreElements()) {
            String entryName = ((ZipEntry) lEnumer.nextElement()).getName();
            lUnzippedFileNames.addElement(entryName);
        }

        LOGGER.fine("Unzipping " + lTestPackageFile.toString() + "  To: " + lWorkingFolder.toString());

        // unzip testpackage
        Zipper.Unzip(lTestPackageFile, lWorkingFolder);

        // update manifest
        BufferedWriter lBw = new BufferedWriter(
                new FileWriter(lWorkingFolder.getCanonicalPath() + File.separator + "Manifest.mf", true));
        PrintWriter lPw = new PrintWriter(lBw);

        if (aImage != null) {
            lPw.println("romFile=" + aImage);
        }

        lPw.println("platsec=" + aPlatsec);

        if (aTransport != null) {
            lPw.println("transport=" + aTransport);
        }

        lPw.println("sysbin=" + aSysbin);

        lPw.println("statlite=" + aSysbin);

        lPw.println("teflite=" + aTefLite);

        lPw.println("testexec=" + aTestexec);

        if (aRdebug != null) {
            lPw.println("rdebug=" + aRdebug);
        }

        lPw.flush();
        lPw.close();
        lBw.close();

        // add image (rom by the moment)
        if (aImage != null) {
            lZip.addFile(new File(lWorkingFolder.getCanonicalPath() + File.separator + aImage));
        }
        // zip testpackage

        for (int i = 0; i < lUnzippedFileNames.size(); i++) {
            LOGGER.fine("Adding file : " + lWorkingFolder.toString() + " + " + lUnzippedFileNames.elementAt(i));
            lZip.addFile(
                    new File(lWorkingFolder.toString() + File.separator + lUnzippedFileNames.elementAt(i)));
        }

        LOGGER.fine("Zipping the updated package");
        lZip.zip(new File(lWorkingFolder, lTPUpdatedName), lWorkingFolder.getCanonicalPath());

        // delete all files previously unzipped in the working folder

        for (int i = 0; i < lUnzippedFileNames.size(); i++) {
            new File(lWorkingFolder + lUnzippedFileNames.elementAt(i)).delete();
        }

    } catch (IOException lException) {
        LOGGER.log(Level.SEVERE, "Failed to update package. " + lException.getMessage(), lException);
        return null;
    }

    return lTPUpdatedName;
}

From source file:gov.nih.nci.evs.browser.utils.SourceTreeUtils.java

public Vector findViewInHierarchySources(String body) {
    if (body == null)
        return null;
    String source_hierarchy = getSourceHierarchies();
    Vector u = gov.nih.nci.evs.browser.utils.StringUtils.parseData(source_hierarchy);
    System.out.println("u.size: " + u.size());
    for (int i = 0; i < u.size(); i++) {
        String t = (String) u.elementAt(i);
        if (body.contains("View In " + t + " Hierarchy")) {
            u.add(t);/*from  w w w  .j  av a 2 s  . c  om*/
        }
    }
    return u;
}

From source file:org.adl.samplerte.server.CourseService.java

/**
 * This method is used to update SCOData object and its associated comments.
 * <br>//w  w w. j a va 2  s  .c om
 * 
 * @param iActivityID -
 *           The unique identifier (internal to the Sample RTE) used to
 *           identify a single SCO in the Sample RTE.
 * @param iComments -
 *           A '[.]' delimited list of comments_from_lms Strings to be used
 *           to initialize the SCO when it is launched
 * @param iUpdate - 
 *          String representation of whether this is an update (true or false)
 * @param iLocations - 
 *          The locations
 * @return String - indicates whether the update was successful
 */
public String updateSCO(int iActivityID, String iComments, String iUpdate, String iLocations) {
    String result = "true";

    // Get all of the course information out of the database
    Connection conn = LMSDatabaseHandler.getConnection();

    PreparedStatement stmtDeleteComment;
    PreparedStatement stmtSetComment;

    String sqlSetComment = "INSERT INTO SCOComments(ActivityID, Comment,  "
            + "CommentDateTime, CommentLocation) VALUES(?,?,?,?)";

    String sqlDeleteComment = "DELETE FROM SCOComments WHERE ActivityID " + "= ?";

    Vector comments = new Vector();
    comments = getCommentVector(iComments);

    Vector locations = new Vector();
    locations = getCommentVector(iLocations);

    try {
        stmtSetComment = conn.prepareStatement(sqlSetComment);

        if (iUpdate.equals("false")) {
            // Clean out old comments then insert the new
            stmtDeleteComment = conn.prepareStatement(sqlDeleteComment);

            synchronized (stmtDeleteComment) {
                stmtDeleteComment.setInt(1, iActivityID);
                stmtDeleteComment.executeUpdate();
            }

            stmtDeleteComment.close();
        }

        DateFormat date = DateFormat.getDateTimeInstance();

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

            for (int i = 0; i < comments.size(); i++) {
                if (locations.elementAt(i).equals("")) {
                    synchronized (stmtSetComment) {
                        stmtSetComment.setInt(1, iActivityID);
                        stmtSetComment.setString(2, (String) comments.elementAt(i));
                        stmtSetComment.setString(3, date.format(new Date()));
                        stmtSetComment.executeUpdate();
                    }
                } else {
                    synchronized (stmtSetComment) {
                        stmtSetComment.setInt(1, iActivityID);
                        stmtSetComment.setString(2, (String) comments.elementAt(i));
                        stmtSetComment.setString(3, date.format(new Date()));
                        stmtSetComment.setString(4, (String) locations.elementAt(i));
                        stmtSetComment.executeUpdate();
                    }
                }
            }

            stmtSetComment.close();
        }

        conn.close();
    } catch (Exception e) {
        result = "false";
        e.printStackTrace();
    }

    return result;
}

From source file:skoa.helpers.Graficos.java

private void unificarDatosFicheros() {
    Vector<String> nombresFicheros2 = new Vector<String>(nombresFicheros); //Copiamos los nombres
    String nombreFicheroEscogido;
    String nombreFicheroReferencia = nombresFicheros2.get(0); //Se coge el 1 fichero de referencia, al que se le irn aadiendo los datos.
    nombresFicheros2.remove(0);//from   w  w w.ja  va2  s.  c om
    crearFicheroTemporal(nombreFicheroReferencia);
    for (int i = 0; i < nombresFicheros2.size(); i++) {
        nombreFicheroEscogido = nombresFicheros2.elementAt(i);
        File archivo = new File(ruta + nombreFicheroEscogido);
        FileReader fr = null;
        BufferedReader linea = null;
        String line;
        try {
            fr = new FileReader(archivo);
            linea = new BufferedReader(fr);
            while ((line = linea.readLine()) != null) { //Lectura del fichero
                incluirDatos(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != fr)
                    fr.close(); //Se cierra si todo va bien.
            } catch (Exception e2) { //Sino salta una excepcion.
                e2.printStackTrace();
            }
        }
    } //fin for
}

From source file:skoa.helpers.Graficos.java

private void barrasDual2() {
    unificarDatosFicheros();/*from  w  w w.  java  2  s . co m*/
    Vector<String> vectorOrdenUnidades = new Vector<String>();
    vectorOrdenUnidades = ordenDeUnidades();
    aplicarDiferencia(vectorOrdenUnidades);
    //En este caso, que queremos 2 ejes, MARCAMOS LA DIFERENCIA AL RECOGER EL 2 DATASET.
    CategoryDataset dataset = obtenerSerieBarrasDual(1);
    //String unidad=vectorOrdenUnidades.elementAt(0);
    String unidad;
    if (vectorOrdenUnidades.elementAt(0).indexOf("W") >= 0 || vectorOrdenUnidades.elementAt(0).indexOf("L") >= 0
            || vectorOrdenUnidades.elementAt(0).indexOf("m") >= 0
            || vectorOrdenUnidades.elementAt(0).indexOf("B") >= 0)
        unidad = vectorOrdenUnidades.elementAt(0);
    else if (vectorOrdenUnidades.elementAt(0).indexOf("C") >= 0)
        unidad = "C";
    else
        unidad = "";
    final CategoryAxis domainAxis = new CategoryAxis("Fechas");
    final NumberAxis rangeAxis = new NumberAxis("Mediciones (" + unidad + ")");
    final BarRenderer renderer1 = new BarRenderer();
    final CategoryPlot plot = new CategoryPlot(dataset, domainAxis, rangeAxis, renderer1) {
        private static final long serialVersionUID = 1L;

        //ESPECIAL. Modificamos la leyenda, para que se vea correcta, cogiendo los 2 items deseados.
        public LegendItemCollection getLegendItems() {
            final LegendItemCollection result = new LegendItemCollection();
            final CategoryDataset data = getDataset();
            if (data != null) {
                final CategoryItemRenderer r = getRenderer();
                if (r != null) {
                    final LegendItem item;
                    try { //Se recoge la excepcion en caso de haber solo
                        item = r.getLegendItem(0, 0); //una lnea en el fichero unificado, porque
                    } catch (Exception e) { //no habria nada en diferenciaAplicada.
                        System.out.println("MAL " + e);
                        return null;
                    }
                    result.add(item);
                }
            }
            final CategoryDataset dset2 = getDataset(1);
            if (dset2 != null) {
                final CategoryItemRenderer renderer2 = getRenderer(1);
                if (renderer2 != null) {
                    final LegendItem item = renderer2.getLegendItem(1, 1);
                    result.add(item);
                }
            }
            return result;
        }
    };
    final JFreeChart grafica = new JFreeChart("Valores medidos de las direcciones de grupo", plot);
    plot.setBackgroundPaint(new Color(0xEE, 0xEE, 0xFF));
    plot.setDomainAxisLocation(AxisLocation.BOTTOM_OR_RIGHT);
    CategoryDataset dataset2 = obtenerSerieBarrasDual(2);
    //unidad=vectorOrdenUnidades.elementAt(1);
    if (vectorOrdenUnidades.elementAt(1).indexOf("W") >= 0 || vectorOrdenUnidades.elementAt(1).indexOf("L") >= 0
            || vectorOrdenUnidades.elementAt(1).indexOf("m") >= 0
            || vectorOrdenUnidades.elementAt(1).indexOf("B") >= 0)
        unidad = vectorOrdenUnidades.elementAt(1);
    else if (vectorOrdenUnidades.elementAt(1).indexOf("C") >= 0)
        unidad = "C";
    else
        unidad = "";
    plot.setDataset(1, dataset2);
    plot.mapDatasetToRangeAxis(1, 1);
    final ValueAxis axis2 = new NumberAxis("Mediciones (" + unidad + ")");
    plot.setRangeAxis(1, axis2);
    plot.setRangeAxisLocation(1, AxisLocation.BOTTOM_OR_RIGHT);
    final BarRenderer renderer2 = new BarRenderer();
    renderer2.setShadowVisible(false); //Esconder las sombras de la barra 1.
    plot.setRenderer(1, renderer2);
    BarRenderer renderer = new BarRenderer();
    renderer.setShadowVisible(false); //Esconder las sombras de la barra 2.
    plot.setRenderer(0, renderer);
    plot.setRangeGridlinePaint(Color.BLACK); //Color de las lineas divisorias.
    //Subttulos
    if (fechaInicial.isEmpty()) {
        fechaInicial = fechaFinal = "?";
    }
    TextTitle t = new TextTitle("desde " + fechaInicial + " hasta " + fechaFinal,
            new Font("SanSerif", Font.ITALIC, 12));
    grafica.addSubtitle(t);
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 6.0));
    domainAxis.setTickLabelFont(new Font("Dialog", Font.PLAIN, 8)); //Letra de las fechas ms pequea
    grafica.setBackgroundPaint(Color.white);
    //-------------------------------------------------
    //Guarda la imagen:
    BufferedImage i1 = grafica.createBufferedImage(400, 300);
    BufferedImage i2 = grafica.createBufferedImage(900, 600);
    BufferedImage imag1 = convertirTipo(i1, BufferedImage.TYPE_INT_RGB);//!OBLIGATORIO!Para que al guardar la imagen,
    BufferedImage imag2 = convertirTipo(i2, BufferedImage.TYPE_INT_RGB);//no se vea transparente naranja.
    try {
        ImageIO.write(imag1, "jpg", new File(ruta + "BarrasSmall.jpg"));
        ImageIO.write(imag2, "jpg", new File(ruta + "BarrasBig.jpg"));
    } catch (IOException e) {
        System.out.println("Error de escritura");
    }
}

From source file:org.ecoinformatics.datamanager.database.DatabaseAdapter.java

/**
 * Creates a SQL command to insert data. If some error happens, null will be
 * returned./*from  ww w  .  java  2 s .c  om*/
 * 
 * @param attributeList  AttributeList which will be inserted
 * @param tableName      The name of the table which the data will be inserted into
 * @param oneRowData     The data vector which contains data to be inserted
 * @return A SQL String that can be run to insert one row of data into table
 */
public String generateInsertSQL(AttributeList attributeList, String tableName, Vector oneRowData)
        throws DataNotMatchingMetadataException, SQLException {
    String sqlString = null;
    int NULLValueCounter = 0;
    int hasValueCounter = 0;

    if (attributeList == null) {
        //log.debug("There is no attribute definition in entity");
        throw new SQLException("The attribute list is null and couldn't generate insert sql statement");
    }

    if (oneRowData == null || oneRowData.isEmpty()) {
        //return sqlString;
        throw new SQLException("The the data is null and couldn't generte insert sql statement");
    }

    StringBuffer sqlAttributePart = new StringBuffer();
    StringBuffer sqlDataPart = new StringBuffer();
    sqlAttributePart.append(INSERT);
    sqlAttributePart.append(SPACE);
    sqlAttributePart.append(tableName);
    sqlAttributePart.append(LEFTPARENTH);
    sqlDataPart.append(SPACE);
    sqlDataPart.append(VALUES);
    sqlDataPart.append(SPACE);
    sqlDataPart.append(LEFTPARENTH);
    Attribute[] list = attributeList.getAttributes();

    if (list == null || list.length == 0) {
        //log.debug("There is no attribute definition in entity");
        //return sqlString;
        throw new SQLException("The attributes is null and couldn't generate insert sql statement");
    }

    int size = list.length;
    // column name part
    boolean firstAttribute = true;

    for (int i = 0; i < size; i++) {
        // if data vector
        Object obj = oneRowData.elementAt(i);
        String value = null;

        if (obj == null) {
            NULLValueCounter++;
            continue;
        } else {
            value = (String) obj;
            if (value.trim().equals("")) {
                continue;
            }
        }

        Attribute attribute = list[i];

        if (attribute == null) {
            //log.debug("One attribute definition is null attribute list");
            //return null;
            throw new SQLException("Attribute list contains a null attribute");
        }
        String[] missingValues = attribute.getMissingValueCode();
        boolean isMissingValue = isMissingValue(value, missingValues);
        if (isMissingValue) {
            continue;
        }
        String name = attribute.getDBFieldName();
        String attributeType = getAttributeType(attribute);

        if (!firstAttribute) {
            sqlAttributePart.append(COMMA);
            sqlDataPart.append(COMMA);
        }

        sqlAttributePart.append(name);
        Domain domain = attribute.getDomain();
        //System.out.println("the value in element is "+value);

        /* If attributeType is "datetime", convert to a timestamp
         * and wrap single quotes around the value. But only if we
         * have a format string!
         */
        if (attributeType.equalsIgnoreCase("datetime")) {
            String formatString = ((DateTimeDomain) domain).getFormatString();
            //System.out.println("in DateTimeDomain " + value);
            value = escapeSpecialCharacterInData(value);
            sqlDataPart.append(TO_DATE_FUNCTION);
            sqlDataPart.append(LEFTPARENTH);

            sqlDataPart.append(SINGLEQUOTE);
            sqlDataPart.append(value);
            sqlDataPart.append(SINGLEQUOTE);

            sqlDataPart.append(COMMA);

            sqlDataPart.append(SINGLEQUOTE);
            sqlDataPart.append(formatString);
            sqlDataPart.append(SINGLEQUOTE);

            sqlDataPart.append(RIGHTPARENTH);
            hasValueCounter++;
            log.debug("datetime value expression= " + sqlDataPart.toString());
        }
        /* If domain is null or it is not NumericDomain we assign it text type
         * and wrap single quotes around the value.
         */
        else if (attributeType.equals("string")) {
            //System.out.println("in non NumericDomain " + value);
            value = escapeSpecialCharacterInData(value);
            sqlDataPart.append(SINGLEQUOTE);
            sqlDataPart.append(value);
            sqlDataPart.append(SINGLEQUOTE);
            hasValueCounter++;
        }
        /* Else we have a NumericDomain. Determine whether it is a float or
         * integer.
         */
        else {

            String dataType = mapDataType(attributeType);

            try {
                if (dataType.equals("FLOAT")) {
                    //System.out.println("in float NumericDomain " + value);
                    Float floatObj = new Float(value);
                    /* System.out.println("after generating floatObj numericDomain "
                         + value); */
                    float floatNum = floatObj.floatValue();
                    //System.out.println("float number " + floatNum);
                    sqlDataPart.append(floatNum);
                    //System.out.println("end of float");
                } else {
                    //System.out.println("in integer NumericDomain " + value);
                    Integer integerObj = new Integer(value);
                    //System.out.println("after generate Integer Obj NumericDomain "
                    //                   + value);
                    int integerNum = integerObj.intValue();
                    //System.out.println("the int value is " + integerNum);
                    sqlDataPart.append(integerNum);
                    //System.out.println("end of integer");
                }
            } catch (Exception e) {
                System.out.println("Error determining numeric value: " + e.getMessage());
                //return sqlString;
                throw new DataNotMatchingMetadataException(
                        "Data " + value + " is NOT a " + dataType + " : " + e.getMessage());
            }
            hasValueCounter++;
        }

        firstAttribute = false;
        // insert
    }

    // If all data is null, return null value for sql string.
    if (NULLValueCounter == list.length || hasValueCounter == 0) {
        return sqlString;
        //throw new SQLException("All data is null and couldn't generate insert data statement");
    }

    sqlAttributePart.append(RIGHTPARENTH);
    sqlDataPart.append(RIGHTPARENTH);
    sqlDataPart.append(SEMICOLON);

    // Combine the two parts
    sqlAttributePart.append(sqlDataPart.toString());
    sqlString = sqlAttributePart.toString();
    //System.out.println("the sql command is " + sqlString);

    return sqlString;
}

From source file:skoa.helpers.Graficos.java

private void barras() {
    unificarDatosFicheros();//from ww w. j  a va 2  s  . c o m
    Vector<String> vectorOrdenUnidades = new Vector<String>();
    vectorOrdenUnidades = ordenDeUnidades();
    aplicarDiferencia(vectorOrdenUnidades);
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    dataset = obtenerSerieBarras(vectorOrdenUnidades);
    String unidad = "";
    //for (int i=0;i<vectorOrdenUnidades.size();i++) unidad=unidad+vectorOrdenUnidades.elementAt(i)+", ";
    for (int i = 0; i < vectorOrdenUnidades.size(); i++) {
        if (vectorOrdenUnidades.elementAt(i).indexOf("W") >= 0
                || vectorOrdenUnidades.elementAt(i).indexOf("L") >= 0
                || vectorOrdenUnidades.elementAt(i).indexOf("m") >= 0
                || vectorOrdenUnidades.elementAt(i).indexOf("B") >= 0)
            unidad = unidad + vectorOrdenUnidades.elementAt(i) + ", ";
        else if (vectorOrdenUnidades.elementAt(i).indexOf("C") >= 0)
            unidad = unidad + "C, ";
        else
            unidad = unidad + ", ";
    }
    unidad = unidad.substring(0, unidad.length() - 2); //Quita el ultimo espacio y la ultima coma.

    JFreeChart grafica = ChartFactory.createBarChart("Valores medidos de las direcciones de grupo", "Fechas", //titulo eje x
            "Mediciones (" + unidad + ")", dataset, PlotOrientation.VERTICAL, true, //leyenda
            true, false);
    if (fechaInicial.isEmpty()) {
        fechaInicial = fechaFinal = "?";
    }
    TextTitle t = new TextTitle("desde " + fechaInicial + " hasta " + fechaFinal,
            new Font("SanSerif", Font.ITALIC, 12));
    grafica.addSubtitle(t);
    CategoryPlot plot = grafica.getCategoryPlot();
    //Modificar eje X
    CategoryAxis domainAxis = plot.getDomainAxis();
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 6.0));
    domainAxis.setTickLabelFont(new Font("Dialog", Font.PLAIN, 8)); //Letra de las fechas ms pequea
    //Esconder las sombras de las barras del barchart.
    CategoryPlot categoryPlot = (CategoryPlot) grafica.getPlot();
    BarRenderer renderer = new BarRenderer();
    renderer.setShadowVisible(false);
    categoryPlot.setRenderer(renderer);
    //-------------------------------------------------
    try {
        ChartUtilities.saveChartAsJPEG(new File(ruta + "BarrasSmall.jpg"), grafica, 400, 300);
        ChartUtilities.saveChartAsJPEG(new File(ruta + "BarrasBig.jpg"), grafica, 900, 600);
    } catch (IOException e) {
        System.err.println("Problem occurred creating chart.");
    }
}

From source file:je3.rmi.MudClient.java

/** 
 * Create and start a thread that sends out a message everyone in this
 * place.  If it gets a RemoteException talking to a person, it silently
 * removes that person from this place.  This is not a remote method, but
 * is used internally by a number of remote methods.
 **/// www .j ava 2 s .  c o  m
protected void tellEveryone(final String message) {
    // If there is no-one here, don't bother sending the message!
    if (people.size() == 0) return;
    // Make a copy of the people here now.  The message is sent
    // asynchronously and the list of people in the room may change before
    // the message is sent to everyone.
    final Vector recipients = (Vector) people.clone();
    // Create and start a thread to send the message, using an anonymous
    // class.  We do this because sending the message to everyone in this
    // place might take some time, (particularly on a slow or flaky
    // network) and we don't want to wait.
    new Thread() {
  public void run() {
      // Loop through the recipients
      for(int i = 0; i < recipients.size(); i++) {
     RemoteMudPerson person =
         (RemoteMudPerson)recipients.elementAt(i);
     // Try to send the message to each one.
     try { person.tell(message); } 
     // If it fails, assume that that person's client or
     // network has failed, and silently remove them from
     // this place.
     catch (RemoteException e) { 
         try { MudPlace.this.exit(person, null); } 
         catch (Exception ex) {} 
     }
      }
  }
   }.start();
}

From source file:org.ecoinformatics.seek.datasource.eml.eml2.Eml200Parser.java

/**
 * pulls the entity information out of the xml and stores it in a hashtable
 *//*from w ww. j  a  v a 2s  .  c  om*/
private void processEntities(CachedXPathAPI xpathapi, NodeList entities, String xpath)
        throws SAXException, javax.xml.transform.TransformerException, Exception {
    // make sure that entities is not null
    if (entities == null) {
        return;
    }
    int entityNodeListLength = entities.getLength();

    String entityName = "";
    String entityDescription = "";
    String entityOrientation = "";
    String entityCaseSensitive = "";
    String entityNumberOfRecords = "-1";
    String physicalFile = "";
    String numHeaderLines = "0";
    int numFooterLines = 0;
    String fieldDelimiter = null;
    String recordDelimiter = "";
    String compressionMethod = "";
    String encodingMethod = "";
    boolean isImageEntity = false;
    boolean isGZipDataFile = false;
    boolean isZipDataFile = false;
    boolean isTarDataFile = false;
    boolean isSimpleDelimited = true;
    boolean isCollapseDelimiter = false;
    TextComplexDataFormat[] formatArray = null;
    int entityCounter = 0;

    for (int i = 0; i < entityNodeListLength; i++) {

        if (xpath != null && (xpath.equals(SPATIALRASTERENTITY) || xpath.equals(SPATIALVECTORENTITY))) {
            isImageEntity = true;
        }
        // go through the entities and put the information into the hash.
        elementId++;
        Node entity = entities.item(i);
        NodeList entityChildren = entity.getChildNodes();
        for (int j = 0; j < entityChildren.getLength(); j++) {
            Node child = entityChildren.item(j);
            String childName = child.getNodeName();

            if (childName.equals("entityName")) {
                entityName = child.getFirstChild().getNodeValue();
            } else if (childName.equals("entityDescription")) {
                entityDescription = child.getFirstChild().getNodeValue();
            } else if (childName.equals("caseSensitive")) {
                entityCaseSensitive = child.getFirstChild().getNodeValue();
            } else if (childName.equals("numberOfRecords")) {
                entityNumberOfRecords = child.getFirstChild().getNodeValue();
                if (entityNumberOfRecords != null) {
                    entityNumberOfRecords = entityNumberOfRecords.trim();
                    numRecords = (new Integer(entityNumberOfRecords)).intValue();
                }
            }

        }

        NodeList orientationNodeList = xpathapi.selectNodeList(entity,
                "physical/dataFormat/textFormat/attributeOrientation");
        if (orientationNodeList != null && orientationNodeList.getLength() > 0) {
            entityOrientation = orientationNodeList.item(0).getFirstChild().getNodeValue();

        }

        NodeList headerLinesNL = xpathapi.selectNodeList(entity,
                "physical/dataFormat/textFormat/numHeaderLines");
        if ((headerLinesNL != null) && (headerLinesNL.getLength() > 0)) {
            Node headerLinesNode = headerLinesNL.item(0);
            if (headerLinesNode != null) {
                numHeaderLines = headerLinesNode.getFirstChild().getNodeValue();
            }
        }

        NodeList footerLinesNL = xpathapi.selectNodeList(entity,
                "physical/dataFormat/textFormat/numFooterLines");
        if ((footerLinesNL != null) && (footerLinesNL.getLength() > 0)) {
            Node footerLinesNode = footerLinesNL.item(0);
            if (footerLinesNode != null) {
                String footerLineStr = footerLinesNode.getFirstChild().getNodeValue();
                numFooterLines = (new Integer(footerLineStr.trim())).intValue();
            }
        }

        // Here is the simple delimited data file
        NodeList delimiterNL = xpathapi.selectNodeList(entity,
                "physical/dataFormat/textFormat/simpleDelimited/fieldDelimiter");
        if (delimiterNL != null && delimiterNL.getLength() > 0) {
            fieldDelimiter = delimiterNL.item(0).getFirstChild().getNodeValue();
        }

        // Here is the simple delimited data file
        NodeList collapseDelimiterNL = xpathapi.selectNodeList(entity,
                "physical/dataFormat/textFormat/simpleDelimited/collapseDelimiters");
        if (collapseDelimiterNL != null && collapseDelimiterNL.getLength() > 0) {
            String collapseDelimiter = collapseDelimiterNL.item(0).getFirstChild().getNodeValue();
            if (collapseDelimiter.equalsIgnoreCase("yes")) {
                isCollapseDelimiter = true;
            }

        }

        // for complex format data file
        NodeList complexFormatNL = xpathapi.selectNodeList(entity, "physical/dataFormat/textFormat/complex");
        if (complexFormatNL != null && complexFormatNL.getLength() > 0) {
            log.debug("in handle complex text data format");
            isSimpleDelimited = false;
            Node complexFormatNode = complexFormatNL.item(0);
            NodeList complexFormatChildren = complexFormatNode.getChildNodes();
            int childrenLength = complexFormatChildren.getLength();
            Vector formatVector = new Vector();
            for (int k = 0; k < childrenLength; k++) {
                Node node = complexFormatChildren.item(k);
                if (node != null && node.getNodeName().equals("textFixed")) {
                    TextWidthFixedDataFormat textFixedFormat = handleTextFixedDataFormatNode(node);
                    if (textFixedFormat != null) {
                        formatVector.add(textFixedFormat);
                        // complexFormatsNumber++;
                    }

                } else if (node != null && node.getNodeName().equals("textDelimited")) {
                    TextDelimitedDataFormat delimitedFormat = handleComplexDelimitedDataFormatNode(node);
                    if (delimitedFormat != null) {
                        formatVector.add(delimitedFormat);
                        // complexFormatsNumber++;
                    }
                }
            }
            // transfer vector to array
            complexFormatsNumber = formatVector.size();
            formatArray = new TextComplexDataFormat[complexFormatsNumber];
            for (int j = 0; j < complexFormatsNumber; j++) {
                formatArray[j] = (TextComplexDataFormat) formatVector.elementAt(j);
            }

        }

        NodeList recDelimiterNL = xpathapi.selectNodeList(entity,
                "physical/dataFormat/textFormat/recordDelimiter");
        if ((recDelimiterNL != null) && (recDelimiterNL.getLength() > 0)) {
            recordDelimiter = recDelimiterNL.item(0).getFirstChild().getNodeValue();
        } else {
            recordDelimiter = "\r\n";
        }
        // get the distribution information
        NodeList distributionNL = xpathapi.selectNodeList(entity, "physical/distribution/online/url");
        if (distributionNL != null && distributionNL.getLength() > 0) {
            physicalFile = distributionNL.item(0).getFirstChild().getNodeValue();
            if (isDebugging) {
                log.debug("The url is " + physicalFile);
            }
        }
        // if this url is donwloadable, if the value is "information", it is
        // not downloadable
        // otherwise, it is downloadable
        Boolean isDownloadable = true;
        NodeList distributionURLNL = xpathapi.selectNodeList(entity,
                "physical/distribution/online/url/@function");
        if (distributionURLNL != null && distributionURLNL.getLength() > 0) {
            String function = distributionURLNL.item(0).getNodeValue();
            log.debug("The function value is ============ " + function);
            if (function != null && function.equals(INFORMATION)) {
                isDownloadable = false;
            }
        }

        // get the compressionMethod information
        NodeList compressionNL = xpathapi.selectNodeList(entity, "physical/compressionMethod");
        if (compressionNL != null && compressionNL.getLength() > 0) {
            compressionMethod = compressionNL.item(0).getFirstChild().getNodeValue();
            if (isDebugging) {
                log.debug("Compression method is " + compressionMethod);
            }
            if (compressionMethod != null && compressionMethod.equals(Entity.GZIP)) {
                isGZipDataFile = true;
            } else if (compressionMethod != null && compressionMethod.equals(Entity.ZIP)) {
                isZipDataFile = true;
            }
        }

        // get encoding method info (mainly for tar file)
        NodeList encodingNL = xpathapi.selectNodeList(entity, "physical/encodingMethod");
        if (encodingNL != null && encodingNL.getLength() > 0) {
            encodingMethod = encodingNL.item(0).getFirstChild().getNodeValue();
            if (isDebugging) {
                log.debug("encoding method is " + encodingMethod);
            }
            if (encodingMethod != null && encodingMethod.equals(Entity.TAR)) {
                isTarDataFile = true;
            }
        }

        if (entityOrientation.trim().equals("column")) {
            entityOrientation = Entity.COLUMNMAJOR;
        } else {
            entityOrientation = Entity.ROWMAJOR;
        }

        if (entityCaseSensitive.equals("yes")) {
            entityCaseSensitive = "true";
        } else {
            entityCaseSensitive = "false";
        }

        entityObject = new Entity(Integer.toString(elementId), entityName.trim(), entityDescription.trim(),
                new Boolean(entityCaseSensitive), entityOrientation,
                new Integer(entityNumberOfRecords).intValue());
        entityObject.setNumHeaderLines((new Integer(numHeaderLines)).intValue());
        entityObject.setNumFooterLines(numFooterLines);
        entityObject.setSimpleDelimited(isSimpleDelimited);
        // for simple dimited data file
        if (fieldDelimiter != null) {
            entityObject.setDelimiter(fieldDelimiter);
        }
        entityObject.setCollaplseDelimiter(isCollapseDelimiter);

        entityObject.setRecordDelimiter(recordDelimiter);
        entityObject.setURL(physicalFile);
        entityObject.setCompressionMethod(compressionMethod);
        entityObject.setIsImageEntity(isImageEntity);
        entityObject.setHasGZipDataFile(isGZipDataFile);
        entityObject.setHasZipDataFile(isZipDataFile);
        entityObject.setHasTarDataFile(isTarDataFile);
        entityObject.setDownloadable(isDownloadable);

        try {
            NodeList attNL = xpathapi.selectNodeList(entity, "attributeList");
            processAttributeList(xpathapi, attNL, entityObject);
            entityObject.setDataFormatArray(formatArray);

        } catch (Exception e) {
            log.warn("Error parsing attributes: " + e.getMessage() + " So this entity " + entityObject.getName()
                    + " may not have attribute list");
        }
        if (entityObject.isDownloadable()) {
            entityHash.put(Integer.toString(elementId), entityObject);
            entityList.add(entityObject);
            entityCounter++;
        }

        // fileHash.put(elementId, physicalFile);

    }
    numEntities = numEntities + entityCounter;

}

From source file:com.netscape.admin.certsrv.Console.java

/**
 * A helper method to find an SIE DN from its ID. See -s Console option.
 * Called by createPerInstanceUI()./*w w w. j  av a  2  s.  c o  m*/
 */
private String serverIDtoDN(String id) {

    LDAPConnection ldc = _info.getLDAPConnection();
    Vector<String> instances = new Vector<>();

    try {
        LDAPSearchResults res = ldc.search("o=netscapeRoot", LDAPConnection.SCOPE_SUB,
                "(nsServerID=" + id + ")", new String[] { "dn" }, false);

        while (res.hasMoreElements()) {
            LDAPEntry hostEntry = res.next();
            instances.addElement(hostEntry.getDN());
        }

        if (instances.size() == 0) {
            System.err.println("Server instance " + id + " does not exist.");
            System.exit(0);
        } else if (instances.size() == 1) {
            id = instances.elementAt(0);
        } else {

            if (_splashScreen != null) {
                _splashScreen.setVisible(false);
            }

            int idx = -1;
            while (idx == -1) {
                System.out.println("\nThere are multiple instances of server \"" + id + "\":\n");
                for (int i = 0; i < instances.size(); i++) {
                    System.out.println((i + 1) + ") " + instances.elementAt(i));
                }
                System.out.print("\nPlease select an instance form the above list [1]: ");
                try {
                    String rsp = new BufferedReader(new InputStreamReader(System.in)).readLine();
                    if (rsp.length() == 0) {
                        idx = 1;
                    } else {
                        try {
                            idx = Integer.parseInt(rsp);
                        } catch (Exception ignore) {
                        }
                    }

                    if (idx >= 1 && idx <= instances.size()) {
                        idx = idx - 1;
                    } else {
                        idx = -1;
                    }
                } catch (Exception e) {
                    break;
                }
            }
            id = instances.elementAt(idx);
        }
    } catch (Exception e) {
        if (Debug.isEnabled()) {
            e.printStackTrace();
        }
    }
    return id;
}