Search in sources :

Example 31 with DBException

use of org.jkiss.dbeaver.DBException in project dbeaver by serge-rider.

the class DiagramLoader method save.

public static void save(DBRProgressMonitor monitor, DiagramPart diagramPart, final EntityDiagram diagram, boolean verbose, OutputStream out) throws IOException {
    // Prepare DS objects map
    Map<DBPDataSourceContainer, DataSourceObjects> dsMap = new IdentityHashMap<>();
    if (diagram != null) {
        for (ERDEntity erdEntity : diagram.getEntities()) {
            final DBPDataSourceContainer dsContainer = erdEntity.getObject().getDataSource().getContainer();
            DataSourceObjects desc = dsMap.get(dsContainer);
            if (desc == null) {
                desc = new DataSourceObjects();
                dsMap.put(dsContainer, desc);
            }
            desc.entities.add(erdEntity);
        }
    }
    Map<ERDEntity, TableSaveInfo> infoMap = new IdentityHashMap<>();
    // Save as XML
    XMLBuilder xml = new XMLBuilder(out, GeneralUtils.UTF8_ENCODING);
    xml.setButify(true);
    if (verbose) {
        xml.addContent("\n<!DOCTYPE diagram [\n" + "<!ATTLIST diagram version CDATA #REQUIRED\n" + " name CDATA #IMPLIED\n" + " time CDATA #REQUIRED>\n" + "<!ELEMENT diagram (entities, relations, notes)>\n" + "<!ELEMENT entities (data-source*)>\n" + "<!ELEMENT data-source (entity*)>\n" + "<!ATTLIST data-source id CDATA #REQUIRED>\n" + "<!ELEMENT entity (path*)>\n" + "<!ATTLIST entity id ID #REQUIRED\n" + " name CDATA #REQUIRED\n" + " fq-name CDATA #REQUIRED>\n" + "<!ELEMENT relations (relation*)>\n" + "<!ELEMENT relation (bend*)>\n" + "<!ATTLIST relation name CDATA #REQUIRED\n" + " fq-name CDATA #REQUIRED\n" + " pk-ref IDREF #REQUIRED\n" + " fk-ref IDREF #REQUIRED>\n" + "]>\n");
    }
    xml.startElement(TAG_DIAGRAM);
    xml.addAttribute(ATTR_VERSION, ERD_VERSION_1);
    if (diagram != null) {
        xml.addAttribute(ATTR_NAME, diagram.getName());
    }
    xml.addAttribute(ATTR_TIME, RuntimeUtils.getCurrentTimeStamp());
    if (diagram != null) {
        xml.startElement(TAG_ENTITIES);
        for (DBPDataSourceContainer dsContainer : dsMap.keySet()) {
            xml.startElement(TAG_DATA_SOURCE);
            xml.addAttribute(ATTR_ID, dsContainer.getId());
            final DataSourceObjects desc = dsMap.get(dsContainer);
            int tableCounter = ERD_VERSION_1;
            for (ERDEntity erdEntity : desc.entities) {
                final DBSEntity table = erdEntity.getObject();
                EntityPart tablePart = diagramPart == null ? null : diagramPart.getEntityPart(erdEntity);
                TableSaveInfo info = new TableSaveInfo(erdEntity, tablePart, tableCounter++);
                infoMap.put(erdEntity, info);
                xml.startElement(TAG_ENTITY);
                xml.addAttribute(ATTR_ID, info.objectId);
                xml.addAttribute(ATTR_NAME, table.getName());
                if (table instanceof DBPQualifiedObject) {
                    xml.addAttribute(ATTR_FQ_NAME, ((DBPQualifiedObject) table).getFullyQualifiedName(DBPEvaluationContext.UI));
                }
                Rectangle tableBounds;
                if (tablePart != null) {
                    tableBounds = tablePart.getBounds();
                } else {
                    tableBounds = diagram.getInitBounds(erdEntity);
                }
                if (tableBounds != null) {
                    xml.addAttribute(ATTR_X, tableBounds.x);
                    xml.addAttribute(ATTR_Y, tableBounds.y);
                }
                for (DBSObject parent = table.getParentObject(); parent != null && parent != dsContainer; parent = parent.getParentObject()) {
                    xml.startElement(TAG_PATH);
                    xml.addAttribute(ATTR_NAME, parent.getName());
                    xml.endElement();
                }
                xml.endElement();
            }
            xml.endElement();
        }
        xml.endElement();
        // Relations
        xml.startElement(TAG_RELATIONS);
        for (ERDEntity erdEntity : diagram.getEntities()) {
            for (ERDAssociation rel : erdEntity.getPrimaryKeyRelationships()) {
                xml.startElement(TAG_RELATION);
                DBSEntityAssociation association = rel.getObject();
                xml.addAttribute(ATTR_NAME, association.getName());
                if (association instanceof DBPQualifiedObject) {
                    xml.addAttribute(ATTR_FQ_NAME, ((DBPQualifiedObject) association).getFullyQualifiedName(DBPEvaluationContext.UI));
                }
                xml.addAttribute(ATTR_TYPE, association.getConstraintType().getId());
                TableSaveInfo pkInfo = infoMap.get(rel.getPrimaryKeyEntity());
                if (pkInfo == null) {
                    log.error("Cannot find PK table '" + DBUtils.getObjectFullName(rel.getPrimaryKeyEntity().getObject(), DBPEvaluationContext.UI) + "' in info map");
                    continue;
                }
                TableSaveInfo fkInfo = infoMap.get(rel.getForeignKeyEntity());
                if (fkInfo == null) {
                    log.error("Cannot find FK table '" + DBUtils.getObjectFullName(rel.getForeignKeyEntity().getObject(), DBPEvaluationContext.UI) + "' in info map");
                    continue;
                }
                xml.addAttribute(ATTR_PK_REF, pkInfo.objectId);
                xml.addAttribute(ATTR_FK_REF, fkInfo.objectId);
                if (association instanceof ERDLogicalForeignKey) {
                    // Save columns
                    for (DBSEntityAttributeRef column : ((ERDLogicalForeignKey) association).getAttributeReferences(VoidProgressMonitor.INSTANCE)) {
                        xml.startElement(TAG_COLUMN);
                        xml.addAttribute(ATTR_NAME, column.getAttribute().getName());
                        try {
                            xml.addAttribute(ATTR_REF_NAME, DBUtils.getReferenceAttribute(monitor, association, column.getAttribute()).getName());
                        } catch (DBException e) {
                            log.warn("Error getting reference attribute", e);
                        }
                        xml.endElement();
                    }
                }
                // Save bends
                if (pkInfo.tablePart != null) {
                    AssociationPart associationPart = pkInfo.tablePart.getConnectionPart(rel, false);
                    if (associationPart != null) {
                        final List<Bendpoint> bendpoints = associationPart.getBendpoints();
                        if (!CommonUtils.isEmpty(bendpoints)) {
                            for (Bendpoint bendpoint : bendpoints) {
                                xml.startElement(TAG_BEND);
                                if (bendpoint instanceof AbsoluteBendpoint) {
                                    xml.addAttribute(ATTR_TYPE, BEND_ABSOLUTE);
                                    xml.addAttribute(ATTR_X, bendpoint.getLocation().x);
                                    xml.addAttribute(ATTR_Y, bendpoint.getLocation().y);
                                } else if (bendpoint instanceof RelativeBendpoint) {
                                    xml.addAttribute(ATTR_TYPE, BEND_RELATIVE);
                                    xml.addAttribute(ATTR_X, bendpoint.getLocation().x);
                                    xml.addAttribute(ATTR_Y, bendpoint.getLocation().y);
                                }
                                xml.endElement();
                            }
                        }
                    }
                }
                xml.endElement();
            }
        }
        xml.endElement();
        // Notes
        xml.startElement(TAG_NOTES);
        for (ERDNote note : diagram.getNotes()) {
            NotePart notePart = diagramPart == null ? null : diagramPart.getNotePart(note);
            xml.startElement(TAG_NOTE);
            if (notePart != null) {
                Rectangle noteBounds = notePart.getBounds();
                if (noteBounds != null) {
                    xml.addAttribute(ATTR_X, noteBounds.x);
                    xml.addAttribute(ATTR_Y, noteBounds.y);
                    xml.addAttribute(ATTR_W, noteBounds.width);
                    xml.addAttribute(ATTR_H, noteBounds.height);
                }
            }
            xml.addText(note.getObject());
            xml.endElement();
        }
        xml.endElement();
    }
    xml.endElement();
    xml.flush();
}
Also used : DBException(org.jkiss.dbeaver.DBException) Rectangle(org.eclipse.draw2d.geometry.Rectangle) XMLBuilder(org.jkiss.utils.xml.XMLBuilder) AbsoluteBendpoint(org.eclipse.draw2d.AbsoluteBendpoint) AbsoluteBendpoint(org.eclipse.draw2d.AbsoluteBendpoint) Point(org.eclipse.draw2d.geometry.Point) RelativeBendpoint(org.eclipse.draw2d.RelativeBendpoint) Bendpoint(org.eclipse.draw2d.Bendpoint) RelativeBendpoint(org.eclipse.draw2d.RelativeBendpoint) NotePart(org.jkiss.dbeaver.ext.erd.part.NotePart) AssociationPart(org.jkiss.dbeaver.ext.erd.part.AssociationPart) EntityPart(org.jkiss.dbeaver.ext.erd.part.EntityPart) AbsoluteBendpoint(org.eclipse.draw2d.AbsoluteBendpoint) RelativeBendpoint(org.eclipse.draw2d.RelativeBendpoint) Bendpoint(org.eclipse.draw2d.Bendpoint)

