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:de.ipbhalle.metfrag.pubchem.PubChemWebService.java

/**
 * /* w  w  w .  ja  va 2  s .com*/
 * @author c-ruttkies
 * 
 * 
 * @param filename
 * @throws AxisFault 
 */
private boolean savingRetrievedHits(File filename, Vector<String> cidsVec) throws AxisFault {
    org.apache.commons.httpclient.params.DefaultHttpParams.getDefaultParams().setParameter(
            "http.protocol.cookie-policy",
            org.apache.commons.httpclient.cookie.CookiePolicy.BROWSER_COMPATIBILITY);

    PUGStub ps = new PUGStub();
    ps._getServiceClient().getOptions().setProperty(HTTPConstants.CHUNKED, false);
    ps._getServiceClient().getOptions().setTimeOutInMilliSeconds(5 * 60 * 1000);

    ArrayOfInt aoi = new ArrayOfInt();
    InputList il = new InputList();
    il.setIdType(gov.nih.nlm.ncbi.pubchemAxis2.PCIDType.eID_CID);
    Download d = new Download();
    d.setEFormat(gov.nih.nlm.ncbi.pubchemAxis2.FormatType.eFormat_SDF);
    d.setECompress(gov.nih.nlm.ncbi.pubchemAxis2.CompressType.eCompress_None);
    d.setUse3D(false);
    int[] cids = new int[cidsVec.size()];
    for (int i = 0; i < cidsVec.size(); i++) {
        try {
            cids[i] = Integer.parseInt(cidsVec.get(i));
        } catch (java.lang.NumberFormatException e) {
            System.err.println("Error: " + cidsVec.get(i) + " is no valid pubchem ID!");
            return false;
        }
    }
    aoi.set_int(cids);
    il.setIds(aoi);
    InputListResponse ilr = null;
    try {
        ilr = ps.inputList(il);
    } catch (RemoteException e) {
        System.err.println("Error: Pubchem sdf download failed. Contact cruttkie@ipb-halle.de!");
        e.printStackTrace();
        return false;
    }
    if (ilr == null) {
        System.err.println("Error: Pubchem sdf download failed. Contact cruttkie@ipb-halle.de!");
        return false;
    }
    String listKey = ilr.getListKey();
    d.setListKey(listKey);
    DownloadResponse dr = null;
    try {
        dr = ps.download(d);
    } catch (RemoteException e) {
        System.err.println("Error: Pubchem sdf download failed. Contact cruttkie@ipb-halle.de!");
        e.printStackTrace();
        return false;
    }
    gov.nih.nlm.ncbi.pubchemAxis2.GetOperationStatus req4 = new GetOperationStatus();
    AnyKeyType anyKey = new AnyKeyType();
    anyKey.setAnyKey(dr.getDownloadKey());
    req4.setGetOperationStatus(anyKey);
    gov.nih.nlm.ncbi.pubchemAxis2.StatusType status;
    try {
        if (this.verbose)
            System.out.print("downloading compounds from pubchem");
        while ((status = ps.getOperationStatus(req4)
                .getStatus()) == gov.nih.nlm.ncbi.pubchemAxis2.StatusType.eStatus_Running
                || status == gov.nih.nlm.ncbi.pubchemAxis2.StatusType.eStatus_Queued) {
            Thread.sleep(2000);
            if (this.verbose)
                System.out.print(".");
        }
    } catch (RemoteException e) {
        System.err.println("Error: Pubchem sdf download failed. Please contact cruttkie@ipb-halle.de!");
        e.printStackTrace();
        return false;
    } catch (InterruptedException e) {
        System.err.println("Error: Pubchem sdf download failed. Please contact cruttkie@ipb-halle.de!");
        e.printStackTrace();
        return false;
    }

    if (status == gov.nih.nlm.ncbi.pubchemAxis2.StatusType.eStatus_Success) {
        GetDownloadUrl req5 = new GetDownloadUrl();
        req5.setDownloadKey(dr.getDownloadKey());
        URL url = null;
        try {
            url = new URL(ps.getDownloadUrl(req5).getUrl());
        } catch (MalformedURLException e) {
            System.err.println("Error: Pubchem sdf download failed. Please contact cruttkie@ipb-halle.de!");
            e.printStackTrace();
            return false;
        } catch (RemoteException e) {
            System.err.println("Error: Pubchem sdf download failed. Please contact cruttkie@ipb-halle.de!");
            e.printStackTrace();
            return false;
        }

        if (this.verbose)
            System.out.println("\ndownload finished!");

        URLConnection fetch;
        InputStream input;
        try {
            fetch = url.openConnection();
            input = fetch.getInputStream();
        } catch (IOException e) {
            System.err.println("Error: Pubchem sdf download failed. Please contact cruttkie@ipb-halle.de!");
            e.printStackTrace();
            return false;
        }

        FileOutputStream output;
        try {
            output = new FileOutputStream(filename.getAbsoluteFile());
        } catch (FileNotFoundException e) {
            System.err.println("Error: Pubchem sdf download failed. Please contact cruttkie@ipb-halle.de!");
            e.printStackTrace();
            return false;
        }

        byte[] buffer = new byte[10000];
        int n;
        try {
            while ((n = input.read(buffer)) > 0)
                output.write(buffer, 0, n);
            output.close();
        } catch (IOException e) {
            System.err.println("Error: Pubchem sdf download failed. Please contact cruttkie@ipb-halle.de!");
            e.printStackTrace();
            return false;
        }
    } else {
        System.err.println("Error: Pubchem sdf download failed. Please contact cruttkie@ipb-halle.de!");
        return false;
    }

    FileInputStream in = null;
    try {
        in = new FileInputStream(filename);
    } catch (FileNotFoundException e) {
        System.err.println("Error: Pubchem sdf download failed. Please contact cruttkie@ipb-halle.de!");
        return false;
    }

    MDLV2000Reader reader = new MDLV2000Reader(in);
    ChemFile fileContents;
    try {
        fileContents = (ChemFile) reader.read(new ChemFile());
    } catch (CDKException e) {
        System.err.println("Error: Pubchem sdf download failed. Please contact cruttkie@ipb-halle.de!");
        e.printStackTrace();
        return false;
    }

    SmilesGenerator generatorSmiles = new SmilesGenerator();
    for (int i = 0; i < fileContents.getChemSequence(0).getChemModelCount(); i++) {
        this.containers
                .add(fileContents.getChemSequence(0).getChemModel(i).getMoleculeSet().getAtomContainer(0));

        Map<Object, Object> properties = fileContents.getChemSequence(0).getChemModel(i).getMoleculeSet()
                .getAtomContainer(0).getProperties();
        this.retrievedHits.put(Integer.parseInt(properties.get("PUBCHEM_COMPOUND_CID").toString()),
                generatorSmiles.createSMILES(
                        fileContents.getChemSequence(0).getChemModel(i).getMoleculeSet().getMolecule(0)));
    }

    return true;
}

