org.bridgedb.IDMapper - java examples

Here are the examples of the java api org.bridgedb.IDMapper taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

57 Examples 7

19 View Complete Implementation : Test.java
Copyright Apache License 2.0
Author : bridgedb
public clreplaced Test {

    private IDMapper mapper;

    private Server server;

    private boolean configExists;

    @BeforeEach
    public void setUp() throws Exception {
        File f = new File(IDMapperService.CONF_GDBS);
        configExists = f.exists();
        if (configExists) {
            if (server == null) {
                server = new Server();
                server.run(8183, null, false);
            }
            if (mapper == null) {
                // Create a client
                Clreplaced.forName("org.bridgedb.webservice.bridgerest.BridgeRest");
                mapper = BridgeDb.connect("idmapper-bridgerest:http://localhost:8183/Human");
            }
        } else {
            System.err.println("Skipping server tests. No " + IDMapperService.CONF_GDBS + " found.");
        }
    }

    @AfterEach
    public void tearDown() throws Exception {
        if (server != null) {
            server.stop();
        }
    }

    public IDMapper getLocalService() {
        return mapper;
    }

    @org.junit.jupiter.api.Test
    public void testLocalMapID() throws IDMapperException, ClreplacedNotFoundException {
        if (configExists) {
            IDMapper mapper = getLocalService();
            Xref insr = new Xref("3643", BioDataSource.ENTREZ_GENE);
            Xref affy = new Xref("33162_at", BioDataSource.AFFY);
            Set<Xref> result = mapper.mapID(insr);
            replacedertTrue(result.contains(affy));
            replacedertTrue(mapper.xrefExists(insr));
        }
    }

    @org.junit.jupiter.api.Test
    public void testLocalCapabilities() throws IDMapperException, ClreplacedNotFoundException {
        if (configExists) {
            IDMapper mapper = getLocalService();
            IDMapperCapabilities cap = mapper.getCapabilities();
            Set<DataSource> supported = cap.getSupportedSrcDataSources();
            replacedertTrue(supported.contains(DataSource.getBySystemCode("L")));
            String val = cap.getProperty("SCHEMAVERSION");
            replacedertNotNull(val);
            Set<DataSource> srcDs = cap.getSupportedSrcDataSources();
            replacedertTrue(srcDs.size() > 0);
            replacedertTrue(cap.isFreeSearchSupported());
            replacedertTrue(cap.isMappingSupported(BioDataSource.UNIPROT, BioDataSource.ENTREZ_GENE));
            replacedertFalse(cap.isMappingSupported(DataSource.getBySystemCode("??"), DataSource.getBySystemCode("!!")));
        }
    }

    @org.junit.jupiter.api.Test
    public void testLocalSearch() throws IDMapperException, ClreplacedNotFoundException {
        if (configExists) {
            IDMapper mapper = getLocalService();
            Set<Xref> result = mapper.freeSearch("1234", 100);
            System.out.println(result);
            replacedertTrue(result.size() > 0);
        }
    }

    @org.junit.jupiter.api.Test
    public void testLocalAttributes() throws ClreplacedNotFoundException, IDMapperException {
        if (configExists) {
            AttributeMapper mapper = (AttributeMapper) getLocalService();
            Xref insr = new Xref("3643", BioDataSource.ENTREZ_GENE);
            Map<String, Set<String>> attrMap = mapper.getAttributes(insr);
            replacedertNotNull(attrMap.get("Symbol"));
            replacedertEquals(2, attrMap.get("Symbol").size());
            Set<String> attrValues = mapper.getAttributes(insr, "Symbol");
            replacedertEquals(2, attrValues.size());
            Map<Xref, String> xrefMap = mapper.freeAttributeSearch("INSR", "Symbol", 1);
            replacedertEquals(1, xrefMap.size());
            xrefMap = mapper.freeAttributeSearch("INSR", "Symbol", 100);
            replacedertTrue(xrefMap.containsKey(insr));
            replacedertTrue(xrefMap.size() > 1);
            Set<String> attrs = mapper.getAttributeSet();
            replacedertTrue(attrs.size() > 0);
        }
    }
}

19 View Complete Implementation : CachedData.java
Copyright Apache License 2.0
Author : PathVisio
/**
 * Set the mapper that is used for ID Mapping. Clears cache if necessary.
 * TODO In the future I want to set this in the constructor, and
 * make mapper final.
 */
public void setMapper(IDMapper mapper) {
    if (this.mapper != mapper) {
        this.mapper = mapper;
        clearCache();
    }
}

19 View Complete Implementation : Test.java
Copyright Apache License 2.0
Author : bridgedb
@org.junit.jupiter.api.Test
public void testLocalSearch() throws IDMapperException, ClreplacedNotFoundException {
    if (configExists) {
        IDMapper mapper = getLocalService();
        Set<Xref> result = mapper.freeSearch("1234", 100);
        System.out.println(result);
        replacedertTrue(result.size() > 0);
    }
}

19 View Complete Implementation : BridgeDbActivity.java
Copyright Apache License 2.0
Author : bridgedb
public clreplaced BridgeDbActivity extends AbstractAsynchronousActivity<BridgeDbActivityConfigurationBean> implements AsynchronousActivity<BridgeDbActivityConfigurationBean> {

    /*
	 * Best practice: Keep port names as constants to avoid misspelling. This
	 * would not apply if port names are looked up dynamically from the service
	 * operation, like done for WSDL services.
	 */
    private static final String IN_ID = "identifier";

    private static final String IN_DS = "source datasource";

    private static final String IN_DESTDS = "target datasource";

    private static final String OUT_IDS = "identifiers";

    private static final String OUT_DSS = "datasources";

    private BridgeDbActivityConfigurationBean configBean;

    private IDMapper mapper;

    private boolean isTargetted;

    @Override
    public void configure(BridgeDbActivityConfigurationBean configBean) throws ActivityConfigurationException {
        // Any pre-config sanity checks
        if (configBean.getConnectionString().equals("")) {
        }
        // Store for getConfiguration(), but you could also make
        // getConfiguration() return a new bean from other sources
        this.configBean = configBean;
        // OPTIONAL:
        synchronized (this) {
            String clreplacedName = configBean.getDriverClreplaced();
            String connectionString = configBean.getConnectionString();
            BioDataSource.init();
            try {
                Clreplaced.forName(clreplacedName);
                mapper = BridgeDb.connect(connectionString);
            } catch (ClreplacedNotFoundException ex) {
                throw new ActivityConfigurationException("Could not find BridgeDb driver clreplaced '" + clreplacedName + "'", ex);
            } catch (IDMapperException ex) {
                throw new ActivityConfigurationException("Could not establish connection to mapping source '" + connectionString + "'", ex);
            }
        }
        // REQUIRED: (Re)create input/output ports depending on configuration
        configurePorts();
    }

    protected void configurePorts() {
        // In case we are being reconfigured - remove existing ports first
        // to avoid duplicates
        removeInputs();
        removeOutputs();
        // FIXME: Replace with your input and output port definitions
        // Hard coded input port, expecting a single String
        addInput(IN_ID, 0, true, null, String.clreplaced);
        addInput(IN_DS, 0, true, null, String.clreplaced);
        // Optional ports depending on configuration
        if (isTargetted) {
            addInput(IN_DESTDS, 0, true, null, String.clreplaced);
        }
        // Single value output port (depth 0)
        // Output port with list of values (depth 1)
        addOutput(OUT_IDS, 1);
        addOutput(OUT_DSS, 1);
    }

    @SuppressWarnings("unchecked")
    @Override
    public void executeAsynch(final Map<String, T2Reference> inputs, final AsynchronousActivityCallback callback) {
        // Don't execute service directly now, request to be run ask to be run
        // from thread pool and return asynchronously
        callback.requestRun(new Runnable() {

            public void run() {
                InvocationContext context = callback.getContext();
                ReferenceService referenceService = context.getReferenceService();
                // Resolve inputs
                String id = (String) referenceService.renderIdentifier(inputs.get(IN_ID), String.clreplaced, context);
                String ds = (String) referenceService.renderIdentifier(inputs.get(IN_DS), String.clreplaced, context);
                String targetDs = null;
                if (isTargetted) {
                    targetDs = (String) referenceService.renderIdentifier(inputs.get(IN_DESTDS), String.clreplaced, context);
                }
                Set<Xref> result;
                Xref srcRef = new Xref(id, DataSource.getByFullName(ds));
                try {
                    synchronized (this) {
                        if (isTargetted) {
                            result = mapper.mapID(srcRef, DataSource.getByFullName(targetDs));
                        } else {
                            result = mapper.mapID(srcRef);
                        }
                    }
                } catch (IDMapperException ex) {
                    callback.fail("ID mapping of " + srcRef + " failed.", ex);
                    return;
                }
                // Register outputs
                Map<String, T2Reference> outputs = new HashMap<String, T2Reference>();
                String simpleValue = "simple";
                T2Reference simpleRef = referenceService.register(simpleValue, 0, true, context);
                outputs.put(OUT_IDS, simpleRef);
                // For list outputs, only need to register the top level list
                List<String> ids = new ArrayList<String>();
                List<String> dss = new ArrayList<String>();
                for (Xref ref : result) {
                    ids.add(ref.getId());
                    dss.add(ref.getDataSource().getFullName());
                }
                T2Reference idsRef = referenceService.register(ids, 1, true, context);
                outputs.put(OUT_IDS, idsRef);
                T2Reference dssRef = referenceService.register(dss, 1, true, context);
                outputs.put(OUT_DSS, dssRef);
                // if (optionalPorts) {
                // // Populate our optional output port
                // // NOTE: Need to return output values for all defined output ports
                // String report = "Everything OK";
                // outputs.put(OUT_DSS, referenceService.register(report,
                // 0, true, context));
                // }
                // return map of output data, with empty index array as this is
                // the only and final result (this index parameter is used if
                // pipelining output)
                callback.receiveResult(outputs, new int[0]);
            }
        });
    }

    @Override
    public BridgeDbActivityConfigurationBean getConfiguration() {
        return this.configBean;
    }
}