Example 32 with DBException

use of org.jkiss.dbeaver.DBException in project dbeaver by serge-rider.

the class DiagramObjectCollector method generateEntityList.

public static List<ERDEntity> generateEntityList(final EntityDiagram diagram, Collection<DBPNamedObject> objects) {
    final List<DBSObject> roots = new ArrayList<>();
    for (DBPNamedObject object : objects) {
        if (object instanceof DBSObject) {
            roots.add((DBSObject) object);
        }
    }
    final List<ERDEntity> entities = new ArrayList<>();
    try {
        DBeaverUI.runInProgressService(new DBRRunnableWithProgress() {

            @Override
            public void run(DBRProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                DiagramObjectCollector collector = new DiagramObjectCollector(diagram);
                try {
                    collector.generateDiagramObjects(monitor, roots);
                } catch (DBException e) {
                    throw new InvocationTargetException(e);
                }
                entities.addAll(collector.getDiagramEntities());
            }
        });
    } catch (InvocationTargetException e) {
        log.error(e.getTargetException());
    } catch (InterruptedException e) {
    // interrupted
    }
    return entities;
}
Also used : DBException(org.jkiss.dbeaver.DBException) DBPNamedObject(org.jkiss.dbeaver.model.DBPNamedObject) InvocationTargetException(java.lang.reflect.InvocationTargetException) DBRRunnableWithProgress(org.jkiss.dbeaver.model.runtime.DBRRunnableWithProgress) DBRProgressMonitor(org.jkiss.dbeaver.model.runtime.DBRProgressMonitor)