From source file:edu.xtec.colex.client.beans.ColexRecordBean.java

/**
 * Calls the web service operation//w  w  w . ja v a 2 s  . c o  m
 * <I>addRecord(User,Owner,Collection,Record) : void</I>
 *
 * @param r the Record to add
 * @param vAttachments a Vector containing the Attachments of the Record
 * @throws java.lang.Exception when an Exception error occurs
 */
protected void addRecord(Record r, Vector vAttachments) throws Exception {
    User u = new User(getUserId());
    Collection c = new Collection("");

    Vector vTempFiles = new Vector();

    c.setName(collection);

    try {
        smRequest = mf.createMessage();

        SOAPBodyElement sbeRequest = setRequestName(smRequest, "addRecord");

        addParam(sbeRequest, u);
        if (owner != null) {
            Owner oRequest = new Owner(owner);
            addParam(sbeRequest, oRequest);
        }
        addParam(sbeRequest, c);
        addParam(sbeRequest, r);

        for (int i = 0; i < vAttachments.size(); i++) {

            FileItem fi = (FileItem) vAttachments.get(i);

            String sNomFitxer = Utils.getFileName(fi.getName());

            File fTemp = File.createTempFile("attach", null);

            fi.write(fTemp);

            vTempFiles.add(fTemp);

            URL urlFile = new URL("file://" + fTemp.getPath());

            AttachmentPart ap = smRequest.createAttachmentPart(new DataHandler(urlFile));

            String fieldName = fi.getFieldName();

            ap.setContentId(fieldName + "/" + sNomFitxer);

            smRequest.addAttachmentPart(ap);
        }
        smRequest.saveChanges();

        SOAPMessage smResponse = sendMessage(smRequest,
                this.getJspProperties().getProperty("url.servlet.record"));

        SOAPBody sbResponse = smResponse.getSOAPBody();

        if (sbResponse.hasFault()) {
            checkFault(sbResponse, "add");
        } else {

        }
    } catch (Exception e) {
        throw e;
    } finally {
        File fAux;

        for (int i = 0; i < vTempFiles.size(); i++) {
            fAux = (File) vTempFiles.get(i);
            fAux.delete();
        }
    }
}

From source file:de.mogwai.common.web.component.renderkit.html.common.TableRenderer.java

