Example usage for org.jdom2 Element getChild

List of usage examples for org.jdom2 Element getChild

Introduction

In this page you can find the example usage for org.jdom2 Element getChild.

Prototype

public Element getChild(final String cname) 

Source Link

Document

This returns the first child element within this element with the given local name and belonging to no namespace.

Usage

From source file:com.athena.chameleon.engine.utils.PDFWriterUtil.java

License:Apache License

/**
 * /* w  w  w.  j a  va  2s  .c  o  m*/
 * chart 
 *
 * @param section chart   section ?
 * @param e chart   element
 * @throws Exception
 */
public static void setChart(PdfWriter writer, Section section, Element e) throws Exception {

    DefaultCategoryDataset dataset = new DefaultCategoryDataset();

    for (Element e1 : e.getChildren()) {
        if (!e1.getChild("column").getText().equals(FileType.DIRECTORY.toString())
                && !e1.getChild("column").getText().equals(FileType.SUM.toString())) {
            dataset.setValue(Integer.parseInt(e1.getChild("value").getText()), e.getAttributeValue("title"),
                    e1.getChild("column").getText());
        }
    }

    JFreeChart chart = ChartFactory.createBarChart3D(e.getAttributeValue("title"), "", "", dataset,
            PlotOrientation.VERTICAL, false, true, false);

    CategoryPlot plot = chart.getCategoryPlot();
    java.awt.Font labelFont = chart.getCategoryPlot().getDomainAxis().getLabelFont();
    plot.getDomainAxis().setLabelFont(new java.awt.Font(labelFont.getName(), Font.NORMAL, 6));
    plot.getDomainAxis().setTickLabelFont(new java.awt.Font(labelFont.getName(), Font.NORMAL, 6));

    PdfContentByte cb = writer.getDirectContent();
    PdfTemplate bar = cb.createTemplate(500, 150);
    Graphics2D g2d2 = new PdfGraphics2D(bar, 500, 150);
    Rectangle2D r2d2 = new Rectangle2D.Double(0, 0, 500, 150);
    chart.draw(g2d2, r2d2);
    g2d2.dispose();

    Image image = Image.getInstance(bar);
    image.setAlignment(com.itextpdf.text.Element.ALIGN_CENTER);
    section.add(image);
}

From source file:com.athena.chameleon.engine.utils.PDFWriterUtil.java

License:Apache License

/**
 * /*  w  w w . j a  va 2 s. c  o m*/
 * ?? header 
 *
 * @param e table   element
 * @param t header  table ?
 * @param colCount column 
 * @throws Exception
 */
public static void setTableHeader(Element e, PdfPTable t, int colCount) throws Exception {

    t.getDefaultCell().setBackgroundColor(new BaseColor(217, 217, 217));
    t.getDefaultCell().setHorizontalAlignment(com.itextpdf.text.Element.ALIGN_CENTER);

    ArrayList<Integer> colWidth = new ArrayList<Integer>();
    for (Element e1 : e.getChild("header").getChildren()) {
        t.addCell(new Phrase(e1.getText(), fnNormalBold));

        if (e1.getAttributeValue("width") != null)
            colWidth.add(Integer.parseInt(e1.getAttributeValue("width")));
    }

    if (colCount == colWidth.size()) {
        int[] col = new int[colCount];
        for (int i = 0; i < colCount; i++)
            col[i] = colWidth.get(i);

        t.setWidths(col);
    }

}

From source file:com.athena.chameleon.engine.utils.PDFWriterUtil.java

License:Apache License

/**
 * /*  w  w w. j  a va  2  s.c  om*/
 * ?? row 
 *
 * @param e table   element
 * @param t header  table ?
 * @throws Exception
 */
public static void setTableRow(Element e, PdfPTable t) throws Exception {

    t.getDefaultCell().setBackgroundColor(new BaseColor(255, 255, 255));
    t.getDefaultCell().setHorizontalAlignment(com.itextpdf.text.Element.ALIGN_LEFT);

    for (Element e1 : e.getChild("row").getChildren()) {
        t.addCell(new Phrase(e1.getText(), fnNormal));
    }

}

From source file:com.aurum.whitehole.ObjectDB.java

License:Open Source License