Example 33 with DBException

use of org.jkiss.dbeaver.DBException in project dbeaver by serge-rider.

the class ERDEditorStandalone method loadDiagram.

/*
    protected void createActions()
    {
        super.createActions();

        //addEditorAction(new SaveAction(this));
    }
*/
@Override
protected synchronized void loadDiagram(boolean refreshMetadata) {
    if (diagramLoadingJob != null) {
        // Do not start new one while old is running
        return;
    }
    diagramLoadingJob = LoadingJob.createService(new AbstractLoadService<EntityDiagram>("Load diagram '" + getEditorInput().getName() + "'") {

        @Override
        public EntityDiagram evaluate(DBRProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
            try {
                return loadContentFromFile(monitor);
            } catch (DBException e) {
                log.error(e);
            }
            return null;
        }

        @Override
        public Object getFamily() {
            return ERDEditorStandalone.this;
        }
    }, progressControl.createLoadVisualizer());
    diagramLoadingJob.addJobChangeListener(new JobChangeAdapter() {

        @Override
        public void done(IJobChangeEvent event) {
            diagramLoadingJob = null;
        }
    });
    diagramLoadingJob.schedule();
    setPartName(getEditorInput().getName());
}
Also used : DBException(org.jkiss.dbeaver.DBException) AbstractLoadService(org.jkiss.dbeaver.model.runtime.load.AbstractLoadService) JobChangeAdapter(org.eclipse.core.runtime.jobs.JobChangeAdapter) DBRProgressMonitor(org.jkiss.dbeaver.model.runtime.DBRProgressMonitor) IJobChangeEvent(org.eclipse.core.runtime.jobs.IJobChangeEvent)

Example 34 with DBException

use of org.jkiss.dbeaver.DBException in project dbeaver by serge-rider.

the class DerbyMetaModel method loadSequences.

