Example usage for org.dom4j DocumentHelper parseText

List of usage examples for org.dom4j DocumentHelper parseText

Introduction

In this page you can find the example usage for org.dom4j DocumentHelper parseText.

Prototype

public static Document parseText(String text) throws DocumentException 

Source Link

Document

parseText parses the given text as an XML document and returns the newly created Document.

Usage

From source file:org.pentaho.agilebi.spoon.publish.ModelServerPublish.java

License:Open Source License

public int publishOlapSchemaToServer(String schemaName, String jndiName, String modelName,
        String schemaFilePath, boolean overwriteInRepository, boolean showFeedback,
        boolean isExistentDatasource, String publishModelFileName) throws Exception {

    File modelsDir = new File("models"); //$NON-NLS-1$
    if (!modelsDir.exists()) {
        modelsDir.mkdir();//ww w .  j a v a 2s.  c om
    }
    File publishFile;
    publishFile = new File(modelsDir, schemaName);
    publishFile.createNewFile();

    LogicalModel lModel = this.model.getLogicalModel(ModelerPerspective.ANALYSIS);

    MondrianModelExporter exporter = new MondrianModelExporter(lModel, LocalizedString.DEFAULT_LOCALE);
    String mondrianSchema = exporter.createMondrianModelXML();

    org.dom4j.Document schemaDoc = DocumentHelper.parseText(mondrianSchema);
    byte schemaBytes[] = schemaDoc.asXML().getBytes();

    if (!publishFile.exists()) {
        throw new ModelerException("Schema file does not exist"); //$NON-NLS-1$
    }

    //local file
    OutputStream out = new FileOutputStream(publishFile);
    out.write(schemaBytes);
    out.flush();
    out.close();
    //file to send to Jcr Repository
    InputStream schema = new ByteArrayInputStream(schemaBytes);

    int result = publishMondrainSchema(schema, modelName, jndiName, overwriteInRepository);
    if (result != ModelServerPublish.PUBLISH_SUCCESS && result != ModelServerPublish.PUBLISH_CATALOG_EXISTS) {
        showFeedback(result);
        return result;
    }
    result = handleModelOverwrite(jndiName, modelName, showFeedback, schemaDoc, result);

    return result;
}

From source file:org.pentaho.agilebi.spoon.visualizations.analyzer.AnalyzerVisualization.java

License:Open Source License

public static Document getXAnalyzerDocument(File file) throws Exception {

    FileInputStream in = new FileInputStream(file);
    StringBuilder sb = new StringBuilder();
    byte b[] = new byte[2048];
    int n = in.read(b);
    while (n != -1) {
        sb.append(new String(b, 0, n));
        n = in.read(b);// www  .j  a  v  a  2s.  co m
    }

    Document doc = DocumentHelper.parseText(sb.toString());

    return doc;
}

From source file:org.pentaho.agilebi.spoon.visualizations.analyzer.AnalyzerVisualization.java

License:Open Source License