public static void init() {
    fallback = true;//from   w w  w .  j  a  va  2  s .com
    timestamp = 0;

    categories = new LinkedHashMap();
    objects = new LinkedHashMap();

    File odbfile = new File("objectdb.xml");
    if (!(odbfile.exists() && odbfile.isFile()))
        return;

    try {
        Element root = new SAXBuilder().build(odbfile).getRootElement();
        timestamp = root.getAttribute("timestamp").getLongValue();

        List<Element> catelems = root.getChild("categories").getChildren("category");
        for (Element catelem : catelems)
            categories.put(catelem.getAttribute("id").getIntValue(), catelem.getText());

        List<Element> objelems = root.getChildren("object");
        for (Element objelem : objelems) {
            Object entry = new Object();
            entry.ID = objelem.getAttributeValue("id");
            entry.name = objelem.getChildText("name");
            entry.category = objelem.getChild("category").getAttribute("id").getIntValue();
            entry.type = objelem.getChild("preferredfile").getAttributeValue("name");
            entry.notes = objelem.getChildText("notes");

            Element flags = objelem.getChild("flags");
            entry.games = flags.getAttribute("games").getIntValue();
            entry.known = flags.getAttribute("known").getIntValue();
            entry.complete = flags.getAttribute("complete").getIntValue();

            if (entry.notes.isEmpty() || entry.notes.equals(""))
                entry.notes = "(No description found for this objects.)";
            if (entry.type.isEmpty() || entry.notes.equals(""))
                entry.type = "Unknown";

            entry.files = new ArrayList();
            String files = objelem.getChildText("files");
            for (String file : files.split("\n")) {
                entry.files.add(file);
            }

            List<Element> fields = objelem.getChildren("field");
            entry.fields = new HashMap(fields.size());
            if (!fields.isEmpty()) {
                for (Element field : fields) {
                    Object.Field fielddata = new Object.Field();

                    fielddata.ID = field.getAttribute("id").getIntValue();
                    fielddata.type = field.getAttributeValue("type");
                    fielddata.name = field.getAttributeValue("name");
                    fielddata.values = field.getAttributeValue("values");
                    fielddata.notes = field.getAttributeValue("notes");

                    entry.fields.put(fielddata.ID, fielddata);
                }
            }

            objects.put(entry.ID, entry);
        }
    } catch (IOException | JDOMException ex) {
        timestamp = 0;
        return;
    }

    fallback = false;
}

From source file:com.bc.ceres.jai.opimage.XmlRIF.java

License:Open Source License

private RenderedImage create(URI location, Map<String, Object> configuration, RenderingHints renderingHints)
        throws JDOMException, IOException, IllegalArgumentException {
    configuration = new HashMap<String, Object>(configuration);

    SAXBuilder builder = new SAXBuilder();
    Document document = builder.build(location.toURL());
    Element rootElement = document.getRootElement();
    Map<String, Element> sourceMap = getElementMap(rootElement, ENAME_SOURCE);
    Map<String, Element> parameterMap = getElementMap(rootElement, ENAME_PARAMETER);
    Element targetElement = rootElement.getChild(ENAME_TARGET);
    return parseImage(targetElement, sourceMap, parameterMap, configuration, renderingHints, "rendered");
}

From source file:com.bc.ceres.jai.opimage.XmlRIF.java

License:Open Source License

private RenderedOp parseImage(Element targetElement, Map<String, Element> definedSourceElements,
        Map<String, Element> definedParameterElements, Map<String, Object> configuration,
        RenderingHints renderHints, String modeName) {
    Element opElement = targetElement.getChild(ENAME_OP);
    String opName = opElement.getValue();

    ParameterBlockJAI parameterBlock = new ParameterBlockJAI(opName, modeName);

    parseSources(parameterBlock, targetElement, definedSourceElements, definedParameterElements, configuration,
            renderHints);//from w ww .ja  v a2s . c  o  m

    parseParameters(parameterBlock, targetElement, definedParameterElements, configuration);

    return JAI.create(opName, parameterBlock, renderHints);
}

From source file:com.bc.ceres.nbmgen.NbmGenTool.java

License:Open Source License