@Override
public List<GenericSequence> loadSequences(@NotNull DBRProgressMonitor monitor, @NotNull GenericStructContainer container) throws DBException {
    try (JDBCSession session = DBUtils.openMetaSession(monitor, container.getDataSource(), "Read procedure definition")) {
        try (JDBCPreparedStatement dbStat = session.prepareStatement("SELECT seq.SEQUENCENAME,seq.CURRENTVALUE,seq.MINIMUMVALUE,seq.MAXIMUMVALUE,seq.INCREMENT\n" + "FROM sys.SYSSEQUENCES seq,sys.SYSSCHEMAS s\n" + "WHERE seq.SCHEMAID=s.SCHEMAID AND s.SCHEMANAME=?")) {
            dbStat.setString(1, container.getName());
            try (JDBCResultSet dbResult = dbStat.executeQuery()) {
                List<GenericSequence> result = new ArrayList<GenericSequence>();
                while (dbResult.next()) {
                    GenericSequence sequence = new GenericSequence(container, JDBCUtils.safeGetString(dbResult, 1), "", JDBCUtils.safeGetLong(dbResult, 2), JDBCUtils.safeGetLong(dbResult, 3), JDBCUtils.safeGetLong(dbResult, 4), JDBCUtils.safeGetLong(dbResult, 5));
                    result.add(sequence);
                }
                return result;
            }
        }
    } catch (SQLException e) {
        throw new DBException(e, container.getDataSource());
    }
}
Also used : JDBCPreparedStatement(org.jkiss.dbeaver.model.exec.jdbc.JDBCPreparedStatement) JDBCSession(org.jkiss.dbeaver.model.exec.jdbc.JDBCSession) DBException(org.jkiss.dbeaver.DBException) SQLException(java.sql.SQLException) JDBCResultSet(org.jkiss.dbeaver.model.exec.jdbc.JDBCResultSet) ArrayList(java.util.ArrayList)

Example 35 with DBException

use of org.jkiss.dbeaver.DBException in project dbeaver by serge-rider.

the class DefaultCertificateStorage method addCertificate.

@Override
public void addCertificate(DBPDataSourceContainer dataSource, String certType, byte[] caCertData, byte[] clientCertData, byte[] keyData) throws DBException {
    final KeyStore keyStore = getKeyStore(dataSource, certType);
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        List<Certificate> certChain = new ArrayList<>();
        if (caCertData != null) {
            Certificate caCert = cf.generateCertificate(new ByteArrayInputStream(caCertData));
            keyStore.setCertificateEntry("ca-cert", caCert);
        //certChain.add(caCert);
        }
        if (clientCertData != null) {
            Certificate clientCert = cf.generateCertificate(new ByteArrayInputStream(clientCertData));
            keyStore.setCertificateEntry("client-cert", clientCert);
            certChain.add(clientCert);
        }
        if (keyData != null) {
            PrivateKey privateKey = loadPrivateKeyFromPEM(keyData);
            keyStore.setKeyEntry("key-cert", privateKey, DEFAULT_PASSWORD, certChain.toArray(new Certificate[certChain.size()]));
        }
        saveKeyStore(dataSource, certType, keyStore);
    } catch (Throwable e) {
        throw new DBException("Error adding certificate to keystore", e);
    }
}
Also used : DBException(org.jkiss.dbeaver.DBException) PrivateKey(java.security.PrivateKey) ArrayList(java.util.ArrayList) KeyStore(java.security.KeyStore) CertificateFactory(java.security.cert.CertificateFactory) Certificate(java.security.cert.Certificate)

Aggregations

DBException (org.jkiss.dbeaver.DBException)232 SQLException (java.sql.SQLException)58 JDBCSession (org.jkiss.dbeaver.model.exec.jdbc.JDBCSession)51 JDBCResultSet (org.jkiss.dbeaver.model.exec.jdbc.JDBCResultSet)50 DBRProgressMonitor (org.jkiss.dbeaver.model.runtime.DBRProgressMonitor)43 JDBCPreparedStatement (org.jkiss.dbeaver.model.exec.jdbc.JDBCPreparedStatement)42 ArrayList (java.util.ArrayList)37 InvocationTargetException (java.lang.reflect.InvocationTargetException)23 DBSObject (org.jkiss.dbeaver.model.struct.DBSObject)23 DBNDatabaseNode (org.jkiss.dbeaver.model.navigator.DBNDatabaseNode)16 DBRRunnableWithProgress (org.jkiss.dbeaver.model.runtime.DBRRunnableWithProgress)14 DBPDataSource (org.jkiss.dbeaver.model.DBPDataSource)13 DBNNode (org.jkiss.dbeaver.model.navigator.DBNNode)13 GridData (org.eclipse.swt.layout.GridData)12 DBCException (org.jkiss.dbeaver.model.exec.DBCException)12 CoreException (org.eclipse.core.runtime.CoreException)11 AbstractObjectReference (org.jkiss.dbeaver.model.impl.struct.AbstractObjectReference)10 IStatus (org.eclipse.core.runtime.IStatus)9 DBSEntityAttribute (org.jkiss.dbeaver.model.struct.DBSEntityAttribute)8 XMLException (org.jkiss.utils.xml.XMLException)8