public boolean open(Node transNode, String fname, boolean importfile) {
    Spoon spoon = ((Spoon) SpoonFactory.getInstance());
    try {/*w  w  w. j  a  v a 2 s.  c o m*/
        File f = new File(fname);
        reportName = f.getName();
        reportName = reportName.substring(0, reportName.indexOf(".xanalyzer")); //$NON-NLS-1$
        FileInputStream in = new FileInputStream(f);
        StringBuilder sb = new StringBuilder();
        byte b[] = new byte[2048];
        int n = in.read(b);
        while (n != -1) {
            sb.append(new String(b, 0, n));
            n = in.read(b);
        }

        Document doc = DocumentHelper.parseText(sb.toString());
        Dom4jXPath xpath = new Dom4jXPath("//@catalog"); //$NON-NLS-1$
        Dom4jXPath xpath2 = new Dom4jXPath("//@cube"); //$NON-NLS-1$
        HashMap map = new HashMap();
        map.put("pho", "http://www.pentaho.com"); //$NON-NLS-1$ //$NON-NLS-2$
        xpath.setNamespaceContext(new SimpleNamespaceContext(map));
        xpath2.setNamespaceContext(new SimpleNamespaceContext(map));
        org.dom4j.Node node = (org.dom4j.Node) xpath.selectSingleNode(doc);
        org.dom4j.Node node2 = (org.dom4j.Node) xpath2.selectSingleNode(doc);

        String modelFileName = node.getText();
        String modelId = node2.getText();

        SwtXulLoader theXulLoader = new SwtXulLoader();
        theXulLoader.registerClassLoader(getClass().getClassLoader());
        AnalyzerVisualizationController theController = new AnalyzerVisualizationController(
                spoon.tabfolder.getSwtTabset(), this, modelFileName, modelId, f.toString(), f.getName());
        theController.setDirty(false);
        XulDomContainer theXulContainer = theXulLoader.loadXul(WEB_VISUALIZATION,
                new PDIMessages(IVisualization.class));
        theXulContainer.addEventHandler(theController);
        Composite theMainBox = (Composite) theXulContainer.getDocumentRoot().getElementById("mainVBox") //$NON-NLS-1$
                .getManagedObject();
        SwtXulRunner theRunner = new SwtXulRunner();
        theRunner.addContainer(theXulContainer);
        theRunner.initialize();

        ModelerWorkspace model = new ModelerWorkspace(new SpoonModelerWorkspaceHelper(),
                SpoonModelerWorkspaceHelper.initGeoContext());
        XmiParser parser = new XmiParser();
        FileInputStream inputStream = new FileInputStream(new File(modelFileName));
        Domain domain = parser.parseXmi(inputStream);
        inputStream.close();
        if (model.getDomain() != null) {
            LogicalModel logical = model.getLogicalModel(ModelerPerspective.ANALYSIS);
            Object property = logical.getProperty("source_type"); //$NON-NLS-1$
            if (property != null) {
                IModelerSource theSource = ModelerSourceFactory.generateSource(property.toString());
                theSource.initialize(domain);
                model.setModelSource(theSource);
            }
        }
        if (domain.getId() == null) {
            domain.setId(modelId);
        }
        model.setDomain(domain);
        model.setModelName(domain.getId());
        model.setFileName(modelFileName);
        model.setTemporary(false);
        theController.setModel(model);
        theXulContainer.addEventHandler(theController);

        createTabForBrowser(theMainBox, theController, model);

        // flush the cache before opening an analyzer visualization
        flushAnalyzerCache();
        theController.openReport(fname);

        String fullPath = f.getAbsolutePath();
        spoon.getProperties().addLastFile("Analyzer", fullPath, null, false, null); //$NON-NLS-1$
        spoon.addMenuLast();
    } catch (Throwable e) {
        throw new RuntimeException(e);
    }
    return true;
}

From source file:org.pentaho.common.ui.services.SolutionRepoService.java

License:Open Source License

/**
 * Saves state into the solution repository
 *//*from  w  w w .j a  v  a2s  . c o m*/
protected StateMessage saveState(String filepath, String state, boolean stateIsXml, String type,
        Boolean replace, String title, String description) throws Exception {

    StateMessage result = new StateMessage();

    result.setStatus(StateMessage.STATUS_FAILED);
    if (StringUtils.isEmpty(filepath)) {
        result.setMessage(Messages.getErrorString("SolutionRepo.ERROR_0001_NO_FILEPATH")); //$NON-NLS-1$
        return result;
    }
    if (StringUtils.isEmpty(state)) {
        result.setMessage(Messages.getErrorString("SolutionRepo.ERROR_0002_NO_STATE")); //$NON-NLS-1$
        return result;
    }
    if (StringUtils.isEmpty(type)) {
        result.setMessage(Messages.getErrorString("SolutionRepo.ERROR_0007_NO_TYPE")); //$NON-NLS-1$
        return result;
    }
    if (replace == null) {
        replace = Boolean.FALSE;
        //      return result;
    }

    // make sure the path is good
    ActionInfo info = ActionInfo.parseActionString(filepath);
    if (info == null) {
        result.setMessage(
                Messages.getErrorString("SolutionUrlContentGenerator.ERROR_0005_BAD_FILEPATH", filepath)); //$NON-NLS-1$
        return result;
    }

    IPentahoSession userSession = PentahoSessionHolder.getSession();
    ISolutionRepository repo = PentahoSystem.get(ISolutionRepository.class, userSession);

    // create the state file to save
    Document doc = DocumentHelper.createDocument();
    Element root = doc.addElement("state-file"); //$NON-NLS-1$
    Element documentation = root.addElement("documentation"); //$NON-NLS-1$
    documentation.addElement("author").addCDATA(userSession.getName()); //$NON-NLS-1$

    if (stateIsXml) {
        Element stateElement = root.addElement("state-xml"); //$NON-NLS-1$
        Document stateDoc = null;
        try {
            stateDoc = DocumentHelper.parseText(state);
        } catch (Exception e) {
            result.setMessage(Messages.getErrorString("SolutionRepo.ERROR_0009_BAD_STATE", state)); //$NON-NLS-1$
            return result;
        }
        Node stateRoot = stateDoc.getRootElement();
        stateRoot = stateRoot.detach();
        stateElement.add(stateRoot);
    } else {
        Element stateElement = root.addElement("state-text"); //$NON-NLS-1$
        stateElement.addCDATA(state);
    }

    documentation.addElement("title").addCDATA(title); //$NON-NLS-1$
    documentation.addElement("description").addCDATA(description); //$NON-NLS-1$

    String fileName = info.getActionName();
    if (!fileName.endsWith('.' + type)) {
        fileName = fileName + '.' + type;
    }

    // see if we can find a content generator to get the file icon
    IPluginManager pluginManager = PentahoSystem.get(IPluginManager.class, userSession);
    if (pluginManager != null) {
        //      IContentInfo contentInfo = pluginManager.getContentInfoFromExtension(type, userSession);
        IContentInfo contentInfo = pluginManager.getContentTypeInfo(type);
        if (contentInfo != null) {
            String icon = contentInfo.getIconUrl();
            documentation.addElement("icon").addCDATA(icon); //$NON-NLS-1$
        }
    }

    String basePath = PentahoSystem.getApplicationContext().getSolutionRootPath();
    if (!basePath.endsWith("" + ISolutionRepository.SEPARATOR)) { //$NON-NLS-1$
        basePath = basePath + ISolutionRepository.SEPARATOR;
    }
    // save the file
    int ret = repo.addSolutionFile(basePath, info.getSolutionName() + '/' + info.getPath(), fileName,
            doc.asXML().getBytes(), replace);

    if (ret == ISolutionRepository.FILE_EXISTS) {
        result.setMessage(Messages.getErrorString("SolutionRepo.ERROR_0004_CANNOT_REPLACE")); //$NON-NLS-1$
        return result;
    } else if (ret == ISolutionRepository.FILE_ADD_INVALID_USER_CREDENTIALS) {
        result.setMessage(Messages.getErrorString("SolutionRepo.ERROR_0005_CREDENTIALS")); //$NON-NLS-1$
        return result;
    } else if (ret != ISolutionRepository.FILE_ADD_SUCCESSFUL) {
        result.setMessage(Messages.getErrorString("SolutionRepo.ERROR_0006_SAVE_FAILED")); //$NON-NLS-1$
        return result;
    }

    result.setStatus(StateMessage.STATUS_SUCCESS);
    result.setMessage(Messages.getString("SolutionRepo.USER_FILE_SAVE")); //$NON-NLS-1$
    return result;
}