@Override
public void process(CeresModuleProject project) throws JDOMException, IOException {

    System.out.println("Project [" + project.projectDir.getName() + "]:");

    File originalPomFile = getFile(project.projectDir, CeresModuleProject.ORIGINAL_POM_XML);
    File pomFile = getFile(project.projectDir, CeresModuleProject.POM_XML);
    File manifestBaseFile = getFile(project.projectDir, "src", "main", "nbm", "manifest.mf");

    Element projectElement = project.pomDocument.getRootElement();
    Namespace ns = projectElement.getNamespace();

    Element moduleElement = project.moduleDocument.getRootElement();
    String moduleName = moduleElement.getChildTextTrim("name");
    String moduleDescription = moduleElement.getChildTextNormalize("description");
    String modulePackaging = moduleElement.getChildTextTrim("packaging");
    String moduleNative = moduleElement.getChildTextTrim("native");
    String moduleActivator = moduleElement.getChildTextTrim("activator");
    String moduleChangelog = moduleElement.getChildTextTrim("changelog");
    String moduleFunding = moduleElement.getChildTextTrim("funding");
    String moduleVendor = moduleElement.getChildTextTrim("vendor");
    String moduleContactAddress = moduleElement.getChildTextTrim("contactAddress");
    String moduleCopyright = moduleElement.getChildTextTrim("copyright");
    String moduleLicenseUrl = moduleElement.getChildTextTrim("licenseUrl");
    // Not used anymore:
    //String moduleUrl = moduleElement.getChildTextTrim("url");
    //String moduleAboutUrl = moduleElement.getChildTextTrim("aboutUrl");

    if (moduleName != null) {
        Element nameElement = getOrAddElement(projectElement, "name", ns);
        nameElement.setText(moduleName);
    }//from  w  w  w. j av a2s. c o m
    if (moduleDescription != null) {
        int nameIndex = projectElement.indexOf(projectElement.getChild("name"));
        Element descriptionElement = getOrAddElement(projectElement, "description", nameIndex + 1, ns);
        descriptionElement.setText(moduleDescription);
    }
    Element descriptionElement = getOrAddElement(projectElement, "packaging", ns);
    descriptionElement.setText("nbm");

    Element urlElement = getOrAddElement(projectElement, "url", ns);
    urlElement.setText("https://sentinel.esa.int/web/sentinel/toolboxes");

    Element buildElement = getOrAddElement(projectElement, "build", ns);
    Element pluginsElement = getOrAddElement(buildElement, "plugins", ns);

    Map<String, String> nbmConfiguration = new LinkedHashMap<>();
    // moduleType is actually a constant which can be put it into the <pluginManagement-element of the parent
    nbmConfiguration.put("moduleType", "normal");
    // licenseName/File should also be constant
    nbmConfiguration.put("licenseName", "GPL 3");
    nbmConfiguration.put("licenseFile", "../LICENSE.html");

    nbmConfiguration.put("cluster", cluster);
    nbmConfiguration.put("defaultCluster", cluster);
    nbmConfiguration.put("publicPackages", "");
    nbmConfiguration.put("requiresRestart", "true");

    addPluginElement(pluginsElement, "org.codehaus.mojo", "nbm-maven-plugin", nbmConfiguration, ns);

    Map<String, String> jarConfiguration = new LinkedHashMap<>();
    jarConfiguration.put("useDefaultManifestFile", "true");

    addPluginElement(pluginsElement, "org.apache.maven.plugins", "maven-jar-plugin", jarConfiguration, ns);

    StringBuilder longDescription = new StringBuilder();

    longDescription.append(moduleDescription != null ? "<p>" + moduleDescription + "" : "")
            .append(descriptionEntry("Funding", moduleFunding)).append(descriptionEntry("Vendor", moduleVendor))
            .append(descriptionEntry("Contact address", moduleContactAddress))
            .append(descriptionEntry("Copyright", moduleCopyright))
            .append(descriptionEntry("Vendor", moduleVendor))
            .append(descriptionEntry("License", moduleLicenseUrl))
            .append(descriptionEntry("Changelog", moduleChangelog));

    Map<String, String> manifestContent = new LinkedHashMap<>();
    manifestContent.put("Manifest-Version", "1.0");
    manifestContent.put("AutoUpdate-Show-In-Client", "false");
    manifestContent.put("AutoUpdate-Essential-Module", "true");
    manifestContent.put("OpenIDE-Module-Java-Dependencies", "Java > 1.8");
    manifestContent.put("OpenIDE-Module-Display-Category", "SNAP");
    if (longDescription.length() > 0) {
        manifestContent.put("OpenIDE-Module-Long-Description", longDescription.toString());
    }
    if (moduleActivator != null) {
        warnModuleDetail("Activator may be reimplemented for NB: " + moduleActivator + " (--> "
                + "consider using @OnStart, @OnStop, @OnShowing, or a ModuleInstall)");
        manifestContent.put("OpenIDE-Module-Install", moduleActivator);
    }
    if (modulePackaging != null && !"jar".equals(modulePackaging)) {
        warnModuleDetail("Unsupported module packaging: " + modulePackaging + " (--> "
                + "provide a ModuleInstall that does the job on install/uninstall)");
    }
    if (moduleNative != null && "true".equals(moduleNative)) {
        warnModuleDetail("Module contains native code: no auto-conversion possible (--> "
                + "follow NB instructions see http://bits.netbeans.org/dev/javadoc/org-openide-modules/org/openide/modules/doc-files/api.html#how-layer");
    }

    if (!originalPomFile.exists()) {
        if (!dryRun) {
            Files.copy(project.pomFile.toPath(), originalPomFile.toPath());
        }
        infoModuleDetail("Copied " + project.pomFile + " to " + originalPomFile);
    }

    if (!dryRun) {
        writeXml(pomFile, project.pomDocument);
    }
    if (pomFile.equals(project.pomFile)) {
        infoModuleDetail("Updated " + pomFile);
    } else {
        infoModuleDetail("Converted " + project.pomFile + " to " + pomFile);
    }

    //noinspection ResultOfMethodCallIgnored
    if (!dryRun) {
        manifestBaseFile.getParentFile().mkdirs();
        writeManifest(manifestBaseFile, manifestContent);
    }
    infoModuleDetail("Written " + manifestBaseFile);
}

From source file:com.bc.fiduceo.reader.airs.AIRS_L1B_Reader.java

License:Open Source License

static String getElementValue(Element element, String attribute) {
    if (element.getName().equals(attribute)) {
        return element.getChild("VALUE").getValue();
    }// w ww  . jav a  2s .  c o m
    for (Element subElement : element.getChildren()) {
        if (subElement.getName().equals(attribute)) {
            return subElement.getChild("VALUE").getValue();
        } else {
            final String elementValue = getElementValue(subElement, attribute);
            if (StringUtils.isNotNullAndNotEmpty(elementValue)) {
                return elementValue;
            }
        }
    }
    return null;
}

From source file:com.bio4j.neo4jdb.programs.ImportGeneOntology.java

License:Open Source License