protected void renderHeader(FacesContext aContext, UIComponent aComponent, Vector<UIColumn> aColumns,
        Object aGroupObject) throws IOException {

    TableComponent theTableComponent = (TableComponent) aComponent;

    if (!theTableComponent.isShowHeader()) {
        return;//from  ww  w .jav  a 2  s  . c o  m
    }

    GridbagLayoutSizeDefinitionVector theCols = theTableComponent.getCols();

    ResponseWriter theWriter = aContext.getResponseWriter();

    if (aGroupObject != null) {
        theWriter.startElement("tr", aComponent);

        if (theTableComponent.isUseStyles()) {
            theWriter.writeAttribute("class", "mogwaiTableGroupRow", null);
        }

        theWriter.startElement("td", aComponent);
        theWriter.writeAttribute("colspan", aColumns.size(), null);

        if (theTableComponent.isUseStyles()) {
            theWriter.writeAttribute("class", "mogwaiTableGroupCell", null);
        }

        UIComponent theGroupHeader = theTableComponent.getMogwaiFacet(TableComponent.GROUPHEADER_FACET);

        aContext.getExternalContext().getRequestMap().put(TableComponent.HEADER_VAR_ATTRIBUTE, aGroupObject);

        RendererUtils.renderChild(aContext, theGroupHeader);

        aContext.getExternalContext().getRequestMap().remove(TableComponent.HEADER_VAR_ATTRIBUTE);

        theWriter.endElement("td");
        theWriter.endElement("tr");
    }

    theWriter.startElement("tr", aComponent);

    if (theTableComponent.isUseStyles()) {
        theWriter.writeAttribute("class", "mogwaiTableHeaderRow", null);
    }

    for (int i = 0; i < aColumns.size(); i++) {
        UIComponent theColumn = aColumns.get(i);

        theWriter.startElement("th", aComponent);

        if (theTableComponent.isUseStyles()) {
            theWriter.writeAttribute("class",
                    (i == aColumns.size() - 1) ? "mogwaiTableHeaderCellLast" : "mogwaiTableHeaderCell", null);
        }
        theWriter.writeAttribute("align", theCols.get(i).getAlign(), null);

        renderChildAndCheckEmptyness(aContext, theColumn.getFacet("header"));

        theWriter.endElement("th");
    }

    theWriter.endElement("tr");

}

From source file:webServices.RestServiceImpl.java

public Vector<Chart> parseChartsInfo(String info) {
    Vector<Chart> chartsInfo = new Vector<Chart>();
    Vector<String> values = new Vector<String>();

    String[] data;/*from www . ja v a  2  s.  c o m*/
    String[] attr;
    String[] chartInfo = info.split("\\{\"nam");

    //For each chart
    for (int i = 1; i < chartInfo.length; i++) {
        //Initialize values temp variable
        values = new Vector<String>();
        data = chartInfo[i].split("\\$");

        //Attributes of each chart
        for (int j = 0; j < data.length - 1; j++) {
            attr = data[j].split("\":\"");
            values.add(attr[1]);
        }

        Chart temp = new Chart(values.get(1), values.get(2), values.get(3), values.get(4), values.get(5),
                values.get(6));
        chartsInfo.add(temp);
    }

    return chartsInfo;
}

From source file:edu.ku.brc.specify.datamodel.Taxon.java

/**
 * Generates the 'full name' of a node using the <code>IsInFullName</code> field from the tree
 * definition items and following the parent pointer until we hit the root node.  Also used
 * in the process is a "direction indicator" for the tree determining whether the name
 * should start with the higher nodes and work down to the given node or vice versa.
 * //w w w.j a v  a 2  s . c o m
 * @param node the node to get the full name for
 * @return the full name
 */
public String fixFullName() {
    Vector<Taxon> parts = new Vector<Taxon>();
    parts.add(this);
    Taxon node = getParent();
    while (node != null) {
        Boolean include = node.getDefinitionItem().getIsInFullName();
        if (include != null && include.booleanValue() == true) {
            parts.add(node);
        }

        node = node.getParent();
    }
    int direction = getFullNameDirection();

    StringBuilder fullNameBuilder = new StringBuilder(parts.size() * 10);

    switch (direction) {
    case FORWARD: {
        for (int j = parts.size() - 1; j > -1; --j) {
            Taxon part = parts.get(j);
            String before = part.getDefinitionItem().getTextBefore();
            String after = part.getDefinitionItem().getTextAfter();

            if (before != null) {
                fullNameBuilder.append(part.getDefinitionItem().getTextBefore());
            }
            fullNameBuilder.append(part.getName());
            if (after != null) {
                fullNameBuilder.append(part.getDefinitionItem().getTextAfter());
            }
            if (j != parts.size() - 1) {
                fullNameBuilder.append(parts.get(j).getFullNameSeparator());
            }
        }
        break;
    }
    case REVERSE: {
        for (int j = 0; j < parts.size(); ++j) {
            Taxon part = parts.get(j);
            String before = part.getDefinitionItem().getTextBefore();
            String after = part.getDefinitionItem().getTextAfter();

            if (before != null) {
                fullNameBuilder.append(part.getDefinitionItem().getTextBefore());
            }
            fullNameBuilder.append(part.getName());
            if (after != null) {
                fullNameBuilder.append(part.getDefinitionItem().getTextAfter());
            }
            if (j != parts.size() - 1) {
                fullNameBuilder.append(parts.get(j).getFullNameSeparator());
            }
        }
        break;
    }
    default: {
        log.error("Invalid tree walk direction (for creating fullname field) found in tree definition");
        return null;
    }
    }

    return fullNameBuilder.toString().trim();
}