18 View Complete Implementation : TestBiomart.java
Copyright Apache License 2.0
Author : bridgedb
@Tag("webservice")
@Test
public void testBioMartConnector2() throws IOException, IDMapperException, ClreplacedNotFoundException {
    Clreplaced.forName("org.bridgedb.webservice.biomart.IDMapperBiomart");
    IDMapper mapper = BridgeDb.connect("idmapper-biomart:http://www.biomart.org/biomart/martservice?mart=ensembl&dataset=hsapiens_gene_ensembl");
    Set<DataSource> dest = mapper.getCapabilities().getSupportedTgtDataSources();
    replacedertTrue(dest.size() > 0);
    replacedertTrue(dest.contains(DataSource.getByFullName("entrezgene")));
    Set<DataSource> src = mapper.getCapabilities().getSupportedSrcDataSources();
    replacedertTrue(src.size() > 0);
    replacedertTrue(dest.contains(DataSource.getByFullName("entrezgene")));
}

18 View Complete Implementation : Test.java
Copyright Apache License 2.0
Author : PathVisio
public void testImportAffy() throws IOException, IDMapperException {
    ImportInformation info = new ImportInformation();
    File f = new File("example-data/sample_affymetrix.txt");
    replacedertTrue(f.exists());
    info.setTxtFile(f);
    info.guessSettings();
    replacedertEquals(info.getDataSource(), DataSource.getExistingBySystemCode("X"));
    replacedertTrue(info.isSyscodeFixed());
    replacedertTrue(info.digitIsDot());
    replacedertEquals(info.getIdColumn(), 0);
    String dbFileName = System.getProperty("java.io.tmpdir") + File.separator + "tempgex2";
    info.setGexName(dbFileName);
    info.setSyscodeFixed(true);
    info.setDataSource(DataSource.getExistingBySystemCode("X"));
    IDMapper gdb = BridgeDb.connect("idmapper-pgdb:" + GDB_RAT);
    GexTxtImporter.importFromTxt(info, null, gdb, gexManager);
    // just 6 errors if all goes well
    replacedertEquals(6, info.getErrorList().size());
}

18 View Complete Implementation : ZScoreTest.java
Copyright Apache License 2.0
Author : PathVisio
public clreplaced ZScoreTest extends TestCase {

    static final File PATHWAY_DIR = new File("testData/zscore/gpml");

    static final File DATASET_FILE = new File("testData/zscore/data/Myometrium_input.pgex");

    // TODO: replace this with web service
    static final File IDMAPPER_FILE = new File("testData/zscore/data/idmapper.bridge");

    static final String CRITERION = "[24hrs-v14 fold]  > 1.2";

    static final File TEST_PATHWAY = new File(PATHWAY_DIR, "testAlternative.gpml");

    GexManager gexMgr;

    IDMapper idMapper;

    @Override
    protected void setUp() throws Exception {
        PreferenceManager.init();
        DataSourceTxt.init();
        // Load the expression data
        gexMgr = new GexManager();
        gexMgr.setCurrentGex(DATASET_FILE.getAbsolutePath(), false);
        Clreplaced.forName("org.bridgedb.rdb.IDMapperRdb");
        idMapper = BridgeDb.connect("idmapper-pgdb:" + IDMAPPER_FILE.getAbsolutePath());
    }

    public void testAlternative() {
        try {
            Criterion crit = new Criterion();
            crit.setExpression(CRITERION, gexMgr.getCurrentGex().getSampleNames());
            ZScoreCalculator calc = new ZScoreCalculator(crit, PATHWAY_DIR, gexMgr.getCachedData(), idMapper, null);
            StatisticsResult result = calc.calculateAlternative();
            replacedertEquals("bigN doesn't equal number rows in data", gexMgr.getCurrentGex().getNrRow(), result.getBigN());
            // Check the pathway with known results
            StatisticsPathwayResult pathRes = null;
            for (StatisticsPathwayResult r : result.getPathwayResults()) {
                if (r.getFile().equals(TEST_PATHWAY)) {
                    pathRes = r;
                    break;
                }
            }
            result.getPathwayResults();
            int n = Integer.parseInt(pathRes.getProperty(Column.N));
            // 8 probes measured
            int nE = 9;
            int r = Integer.parseInt(pathRes.getProperty(Column.R));
            // 2 measured probes significant
            int rE = 2;
            replacedertEquals("expected n = " + nE + ", got n = " + n, nE, n);
            replacedertEquals("expected r = " + rE + ", got r = " + r, rE, r);
        } catch (Exception e) {
            e.printStackTrace();
            fail(e.getMessage());
        }
    }

    public void testMAPPFinder() {
        try {
            Criterion crit = new Criterion();
            crit.setExpression(CRITERION, gexMgr.getCurrentGex().getSampleNames());
            ZScoreCalculator calc = new ZScoreCalculator(crit, PATHWAY_DIR, gexMgr.getCachedData(), idMapper, null);
            StatisticsResult result = calc.calculateMappFinder();
            // Check the pathway with known results
            StatisticsPathwayResult pathRes = null;
            for (StatisticsPathwayResult r : result.getPathwayResults()) {
                if (r.getFile().equals(TEST_PATHWAY)) {
                    pathRes = r;
                    break;
                }
            }
            result.getPathwayResults();
            int n = Integer.parseInt(pathRes.getProperty(Column.N));
            // 5 genes measured
            int nE = 5;
            int r = Integer.parseInt(pathRes.getProperty(Column.R));
            // 2 measured genes significant
            int rE = 2;
            replacedertEquals("expected n = " + nE + ", got n = " + n, nE, n);
            replacedertEquals("expected r = " + rE + ", got r = " + r, rE, r);
        } catch (Exception e) {
            e.printStackTrace();
            fail(e.getMessage());
        }
    }
}

18 View Complete Implementation : IDMapperCapabilitiesTest.java
Copyright Apache License 2.0
Author : bridgedb
@BeforeAll
public static void setupIDMapper() throws IDMapperException, MalformedURLException {
    URL INTERFACE_TEST_FILE = IDMapperCapabilitiesTest.clreplaced.getResource("/interfaceTest.txt");
    replacedertNotNull("Can't find test-data/interfaceTest.txt", INTERFACE_TEST_FILE);
    IDMapper inner = new IDMapperText(INTERFACE_TEST_FILE);
    WSCoreInterface webService = new WSCoreService(inner);
    capabilities = new WSCoreMapper(webService);
}

18 View Complete Implementation : ExHello.java
Copyright Apache License 2.0
Author : bridgedb
public static void main(String[] args) throws ClreplacedNotFoundException, IDMapperException {
    // This example shows how to map an identifier
    // using BridgeWebservice
    // first we have to load the driver
    // and initialize information about DataSources
    Clreplaced.forName("org.bridgedb.webservice.bridgerest.BridgeRest");
    DataSourceTxt.init();
    // now we connect to the driver and create a IDMapper instance.
    IDMapper mapper = BridgeDb.connect("idmapper-bridgerest:http://webservice.bridgedb.org/Human");
    // We create an Xref instance for the identifier that we want to look up.
    // In this case we want to look up Entrez gene 3643.
    Xref src = new Xref("3643", BioDataSource.ENTREZ_GENE);
    // let's see if there are cross-references to Ensembl Human
    Set<Xref> dests = mapper.mapID(src, DataSource.getBySystemCode("EnHs"));
    // and print the results.
    // with getURN we obtain valid MIRIAM urn's if possible.
    System.out.println(src.getURN() + " maps to:");
    for (Xref dest : dests) System.out.println("  " + dest.getURN());
}

18 View Complete Implementation : ExampleWithBridgeDb.java
Copyright Apache License 2.0
Author : bridgedb
/*
	 * Connect to a mapping service.
	 * replacedume id is from the given source DataSource,
	 * and map that id to the given destination.  
	 */
private void domapping(String connectString, String id, DataSource src, DataSource dest) throws IDMapperException {
    // connect to the mapper.
    IDMapper mapper = BridgeDb.connect(connectString);
    Xref srcRef = new Xref(id, src);
    // map the source Xref and print the results, one per line
    for (Xref destRef : mapper.mapID(srcRef, dest)) {
        System.out.println("  " + destRef);
    }
}

18 View Complete Implementation : IDMapperTest.java
Copyright Apache License 2.0
Author : bridgedb
@BeforeAll
public static void setupIDMapper() throws IDMapperException, MalformedURLException {
    URL INTERFACE_TEST_FILE = IDMapperCapabilitiesTest.clreplaced.getResource("/interfaceTest.txt");
    replacedertNotNull("Can't find test-data/interfaceTest.txt", INTERFACE_TEST_FILE);
    IDMapper inner = new IDMapperText(INTERFACE_TEST_FILE);
    WSCoreInterface webService = new WSCoreService(inner);
    idMapper = new WSCoreMapper(webService);
    capabilities = idMapper.getCapabilities();
}

18 View Complete Implementation : Test.java
Copyright Apache License 2.0
Author : PathVisio
/**
 * Column headers have lenghts of over 50.
 * Make sure this doesn't lead to problems when setting sample names
 */
public void testImportLongHeaders() throws IOException, IDMapperException {
    ImportInformation info = new ImportInformation();
    File f = new File("example-data/sample_data_long_headers.txt");
    replacedertTrue(f.exists());
    info.setTxtFile(f);
    info.guessSettings();
    replacedertEquals(info.getDataSource(), DataSource.getExistingBySystemCode("L"));
    replacedertTrue(info.isSyscodeFixed());
    replacedertTrue(info.digitIsDot());
    replacedertEquals(0, info.getIdColumn());
    String dbFileName = System.getProperty("java.io.tmpdir") + File.separator + "tempgex3";
    info.setGexName(dbFileName);
    IDMapper gdb = BridgeDb.connect("idmapper-pgdb:" + GDB_HUMAN);
    GexTxtImporter.importFromTxt(info, null, gdb, gexManager);
    // 0 errors if all goes well
    replacedertEquals(0, info.getErrorList().size());
}

18 View Complete Implementation : Test.java
Copyright Apache License 2.0
Author : bridgedb
@org.junit.jupiter.api.Test
public void testLocalMapID() throws IDMapperException, ClreplacedNotFoundException {
    if (configExists) {
        IDMapper mapper = getLocalService();
        Xref insr = new Xref("3643", BioDataSource.ENTREZ_GENE);
        Xref affy = new Xref("33162_at", BioDataSource.AFFY);
        Set<Xref> result = mapper.mapID(insr);
        replacedertTrue(result.contains(affy));
        replacedertTrue(mapper.xrefExists(insr));
    }
}

18 View Complete Implementation : StatisticsResult.java
Copyright Apache License 2.0
Author : PathVisio
/**
 * Result of a statistics calculation on a whole Pathway set.
 * Can be saved to disk
 */