From source file:org.pentaho.common.ui.test.MockSolutionRepository.java

License:Open Source License

public Document getResourceAsDocument(String path) throws IOException {

    String xml = files.get(path);
    if (xml == null) {
        return null;
    }//  w w  w  .j av  a  2s.  com
    try {
        return DocumentHelper.parseText(xml);
    } catch (DocumentException e) {
        return null;
    }
}

From source file:org.pentaho.pac.server.config.AbstractDiagnosticsJmxXml.java

License:Open Source License

public AbstractDiagnosticsJmxXml(String jmxXml) throws DocumentException {
    this(DocumentHelper.parseText(jmxXml));
}

From source file:org.pentaho.pac.server.config.ConsoleConfigXml.java

License:Open Source License

public ConsoleConfigXml(String xml) throws DocumentException {
    this(DocumentHelper.parseText(xml));
}

From source file:org.pentaho.platform.dataaccess.client.ConnectionServiceClient.java

License:Open Source License

/**
 * Submits an HTTP result with the provided HTTPMethod and returns a dom4j document of the
 * response/*from   w  ww . jav  a2s .  c  om*/
 * @param callMethod
 * @return
 * @throws ConnectionServiceException
 */
protected Document getResultDocument(HttpMethod callMethod) throws ConnectionServiceException {

    try {
        HttpClient client = getClient();
        // execute the HTTP call
        int status = client.executeMethod(callMethod);
        if (status != HttpStatus.SC_OK) {
            throw new ConnectionServiceException("Web service call failed with code " + status); //$NON-NLS-1$
        }
        // get the result as a string
        InputStream in = callMethod.getResponseBodyAsStream();
        byte buffer[] = new byte[2048];
        int n = in.read(buffer);
        StringBuilder sb = new StringBuilder();
        while (n != -1) {
            sb.append(new String(buffer, 0, n));
            n = in.read(buffer);
        }
        String result = sb.toString();
        // convert to XML
        return DocumentHelper.parseText(result);
    } catch (IOException e) {
        throw new ConnectionServiceException(e);
    } catch (DocumentException e) {
        throw new ConnectionServiceException(e);
    }

}

From source file:org.pentaho.platform.dataaccess.datasource.wizard.service.impl.ModelerService.java

License:Open Source License

