Olá pessoal, gostaria de tirar uma dúvida.
Estou desenvolvendo um projeto usando o GMF, porém preciso persistir dados a partir das classes auto geradas.
mas quando faço a instância da classe de persistência (não só ela, como qualquer outra) ele da um erro.
“Projeto/pacote/classe/Classe”
Detalhe: basta eu escrever:
Persistence p = new Persistence();
que ele dá logo um erro e não apresenta nenhuma excessão
tanto a classe de persistencia quanto a classe auto-gerada pelo GMF é PUBLIC
Vou descrever +/- como está aki no projeto:
existe um projeto de persistencia.
e separadamente existem 3 projetos do GMF, um que é o principal (projeto), e outros dois auto-gerados (projeto.edit e projeto.diagram). O “projeto.diagram”, que é onde tem a classe que termina com …DiagramEditorUtil.java contêm o método public static Map getSaveOptions() que é o método chamado quando o usuario salva o diagrama, daí eu pretendo instanciar a classe contida no .jar do projeto de persistencia, observem:
public static Map getSaveOptions() {
Map saveOptions = new HashMap();
saveOptions.put(XMLResource.OPTION_ENCODING, "UTF-8"); //$NON-NLS-1$
saveOptions.put(Resource.OPTION_SAVE_ONLY_IF_CHANGED,
Resource.OPTION_SAVE_ONLY_IF_CHANGED_MEMORY_BUFFER);
IPersistence p = new Persistence();
p.save("Teste", "Descrição", new Date(System.currentTimeMillis())); // nome, descrição e data atual
return saveOptions;
}
Este trecho acima corresponde ao método getSaveOptions da classe abaixo
/**
* @generated
*/
public class ClassDiagramDiagramEditorUtil {
/**
* @generated
*/
public static Map getSaveOptions() {
Map saveOptions = new HashMap();
saveOptions.put(XMLResource.OPTION_ENCODING, "UTF-8"); //$NON-NLS-1$
saveOptions.put(Resource.OPTION_SAVE_ONLY_IF_CHANGED,
Resource.OPTION_SAVE_ONLY_IF_CHANGED_MEMORY_BUFFER);
return saveOptions;
}
/**
* @generated
*/
public static boolean openDiagram(Resource diagram)
throws PartInitException {
IWorkbenchPage page = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getActivePage();
page.openEditor(new URIEditorInput(diagram.getURI()),
classDiagram.diagram.part.ClassDiagramDiagramEditor.ID);
return true;
}
/**
* @generated
*/
public static String getUniqueFileName(IPath containerFullPath,
String fileName, String extension) {
if (containerFullPath == null) {
containerFullPath = new Path(""); //$NON-NLS-1$
}
if (fileName == null || fileName.trim().length() == 0) {
fileName = "default"; //$NON-NLS-1$
}
IPath filePath = containerFullPath.append(fileName);
if (extension != null && !extension.equals(filePath.getFileExtension())) {
filePath = filePath.addFileExtension(extension);
}
extension = filePath.getFileExtension();
fileName = filePath.removeFileExtension().lastSegment();
int i = 1;
while (filePath.toFile().exists()) {
i++;
filePath = containerFullPath.append(fileName + i);
if (extension != null) {
filePath = filePath.addFileExtension(extension);
}
}
return filePath.lastSegment();
}
/**
* Allows user to select file and loads it as a model.
*
* @generated
*/
public static Resource openModel(Shell shell, String description,
TransactionalEditingDomain editingDomain) {
FileDialog fileDialog = new FileDialog(shell, SWT.OPEN);
if (description != null) {
fileDialog.setText(description);
}
fileDialog.open();
String fileName = fileDialog.getFileName();
if (fileName == null || fileName.length() == 0) {
return null;
}
if (fileDialog.getFilterPath() != null) {
fileName = fileDialog.getFilterPath() + File.separator + fileName;
}
URI uri = URI.createFileURI(fileName);
Resource resource = null;
try {
resource = editingDomain.getResourceSet().getResource(uri, true);
} catch (WrappedException we) {
classDiagram.diagram.part.ClassDiagramDiagramEditorPlugin
.getInstance().logError(
"Unable to load resource: " + uri, we); //$NON-NLS-1$
MessageDialog
.openError(
shell,
classDiagram.diagram.part.Messages.ClassDiagramDiagramEditorUtil_OpenModelResourceErrorDialogTitle,
NLS
.bind(
classDiagram.diagram.part.Messages.ClassDiagramDiagramEditorUtil_OpenModelResourceErrorDialogMessage,
fileName));
}
return resource;
}
/**
* Runs the wizard in a dialog.
*
* @generated
*/
public static void runWizard(Shell shell, Wizard wizard, String settingsKey) {
IDialogSettings pluginDialogSettings = classDiagram.diagram.part.ClassDiagramDiagramEditorPlugin
.getInstance().getDialogSettings();
IDialogSettings wizardDialogSettings = pluginDialogSettings
.getSection(settingsKey);
if (wizardDialogSettings == null) {
wizardDialogSettings = pluginDialogSettings
.addNewSection(settingsKey);
}
wizard.setDialogSettings(wizardDialogSettings);
WizardDialog dialog = new WizardDialog(shell, wizard);
dialog.create();
dialog.getShell().setSize(Math.max(500, dialog.getShell().getSize().x),
500);
dialog.open();
}
/**
* @generated
*/
public static Resource createDiagram(URI diagramURI, URI modelURI,
IProgressMonitor progressMonitor) {
TransactionalEditingDomain editingDomain = GMFEditingDomainFactory.INSTANCE
.createEditingDomain();
progressMonitor
.beginTask(
classDiagram.diagram.part.Messages.ClassDiagramDiagramEditorUtil_CreateDiagramProgressTask,
3);
final Resource diagramResource = editingDomain.getResourceSet()
.createResource(diagramURI);
final Resource modelResource = editingDomain.getResourceSet()
.createResource(modelURI);
final String diagramName = diagramURI.lastSegment();
AbstractTransactionalCommand command = new AbstractTransactionalCommand(
editingDomain,
classDiagram.diagram.part.Messages.ClassDiagramDiagramEditorUtil_CreateDiagramCommandLabel,
Collections.EMPTY_LIST) {
protected CommandResult doExecuteWithResult(
IProgressMonitor monitor, IAdaptable info)
throws ExecutionException {
classDiagram.ProcessEditor model = createInitialModel();
attachModelToResource(model, modelResource);
Diagram diagram = ViewService
.createDiagram(
model,
classDiagram.diagram.edit.parts.ProcessEditorEditPart.MODEL_ID,
classDiagram.diagram.part.ClassDiagramDiagramEditorPlugin.DIAGRAM_PREFERENCES_HINT);
if (diagram != null) {
diagramResource.getContents().add(diagram);
diagram.setName(diagramName);
diagram.setElement(model);
}
try {
modelResource
.save(classDiagram.diagram.part.ClassDiagramDiagramEditorUtil
.getSaveOptions());
diagramResource
.save(classDiagram.diagram.part.ClassDiagramDiagramEditorUtil
.getSaveOptions());
} catch (IOException e) {
classDiagram.diagram.part.ClassDiagramDiagramEditorPlugin
.getInstance()
.logError(
"Unable to store model and diagram resources", e); //$NON-NLS-1$
}
return CommandResult.newOKCommandResult();
}
};
try {
OperationHistoryFactory.getOperationHistory().execute(command,
new SubProgressMonitor(progressMonitor, 1), null);
} catch (ExecutionException e) {
classDiagram.diagram.part.ClassDiagramDiagramEditorPlugin
.getInstance().logError(
"Unable to create model and diagram", e); //$NON-NLS-1$
}
return diagramResource;
}
/**
* Create a new instance of domain element associated with canvas. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
private static classDiagram.ProcessEditor createInitialModel() {
return classDiagram.ClassDiagramFactory.eINSTANCE.createProcessEditor();
}
/**
* Store model element in the resource. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @generated
*/
private static void attachModelToResource(classDiagram.ProcessEditor model,
Resource resource) {
resource.getContents().add(model);
}
/**
* @generated
*/
public static void selectElementsInDiagram(
IDiagramWorkbenchPart diagramPart, List/* EditPart */editParts) {
diagramPart.getDiagramGraphicalViewer().deselectAll();
EditPart firstPrimary = null;
for (Iterator it = editParts.iterator(); it.hasNext();) {
EditPart nextPart = (EditPart) it.next();
diagramPart.getDiagramGraphicalViewer().appendSelection(nextPart);
if (firstPrimary == null && nextPart instanceof IPrimaryEditPart) {
firstPrimary = nextPart;
}
}
if (!editParts.isEmpty()) {
diagramPart.getDiagramGraphicalViewer().reveal(
firstPrimary != null ? firstPrimary : (EditPart) editParts
.get(0));
}
}
/**
* @generated
*/
private static int findElementsInDiagramByID(DiagramEditPart diagramPart,
EObject element, List editPartCollector) {
IDiagramGraphicalViewer viewer = (IDiagramGraphicalViewer) diagramPart
.getViewer();
final int intialNumOfEditParts = editPartCollector.size();
if (element instanceof View) { // support notation element lookup
EditPart editPart = (EditPart) viewer.getEditPartRegistry().get(
element);
if (editPart != null) {
editPartCollector.add(editPart);
return 1;
}
}
String elementID = EMFCoreUtil.getProxyID(element);
List associatedParts = viewer.findEditPartsForElement(elementID,
IGraphicalEditPart.class);
// perform the possible hierarchy disjoint -> take the top-most parts
// only
for (Iterator editPartIt = associatedParts.iterator(); editPartIt
.hasNext();) {
EditPart nextPart = (EditPart) editPartIt.next();
EditPart parentPart = nextPart.getParent();
while (parentPart != null && !associatedParts.contains(parentPart)) {
parentPart = parentPart.getParent();
}
if (parentPart == null) {
editPartCollector.add(nextPart);
}
}
if (intialNumOfEditParts == editPartCollector.size()) {
if (!associatedParts.isEmpty()) {
editPartCollector.add(associatedParts.iterator().next());
} else {
if (element.eContainer() != null) {
return findElementsInDiagramByID(diagramPart, element
.eContainer(), editPartCollector);
}
}
}
return editPartCollector.size() - intialNumOfEditParts;
}
/**
* @generated
*/
public static View findView(DiagramEditPart diagramEditPart,
EObject targetElement, LazyElement2ViewMap lazyElement2ViewMap) {
boolean hasStructuralURI = false;
if (targetElement.eResource() instanceof XMLResource) {
hasStructuralURI = ((XMLResource) targetElement.eResource())
.getID(targetElement) == null;
}
View view = null;
if (hasStructuralURI
&& !lazyElement2ViewMap.getElement2ViewMap().isEmpty()) {
view = (View) lazyElement2ViewMap.getElement2ViewMap().get(
targetElement);
} else if (findElementsInDiagramByID(diagramEditPart, targetElement,
lazyElement2ViewMap.editPartTmpHolder) > 0) {
EditPart editPart = (EditPart) lazyElement2ViewMap.editPartTmpHolder
.get(0);
lazyElement2ViewMap.editPartTmpHolder.clear();
view = editPart.getModel() instanceof View ? (View) editPart
.getModel() : null;
}
return (view == null) ? diagramEditPart.getDiagramView() : view;
}
/**
* @generated
*/
public static class LazyElement2ViewMap {
/**
* @generated
*/
private Map element2ViewMap;
/**
* @generated
*/
private View scope;
/**
* @generated
*/
private Set elementSet;
/**
* @generated
*/
public final List editPartTmpHolder = new ArrayList();
/**
* @generated
*/
public LazyElement2ViewMap(View scope, Set elements) {
this.scope = scope;
this.elementSet = elements;
}
/**
* @generated
*/
public final Map getElement2ViewMap() {
if (element2ViewMap == null) {
element2ViewMap = new HashMap();
// map possible notation elements to itself as these can't be
// found by view.getElement()
for (Iterator it = elementSet.iterator(); it.hasNext();) {
EObject element = (EObject) it.next();
if (element instanceof View) {
View view = (View) element;
if (view.getDiagram() == scope.getDiagram()) {
element2ViewMap.put(element, element); // take only
// those
// that part
// of our
// diagram
}
}
}
buildElement2ViewMap(scope, element2ViewMap, elementSet);
}
return element2ViewMap;
}
/**
* @generated
*/
static Map buildElement2ViewMap(View parentView, Map element2ViewMap,
Set elements) {
if (elements.size() == element2ViewMap.size())
return element2ViewMap;
if (parentView.isSetElement()
&& !element2ViewMap.containsKey(parentView.getElement())
&& elements.contains(parentView.getElement())) {
element2ViewMap.put(parentView.getElement(), parentView);
if (elements.size() == element2ViewMap.size())
return element2ViewMap;
}
for (Iterator it = parentView.getChildren().iterator(); it
.hasNext();) {
buildElement2ViewMap((View) it.next(), element2ViewMap,
elements);
if (elements.size() == element2ViewMap.size())
return element2ViewMap;
}
for (Iterator it = parentView.getSourceEdges().iterator(); it
.hasNext();) {
buildElement2ViewMap((View) it.next(), element2ViewMap,
elements);
if (elements.size() == element2ViewMap.size())
return element2ViewMap;
}
for (Iterator it = parentView.getSourceEdges().iterator(); it
.hasNext();) {
buildElement2ViewMap((View) it.next(), element2ViewMap,
elements);
if (elements.size() == element2ViewMap.size())
return element2ViewMap;
}
return element2ViewMap;
}
} // LazyElement2ViewMap
}
E a classe de persistência segue abaixo:
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import processEditor.model.entityData.Process;
public class Persistence implements IPersistence {
private Configuration configuration;
private SessionFactory sessionFactory;
private Session session;
private Transaction transaction;
public Persistence() {
}
public void save(String name, String description, Date date) {
this.doConnection();
Process process = new Process();
process.setName(name);
process.setDescription(description);
process.setDate(date);
session.save(process);
this.closeConnection();
}
public void doConnection() {
configuration = new AnnotationConfiguration();
configuration
.configure("/projeto/pacote/persistence/hibernate.cfg.xml");
sessionFactory = configuration.buildSessionFactory();
session = sessionFactory.openSession();
transaction = session.beginTransaction();
}
public void closeConnection() {
transaction.commit();
session.close();
}
}
por meio de testes de System.out.println(), percebi que o erro ocorre quando se faz o
"new" no trecho IPersistence p = new Persistence();
quando o usuario vai salvar ele da um erro dizendo que nao pode salvar e diz “Projeto/pacote/classe/Classe”
Alguém poderia me ajudar?
desde já obrigado!
Alabê Duarte