public clreplaced StatisticsResult {

    StatisticsTableModel stm;

    int bigN = 0;

    int bigR = 0;

    Criterion crit;

    File pwDir;

    CachedData gex;

    IDMapper gdb;

    String methodDesc;

    public void save(File f) throws IOException {
        PrintStream out = new PrintStream(new FileOutputStream(f));
        out.println("Statistics results for " + new Date());
        out.println("Dataset: " + gex.getDbName());
        out.println("Pathway directory: " + pwDir);
        out.println("Gene database: " + gdb);
        out.println("Criterion: " + crit.getExpression());
        out.println(methodDesc);
        out.println("Total data points (N): " + bigN);
        out.println("Data points meeting criterion (R): " + bigR);
        out.println();
        stm.printData(out);
    }

    /**
     * Get a list containing the statistics results per pathway.
     */
    public List<StatisticsPathwayResult> getPathwayResults() {
        List<StatisticsPathwayResult> results = new ArrayList<StatisticsPathwayResult>(stm.getRowCount());
        for (int i = 0; i < stm.getRowCount(); i++) {
            results.add(stm.getRow(i));
        }
        return results;
    }

    public int getBigN() {
        return bigN;
    }

    public int getBigR() {
        return bigR;
    }

    public Criterion getCriterion() {
        return crit;
    }

    public IDMapper getIDMapper() {
        return gdb;
    }

    public CachedData getGex() {
        return gex;
    }

    public File getPathwayDir() {
        return pwDir;
    }
}

18 View Complete Implementation : GdbManager.java
Copyright Apache License 2.0
Author : PathVisio
public void addMapper(String connectionString) throws IDMapperException {
    IDMapper mapper = BridgeDb.connect(connectionString);
    addMapper(mapper, connectionString);
}

18 View Complete Implementation : Test.java
Copyright Apache License 2.0
Author : PathVisio
public void testImportNoHeader() throws IOException, IDMapperException {
    ImportInformation info = new ImportInformation();
    File f = new File("example-data/sample_data_no_header.txt");
    replacedertTrue(f.exists());
    info.setTxtFile(f);
    info.setFirstDataRow(0);
    info.guessSettings();
    replacedertEquals(info.getDataSource(), DataSource.getExistingBySystemCode("L"));
    replacedertFalse(info.isSyscodeFixed());
    replacedertTrue(info.digitIsDot());
    replacedertEquals(0, info.getIdColumn());
    replacedertTrue(info.getNoHeader());
    replacedertEquals("Column A", info.getColNames()[0]);
    String dbFileName = System.getProperty("java.io.tmpdir") + File.separator + "tempgex5";
    info.setGexName(dbFileName);
    IDMapper gdb = BridgeDb.connect("idmapper-pgdb:" + GDB_HUMAN);
    GexTxtImporter.importFromTxt(info, null, gdb, gexManager);
    // 0 errors if all goes well
    replacedertEquals(0, info.getErrorList().size());
}

18 View Complete Implementation : Test.java
Copyright Apache License 2.0
Author : PathVisio
/**
 * Test dataset contains two columns with textual data
 * make sure this doesn't give problems during import
 */
public void testImportWithText() throws IOException, IDMapperException {
    ImportInformation info = new ImportInformation();
    File f = new File("example-data/sample_data_with_text.txt");
    replacedertTrue(f.exists());
    info.setTxtFile(f);
    info.guessSettings();
    replacedertEquals(info.getDataSource(), DataSource.getExistingBySystemCode("L"));
    replacedertFalse(info.isSyscodeFixed());
    replacedertEquals(info.getSyscodeColumn(), 1);
    replacedertTrue(info.digitIsDot());
    replacedertEquals(info.getIdColumn(), 0);
    String dbFileName = System.getProperty("java.io.tmpdir") + File.separator + "tempgex4";
    info.setGexName(dbFileName);
    IDMapper gdb = BridgeDb.connect("idmapper-pgdb:" + GDB_HUMAN);
    GexTxtImporter.importFromTxt(info, null, gdb, gexManager);
    // 0 errors if all goes well
    replacedertEquals(info.getErrorList().size(), 0);
}

18 View Complete Implementation : ExIDSearch.java
Copyright Apache License 2.0
Author : bridgedb
public static void main(String[] args) throws ClreplacedNotFoundException, IDMapperException {
    // This example shows how to do a free text search for an identifier
    // first we have to load the driver
    // and initialize information about DataSources
    Clreplaced.forName("org.bridgedb.webservice.bridgerest.BridgeRest");
    DataSourceTxt.init();
    // now we connect to the driver and create a IDMapper instance.
    IDMapper mapper = BridgeDb.connect("idmapper-bridgerest:http://webservice.bridgedb.org/Human");
    String query = "3643";
    // let's do a free search without specifying the input type:
    Set<Xref> hits = mapper.freeSearch(query, 100);
    // Now print the results.
    // with getURN we obtain valid MIRIAM urn's if possible.
    System.out.println(query + " search results:");
    for (Xref hit : hits) System.out.println("  " + hit.getURN());
}

18 View Complete Implementation : Test.java
Copyright Apache License 2.0
Author : PathVisio
public void testImportSimplyWrong() throws IOException, IDMapperException {
    ImportInformation info2 = new ImportInformation();
    File f = new File("example-data/sample_data_1.txt");
    replacedertTrue(f.exists());
    info2.setTxtFile(f);
    String dbFileName = System.getProperty("java.io.tmpdir") + File.separator + "tempgex3";
    info2.setGexName(dbFileName);
    IDMapper gdb = BridgeDb.connect("idmapper-pgdb:" + GDB_HUMAN);
    GexTxtImporter.importFromTxt(info2, null, gdb, gexManager);
    // 91 errors expected if no genes can be looked up.
    replacedertEquals(91, info2.getErrorList().size());
}

17 View Complete Implementation : CachedData.java
Copyright Apache License 2.0
Author : PathVisio
private Collection<? extends IRow> getDataForXref(Xref srcRef, IDMapper gdb, Set<DataSource> destFilter) throws IDMapperException, DataException {
    // get all cross-refs for this id
    Set<Xref> destRefs = new HashSet<Xref>();
    if (gdb.isConnected() && srcRef.getId() != null && srcRef.getDataSource() != null) {
        for (Xref destRef : gdb.mapID(srcRef)) {
            // add only the ones that are in the dest filter.
            if (destFilter.contains(destRef.getDataSource())) {
                destRefs.add(destRef);
            }
        }
    }
    // also the srcRef, in case we can't look up cross references
    if (destFilter.contains(srcRef.getDataSource())) {
        destRefs.add(srcRef);
    }
    if (destRefs.size() > 0) {
        return parent.getData(destRefs);
    } else
        return Collections.emptyList();
}

17 View Complete Implementation : ChebiPubchemExample.java
Copyright Apache License 2.0
Author : bridgedb
public static void main(String[] args) throws ClreplacedNotFoundException, IDMapperException {
    // We'll use the BridgeRest webservice in this case, as it does compound mapping fairly well.
    // We'll use the human database, but it doesn't really matter which species we pick.
    Clreplaced.forName("org.bridgedb.webservice.bridgerest.BridgeRest");
    IDMapper mapper = BridgeDb.connect("idmapper-bridgerest:http://webservice.bridgedb.org/Human");
    // Start with defining the Chebi identifier for
    // Methionine, id 16811
    Xref src = new Xref("16811", BioDataSource.CHEBI);
    // the method returns a set, but in actual fact there is only one result
    for (Xref dest : mapper.mapID(src, BioDataSource.PUBCHEM_COMPOUND)) {
        // this should print 6137, the pubchem identifier for Methionine.
        System.out.println("" + dest.getId());
    }
}

17 View Complete Implementation : InternalUtils.java
Copyright Apache License 2.0
Author : bridgedb
/**
 * call the "single" mapID (Xref, ...) multiple times
 * to perform mapping of a Set.
 * <p>
 * This is intended for IDMappers that don't gain any advantage of mapping
 * multiple ID's at a time. They can implement mapID(Xref, ...), and
 * use mapMultiFromSingle to simulate mapID(Set, ...)
 * @param mapper used for performing a single mapping
 * @param srcXrefs xrefs to translate
 * @param tgt DataSource(s) to map to, optional.
 * @return mappings with the translated result for each input Xref. Never returns null, but
 *    not each input is a key in the output map.
 * @throws IDMapperException when mapper.mapID throws IDMapperException
 */
public static Map<Xref, Set<Xref>> mapMultiFromSingle(IDMapper mapper, Collection<Xref> srcXrefs, DataSource... tgt) throws IDMapperException {
    final Map<Xref, Set<Xref>> result = new HashMap<Xref, Set<Xref>>();
    for (Xref src : srcXrefs) {
        final Set<Xref> refs = mapper.mapID(src, tgt);
        if (refs.size() > 0)
            result.put(src, refs);
    }
    return result;
}

17 View Complete Implementation : CreateRdf.java
Copyright Apache License 2.0
Author : bridgedb
/**
 * @author Christian
 */
public clreplaced CreateRdf {

    private IDMapper mapper;

    private String name;

    private BufferedWriter buffer;

    private String sourceUriSpace;

    private String targetUriSpace;

    private final String LINK_PREDICATE = "skos:relatedMatch";

    static final Logger logger = Logger.getLogger(CreateRdf.clreplaced);

    public static void main(String[] args) throws BridgeDBException, IOException, ClreplacedNotFoundException {
        ConfigReader.logToConsole();
        // Load DataSources from BioDataSource and save that
        DataSourceTxt.init();
        File biofile = new File("resources/BioDataSource.ttl");
        BridgeDBRdfHandler.writeRdfToFile(biofile);
        BridgeDBRdfHandler.parseRdfFile(biofile);
    }
}

17 View Complete Implementation : IsFreeSearchSupported.java
Copyright Apache License 2.0
Author : bridgedb
@Get
public String isFreeSearchSupported() {
    try {
        IDMapper mapper = getIDMappers();
        boolean isSupported = mapper.getCapabilities().isFreeSearchSupported();
        return "" + isSupported;
    } catch (Exception e) {
        e.printStackTrace();
        setStatus(Status.SERVER_ERROR_INTERNAL);
        return e.getMessage();
    }
}

17 View Complete Implementation : IsMappingSupported.java
Copyright Apache License 2.0
Author : bridgedb
@Get
public String isMappingSupported() {
    try {
        IDMapper m = getIDMappers();
        boolean supported = m.getCapabilities().isMappingSupported(srcDs, destDs);
        return "" + supported;
    } catch (Exception e) {
        e.printStackTrace();
        setStatus(Status.SERVER_ERROR_INTERNAL);
        return e.getMessage();
    }
}