From source file:gate.util.reporting.DocTimeReporter.java

/**
 * A method for reading the file upside down.
 *
 * @param fileToBeRead//w  w w  .j  a  va  2s.com
 *          An object of the file to be read.
 * @param chunkSize
 *          An integer specifying the size of the chunks in which file will be
 *          read.
 * @return A long value pointing to the start position of the given file
 *         chunk.
 */
private long tail(File fileToBeRead, int chunkSize) throws BenchmarkReportInputFileFormatException {
    RandomAccessFile raf = null;
    try {
        raf = new RandomAccessFile(fileToBeRead, "r");
        Vector<String> lastNlines = new Vector<String>();
        int delta = 0;
        long curPos = 0;
        curPos = raf.length() - 1;
        long fromPos;
        byte[] bytearray;
        while (true) {
            fromPos = curPos - chunkSize;
            if (fromPos <= 0) {
                raf.seek(0);
                bytearray = new byte[(int) curPos];
                raf.readFully(bytearray);
                if (parseLinesFromLast(bytearray, lastNlines, fromPos)) {
                    if (fromPos < 0)
                        fromPos = 0;
                }
                break;
            } else {
                raf.seek(fromPos);
                bytearray = new byte[chunkSize];
                raf.readFully(bytearray);
                if (parseLinesFromLast(bytearray, lastNlines, fromPos)) {
                    break;
                }
                delta = lastNlines.get(lastNlines.size() - 1).length();
                lastNlines.remove(lastNlines.size() - 1);
                curPos = fromPos + delta;
            }
        }
        if (fromPos < 0)
            throw new BenchmarkReportInputFileFormatException(
                    getBenchmarkFile() + " does not contain a marker named " + getLogicalStart()
                            + " indicating logical start of a run.");
        return fromPos;

    } catch (IOException e) {
        e.printStackTrace();
        return -1;
    } finally {
        IOUtils.closeQuietly(raf);
    }
}

From source file:com.l2jfree.gameserver.handler.admincommands.AdminSortMultisellItems.java

private Vector<L2Item> sortItemsByPrice(Vector<L2Item> items, String[] array) {

    Vector<Integer> itemPrice = new Vector<Integer>();

    for (String string : array) {
        String[] param = string.split(splitting);

        if (param.length != 3)
            continue;

        String itemID = (MULTISELL_ID_SORT) ? param[0] : param[1];

        try {/*from w  ww.  ja va 2 s  .c om*/
            L2Item item = ItemTable.getInstance().getTemplate(Integer.valueOf(itemID));
            Integer price = Integer.valueOf(param[2]);

            if (item == null)
                continue;

            itemPrice.add(price);
        }

        catch (Exception e) {
            continue;
        }
    }

    for (int x = 0; x < itemPrice.size() - 1; x++)
        for (int y = x + 1; y < itemPrice.size(); y++) {
            if (itemPrice.get(x) > itemPrice.get(y)) {
                try {
                    //swap integers
                    Integer temp = itemPrice.get(x);
                    itemPrice.set(x, itemPrice.get(y));
                    itemPrice.set(y, temp);
                    //swap items
                    L2Item tempItem = items.get(x);
                    items.set(x, items.get(y));
                    items.set(y, tempItem);
                } catch (Exception e) {
                    continue;
                }
            }
        }

    return items;
}

From source file:com.google.enterprise.connector.salesforce.BaseTraversalManager.java