public static void main(String[] args) {

    if (args.length != 3) {
        System.out.println(/*  ww  w  . ja  v  a2  s . c o  m*/
                "This program expects the following parameters: \n" + "1. Gene ontology xml filename \n"
                        + "2. Bio4j DB folder \n" + "3. Batch inserter .properties file");

    } else {

        long initTime = System.nanoTime();

        File inFile = new File(args[0]);

        BatchInserter inserter = null;
        BatchInserterIndexProvider indexProvider = null;

        BatchInserterIndex goTermIdIndex;
        BatchInserterIndex isAGoRelIndex;
        BatchInserterIndex nodeTypeIndex;

        BufferedWriter statsBuff = null;

        int termCounter = 0;
        int limitForPrintingOut = 10000;

        try {

            // This block configures the logger with handler and formatter
            fh = new FileHandler("ImportGeneOntology.log", true);
            SimpleFormatter formatter = new SimpleFormatter();
            fh.setFormatter(formatter);
            logger.addHandler(fh);
            logger.setLevel(Level.ALL);

            //---creating writer for stats file-----
            statsBuff = new BufferedWriter(new FileWriter(new File("ImportGeneOntologyStats.txt")));

            // create the batch inserter
            inserter = BatchInserters.inserter(args[1], MapUtil.load(new File(args[2])));

            // create the batch index service
            indexProvider = new LuceneBatchInserterIndexProvider(inserter);
            Map<String, String> indexProps = MapUtil.stringMap("provider", "lucene", "type", "exact");

            goTermIdIndex = indexProvider.nodeIndex(GoTermNode.GO_TERM_ID_INDEX, indexProps);
            isAGoRelIndex = indexProvider.relationshipIndex(IsAGoRel.IS_A_REL_INDEX, indexProps);
            nodeTypeIndex = indexProvider.nodeIndex(Bio4jManager.NODE_TYPE_INDEX_NAME, indexProps);

            //------------------nodes properties maps-----------------------------------
            Map<String, Object> goProperties = new HashMap<String, Object>();
            goProperties.put(GoTermNode.NODE_TYPE_PROPERTY, GoTermNode.NODE_TYPE);
            //--------------------------------------------------------------------------

            //--------------------------------relationships------------------------------------------
            IsAGoRel isAGoRel = new IsAGoRel(null);
            RegulatesGoRel regulatesGoRel = new RegulatesGoRel(null);
            NegativelyRegulatesGoRel negativelyRegulatesGoRel = new NegativelyRegulatesGoRel(null);
            PositivelyRegulatesGoRel positivelyRegulatesGoRel = new PositivelyRegulatesGoRel(null);
            PartOfGoRel partOfGoRel = new PartOfGoRel(null);
            HasPartOfGoRel hasPartGoRel = new HasPartOfGoRel(null);
            //--------------------------------------------------------------------------

            Map<String, ArrayList<String>> termParentsMap = new HashMap<String, ArrayList<String>>();
            Map<String, ArrayList<String>> regulatesMap = new HashMap<String, ArrayList<String>>();
            Map<String, ArrayList<String>> negativelyRegulatesMap = new HashMap<String, ArrayList<String>>();
            Map<String, ArrayList<String>> positivelyRegulatesMap = new HashMap<String, ArrayList<String>>();
            Map<String, ArrayList<String>> partOfMap = new HashMap<String, ArrayList<String>>();
            Map<String, ArrayList<String>> hasPartMap = new HashMap<String, ArrayList<String>>();

            BufferedReader reader = new BufferedReader(new FileReader(inFile));
            String line;
            StringBuilder termStBuilder = new StringBuilder();

            logger.log(Level.INFO, "inserting nodes....");

            //-----first I create all the elements whitout their relationships-------------

            while ((line = reader.readLine()) != null) {
                if (line.trim().startsWith("<" + TERM_TAG_NAME)) {

                    while (!line.trim().startsWith("</" + TERM_TAG_NAME + ">")) {
                        termStBuilder.append(line);
                        line = reader.readLine();
                    }
                    //linea final del organism
                    termStBuilder.append(line);
                    //System.out.println("organismStBuilder.toString() = " + organismStBuilder.toString());
                    XMLElement termXMLElement = new XMLElement(termStBuilder.toString());
                    termStBuilder.delete(0, termStBuilder.length());

                    String goId = termXMLElement.asJDomElement().getChildText(ID_TAG_NAME);
                    String goName = termXMLElement.asJDomElement().getChildText(NAME_TAG_NAME);
                    if (goName == null) {
                        goName = "";
                    }
                    String goNamespace = termXMLElement.asJDomElement().getChildText(NAMESPACE_TAG_NAME);
                    if (goNamespace == null) {
                        goNamespace = "";
                    }
                    String goDefinition = "";
                    Element defElem = termXMLElement.asJDomElement().getChild(DEF_TAG_NAME);
                    if (defElem != null) {
                        Element defstrElem = defElem.getChild(DEFSTR_TAG_NAME);
                        if (defstrElem != null) {
                            goDefinition = defstrElem.getText();
                        }
                    }
                    String goComment = termXMLElement.asJDomElement().getChildText(COMMENT_TAG_NAME);
                    if (goComment == null) {
                        goComment = "";
                    }
                    String goIsObsolete = termXMLElement.asJDomElement().getChildText(IS_OBSOLETE_TAG_NAME);
                    if (goIsObsolete == null) {
                        goIsObsolete = "";
                    } else {
                        if (goIsObsolete.equals("1")) {
                            goIsObsolete = "true";
                        } else {
                            goIsObsolete = "false";
                        }
                    }

                    List<Element> altIdElems = termXMLElement.asJDomElement().getChildren("alt_id");
                    String[] alternativeIds = new String[altIdElems.size()];
                    for (int i = 0; i < altIdElems.size(); i++) {
                        alternativeIds[i] = altIdElems.get(i).getText();
                    }

                    //----term parents----
                    List<Element> termParentTerms = termXMLElement.asJDomElement()
                            .getChildren(IsAGoRel.OBOXML_RELATIONSHIP_NAME);
                    ArrayList<String> array = new ArrayList<String>();
                    for (Element elem : termParentTerms) {
                        array.add(elem.getText().trim());
                    }
                    termParentsMap.put(goId, array);
                    //---------------------

                    //-------relationship tags-----------
                    List<Element> relationshipTags = termXMLElement.asJDomElement()
                            .getChildren(RELATIONSHIP_TAG_NAME);

                    for (Element relationshipTag : relationshipTags) {

                        String relType = relationshipTag.getChildText("type");
                        String toSt = relationshipTag.getChildText("to");

                        if (relType.equals(RegulatesGoRel.OBOXML_RELATIONSHIP_NAME)) {

                            ArrayList<String> tempArray = regulatesMap.get(goId);
                            if (tempArray == null) {
                                tempArray = new ArrayList<String>();
                                regulatesMap.put(goId, tempArray);
                            }
                            tempArray.add(toSt);

                        } else if (relType.equals(PositivelyRegulatesGoRel.OBOXML_RELATIONSHIP_NAME)) {

                            ArrayList<String> tempArray = positivelyRegulatesMap.get(goId);
                            if (tempArray == null) {
                                tempArray = new ArrayList<String>();
                                positivelyRegulatesMap.put(goId, tempArray);
                            }
                            tempArray.add(toSt);

                        } else if (relType.equals(NegativelyRegulatesGoRel.OBOXML_RELATIONSHIP_NAME)) {

                            ArrayList<String> tempArray = negativelyRegulatesMap.get(goId);
                            if (tempArray == null) {
                                tempArray = new ArrayList<String>();
                                negativelyRegulatesMap.put(goId, tempArray);
                            }
                            tempArray.add(toSt);

                        } else if (relType.equals(PartOfGoRel.OBOXML_RELATIONSHIP_NAME)) {

                            ArrayList<String> tempArray = partOfMap.get(goId);
                            if (tempArray == null) {
                                tempArray = new ArrayList<String>();
                                partOfMap.put(goId, tempArray);
                            }
                            tempArray.add(toSt);

                        } else if (relType.equals(HasPartOfGoRel.OBOXML_RELATIONSHIP_NAME)) {

                            ArrayList<String> tempArray = hasPartMap.get(goId);
                            if (tempArray == null) {
                                tempArray = new ArrayList<String>();
                                hasPartMap.put(goId, tempArray);
                            }
                            tempArray.add(toSt);

                        }
                    }
                    //-------------------------------------

                    goProperties.put(GoTermNode.ID_PROPERTY, goId);
                    goProperties.put(GoTermNode.NAME_PROPERTY, goName);
                    goProperties.put(GoTermNode.DEFINITION_PROPERTY, goDefinition);
                    goProperties.put(GoTermNode.NAMESPACE_PROPERTY, goNamespace);
                    goProperties.put(GoTermNode.ALTERNATIVE_IDS_PROPERTY, alternativeIds);
                    goProperties.put(GoTermNode.OBSOLETE_PROPERTY, goIsObsolete);
                    goProperties.put(GoTermNode.COMMENT_PROPERTY, goComment);
                    long currentGoTermId = inserter.createNode(goProperties);
                    //--------indexing term by id (and alternative ids)----------
                    goTermIdIndex.add(currentGoTermId, MapUtil.map(GoTermNode.GO_TERM_ID_INDEX, goId));
                    for (int i = 0; i < alternativeIds.length; i++) {
                        goTermIdIndex.add(currentGoTermId,
                                MapUtil.map(GoTermNode.GO_TERM_ID_INDEX, alternativeIds[i]));
                    }
                    //--------indexing node by node_type index----------
                    nodeTypeIndex.add(currentGoTermId,
                            MapUtil.map(Bio4jManager.NODE_TYPE_INDEX_NAME, GoTermNode.NODE_TYPE));

                }
                termCounter++;
                if ((termCounter % limitForPrintingOut) == 0) {
                    logger.log(Level.INFO, (termCounter + " terms inserted!!"));
                }
            }
            reader.close();

            //flushing index
            goTermIdIndex.flush();

            //-----------------------------------------------------------------------

            logger.log(Level.INFO, "Inserting relationships....");

            logger.log(Level.INFO, "'is_a' relationships....");

            //-------------------'is_a' relationships-----------------
            Set<String> keys = termParentsMap.keySet();
            for (String key : keys) {
                long currentNodeId = goTermIdIndex.get(GoTermNode.GO_TERM_ID_INDEX, key).getSingle();
                ArrayList<String> tempArray = termParentsMap.get(key);
                for (String string : tempArray) {
                    long tempNodeId = goTermIdIndex.get(GoTermNode.GO_TERM_ID_INDEX, string).getSingle();
                    long isAGorelId = inserter.createRelationship(currentNodeId, tempNodeId, isAGoRel, null);
                    //System.out.println("key = " + key);
                    isAGoRelIndex.add(isAGorelId,
                            MapUtil.map(IsAGoRel.IS_A_REL_INDEX, String.valueOf(currentNodeId)));
                    //System.out.println("indexing key = " + key);
                }
            }

            logger.log(Level.INFO, "'regulates' relationships....");
            //-------------------'regulates' relationships----------------------
            keys = regulatesMap.keySet();
            for (String key : keys) {
                long currentNodeId = goTermIdIndex.get(GoTermNode.GO_TERM_ID_INDEX, key).getSingle();
                ArrayList<String> tempArray = regulatesMap.get(key);
                for (String string : tempArray) {
                    long tempNodeId = goTermIdIndex.get(GoTermNode.GO_TERM_ID_INDEX, string).getSingle();
                    inserter.createRelationship(currentNodeId, tempNodeId, regulatesGoRel, null);
                }
            }

            logger.log(Level.INFO, "'negatively_regulates' relationships....");
            //-------------------'regulates' relationships----------------------
            keys = negativelyRegulatesMap.keySet();
            for (String key : keys) {
                long currentNodeId = goTermIdIndex.get(GoTermNode.GO_TERM_ID_INDEX, key).getSingle();
                ArrayList<String> tempArray = negativelyRegulatesMap.get(key);
                for (String string : tempArray) {
                    long tempNodeId = goTermIdIndex.get(GoTermNode.GO_TERM_ID_INDEX, string).getSingle();
                    inserter.createRelationship(currentNodeId, tempNodeId, negativelyRegulatesGoRel, null);
                }
            }

            logger.log(Level.INFO, "'positively_regulates' relationships....");
            //-------------------'regulates' relationships----------------------
            keys = positivelyRegulatesMap.keySet();
            for (String key : keys) {
                long currentNodeId = goTermIdIndex.get(GoTermNode.GO_TERM_ID_INDEX, key).getSingle();
                ArrayList<String> tempArray = positivelyRegulatesMap.get(key);
                for (String string : tempArray) {
                    long tempNodeId = goTermIdIndex.get(GoTermNode.GO_TERM_ID_INDEX, string).getSingle();
                    inserter.createRelationship(currentNodeId, tempNodeId, positivelyRegulatesGoRel, null);
                }
            }

            logger.log(Level.INFO, "'part_of' relationships....");
            //-------------------'regulates' relationships----------------------
            keys = partOfMap.keySet();
            for (String key : keys) {
                long currentNodeId = goTermIdIndex.get(GoTermNode.GO_TERM_ID_INDEX, key).getSingle();
                ArrayList<String> tempArray = partOfMap.get(key);
                for (String string : tempArray) {
                    long tempNodeId = goTermIdIndex.get(GoTermNode.GO_TERM_ID_INDEX, string).getSingle();
                    inserter.createRelationship(currentNodeId, tempNodeId, partOfGoRel, null);
                }
            }

            logger.log(Level.INFO, "'has_part' relationships....");
            //-------------------'regulates' relationships----------------------
            keys = hasPartMap.keySet();
            for (String key : keys) {
                long currentNodeId = goTermIdIndex.get(GoTermNode.GO_TERM_ID_INDEX, key).getSingle();
                ArrayList<String> tempArray = hasPartMap.get(key);
                for (String string : tempArray) {
                    long tempNodeId = goTermIdIndex.get(GoTermNode.GO_TERM_ID_INDEX, string).getSingle();
                    inserter.createRelationship(currentNodeId, tempNodeId, hasPartGoRel, null);
                }
            }

            logger.log(Level.INFO, "Done! :)");

        } catch (Exception e) {
            logger.log(Level.SEVERE, e.getMessage());
            StackTraceElement[] trace = e.getStackTrace();
            for (StackTraceElement stackTraceElement : trace) {
                logger.log(Level.SEVERE, stackTraceElement.toString());
            }
        } finally {

            try {
                //closing logger file handler
                fh.close();
                logger.log(Level.INFO, "Closing up inserter and index service....");
                // shutdown, makes sure all changes are written to disk
                indexProvider.shutdown();
                inserter.shutdown();

                //-----------------writing stats file---------------------
                long elapsedTime = System.nanoTime() - initTime;
                long elapsedSeconds = Math.round((elapsedTime / 1000000000.0));
                long hours = elapsedSeconds / 3600;
                long minutes = (elapsedSeconds % 3600) / 60;
                long seconds = (elapsedSeconds % 3600) % 60;

                statsBuff.write("Statistics for program ImportGeneOntology:\nInput file: " + inFile.getName()
                        + "\nThere were " + termCounter + " terms inserted.\n" + "The elapsed time was: "
                        + hours + "h " + minutes + "m " + seconds + "s\n");

                //---closing stats writer---
                statsBuff.close();

            } catch (Exception e) {
                logger.log(Level.SEVERE, e.getMessage());
                StackTraceElement[] trace = e.getStackTrace();
                for (StackTraceElement stackTraceElement : trace) {
                    logger.log(Level.SEVERE, stackTraceElement.toString());
                }
            }

        }
    }
}