17 View Complete Implementation : Properties.java
Copyright Apache License 2.0
Author : bridgedb
@Get
public String getPropertiesResult() {
    try {
        StringBuilder result = new StringBuilder();
        IDMapperStack stack = getIDMappers();
        for (int i = 0; i < stack.getSize(); ++i) {
            IDMapper mapper = stack.getIDMapperAt(i);
            for (String key : mapper.getCapabilities().getKeys()) {
                result.append(key);
                result.append("\t");
                result.append(mapper.getCapabilities().getProperty(key));
                result.append("\n");
            }
        }
        return result.toString();
    } catch (Exception e) {
        e.printStackTrace();
        setStatus(Status.SERVER_ERROR_INTERNAL);
        return e.getMessage();
    }
}

17 View Complete Implementation : SupportedSourceDataSources.java
Copyright Apache License 2.0
Author : bridgedb
@Get
public String getSupportedDataSourceResult() {
    try {
        StringBuilder result = new StringBuilder();
        IDMapper mapper = getIDMappers();
        for (DataSource ds : mapper.getCapabilities().getSupportedSrcDataSources()) {
            result.append(ds.getFullName());
            result.append("\n");
        }
        return result.toString();
    } catch (Exception e) {
        e.printStackTrace();
        setStatus(Status.SERVER_ERROR_INTERNAL);
        return e.getMessage();
    }
}

17 View Complete Implementation : SupportedTargetDataSources.java
Copyright Apache License 2.0
Author : bridgedb
@Get
public String getSupportedDataSourceResult() {
    try {
        StringBuilder result = new StringBuilder();
        IDMapper mapper = getIDMappers();
        for (DataSource ds : mapper.getCapabilities().getSupportedTgtDataSources()) {
            result.append(ds.getFullName());
            result.append("\n");
        }
        return result.toString();
    } catch (Exception e) {
        e.printStackTrace();
        setStatus(Status.SERVER_ERROR_INTERNAL);
        return e.getMessage();
    }
}

17 View Complete Implementation : XrefExists.java
Copyright Apache License 2.0
Author : bridgedb
@Get
public String isFreeSearchSupported() {
    try {
        IDMapper mapper = getIDMappers();
        return "" + mapper.xrefExists(xref);
    } catch (Exception e) {
        e.printStackTrace();
        setStatus(Status.SERVER_ERROR_INTERNAL);
        return e.getMessage();
    }
}

17 View Complete Implementation : TestBiomart.java
Copyright Apache License 2.0
Author : bridgedb
@Tag("webservice")
@Test
public void testBioMartMapping() throws IOException, IDMapperException, ClreplacedNotFoundException {
    Clreplaced.forName("org.bridgedb.webservice.biomart.IDMapperBiomart");
    IDMapper mapper = BridgeDb.connect("idmapper-biomart:http://www.biomart.org/biomart/martservice?mart=ensembl&dataset=hsapiens_gene_ensembl");
    Set<Xref> result = mapper.mapID(new Xref("ENSG00000171105", DataSource.getByFullName("ensembl_gene_id")), DataSource.getByFullName("entrezgene"));
    for (Xref ref : result) {
        System.out.println(ref);
    }
    replacedertTrue(result.contains(new Xref("3643", DataSource.getByFullName("entrezgene"))), "Expected entrezgene:3643. Got " + setRep(result));
}

17 View Complete Implementation : WSCoreService.java
Copyright Apache License 2.0
Author : bridgedb
/**
 * Webservice server code, that uses the ws.core
 * functionality to expose BridgeDB data
 * @author Christian Y. A. Brenninkmeijer
 */