private DocumentList traverse(String checkpoint) {

    // count the number of times the traverse() was called
    second_counter++;//ww  w  .  j  av a  2s.c o  m
    if (second_counter == 10) {
        // every 10 seconds print a message
        logger.log(Level.INFO, "[" + connector.getInstanceName() + "] Traverse after [" + checkpoint + "]");
        second_counter = 0;
    }
    // set the current crawled checkpoint
    System.setProperty(this.getConnector().getInstanceName() + "_lcheckpoint", checkpoint);

    // initialize the basedocument list to return
    BaseDocumentList sdl = null;

    try {
        // convert a Date object into a 'numeric' format like
        // 200906010641010
        Date conv_checkpoint = Util.getNumericDate_from_String(checkpoint);

        // if its the first time we're doing this...create the checkpoint
        // for now
        if (conv_checkpoint == null || checkpoint.equalsIgnoreCase("")) {
            Date now = new Date();
            // hmmm...we could set the checkpoint here as either
            checkpoint = this.getConnector().getLastsync();
            // or
            // checkpoint = Util.getNumericString_from_Date(now);
        }

        // initialize a document list with 0 items and now as the checkpoint
        sdl = new BaseDocumentList(0, checkpoint);

        // if your xslt is not processable, return nothing
        if (this.XSLTDoc == null) {
            logger.log(Level.SEVERE, "[" + connector.getInstanceName()
                    + "] Response XSLT not compiled, not proceeded with transforms.");
            return sdl;
        }

        // ok...so our document list has nothing in it so lets go ask the
        // store if we
        // have any more docs to process...
        if (docListIndex.size() == 0) {
            getDocListAfter(checkpoint);
        }

        // now we have some docs in the document array we need to process
        if (docListIndex.size() > 0) {
            // get a doclist from the queue
            DocListEntry de = (DocListEntry) docListIndex.poll();

            // now convert the doclistentry (which is a SOAP response doc)
            // XML to <document><document>
            logger.log(Level.FINE,
                    "Attempting to convert string row to DOM object  [" + de.getCheckpoint() + "]");
            Document doc_in_xml = Util.XMLStringtoDoc(de.getResponseXML());
            logger.log(Level.FINE,
                    "Attempting to Transform DOM object  to <document/> [" + de.getCheckpoint() + "]");
            Document transformed_QueryResult = Util.TransformDoctoDoc(doc_in_xml, this.XSLTDoc);

            // TODO: DTD Validate the transformed SOAP query result

            logger.log(Level.FINE, "Extracting <document> objects from transformed response");

            NodeList nl_documents = transformed_QueryResult.getElementsByTagName("documents");
            // get the NodeList under <document>
            Node n_documents = nl_documents.item(0);
            Vector v_batch = new Vector();
            for (int i = 0; i < n_documents.getChildNodes().getLength(); i++) {
                Node n_doc = n_documents.getChildNodes().item(i);

                if (n_doc.getNodeType() == Node.ELEMENT_NODE) {
                    TransformerFactory transfac = TransformerFactory.newInstance();
                    Transformer trans = transfac.newTransformer();
                    trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
                    trans.setOutputProperty(OutputKeys.INDENT, "yes");

                    if (n_doc.getNodeName().equalsIgnoreCase("document")) {

                        DOMResult dr = new DOMResult();
                        trans.transform(new DOMSource(n_doc), dr);
                        Document newDoc = (Document) dr.getNode();
                        newDoc.getDocumentElement().normalize();
                        v_batch.add(newDoc);
                    }
                }
            }
            logger.log(Level.FINE, "Found " + v_batch.size() + "  documents in batch response");

            // so now we've populated a vector (v_batch) with XML elements
            // of <document></document>
            // objects

            sdl = new BaseDocumentList(v_batch.size(), de.getCheckpoint());
            for (int i = 0; i < v_batch.size(); i++) {

                // now convert each entry in the vector to a basedocument
                BaseSimpleDocument bdoc = this.convertXMLtoBaseDocument((Document) v_batch.get(i));
                SimpleDocument sd = (SimpleDocument) bdoc;
                sdl.add(sd);
            }
        }

        if (sdl.size() > 0) {
            this.running_doc_counter = this.running_doc_counter + sdl.size();
            logger.log(Level.INFO, "[" + connector.getInstanceName() + "]" + "  Returning " + sdl.size()
                    + " documents to the connector manager.  ");
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "traverse() error " + ex);
    }

    // return the doclist
    return sdl;
}

From source file:modnlp.capte.AlignmentInterfaceWS.java