From source file:com.bio4j.neo4jdb.programs.ImportProteinInteractions.java

License:Open Source License

public static void main(String[] args) throws IOException {

    if (args.length != 3) {
        System.out.println("This program expects the following parameters: \n" + "1. Uniprot xml filename \n"
                + "2. Bio4j DB folder\n" + "3. Batch inserter .properties file");
    } else {//from  www.  j a va  2s. c  o  m

        long initTime = System.nanoTime();

        File inFile = new File(args[0]);

        BatchInserter inserter = null;
        BatchInserterIndexProvider indexProvider = null;
        String accessionSt = "";

        BufferedWriter statsBuff = null;

        int proteinCounter = 0;
        int limitForPrintingOut = 10000;

        try {

            // This block configure the logger with handler and formatter
            fh = new FileHandler("ImportProteinInteractions" + args[0].split("\\.")[0] + ".log", false);
            SimpleFormatter formatter = new SimpleFormatter();
            fh.setFormatter(formatter);
            logger.addHandler(fh);
            logger.setLevel(Level.ALL);
            //---------------------------------

            //---creating writer for stats file-----
            statsBuff = new BufferedWriter(new FileWriter(
                    new File("ImportProteinInteractionsStats_" + inFile.getName().split("\\.")[0] + ".txt")));

            // create the batch inserter
            inserter = BatchInserters.inserter(args[1], MapUtil.load(new File(args[2])));

            // create the batch index service
            indexProvider = new LuceneBatchInserterIndexProvider(inserter);

            //------------------nodes properties maps-----------------------------------
            //---------------------------------------------------------------------

            //-------------------relationships properties maps--------------------------
            Map<String, Object> proteinProteinInteractionProperties = new HashMap<String, Object>();
            Map<String, Object> proteinIsoformInteractionProperties = new HashMap<String, Object>();
            //----------------------------------------------------------------------------

            //--------------------------------relationships------------------------------------------
            ProteinProteinInteractionRel proteinProteinInteractionRel = new ProteinProteinInteractionRel(null);
            ProteinIsoformInteractionRel proteinIsoformInteractionRel = new ProteinIsoformInteractionRel(null);
            //------------------------------------------------------------------------------------------------

            //------------------indexes creation----------------------------------
            BatchInserterIndex proteinAccessionIndex = indexProvider.nodeIndex(
                    ProteinNode.PROTEIN_ACCESSION_INDEX,
                    MapUtil.stringMap(PROVIDER_ST, LUCENE_ST, TYPE_ST, EXACT_ST));
            BatchInserterIndex isoformIdIndex = indexProvider.nodeIndex(IsoformNode.ISOFORM_ID_INDEX,
                    MapUtil.stringMap(PROVIDER_ST, LUCENE_ST, TYPE_ST, EXACT_ST));
            //--------------------------------------------------------------------

            BufferedReader reader = new BufferedReader(new FileReader(inFile));
            String line;
            StringBuilder entryStBuilder = new StringBuilder();

            while ((line = reader.readLine()) != null) {
                if (line.trim().startsWith("<" + UniprotStuff.ENTRY_TAG_NAME)) {

                    while (!line.trim().startsWith("</" + UniprotStuff.ENTRY_TAG_NAME + ">")) {
                        entryStBuilder.append(line);
                        line = reader.readLine();
                    }
                    //linea final del organism
                    entryStBuilder.append(line);
                    //System.out.println("organismStBuilder.toString() = " + organismStBuilder.toString());
                    XMLElement entryXMLElem = new XMLElement(entryStBuilder.toString());
                    entryStBuilder.delete(0, entryStBuilder.length());

                    accessionSt = entryXMLElem.asJDomElement()
                            .getChildText(UniprotStuff.ENTRY_ACCESSION_TAG_NAME);

                    long currentProteinId = proteinAccessionIndex
                            .get(ProteinNode.PROTEIN_ACCESSION_INDEX, accessionSt).getSingle();

                    List<Element> comments = entryXMLElem.asJDomElement()
                            .getChildren(UniprotStuff.COMMENT_TAG_NAME);

                    for (Element commentElem : comments) {

                        String commentTypeSt = commentElem
                                .getAttributeValue(UniprotStuff.COMMENT_TYPE_ATTRIBUTE);

                        //----------interaction----------------
                        if (commentTypeSt.equals(ProteinProteinInteractionRel.UNIPROT_ATTRIBUTE_TYPE_VALUE)) {
                            List<Element> interactants = commentElem.getChildren("interactant");
                            Element interactant1 = interactants.get(0);
                            Element interactant2 = interactants.get(1);
                            Element organismsDiffer = commentElem.getChild("organismsDiffer");
                            Element experiments = commentElem.getChild("experiments");
                            String intactId1St = interactant1.getAttributeValue("intactId");
                            String intactId2St = interactant2.getAttributeValue("intactId");
                            String organismsDifferSt = "";
                            String experimentsSt = "";
                            if (intactId1St == null) {
                                intactId1St = "";
                            }
                            if (intactId2St == null) {
                                intactId2St = "";
                            }
                            if (organismsDiffer != null) {
                                organismsDifferSt = organismsDiffer.getText();
                            }
                            if (experiments != null) {
                                experimentsSt = experiments.getText();
                            }

                            //----now we try to retrieve the interactant 2 accession--
                            String interactant2AccessionSt = interactant2.getChildText("id");
                            long protein2Id = -1;
                            if (interactant2AccessionSt != null) {

                                IndexHits<Long> protein2IdIndexHits = proteinAccessionIndex
                                        .get(ProteinNode.PROTEIN_ACCESSION_INDEX, interactant2AccessionSt);
                                if (protein2IdIndexHits.hasNext()) {
                                    if (protein2IdIndexHits.size() == 1) {
                                        protein2Id = protein2IdIndexHits.getSingle();
                                    }
                                }

                                if (protein2Id < 0) {
                                    //Since we did not find the protein we try to find a isoform instead
                                    long isoformId = -1;
                                    IndexHits<Long> isoformIdIndexHits = isoformIdIndex
                                            .get(IsoformNode.ISOFORM_ID_INDEX, interactant2AccessionSt);
                                    if (isoformIdIndexHits.hasNext()) {
                                        if (isoformIdIndexHits.size() == 1) {
                                            isoformId = isoformIdIndexHits.getSingle();
                                        }
                                    }
                                    if (isoformId >= 0) {

                                        proteinIsoformInteractionProperties.put(
                                                ProteinIsoformInteractionRel.EXPERIMENTS_PROPERTY,
                                                experimentsSt);
                                        proteinIsoformInteractionProperties.put(
                                                ProteinIsoformInteractionRel.ORGANISMS_DIFFER_PROPERTY,
                                                organismsDifferSt);
                                        proteinIsoformInteractionProperties.put(
                                                ProteinIsoformInteractionRel.INTACT_ID_1_PROPERTY, intactId1St);
                                        proteinIsoformInteractionProperties.put(
                                                ProteinIsoformInteractionRel.INTACT_ID_2_PROPERTY, intactId2St);

                                        inserter.createRelationship(currentProteinId, isoformId,
                                                proteinIsoformInteractionRel,
                                                proteinIsoformInteractionProperties);

                                    }
                                } else {

                                    proteinProteinInteractionProperties.put(
                                            ProteinProteinInteractionRel.EXPERIMENTS_PROPERTY, experimentsSt);
                                    proteinProteinInteractionProperties.put(
                                            ProteinProteinInteractionRel.ORGANISMS_DIFFER_PROPERTY,
                                            organismsDifferSt);
                                    proteinProteinInteractionProperties.put(
                                            ProteinProteinInteractionRel.INTACT_ID_1_PROPERTY, intactId1St);
                                    proteinProteinInteractionProperties.put(
                                            ProteinProteinInteractionRel.INTACT_ID_2_PROPERTY, intactId2St);

                                    inserter.createRelationship(currentProteinId, protein2Id,
                                            proteinProteinInteractionRel, proteinProteinInteractionProperties);

                                }

                            }

                        }

                    }

                    proteinCounter++;
                    if ((proteinCounter % limitForPrintingOut) == 0) {
                        logger.log(Level.INFO, (proteinCounter + " proteins updated with interactions!!"));
                    }

                }
            }

            reader.close();

        } catch (Exception e) {
            logger.log(Level.SEVERE, ("Exception retrieving protein " + accessionSt));
            logger.log(Level.SEVERE, e.getMessage());
            StackTraceElement[] trace = e.getStackTrace();
            for (StackTraceElement stackTraceElement : trace) {
                logger.log(Level.SEVERE, stackTraceElement.toString());
            }

        } finally {
            //outbBuff.close();

            try {

                // shutdown, makes sure all changes are written to disk
                indexProvider.shutdown();
                inserter.shutdown();

                //closing logger file handler
                fh.close();

                //-----------------writing stats file---------------------
                long elapsedTime = System.nanoTime() - initTime;
                long elapsedSeconds = Math.round((elapsedTime / 1000000000.0));
                long hours = elapsedSeconds / 3600;
                long minutes = (elapsedSeconds % 3600) / 60;
                long seconds = (elapsedSeconds % 3600) % 60;

                statsBuff.write("Statistics for program ImportProteinInteractions:\nInput file: "
                        + inFile.getName() + "\nThere were " + proteinCounter + " proteins analyzed.\n"
                        + "The elapsed time was: " + hours + "h " + minutes + "m " + seconds + "s\n");

                //---closing stats writer---
                statsBuff.close();

            } catch (Exception e) {

                logger.log(Level.SEVERE, ("Exception retrieving protein " + accessionSt));
                logger.log(Level.SEVERE, e.getMessage());
                StackTraceElement[] trace = e.getStackTrace();
                for (StackTraceElement stackTraceElement : trace) {
                    logger.log(Level.SEVERE, stackTraceElement.toString());
                }
                //closing logger file handler
                fh.close();
            }

        }
    }

}