@Path("/")
public clreplaced WSCoreService implements WSCoreInterface {

    static final String NO_CONTENT_ON_EMPTY = "no.content.on.empty";

    protected final boolean noContentOnEmpty;

    static final Logger logger = Logger.getLogger(WSCoreService.clreplaced);

    protected IDMapper idMapper;

    /**
     * Default constructor for super clreplacedes.
     *
     * Super clreplacedes will have the responsibilities of setting up the idMapper.
     */
    private WSCoreService() throws BridgeDBException {
        this(new SQLIdMapper(false, new SyscodeBasedCodeMapper()));
    }

    public WSCoreService(IDMapper idMapper) throws BridgeDBException {
        this.idMapper = idMapper;
        String property = ConfigReader.getProperty(NO_CONTENT_ON_EMPTY);
        noContentOnEmpty = Boolean.valueOf(property);
        logger.info("WS Service running using supplied idMapper");
    }

    private DataSourcesBean getSupportedSrcDataSourcesInner() throws BridgeDBException {
        IDMapperCapabilities capabilities = idMapper.getCapabilities();
        try {
            Set<DataSource> dataSources = capabilities.getSupportedSrcDataSources();
            return new DataSourcesBean(dataSources);
        } catch (IDMapperException e) {
            throw BridgeDBException.convertToBridgeDB(e);
        }
    }

    @GET
    @Produces({ MediaType.APPLICATION_XML })
    @Path("/" + WsConstants.GET_SUPPORTED_SOURCE_DATA_SOURCES)
    @Override
    public Response getSupportedSrcDataSources() throws BridgeDBException {
        DataSourcesBean bean = getSupportedSrcDataSourcesInner();
        if (noContentOnEmpty & bean.isEmpty()) {
            return Response.noContent().build();
        }
        return Response.ok(bean, MediaType.APPLICATION_XML_TYPE).build();
    }

    @GET
    @Produces({ MediaType.APPLICATION_JSON })
    @Path("/" + WsConstants.GET_SUPPORTED_SOURCE_DATA_SOURCES)
    public Response getSupportedSrcDataSourcesJson() throws BridgeDBException {
        DataSourcesBean bean = getSupportedSrcDataSourcesInner();
        if (noContentOnEmpty & bean.isEmpty()) {
            return Response.noContent().build();
        }
        return Response.ok(bean, MediaType.APPLICATION_JSON_TYPE).build();
    }

    @GET
    @Produces({ MediaType.TEXT_HTML })
    @Path("/" + WsConstants.GET_SUPPORTED_SOURCE_DATA_SOURCES)
    public Response getSupportedSrcDataSources(@Context HttpServletRequest httpServletRequest) throws BridgeDBException {
        DataSourcesBean bean = getSupportedSrcDataSourcesInner();
        if (noContentOnEmpty & bean.isEmpty()) {
            noContentWrapper(httpServletRequest);
        }
        return Response.ok(bean, MediaType.APPLICATION_XML_TYPE).build();
    }

    private XrefsBean freeSearchInner(String text, String limitString) throws BridgeDBException {
        if (text == null) {
            throw new BridgeDBException(WsConstants.TEXT + " parameter missing");
        }
        Set<Xref> mappings;
        try {
            if (limitString == null || limitString.isEmpty()) {
                mappings = idMapper.freeSearch(text, Integer.MAX_VALUE);
            } else {
                int limit = Integer.parseInt(limitString);
                mappings = idMapper.freeSearch(text, limit);
            }
        } catch (IDMapperException e) {
            throw BridgeDBException.convertToBridgeDB(e);
        }
        return new XrefsBean(mappings);
    }

    @GET
    @Produces({ MediaType.APPLICATION_XML })
    @Path("/" + WsConstants.FREE_SEARCH)
    @Override
    public Response freeSearch(@QueryParam(WsConstants.TEXT) String text, @QueryParam(WsConstants.LIMIT) String limitString) throws BridgeDBException {
        XrefsBean bean = freeSearchInner(text, limitString);
        if (noContentOnEmpty & bean.isEmpty()) {
            return Response.noContent().build();
        }
        return Response.ok(bean, MediaType.APPLICATION_XML_TYPE).build();
    }

    @GET
    @Produces({ MediaType.APPLICATION_JSON })
    @Path("/" + WsConstants.FREE_SEARCH)
    public Response freeSearchJson(@QueryParam(WsConstants.TEXT) String text, @QueryParam(WsConstants.LIMIT) String limitString) throws BridgeDBException {
        XrefsBean bean = freeSearchInner(text, limitString);
        if (noContentOnEmpty & bean.isEmpty()) {
            return Response.noContent().build();
        }
        return Response.ok(bean, MediaType.APPLICATION_JSON_TYPE).build();
    }

    @GET
    @Produces({ MediaType.TEXT_HTML })
    @Path("/" + WsConstants.FREE_SEARCH)
    public Response freeSearch(@QueryParam(WsConstants.TEXT) String text, @QueryParam(WsConstants.LIMIT) String limitString, @Context HttpServletRequest httpServletRequest) throws BridgeDBException {
        XrefsBean bean = freeSearchInner(text, limitString);
        if (noContentOnEmpty & bean.isEmpty()) {
            return noContentWrapper(httpServletRequest);
        }
        return Response.ok(bean, MediaType.APPLICATION_XML_TYPE).build();
    }

    private XrefMapsBean mapIDInner(List<String> id, List<String> scrCode, List<String> targetCodes) throws BridgeDBException {
        if (id == null) {
            throw new BridgeDBException(WsConstants.ID + " parameter missing");
        }
        if (id.isEmpty()) {
            throw new BridgeDBException(WsConstants.ID + " parameter missing");
        }
        if (scrCode == null) {
            throw new BridgeDBException(WsConstants.DATASOURCE_SYSTEM_CODE + " parameter missing");
        }
        if (scrCode.isEmpty()) {
            throw new BridgeDBException(WsConstants.DATASOURCE_SYSTEM_CODE + " parameter missing");
        }
        if (id.size() != scrCode.size()) {
            throw new BridgeDBException("Must have same number of " + WsConstants.ID + " and " + WsConstants.DATASOURCE_SYSTEM_CODE + " parameters");
        }
        ArrayList<Xref> srcXrefs = new ArrayList<Xref>();
        for (int i = 0; i < id.size(); i++) {
            try {
                DataSource dataSource = DataSource.getExistingBySystemCode(scrCode.get(i));
                Xref source = new Xref(id.get(i), dataSource);
                srcXrefs.add(source);
            } catch (IllegalArgumentException ex) {
                logger.error(ex.getMessage());
            }
        }
        DataSource[] targetDataSources = new DataSource[targetCodes.size()];
        for (int i = 0; i < targetCodes.size(); i++) {
            targetDataSources[i] = DataSource.getExistingBySystemCode(targetCodes.get(i));
        }
        try {
            Map<Xref, Set<Xref>> mappings = idMapper.mapID(srcXrefs, targetDataSources);
            return new XrefMapsBean(mappings);
        } catch (IDMapperException e) {
            throw BridgeDBException.convertToBridgeDB(e);
        }
    }

    @GET
    @Produces({ MediaType.APPLICATION_XML })
    @Path("/" + WsConstants.MAP_ID)
    @Override
    public Response mapID(@QueryParam(WsConstants.ID) List<String> id, @QueryParam(WsConstants.DATASOURCE_SYSTEM_CODE) List<String> scrCode, @QueryParam(WsConstants.TARGET_DATASOURCE_SYSTEM_CODE) List<String> targetCodes) throws BridgeDBException {
        XrefMapsBean bean = mapIDInner(id, scrCode, targetCodes);
        if (noContentOnEmpty & bean.isEmpty()) {
            return Response.noContent().build();
        }
        return Response.ok(bean, MediaType.APPLICATION_XML_TYPE).build();
    }

    @GET
    @Produces({ MediaType.APPLICATION_JSON })
    @Path("/" + WsConstants.MAP_ID)
    public Response mapIDJson(@QueryParam(WsConstants.ID) List<String> id, @QueryParam(WsConstants.DATASOURCE_SYSTEM_CODE) List<String> scrCode, @QueryParam(WsConstants.TARGET_DATASOURCE_SYSTEM_CODE) List<String> targetCodes) throws BridgeDBException {
        XrefMapsBean bean = mapIDInner(id, scrCode, targetCodes);
        if (noContentOnEmpty & bean.isEmpty()) {
            return Response.noContent().build();
        }
        return Response.ok(bean, MediaType.APPLICATION_JSON_TYPE).build();
    }

    @GET
    @Produces({ MediaType.TEXT_HTML })
    @Path("/" + WsConstants.MAP_ID)
    public Response mapID(@QueryParam(WsConstants.ID) List<String> id, @QueryParam(WsConstants.DATASOURCE_SYSTEM_CODE) List<String> scrCode, @QueryParam(WsConstants.TARGET_DATASOURCE_SYSTEM_CODE) List<String> targetCodes, @Context HttpServletRequest httpServletRequest) throws BridgeDBException {
        XrefMapsBean bean = mapIDInner(id, scrCode, targetCodes);
        if (noContentOnEmpty & bean.isEmpty()) {
            return noContentWrapper(httpServletRequest);
        }
        return Response.ok(bean, MediaType.APPLICATION_XML_TYPE).build();
    }

    private XrefExistsBean xrefExistsInner(String id, String scrCode) throws BridgeDBException {
        if (id == null) {
            throw new BridgeDBException(WsConstants.ID + " parameter can not be null");
        }
        if (scrCode == null) {
            throw new BridgeDBException(WsConstants.DATASOURCE_SYSTEM_CODE + " parameter can not be null");
        }
        DataSource dataSource;
        try {
            dataSource = DataSource.getExistingBySystemCode(scrCode);
        } catch (IllegalArgumentException ex) {
            logger.error(ex.getMessage());
            return new XrefExistsBean(id, scrCode, false);
        }
        Xref source = new Xref(id, dataSource);
        try {
            return new XrefExistsBean(source, idMapper.xrefExists(source));
        } catch (IDMapperException e) {
            throw BridgeDBException.convertToBridgeDB(e);
        }
    }

    @GET
    @Produces({ MediaType.APPLICATION_XML })
    @Path("/" + WsConstants.XREF_EXISTS)
    @Override
    public Response xrefExists(@QueryParam(WsConstants.ID) String id, @QueryParam(WsConstants.DATASOURCE_SYSTEM_CODE) String scrCode) throws BridgeDBException {
        XrefExistsBean bean = xrefExistsInner(id, scrCode);
        return Response.ok(bean, MediaType.APPLICATION_XML_TYPE).build();
    }

    @GET
    @Produces({ MediaType.APPLICATION_JSON })
    @Path("/" + WsConstants.XREF_EXISTS)
    public Response xrefExistsJson(@QueryParam(WsConstants.ID) String id, @QueryParam(WsConstants.DATASOURCE_SYSTEM_CODE) String scrCode) throws BridgeDBException {
        XrefExistsBean bean = xrefExistsInner(id, scrCode);
        return Response.ok(bean, MediaType.APPLICATION_JSON_TYPE).build();
    }

    private DataSourcesBean getSupportedTgtDataSourcesInner() throws BridgeDBException {
        try {
            Set<DataSource> dataSources = idMapper.getCapabilities().getSupportedSrcDataSources();
            return new DataSourcesBean(dataSources);
        } catch (IDMapperException e) {
            throw BridgeDBException.convertToBridgeDB(e);
        }
    }

    @GET
    @Produces({ MediaType.APPLICATION_XML })
    @Path("/" + WsConstants.GET_SUPPORTED_TARGET_DATA_SOURCES)
    @Override
    public Response getSupportedTgtDataSources() throws BridgeDBException {
        DataSourcesBean bean = getSupportedTgtDataSourcesInner();
        if (noContentOnEmpty & bean.isEmpty()) {
            return Response.noContent().build();
        }
        return Response.ok(bean, MediaType.APPLICATION_XML_TYPE).build();
    }

    @GET
    @Produces({ MediaType.APPLICATION_JSON })
    @Path("/" + WsConstants.GET_SUPPORTED_TARGET_DATA_SOURCES)
    public Response getSupportedTgtDataSourcesJson() throws BridgeDBException {
        DataSourcesBean bean = getSupportedTgtDataSourcesInner();
        if (noContentOnEmpty & bean.isEmpty()) {
            return Response.noContent().build();
        }
        return Response.ok(bean, MediaType.APPLICATION_JSON_TYPE).build();
    }

    @GET
    @Produces({ MediaType.TEXT_HTML })
    @Path("/" + WsConstants.GET_SUPPORTED_TARGET_DATA_SOURCES)
    public Response getSupportedTgtDataSources(@Context HttpServletRequest httpServletRequest) throws BridgeDBException {
        DataSourcesBean bean = getSupportedTgtDataSourcesInner();
        if (noContentOnEmpty & bean.isEmpty()) {
            return noContentWrapper(httpServletRequest);
        }
        return Response.ok(bean, MediaType.APPLICATION_XML_TYPE).build();
    }

    @GET
    @Produces({ MediaType.APPLICATION_XML })
    @Path(WsConstants.IS_FREE_SEARCH_SUPPORTED)
    @Override
    public Response isFreeSearchSupported() {
        FreeSearchSupportedBean bean = new FreeSearchSupportedBean(idMapper.getCapabilities().isFreeSearchSupported());
        // FreeSearchSupported is never empty so never no context
        return Response.ok(bean, MediaType.APPLICATION_XML_TYPE).build();
    }

    @GET
    @Produces({ MediaType.APPLICATION_JSON })
    @Path(WsConstants.IS_FREE_SEARCH_SUPPORTED)
    public Response isFreeSearchSupportedJson() {
        FreeSearchSupportedBean bean = new FreeSearchSupportedBean(idMapper.getCapabilities().isFreeSearchSupported());
        // FreeSearchSupported is never empty so never no context
        return Response.ok(bean, MediaType.APPLICATION_JSON_TYPE).build();
    }

    private MappingSupportedBean isMappingSupportedInner(String sourceCode, String targetCode) throws BridgeDBException {
        if (sourceCode == null) {
            throw new BridgeDBException(WsConstants.SOURCE_DATASOURCE_SYSTEM_CODE + " parameter can not be null");
        }
        if (targetCode == null) {
            throw new BridgeDBException(WsConstants.TARGET_DATASOURCE_SYSTEM_CODE + " parameter can not be null");
        }
        DataSource src = DataSource.getExistingBySystemCode(sourceCode);
        DataSource tgt = DataSource.getExistingBySystemCode(targetCode);
        try {
            return new MappingSupportedBean(src, tgt, idMapper.getCapabilities().isMappingSupported(src, tgt));
        } catch (IDMapperException e) {
            throw BridgeDBException.convertToBridgeDB(e);
        }
    }

    @GET
    @Produces({ MediaType.APPLICATION_XML })
    @Path("/" + WsConstants.IS_MAPPING_SUPPORTED)
    @Override
    public Response isMappingSupported(@QueryParam(WsConstants.SOURCE_DATASOURCE_SYSTEM_CODE) String sourceCode, @QueryParam(WsConstants.TARGET_DATASOURCE_SYSTEM_CODE) String targetCode) throws BridgeDBException {
        MappingSupportedBean bean = isMappingSupportedInner(sourceCode, targetCode);
        // MappingSupported is never empty so never no content
        return Response.ok(bean, MediaType.APPLICATION_XML_TYPE).build();
    }

    @GET
    @Produces({ MediaType.APPLICATION_XML })
    @Path("/" + WsConstants.IS_MAPPING_SUPPORTED)
    public Response isMappingSupportedJson(@QueryParam(WsConstants.SOURCE_DATASOURCE_SYSTEM_CODE) String sourceCode, @QueryParam(WsConstants.TARGET_DATASOURCE_SYSTEM_CODE) String targetCode) throws BridgeDBException {
        MappingSupportedBean bean = isMappingSupportedInner(sourceCode, targetCode);
        // MappingSupported is never empty so never no content
        return Response.ok(bean, MediaType.APPLICATION_JSON_TYPE).build();
    }

    private PropertyBean getPropertyInner(String key) {
        String property = idMapper.getCapabilities().getProperty(key);
        return new PropertyBean(key, property);
    }

    @GET
    @Produces({ MediaType.APPLICATION_XML })
    @Path("/" + WsConstants.PROPERTY + "/{key}")
    @Override
    public Response getProperty(@PathParam("key") String key) {
        PropertyBean bean = getPropertyInner(key);
        if (noContentOnEmpty & bean.isEmpty()) {
            return Response.noContent().build();
        }
        return Response.ok(bean, MediaType.APPLICATION_XML_TYPE).build();
    }

    @GET
    @Produces({ MediaType.APPLICATION_JSON })
    @Path("/" + WsConstants.PROPERTY + "/{key}")
    public Response getPropertyJson(@PathParam("key") String key) {
        PropertyBean bean = getPropertyInner(key);
        if (noContentOnEmpty & bean.isEmpty()) {
            return Response.noContent().build();
        }
        return Response.ok(bean, MediaType.APPLICATION_JSON_TYPE).build();
    }

    @GET
    @Produces({ MediaType.APPLICATION_XML })
    @Path("/" + WsConstants.PROPERTY + "/{key}")
    public Response getProperty(@PathParam("key") String key, @Context HttpServletRequest httpServletRequest) throws BridgeDBException {
        PropertyBean bean = getPropertyInner(key);
        if (noContentOnEmpty & bean.isEmpty()) {
            return noContentWrapper(httpServletRequest);
        }
        return Response.ok(bean, MediaType.APPLICATION_XML_TYPE).build();
    }

    private PropertiesBean getKeysInner() {
        PropertiesBean bean = new PropertiesBean();
        Set<String> keys = idMapper.getCapabilities().getKeys();
        IDMapperCapabilities idMapperCapabilities = idMapper.getCapabilities();
        for (String key : keys) {
            bean.addProperty(key, idMapperCapabilities.getProperty(key));
        }
        return bean;
    }

    @GET
    @Produces({ MediaType.APPLICATION_XML })
    @Path("/" + WsConstants.GET_KEYS)
    @Override
    public Response getKeys() {
        PropertiesBean bean = getKeysInner();
        if (noContentOnEmpty & bean.isEmpty()) {
            return Response.noContent().build();
        }
        return Response.ok(bean, MediaType.APPLICATION_XML_TYPE).build();
    }

    @GET
    @Produces({ MediaType.APPLICATION_JSON })
    @Path("/" + WsConstants.GET_KEYS)
    public Response getKeysJson() {
        PropertiesBean bean = getKeysInner();
        if (noContentOnEmpty & bean.isEmpty()) {
            return Response.noContent().build();
        }
        return Response.ok(bean, MediaType.APPLICATION_JSON_TYPE).build();
    }

    @GET
    @Produces({ MediaType.TEXT_HTML })
    @Path("/" + WsConstants.GET_KEYS)
    public Response getKeys(@Context HttpServletRequest httpServletRequest) throws BridgeDBException {
        PropertiesBean bean = getKeysInner();
        if (noContentOnEmpty & bean.isEmpty()) {
            return noContentWrapper(httpServletRequest);
        }
        return Response.ok(bean, MediaType.APPLICATION_XML_TYPE).build();
    }

    @GET
    @Produces({ MediaType.APPLICATION_XML })
    @Path("/" + WsConstants.GET_CAPABILITIES)
    @Override
    public Response getCapabilities() {
        CapabilitiesBean bean = new CapabilitiesBean(idMapper.getCapabilities());
        return Response.ok(bean, MediaType.APPLICATION_XML_TYPE).build();
    }

    @GET
    @Produces({ MediaType.APPLICATION_JSON })
    @Path("/" + WsConstants.GET_CAPABILITIES)
    public Response getCapabilitiesJson() {
        CapabilitiesBean bean = new CapabilitiesBean(idMapper.getCapabilities());
        return Response.ok(bean, MediaType.APPLICATION_JSON_TYPE).build();
    }

    /**
     * Simple warning that no Context was found.
     *
     * Can be overwritten with nicer page
     * @param httpServletRequest Used by super clreplacedes
     * @return
     * @throws BridgeDBException thrown by super clreplacedes
     */
    protected Response noContentWrapper(HttpServletRequest httpServletRequest) {
        StringBuilder sb = new StringBuilder();
        sb.append("<?xml version=\"1.0\"?>");
        sb.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" ");
        sb.append("\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
        sb.append("<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\">");
        sb.append("<meta http-equiv=\"content-type\" content=\"text/html; charset=ISO-8859-1\"/>");
        sb.append("<head>\n");
        sb.append("<replacedle>No Results found</replacedle>\n");
        sb.append("</head>\n<body>\n");
        sb.append("<h1>Sorry no results found!</h1>\n");
        sb.append("<h2>The parameters provided resulted in an empty set.</h2>\n");
        sb.append("<h3>No exception was thrown so the parameters where valid just too restrictive.</h3>\n");
        sb.append("<h2>XML and json version return status 204 in this case</h2>\n");
        sb.append("</body></html>");
        return Response.ok(sb.toString(), MediaType.TEXT_HTML).build();
    }
}