public String serializeModels(Domain domain, String name, boolean doOlap) throws Exception {
    String domainId = null;/*from   w w  w.  ja va  2  s .c  o  m*/
    initKettle();

    try {
        ModelerWorkspace model = new ModelerWorkspace(new GwtModelerWorkspaceHelper());
        model.setModelName(name);
        model.setDomain(domain);
        String solutionStorage = AgileHelper.getDatasourceSolutionStorage();

        String metadataLocation = "resources" + ISolutionRepository.SEPARATOR + "metadata"; //$NON-NLS-1$  //$NON-NLS-2$

        String path = solutionStorage + ISolutionRepository.SEPARATOR + metadataLocation
                + ISolutionRepository.SEPARATOR;
        domainId = path + name + ".xmi"; //$NON-NLS-1$ 
        domain.setId(domainId);

        IApplicationContext appContext = PentahoSystem.getApplicationContext();
        if (appContext != null) {
            path = PentahoSystem.getApplicationContext().getSolutionPath(path);
        }

        File pathDir = new File(path);
        if (!pathDir.exists()) {
            pathDir.mkdirs();
        }

        IPentahoObjectFactory pentahoObjectFactory = PentahoSystem.getObjectFactory();
        IPentahoSession session = pentahoObjectFactory.get(IPentahoSession.class, "systemStartupSession", null); //$NON-NLS-1$

        ISolutionRepository repository = PentahoSystem.get(ISolutionRepository.class, session);

        LogicalModel lModel = domain.getLogicalModels().get(0);
        String catName = lModel.getName(Locale.getDefault().toString());

        cleanseExistingCatalog(catName, session);
        if (doOlap) {
            lModel.setProperty("MondrianCatalogRef", catName); //$NON-NLS-1$
        }
        XmiParser parser = new XmiParser();
        String reportXML = parser.generateXmi(model.getDomain());

        // Serialize domain to xmi.
        String base = PentahoSystem.getApplicationContext().getSolutionRootPath();
        String parentPath = ActionInfo.buildSolutionPath(solutionStorage, metadataLocation, ""); //$NON-NLS-1$
        int status = repository.publish(base, '/' + parentPath, name + ".xmi", reportXML.getBytes("UTF-8"), //$NON-NLS-1$//$NON-NLS-2$
                true);
        if (status != ISolutionRepository.FILE_ADD_SUCCESSFUL) {
            throw new RuntimeException("Unable to save to repository. Status: " + status); //$NON-NLS-1$
        }

        // Serialize domain to olap schema.
        if (doOlap) {
            MondrianModelExporter exporter = new MondrianModelExporter(lModel, Locale.getDefault().toString());
            String mondrianSchema = exporter.createMondrianModelXML();
            Document schemaDoc = DocumentHelper.parseText(mondrianSchema);
            byte[] schemaBytes = schemaDoc.asXML().getBytes("UTF-8"); //$NON-NLS-1$

            status = repository.publish(base, '/' + parentPath, name + ".mondrian.xml", schemaBytes, true); //$NON-NLS-1$
            if (status != ISolutionRepository.FILE_ADD_SUCCESSFUL) {
                throw new RuntimeException("Unable to save to repository. Status: " + status); //$NON-NLS-1$
            }

            // Refresh Metadata
            PentahoSystem.publish(session, MetadataPublisher.class.getName());

            // Write this catalog to the default Pentaho DataSource and refresh the cache.
            File file = new File(path + name + ".mondrian.xml"); //$NON-NLS-1$
            // Need to find a better way to get the connection name instead of using the Id.
            String catConnectStr = "Provider=mondrian;DataSource=" //$NON-NLS-1$
                    + ((SqlPhysicalModel) domain.getPhysicalModels().get(0)).getId();
            String catDef = "solution:" + solutionStorage + ISolutionRepository.SEPARATOR //$NON-NLS-1$
                    + "resources" + ISolutionRepository.SEPARATOR + "metadata" + ISolutionRepository.SEPARATOR //$NON-NLS-1$//$NON-NLS-2$
                    + file.getName();
            addCatalog(catName, catConnectStr, catDef, session);
        }

    } catch (Exception e) {
        logger.error(e);
        throw e;
    }
    return domainId;
}

From source file:org.pentaho.platform.plugin.adhoc.AdhocWebServiceInteract.java

License:Open Source License

public static void interactiveOutput(final String reportStr, final OutputStream out,
        final IPentahoSession session) {

    try {//from  w  w  w  . j  a va2 s.  c o  m
        //          System.out.println( "interactiveOutput 1" );
        Document reportXml = DocumentHelper.parseText(reportStr);
        //          System.out.println( "interactiveOutput 2" );
        Document reportDoc = AdhocWebServiceInteractXml.convertXml(reportXml);
        //          System.out.println( "interactiveOutput 3" );
        //          System.out.println( reportDoc.asXML() );

        StringBuffer sb = XmlHelper.transformXml("iwaqr-report.xsl", "adhoc", reportDoc.asXML(), //$NON-NLS-1$//$NON-NLS-2$
                new HashMap<String, String>(), new SolutionURIResolver());
        //          System.out.println( "interactiveOutput 4" );

        //          System.out.println( sb.toString() );

        out.write(sb.toString().getBytes());
        //          System.out.println( "interactiveOutput 5" );

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

}