public void actionPerformed(ActionEvent e) {

    //Handle open button action.
    if (e.getSource() == openButton) {
        int returnVal = fc.showOpenDialog(AlignmentInterfaceWS.this);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            //This is where a real application would open the file.
            sourceFile = file.getAbsolutePath();
            log.append("Source File: " + sourceFile + "." + newline);
        } else {//from w  w  w .  ja  v  a 2  s . c o  m
            log.append("Open command cancelled by user." + newline);
        }
        log.setCaretPosition(log.getDocument().getLength());

    }
    //deleteSegment
    else if (e.getSource() == deleteSegment) {
        Object[] o;
        String ivalue;
        int[] selected = table.getSelectedRows();
        ExampleTableModel em = (ExampleTableModel) table.getModel();

        if (selected.length < 1) {

            System.out.println("Please select at least one row");
            JOptionPane.showMessageDialog(edit, "Please select at least one row");
        } else {
            System.out.println("Deleting rows...");
            for (int i = selected.length - 1; i > -1; i--) {
                em.removeRow(selected[i]);
                //update numbers

                System.out.println("Removed row " + selected[i]);
            }
        }
        //Table should update itself automatically
    } else if (e.getSource() == moveUp) {
        int[] selected = table.getSelectedRows();
        ExampleTableModel em = (ExampleTableModel) table.getModel();
        if (selected.length > 1) {
            System.out.println("You can only move one segment at a time!");
            JOptionPane.showMessageDialog(edit, "You can only move one segment at a time!");
        } else if (selected[0] == 0) {
            System.out.println("Can't move up anymore!");
            JOptionPane.showMessageDialog(edit, "Can't move up anymore!");
        } else {
            System.out.println("Moving " + selected[0]);
            em.moveSegmentUp(selected[0]);
            //Table should repaint
        }
    } else if (e.getSource() == moveDown) {

        int[] selected = table.getSelectedRows();
        ExampleTableModel em = (ExampleTableModel) table.getModel();
        if (selected.length > 1) {

            System.out.println("You can only move one segment at a time!");
            JOptionPane.showMessageDialog(edit, "You can only move one segment at a time!");
        } else if (selected[0] == em.getRowCount() - 1) {

            System.out.println("Can't move down anymore!");
            JOptionPane.showMessageDialog(edit, "Can't move down anymore");
        } else {
            System.out.println("Moving " + selected[0]);
            em.moveSegmentDown(selected[0]);
            //Table should repaint
        }
    } else if (e.getSource() == mergeSource) {
        int[] selected = table.getSelectedRows();
        ExampleTableModel em = (ExampleTableModel) table.getModel();

        if (selected.length < 2 || selected.length > 2) {

            System.out.println("Please select two rows to merge ");
            JOptionPane.showMessageDialog(edit, "Please select two rows to merge");
        } else if (selected[0] - selected[1] > 1 || selected[0] - selected[1] < -1) {

            System.out.println("Can only merge adjacent rows");
            JOptionPane.showMessageDialog(edit, "Can only merge adjacent rows");
        } else {
            System.out.println("Merging source in rows " + selected[0] + " " + selected[1]);
            em.mergeSource(selected[0], selected[1]);
        }
    } else if (e.getSource() == mergeTarget) {
        int[] selected = table.getSelectedRows();
        ExampleTableModel em = (ExampleTableModel) table.getModel();

        if (selected.length < 2 || selected.length > 2) {

            System.out.println("Please select two rows to merge ");
            JOptionPane.showMessageDialog(edit, "Please select two rows to merge");
        } else if (selected[0] - selected[1] > 1 || selected[0] - selected[1] < -1) {

            System.out.println("Can only merge adjacent rows");
            JOptionPane.showMessageDialog(edit, "Can only merge adjacent rows");
        } else {
            System.out.println("Merging target in " + selected[0] + " " + selected[1]);
            em.mergeTarget(selected[0], selected[1]);
        }

    } else if (e.getSource() == newSegment) {
        int[] selected = table.getSelectedRows();
        ExampleTableModel em = (ExampleTableModel) table.getModel();

        if (selected.length < 1) {

            System.out.println("Please select a position to insert at:");
            JOptionPane.showMessageDialog(edit, "Please select a position to insert at");
        } else {
            System.out.println("Inserting new segment at " + (selected[0] + 1));
            //insert empty string array
            Object[] sa = new Object[6];
            sa[0] = "";
            sa[1] = "";
            sa[2] = "0.0";
            sa[3] = new Boolean(false);
            sa[4] = "0";
            sa[5] = em.getValueAt((selected[0]), 5) + "(+)";

            em.insertRow(sa, (selected[0] + 1));

        }
    } else if (e.getSource() == lockSelected) {
        int[] selected = table.getSelectedRows();
        ExampleTableModel em = (ExampleTableModel) table.getModel();

        if (selected.length < 1) {

            System.out.println("Please select some rows to lock:");
            JOptionPane.showMessageDialog(edit, "Please select some rows to lock:");
        } else {

            //lock selected rows

            for (int i = 0; i < selected.length; i++) {
                em.lockRow(selected[i]);
                System.out.println("Locking row " + selected[i]);

            }

        }
    } else if (e.getSource() == unlockSelected) {
        int[] selected = table.getSelectedRows();
        ExampleTableModel em = (ExampleTableModel) table.getModel();

        if (selected.length < 1) {

            System.out.println("Please select some rows to unlock:");
            JOptionPane.showMessageDialog(edit, "Please select some rows to unlock:");
        } else {

            //lock selected rows
            for (int i = 0; i < selected.length; i++) {
                em.unlockRow(selected[i]);
                System.out.println("Unlocking row " + selected[i]);
            }

        }
    } else if (e.getSource() == reAlign) {
        //  if(true){
        // JOptionPane.showMessageDialog(edit,"This feature is currently disabled");
        // }else{
        reNumber++;
        ExampleTableModel em = (ExampleTableModel) table.getModel();

        // Get list of locked segments
        // Find lowest locked segment
        // Realign from lowest locked segment
        // Join the realigned bit back up with the locked bit
        // refresh the table
        int lowestlock = 0;
        Vector<Object[]> slice = new Vector<Object[]>();
        Vector<Object[]> result = new Vector<Object[]>();
        Vector<Object[]> locked = new Vector<Object[]>();
        Boolean b = new Boolean(true);
        for (int i = 0; i < em.getRowCount(); i++) {
            b = (Boolean) em.getValueAt(i, 3);
            if (b.booleanValue() == true) {
                lowestlock = i;
            }
        }

        //get slice of table for realignment
        System.out.println("The lowest lock point is " + (lowestlock));
        System.out.println("Realigning from row:" + (lowestlock + 1) + " to : " + em.getRowCount());
        System.out.println("Total size of realign array =:" + (em.getRowCount() - (lowestlock)));
        //Get locked bits
        for (int h = 0; h < lowestlock + 1; h++) {

            locked.add(em.getRow(h));
        }
        //Get bits to realign
        for (int j = lowestlock + 1; j < em.getRowCount(); j++) {

            slice.add(em.getRow(j));

        }
        //flush 
        em.flush();
        for (int z = 0; z < locked.size(); z++) {
            em.insertRow(locked.get(z), z);
        }
        // System.out.println("Total size of array after bits removed  = " + (em.getRowCount()));
        //get the directory where the source files came from
        File parent = new File(sourceFile).getParentFile();
        String dir = parent.getAbsolutePath();
        //create files
        File sf = null;
        File tf = null;
        try {
            sf = File.createTempFile("source", "tmp");
            tf = File.createTempFile("target", "tmp");
        } catch (IOException ef) {
            ef.printStackTrace();
        }
        System.out.println("Writing temp file:" + sf.getName());
        System.out.println("Writing temp file:" + tf.getName());
        // File mf = new File("merged.tmp");
        //get absolute paths
        String sourceF = sf.getAbsolutePath();
        String targetF = tf.getAbsolutePath();
        //String alignF = mf.getAbsolutePath();
        //write out source and target to files
        //NEW write files to server and return string
        String alignment = "";
        AlignerUtils.reWriteAlignment(targetF, sourceF, slice);
        try {

            alignment = AlignerUtils.MultiPartFileUpload(targetF, sourceF);

        } catch (IOException es) {
            es.printStackTrace();
        }
        //convert the String to a Vector form
        result = AlignerUtils.StringToData(alignment, true, reNumber);
        // append the resultant file to the table
        //System.out.println("Total size of array before bits inserted  = " + (em.getRowCount()));
        for (int y = 0, z = em.getRowCount(); y < result.size(); y++, z++) {

            em.insertRow(result.get(y), z);
            System.out.println("Inserting at position: " + z);
            System.out.println("Inserting from position: " + y);

        }
        //  System.out.println("Total size of array after bits inserted  = " + (em.getRowCount()));
        // }
    } else if (e.getSource() == saveButton) {
        int returnVal = fc.showSaveDialog(AlignmentInterfaceWS.this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            //This is where a real application would save the file.
            targetFile = file.getAbsolutePath();
            log.append("Target File " + targetFile + "." + newline);
        } else {
            log.append("Save command cancelled by user." + newline);
        }
        log.setCaretPosition(log.getDocument().getLength());
    } else if (e.getSource() == export) {
        int returnVal = fc.showSaveDialog(AlignmentInterfaceWS.this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            outputFile = file.getAbsolutePath();
            //aserver.writeAlignment(targetFile,data);
            AlignerUtils.writeAlignment(outputFile, data);
            log.append(newline + "Saving " + outputFile + "." + newline);
        } else {
            log.append("Save command cancelled by user." + newline);
        }
        log.setCaretPosition(log.getDocument().getLength());
    } else if (e.getSource() == alignButton) {

        if (sl.getText().length() >= 2 && tl.getText().length() >= 2) {

            log.append("Attempting to align texts");
            sourcel = sl.getText();
            targetl = tl.getText();
            String aligned = "";
            try {
                aligned = AlignerUtils.MultiPartFileUpload(sourceFile, targetFile);
            } catch (IOException ed) {

                ed.printStackTrace();
            }
            //Convert string to alignment format
            data = AlignerUtils.StringToData(aligned, false, 0);

            int i = 0;

            //
            // AlreadyRun = true;
            if (i == 0) {
                //log.setCaretPosition(log.getDocument().getLength());
                log.append("\nAutomatic alignment successful!");
                log.append("\nOpening display window......");
                //Set up the editor window
                JFrame edit = new JFrame("Alignment Editor");
                cols = new Vector<String>();
                cols.add("Source");
                cols.add("Target");
                cols.add("Score");
                cols.add("Lock");
                cols.add("Index");
                cols.add("Orig");

                System.out.println("Size of data array " + data.size());
                System.out.println(data.get(0)[0]);
                ex = new ExampleTableModel(cols, data);
                //ex.addTableModelListener(this);
                table = new JTable(ex);
                table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

                TableColumnModel cmodel = table.getColumnModel();

                cmodel.getColumn(0).setCellRenderer(new TextAreaRenderer());
                cmodel.getColumn(1).setCellRenderer(new TextAreaRenderer());
                cmodel.getColumn(2).setCellRenderer(new TextAreaRenderer());
                cmodel.getColumn(4).setCellRenderer(new TextAreaRenderer());
                cmodel.getColumn(5).setCellRenderer(new TextAreaRenderer());
                TextAreaEditor textEditor = new TextAreaEditor();
                textEditor.addCellEditorListener(this);
                cmodel.getColumn(0).setCellEditor(textEditor);
                cmodel.getColumn(1).setCellEditor(textEditor);
                cmodel.getColumn(2).setCellEditor(textEditor);
                cmodel.getColumn(4).setCellEditor(textEditor);
                cmodel.getColumn(5).setCellEditor(textEditor);
                mergeTarget = new JButton("Merge target");
                mergeSource = new JButton("Merge source");
                export = new JButton("Export to File");
                newSegment = new JButton("Create New Segment");
                deleteSegment = new JButton("Delete Selected");
                moveUp = new JButton("Move Segment Up");
                moveDown = new JButton("Move Segment Down");
                lockSelected = new JButton("Lock Selected");
                unlockSelected = new JButton("Unlock Selected");
                reAlign = new JButton("Realign");
                reAlign.addActionListener(this);
                lockSelected.addActionListener(this);
                unlockSelected.addActionListener(this);
                mergeSource.addActionListener(this);
                mergeTarget.addActionListener(this);
                export.addActionListener(this);
                newSegment.addActionListener(this);
                deleteSegment.addActionListener(this);
                moveUp.addActionListener(this);
                moveDown.addActionListener(this);
                JPanel control = new JPanel();
                JPanel manipulate = new JPanel();
                control.add(moveUp);
                control.add(moveDown);
                control.add(mergeTarget);
                control.add(mergeSource);
                //control.add(export);
                control.add(newSegment);
                control.add(deleteSegment);
                manipulate.add(reAlign);
                manipulate.add(lockSelected);
                manipulate.add(unlockSelected);
                manipulate.add(export);
                edit.add(control, BorderLayout.PAGE_START);
                edit.add(manipulate, BorderLayout.PAGE_END);
                JScrollPane scr = new JScrollPane(table);
                //   JTable rowTable = new FirstRowNumberTable(table);

                //scr.add(table);
                //scr.setRowHeaderView(rowTable);
                //scr.setCorner(JScrollPane.UPPER_LEFT_CORNER, rowTable.getTableHeader()); 
                scr.repaint();
                edit.add(scr, BorderLayout.CENTER);
                Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
                edit.setSize(screenSize.width - 4, screenSize.height - 50);
                int totwidth = screenSize.width - 50;
                table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
                cmodel.getColumn(0).setPreferredWidth((totwidth / 36) * 15);
                cmodel.getColumn(1).setPreferredWidth((totwidth / 36) * 15);
                cmodel.getColumn(2).setPreferredWidth(totwidth / 36 * 2);
                cmodel.getColumn(3).setPreferredWidth(totwidth / 36 * 2);
                cmodel.getColumn(4).setPreferredWidth(totwidth / 36 * 2);
                cmodel.getColumn(4).setPreferredWidth(totwidth / 36 * 2);
                edit.validate(); // Make sure layout is ok

                //edit.setSize(1024,700);
                edit.setVisible(true);

            } else {
                //log.setCaretPosition(log.getDocument().getLength());
                log.append("\nAutomatic alignment unsuccessful..check error logs");
            }
        } else {
            log.append("Please enter valid two letter language codes");
        }
        log.setCaretPosition(log.getDocument().getLength());

    }
}