17 View Complete Implementation : GdbManager.java
Copyright Apache License 2.0
Author : PathVisio
/**
 * GdbManager is responsible for maintaining a single
 * static Gene database for use in the GUI application
 *
 * This gene database could be a SimpleGdb,
 * DoubleGdb or aggregateGdb or otherwise.
 *
 * This clreplaced is not needed in headless mode.
 */
public clreplaced GdbManager extends AbstractListModel {

    private final IDMapperStack currentGdb = new IDMapperStack();

    private IDMapper metabolites;

    private IDMapper genes;

    private IDMapper interactions;

    private Map<IDMapper, String> connectionStrings = new HashMap<IDMapper, String>();

    public GdbManager() {
        try {
            Clreplaced.forName("org.bridgedb.file.IDMapperText");
            Clreplaced.forName("org.bridgedb.rdb.IDMapperRdb");
        } catch (ClreplacedNotFoundException ex) {
            Logger.log.error("Could not initilize GDB Manager", ex);
        // TODO: propagate exception???
        }
        currentGdb.setTransitive(true);
    }

    public IDMapperStack getCurrentGdb() {
        return currentGdb;
    }

    /**
     * Returns true if the current Gdb isConnected()
     */
    public boolean isConnected() {
        return currentGdb.isConnected();
    }

    /**
     * Set the global gene database
     * with the given file- or
     * directory name.
     * The database type used for the connection
     * depends on the value of the DB_ENGINE_GDB value
     *
     * use null to disconnect the current db.
     */
    public void setGeneDb(String connectString) throws IDMapperException {
        removeMapper(genes);
        genes = null;
        if (connectString != null) {
            genes = BridgeDb.connect(connectString);
            if (genes != null) {
                PreferenceManager.getCurrent().set(GlobalPreference.DB_CONNECTSTRING_GDB, (connectString));
                addMapper(genes, connectString);
            }
        }
    }

    /**
     * Set the global metabolite database
     * with the given file- or
     * directory name.
     * The database type used for the connection
     * depends on the value of the DB_ENGINE_GDB value
     *
     * use null to disconnect the current db
     */
    public void setMetaboliteDb(String connectString) throws IDMapperException {
        removeMapper(metabolites);
        metabolites = null;
        if (connectString != null) {
            metabolites = BridgeDb.connect(connectString);
            if (metabolites != null) {
                PreferenceManager.getCurrent().set(GlobalPreference.DB_CONNECTSTRING_METADB, (connectString));
                addMapper(metabolites, connectString);
            }
        }
    }

    /**
     * Set the global interaction database
     * with the given file- or
     * directory name.
     * The database type used for the connection
     * depends on the value of the DB_ENGINE_GDB value
     *
     * use null to disconnect the current db
     *
     * @author anwesha
     */
    public void setInteractionDb(String connectString) throws IDMapperException {
        removeMapper(interactions);
        interactions = null;
        if (connectString != null) {
            interactions = BridgeDb.connect(connectString);
            if (interactions != null) {
                PreferenceManager.getCurrent().set(GlobalPreference.DB_CONNECTSTRING_IDB, (connectString));
                addMapper(interactions, connectString);
            }
        }
    }

    public void addMapper(String connectionString) throws IDMapperException {
        IDMapper mapper = BridgeDb.connect(connectionString);
        addMapper(mapper, connectionString);
    }

    public void addMapper(IDMapper mapper, String connectionString) throws IDMapperException {
        if (mapper == null)
            throw new NullPointerException();
        currentGdb.addIDMapper(mapper);
        connectionStrings.put(mapper, connectionString);
        GdbEvent e = new GdbEvent(this, GdbEvent.Type.ADDED, mapper.toString());
        fireGdbEvent(e);
        Logger.log.trace("Added database: " + mapper.toString());
    }

    public void removeMapper(IDMapper mapper) throws IDMapperException {
        // ignore
        if (mapper == null)
            return;
        currentGdb.removeIDMapper(mapper);
        connectionStrings.remove(mapper);
        if (mapper == metabolites)
            metabolites = null;
        if (mapper == interactions)
            interactions = null;
        if (mapper == genes)
            genes = null;
        GdbEvent e = new GdbEvent(this, GdbEvent.Type.REMOVED, mapper.toString());
        fireGdbEvent(e);
        mapper.close();
    }

    /**
     * Implement this interface if you want to listen to Gdb Events.
     */
    public interface GdbEventListener {

        public void gdbEvent(GdbEvent e);
    }

    /**
     * Use this method if you want to respond to the connection of Gdb databases
     */
    public void addGdbEventListener(GdbEventListener l) {
        if (l == null)
            throw new NullPointerException();
        gdbEventListeners.add(l);
    }

    public void removeGdbEventListener(GdbEventListener l) {
        gdbEventListeners.remove(l);
    }

    private void fireGdbEvent(GdbEvent e) {
        for (GdbEventListener l : gdbEventListeners) l.gdbEvent(e);
        // also notify ListModel listeners
        this.fireContentsChanged(this, 0, currentGdb.getSize());
    }

    private List<GdbEventListener> gdbEventListeners = new ArrayList<GdbEventListener>();

    /**
     * Initiates this clreplaced. Checks the preferences for a previously
     * used Gene Database and tries to open a connection if found.
     * If that doesn't work, reverts attempts to use the default value for
     * that property.
     *
     * Idem for the metabolite database.
     * TODO: move to src/swing (only used standalone)
     */
    public void initPreferred() {
        PreferenceManager prefs = PreferenceManager.getCurrent();
        // first do the Gene database
        String gdbName = prefs.get(GlobalPreference.DB_CONNECTSTRING_GDB);
        if (!gdbName.equals("") && !prefs.isDefault(GlobalPreference.DB_CONNECTSTRING_GDB)) {
            try {
                setGeneDb(gdbName);
            } catch (IDMapperException e) {
                Logger.log.error("Setting previous Gdb failed.", e);
            }
        }
        // then do the Metabolite database
        gdbName = prefs.get(GlobalPreference.DB_CONNECTSTRING_METADB);
        if (!gdbName.equals("") && !prefs.isDefault(GlobalPreference.DB_CONNECTSTRING_METADB)) {
            try {
                setMetaboliteDb(gdbName);
            } catch (Exception e) {
                Logger.log.error("Setting previous Metabolite db failed.", e);
            }
        }
        /**
         *  then do the Interaction database
         * @author anwesha
         */
        gdbName = prefs.get(GlobalPreference.DB_CONNECTSTRING_IDB);
        if (!gdbName.equals("") && !prefs.isDefault(GlobalPreference.DB_CONNECTSTRING_IDB)) {
            try {
                setInteractionDb(gdbName);
            } catch (Exception e) {
                Logger.log.error("Setting previous Interaction db failed.", e);
            }
        }
    }

    public Object getElementAt(int arg0) {
        return currentGdb.getIDMapperAt(arg0);
    }

    public String getConnectionStringAt(int arg0) {
        return connectionStrings.get(currentGdb.getIDMapperAt(arg0));
    }

    public int getSize() {
        return currentGdb.getSize();
    }

    public IDMapper getGeneDb() {
        return genes;
    }

    public IDMapper getMetaboliteDb() {
        return metabolites;
    }

    public IDMapper getInteractionDb() {
        return interactions;
    }
}

16 View Complete Implementation : GdbProvider.java
Copyright Apache License 2.0
Author : bridgedb
public void addGlobalGdb(IDMapper gdb) {
    if (!globalGdbs.contains(gdb)) {
        globalGdbs.add(gdb);
        for (Organism org : organism2gdb.keySet()) {
            organism2gdb.get(org).addIDMapper(gdb);
        }
    }
}

16 View Complete Implementation : Test2.java
Copyright Apache License 2.0
Author : bridgedb
/**
 * Tests the capability properties of a Schema v3 database.
 * @throws IDMapperException should be considered a failed test
 */
@Disabled
public void testGdbProperties() throws IDMapperException {
    IDMapper gdb = BridgeDb.connect("idmapper-pgdb:" + GDB_CE_V3);
    for (String key : gdb.getCapabilities().getKeys()) {
        System.out.println(key + " -> " + gdb.getCapabilities().getProperty(key));
    }
    replacedertEquals("Caenorhabditis elegans", gdb.getCapabilities().getProperty("SPECIES"));
    replacedertEquals("3", gdb.getCapabilities().getProperty("SCHEMAVERSION"));
    replacedertEquals("Ensembl", gdb.getCapabilities().getProperty("DATASOURCENAME"));
    replacedertEquals("20090720", gdb.getCapabilities().getProperty("BUILDDATE"));
    IDMapper gdb2 = BridgeDb.connect("idmapper-pgdb:" + GDB_HUMAN);
    for (String key : gdb2.getCapabilities().getKeys()) {
        System.out.println(key + " -> " + gdb2.getCapabilities().getProperty(key));
    }
    replacedertEquals("2", gdb2.getCapabilities().getProperty("SCHEMAVERSION"));
    replacedertEquals("20081119", gdb2.getCapabilities().getProperty("BUILDDATE"));
}

16 View Complete Implementation : FreeSearch.java
Copyright Apache License 2.0
Author : bridgedb
@Get
public String search() {
    try {
        IDMapper mapper = getIDMappers();
        Set<Xref> results = mapper.freeSearch(searchStr, limit);
        StringBuilder result = new StringBuilder();
        for (Xref x : results) {
            result.append(x.getId());
            result.append("\t");
            result.append(x.getDataSource().getFullName());
            result.append("\n");
        }
        return (result.toString());
    } catch (Exception e) {
        e.printStackTrace();
        setStatus(Status.SERVER_ERROR_INTERNAL);
        return e.getMessage();
    }
}

16 View Complete Implementation : Xrefs.java
Copyright Apache License 2.0
Author : bridgedb
@Get
public String getXrefs() {
    System.out.println("Xrefs.getXrefs() start");
    try {
        // The result set
        IDMapper mapper = getIDMappers();
        Set<Xref> xrefs;
        if (targetDs == null)
            xrefs = mapper.mapID(xref);
        else
            xrefs = mapper.mapID(xref, targetDs);
        StringBuilder result = new StringBuilder();
        for (Xref x : xrefs) {
            result.append(x.getId());
            result.append("\t");
            result.append(x.getDataSource().getFullName());
            result.append("\n");
        }
        return result.toString();
    } catch (Exception e) {
        e.printStackTrace();
        setStatus(Status.SERVER_ERROR_INTERNAL);
        return e.getMessage();
    }
}

16 View Complete Implementation : GdbManager.java
Copyright Apache License 2.0
Author : PathVisio
public void addMapper(IDMapper mapper, String connectionString) throws IDMapperException {
    if (mapper == null)
        throw new NullPointerException();
    currentGdb.addIDMapper(mapper);
    connectionStrings.put(mapper, connectionString);
    GdbEvent e = new GdbEvent(this, GdbEvent.Type.ADDED, mapper.toString());
    fireGdbEvent(e);
    Logger.log.trace("Added database: " + mapper.toString());
}

16 View Complete Implementation : GdbManager.java
Copyright Apache License 2.0
Author : PathVisio
public void removeMapper(IDMapper mapper) throws IDMapperException {
    // ignore
    if (mapper == null)
        return;
    currentGdb.removeIDMapper(mapper);
    connectionStrings.remove(mapper);
    if (mapper == metabolites)
        metabolites = null;
    if (mapper == interactions)
        interactions = null;
    if (mapper == genes)
        genes = null;
    GdbEvent e = new GdbEvent(this, GdbEvent.Type.REMOVED, mapper.toString());
    fireGdbEvent(e);
    mapper.close();
}

16 View Complete Implementation : CachedData.java
Copyright Apache License 2.0
Author : PathVisio
/**
 * This clreplaced represents cached expression data for a pathway.
 * The caching of expression data will occur when a pathway is opened and an expression dataset is loaded.
 * The cache will be refreshed when another dataset is selected, another gene database is selected or another
 * pathway is opened.
 * A CachedData object will contain a list of {@link ReporterData} object for every gene-product on the pathway for
 * which data is available in the expression dataset
 */