From source file:edu.caltechUcla.sselCassel.projects.jMarkets.server.control.CallMarketEngine.java

/**
 *  Calculate the price p in the given market that minimizes the difference between the number of buy
 *  orders >= p and the number of asks <= p. Return -1 if there is no execute price found (should only
 *  occur if there were no bids/asks on that market. If multiple minima are found, pick one at random.
 *//*from   w  w  w  . j av  a  2s .c o m*/
private int getExecutePrice(int marketId, OfferBook offerBook) {
    int numPrices = offerBook.getNumPrices();
    int difference = 10000;
    Vector executePriceIds = new Vector();

    for (int p = 0; p < numPrices; p++) {
        int numBids = offerBook.getGreaterThanOrEqualToBidOrders(marketId, p, -1);
        int numAsks = offerBook.getLessThanOrEqualToAskOrders(marketId, p, -1);

        int diff = Math.abs(numBids - numAsks);
        if (diff < difference && numBids != 0 && numAsks != 0) {
            difference = diff;
            executePriceIds.removeAllElements();
            executePriceIds.add(new Integer(p));
        } else if (diff == difference && numBids != 0 && numAsks != 0) {
            executePriceIds.add(new Integer(p));
        }
    }

    if (executePriceIds.size() > 0) {
        int mid = executePriceIds.size() / 2;
        log.info("Found the following execute price minima on market " + marketId + ": "
                + executePriceIds.toString() + " -- selecting one at random");

        int executePriceId = ((Integer) executePriceIds.get(mid)).intValue();
        float executePrice = offerBook.getPrice(marketId, executePriceId);

        log.info("Execute price for market " + marketId + " is: ID=" + executePriceId + ", Value="
                + executePrice);
        return executePriceId;
    } else {
        log.info("No possible transactions on market " + marketId + " -- no execute price found");
    }

    return -1;
}