public clreplaced CachedData {

    // Data objects for gene-products on the pathway
    private final ConcurrentHashMap<Xref, List<IRow>> data = new ConcurrentHashMap<Xref, List<IRow>>();

    private final Executor executor;

    private final DataInterface parent;

    /**
     * Do not instantiate in the PathVisio environment!
     * Use GexManager.getCachedData() instead.
     * Or you'll end up with multiple caches.
     */
    public CachedData(DataInterface parent) {
        this.parent = parent;
        executor = Executors.newSingleThreadExecutor();
    }

    /**
     * Check whether the cached data contains data for the given gene-product
     * @param pwId The IdCodePair that represents the gene-product
     * @return true if data is available for the gene-product, false if not
     */
    public boolean hasData(Xref pwId) {
        return data.containsKey(pwId);
    }

    /**
     * Get the cached data the given gene-product. If there was nothing in cache
     * it returns 0. Should be used only in combination with asyncGet.
     * @param idc The Xref for which the data has to be returned
     * @return a list of {@link ReporterData} object containing the cached data, or null when no data is available
     */
    public List<? extends IRow> getData(Xref idc) {
        return data.get(idc);
    }

    public interface Callback {

        public void callback();
    }

    private volatile int tasks = 0;

    // called from two different threads
    @ThreadSafe
    private void updateTasks(int delta) {
        int oldtasks = tasks;
        tasks += delta;
        if (oldtasks == 0 || tasks == 0) {
            Logger.log.info("CACHE: " + (tasks == 0 ? "STOPPED" : "STARTED"));
        }
    }

    // set of data sources that occur in SimpleGex.
    private Set<DataSource> destFilterCache = null;

    @WorkerThreadOnly
    public List<? extends IRow> syncGet(Xref ref) throws IDMapperException, DataException {
        if (destFilterCache == null) {
            destFilterCache = parent.getUsedDatasources();
        }
        List<IRow> result;
        if (!data.containsKey(ref)) {
            // get results and sort them
            result = new ArrayList<IRow>();
            Collection<? extends IRow> collection = getDataForXref(ref, mapper, destFilterCache);
            if (collection != null)
                result.addAll(collection);
            Collections.sort(result);
            data.put(ref, result);
        } else {
            result = data.get(ref);
        }
        return result;
    }

    public void asyncGet(final Xref ref, final Callback callback) {
        updateTasks(+1);
        executor.execute(new Runnable() {

            public void run() {
                try {
                    syncGet(ref);
                } catch (IDMapperException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (DataException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                updateTasks(-1);
                SwingUtilities.invokeLater(new Runnable() {

                    public void run() {
                        callback.callback();
                    }
                });
            }
        });
    }

    private Collection<? extends IRow> getDataForXref(Xref srcRef, IDMapper gdb, Set<DataSource> destFilter) throws IDMapperException, DataException {
        // get all cross-refs for this id
        Set<Xref> destRefs = new HashSet<Xref>();
        if (gdb.isConnected() && srcRef.getId() != null && srcRef.getDataSource() != null) {
            for (Xref destRef : gdb.mapID(srcRef)) {
                // add only the ones that are in the dest filter.
                if (destFilter.contains(destRef.getDataSource())) {
                    destRefs.add(destRef);
                }
            }
        }
        // also the srcRef, in case we can't look up cross references
        if (destFilter.contains(srcRef.getDataSource())) {
            destRefs.add(srcRef);
        }
        if (destRefs.size() > 0) {
            return parent.getData(destRefs);
        } else
            return Collections.emptyList();
    }

    private IDMapper mapper = null;

    /**
     * Set the mapper that is used for ID Mapping. Clears cache if necessary.
     * TODO In the future I want to set this in the constructor, and
     * make mapper final.
     */
    public void setMapper(IDMapper mapper) {
        if (this.mapper != mapper) {
            this.mapper = mapper;
            clearCache();
        }
    }

    /**
     * Starts loading expression data for all the given gene ids into memory
     * @param srcRefs Xrefs to cache the expression data for
     * 	(typically all genes and metabolites in a pathway)
     */
    public void preSeed(Collection<Xref> srcRefs) throws DataException {
        // seed samples cache
        parent.getSamples();
    // TODO preseed cache with srcRefs in background.
    // somehow with lower priority than the ones for visualization
    }

    @WorkerThreadOnly
    public /**
     * Load expression data for given Xrefs into cache.
     * Waits until the process is done.
     */
    void syncSeed(Collection<Xref> srcRefs) throws DataException, IDMapperException {
        // seed samples cache
        parent.getSamples();
        for (Xref ref : srcRefs) {
            syncGet(ref);
        }
    }

    public void clearCache() {
        data.clear();
    }

    public String getDbName() {
        return parent.getDbName();
    }

    /**
     * @deprecated use gereplacederator() instead
     */
    public int getNrRow() throws DataException {
        return parent.getNrRow();
    }

    /**
     * @deprecated use gereplacederator() instead
     */
    public IRow getRow(int i) throws DataException {
        return parent.getRow(i);
    }

    public Iterable<IRow> gereplacederator() throws DataException {
        return parent.gereplacederator();
    }

    public boolean isConnected() {
        return parent.isConnected();
    }

    List<? extends ISample> getOrderedSamples() throws DataException {
        return parent.getOrderedSamples();
    }

    public void dispose() {
        ((ExecutorService) executor).shutdown();
    }
}

15 View Complete Implementation : InternalUtils.java
Copyright Apache License 2.0
Author : bridgedb
/**
 * call the "multi" mapID (Set, ...) using a Set with one item
 * to perform mapping of a single ID.
 * <p>
 * This is intended for IDMappers that have a performance advantage of mapping
 * multiple ID's at a time. They can implement mapID(Set, ...), and
 * use mapSingleFromMulti to simulate mapID(Xref, ...)
 * @param mapper used for performing a multi-mapping
 * @param src xref to translate
 * @param tgt DataSource(s) to map to, optional.
 * @return Set of translated Xrefs, or an empty set if none were found.
 * @throws IDMapperException when mapper.mapID throws IDMapperException
 */
public static Set<Xref> mapSingleFromMulti(IDMapper mapper, Xref src, DataSource... tgt) throws IDMapperException {
    Set<Xref> srcXrefs = new HashSet<Xref>();
    srcXrefs.add(src);
    Map<Xref, Set<Xref>> mapXrefs = mapper.mapID(srcXrefs, tgt);
    if (mapXrefs.containsKey(src))
        return mapXrefs.get(src);
    else
        return Collections.emptySet();
}

15 View Complete Implementation : GdbProvider.java
Copyright Apache License 2.0
Author : bridgedb
public IDMapperStack getStack(Organism organism) {
    IDMapperStack gdbs = organism2gdb.get(organism);
    if (gdbs == null) {
        gdbs = new IDMapperStack();
        gdbs.setTransitive(transitive);
        for (IDMapper globalGdb : globalGdbs) {
            gdbs.addIDMapper(globalGdb);
        }
    }
    return gdbs;
}

15 View Complete Implementation : GdbProvider.java
Copyright Apache License 2.0
Author : bridgedb
public void removeGlobalGdb(IDMapper gdb) {
    if (globalGdbs.contains(gdb)) {
        globalGdbs.remove(gdb);
        for (Organism org : organism2gdb.keySet()) {
            organism2gdb.get(org).removeIDMapper(gdb);
        }
    }
}

15 View Complete Implementation : Test2.java
Copyright Apache License 2.0
Author : bridgedb
@Disabled
public void testGdbConnect() throws IDMapperException {
    // if gdb can't be found, rest of test doesn't make sense.
    replacedertTrue(new File(GDB_HUMAN).exists());
    long start, end, delta;
    start = System.currentTimeMillis();
    IDMapper gdb = BridgeDb.connect("idmapper-pgdb:" + GDB_HUMAN);
    end = System.currentTimeMillis();
    delta = end - start;
    measure.add("timing::idmapper-pgdb connect to database", "" + delta, "msec");
    gdb.close();
}

14 View Complete Implementation : GdbProvider.java
Copyright Apache License 2.0
Author : bridgedb
public void addOrganismGdb(Organism organism, IDMapper gdb) {
    IDMapperStack l = organism2gdb.get(organism);
    if (l == null) {
        organism2gdb.put(organism, l = new IDMapperStack());
        l.setTransitive(transitive);
        for (IDMapper globalGdb : globalGdbs) {
            l.addIDMapper(globalGdb);
        }
    }
    l.addIDMapper(gdb);
}

14 View Complete Implementation : TestStack.java
Copyright Apache License 2.0
Author : bridgedb
public void testPgdb() throws IDMapperException {
    IDMapper mapper = BridgeDb.connect("idmapper-pgdb:" + GDB_HUMAN);
    src.add(INSR);
    Map<Xref, Set<Xref>> refmap = mapper.mapID(src, BioDataSource.ENTREZ_GENE);
    Set<Xref> expected = new HashSet<Xref>();
    expected.add(new Xref("3643", BioDataSource.ENTREZ_GENE));
    replacedertEquals(expected, refmap.get(INSR));
}

14 View Complete Implementation : Test.java
Copyright Apache License 2.0
Author : bridgedb
@org.junit.jupiter.api.Test
public void testLocalCapabilities() throws IDMapperException, ClreplacedNotFoundException {
    if (configExists) {
        IDMapper mapper = getLocalService();
        IDMapperCapabilities cap = mapper.getCapabilities();
        Set<DataSource> supported = cap.getSupportedSrcDataSources();
        replacedertTrue(supported.contains(DataSource.getBySystemCode("L")));
        String val = cap.getProperty("SCHEMAVERSION");
        replacedertNotNull(val);
        Set<DataSource> srcDs = cap.getSupportedSrcDataSources();
        replacedertTrue(srcDs.size() > 0);
        replacedertTrue(cap.isFreeSearchSupported());
        replacedertTrue(cap.isMappingSupported(BioDataSource.UNIPROT, BioDataSource.ENTREZ_GENE));
        replacedertFalse(cap.isMappingSupported(DataSource.getBySystemCode("??"), DataSource.getBySystemCode("!!")));
    }
}

14 View Complete Implementation : Test.java
Copyright Apache License 2.0
Author : PathVisio
public void testImportSimple() throws IOException, IDMapperException, DataException {
    PreferenceManager.init();
    DataSourceTxt.init();
    ImportInformation info = new ImportInformation();
    File f = new File("example-data/sample_data_1.txt");
    replacedertTrue(f.exists());
    info.setTxtFile(f);
    String dbFileName = System.getProperty("java.io.tmpdir") + File.separator + "tempgex2";
    info.setGexName(dbFileName);
    IDMapper gdb = BridgeDb.connect("idmapper-pgdb:" + GDB_HUMAN);
    GexTxtImporter.importFromTxt(info, null, gdb, gexManager);
    // no errors if all genes could be looked up.
    replacedertEquals(0, info.getErrorList().size());
    // Now test caching data
    DataInterface gex = gexManager.getCurrentGex();
    Xref ref1 = new Xref("7124", DataSource.getExistingBySystemCode("L"));
    Xref ref2 = new Xref("1909_at", DataSource.getExistingBySystemCode("X"));
    List<Xref> refs = Arrays.asList(new Xref[] { ref1, ref2 });
    CachedData cache = new CachedData(gex);
    cache.setMapper(gdb);
    cache.preSeed(refs);
    ISample s = gex.getSample(1);
    replacedertEquals(1, (int) s.getId());
    replacedertEquals("Control 2", s.getName());
    // check that there is only one row of data
    List<? extends IRow> data1 = cache.getData(ref1);
    replacedertEquals(1, data1.size());
    // looking up a particular data point in two different ways: L:7124, sample "Control 2"
    replacedertEquals(0.993159836, (Double) data1.get(0).getSampleData(s), 0.001);
    replacedertEquals(0.993159836, (Double) data1.get(0).getByName().get("Control 2"), 0.001);
    // test for aggregating data (in this case we're averaging over just one row)
    ReporterData row = ReporterData.createListSummary(cache.getData(ref2));
    // check data point for X:1909_at, which corresponds to L:596
    replacedertEquals(0.045334852, (Double) (row.getSampleData().get(s)), 0.001);
}

13 View Complete Implementation : TransitiveGraph.java
Copyright Apache License 2.0
Author : bridgedb
/**
 * Create a list of all direct (i.e. one-step) paths.
 *
 * @return Hash that contains all relevant information on maps between
 *         DataSources of all IDMappers in this IDMapperStack. Reflexive
 *         maps (DataSourced X -> DataSource X) are ignored. The map will
 *         contain only DataSources that are connected.
 *
 * @throws IDMapperException
 */
private Set<Path> getDirectPaths(List<IDMapper> gdbs) throws IDMapperException {
    Set<Path> result = new HashSet<Path>();
    // add each DataSource to a PathCollection
    for (IDMapper idm : gdbs) {
        if (idm != null && idm.isConnected()) {
            IDMapperCapabilities capas = idm.getCapabilities();
            for (DataSource src : capas.getSupportedSrcDataSources()) {
                for (DataSource tgt : capas.getSupportedTgtDataSources()) {
                    if (capas.isMappingSupported(src, tgt) && src != tgt) {
                        Edge edge = new Edge(src, tgt, idm);
                        Path path = new Path(edge);
                        result.add(path);
                    }
                }
            }
        }
    }
    return result;
}

13 View Complete Implementation : TestStack.java
Copyright Apache License 2.0
Author : bridgedb
public void testFile() throws IDMapperException, MalformedURLException {
    IDMapper mapper = BridgeDb.connect("idmapper-text:" + YEAST_ID_MAPPING.toURL());
    src.add(RAD51);
    Map<Xref, Set<Xref>> refmap = mapper.mapID(src, BioDataSource.ENTREZ_GENE);
    Set<Xref> expected = new HashSet<Xref>();
    expected.add(new Xref("856831", BioDataSource.ENTREZ_GENE));
    replacedertEquals(expected, refmap.get(RAD51));
    System.out.println(mapper.getCapabilities().getSupportedTgtDataSources());
}

12 View Complete Implementation : Test2.java
Copyright Apache License 2.0
Author : bridgedb
/**
 * From schema v2 to v3 there was a change in how the backpage was stored.
 * In schema v2 there was a backpage column in the datanode table
 * In schema v3 the backpage is split in several attributes.
 * For backwards compatibility, SimpleGdbImpl2 fakes these new attributes.
 * This is tested here.
 * @throws IDMapperException should be considered a failed test
 */
@Disabled
public void testGdbAttributes() throws IDMapperException {
    // test special attributes that are grabbed from backpage
    // since this is a Schema v2 database
    IDMapper gdb = BridgeDb.connect("idmapper-pgdb:" + GDB_HUMAN);
    AttributeMapper am = (AttributeMapper) gdb;
    Xref ref = new Xref("26873", DataSource.getBySystemCode("L"));
    replacedertTrue(am.getAttributes(ref, "Synonyms").contains("5-Opase|DKFZP434H244|OPLA"));
    replacedertTrue(am.getAttributes(ref, "Description").contains("5-oxoprolinase (EC 3.5.2.9) (5-oxo-L-prolinase) (5-OPase) (Pyroglutamase) [Source:UniProtKB/Swiss-Prot.Acc:O14841]"));
    replacedertTrue(am.getAttributes(ref, "Chromosome").contains("8"));
    replacedertTrue(am.getAttributes(ref, "Symbol").contains("OPLAH"));
    Set<String> allExpectedAttributes = new HashSet<String>();
    allExpectedAttributes.add("26873");
}