Print an EObject? - eclipse-emf

I am writing some eclipse emf code and would like to print the content of an EObject (not store it to disk).
Here is what I try:
public static void print(EObject obj) {
Resource eResource = obj.eResource();
try {
eResource.save(System.out, null);
} catch (IOException e) {
e.printStackTrace();
}
}
but that gives a NullPointerException. I have tried this instead:
public static void print(EObject obj) {
ResourceSet resourceSet = new ResourceSetImpl();
resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap()
.put("*", new XMIResourceFactoryImpl());
Resource resource = resourceSet.createResource(URI.createURI("dummyfile.xml"));
resource.getContents().add(obj);
try {
resource.save(System.out, null);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
This works, but is it not possible to print to screen without specifying a dummy URI??

Updated to include EcoreUtil.copy()
Check this code.
Resource res = new XMLResourceImpl ();
res.getContents().add(EcoreUtil.copy(obj));
try {
resource.save(System.out, null);
} catch (IOException ioe) {
ioe.printStackTrace();
}
If that fails then yes you need a dummy URI
Resource res = new XMLResourceImpl (URI.createURI("dummyfile.xml"));
res.getContents().add(EcoreUtil.copy(obj));
try {
resource.save(System.out, null);
} catch (IOException ioe) {
ioe.printStackTrace();
}

Hm when I pass a copy:
Resource res = new XMLResourceImpl ();
res.getContents().add(ECoreUtil.copy(obj));
try {
resource.save(System.out, null);
} catch (IOException ioe) {
ioe.printStackTrace();
}
some of the xmi attributes are not printed. But if I call the above method multiple times and DON't pass a copy I get a NullPointerException. I guess I am not understanding some basic EMF/Containment functionality here?
So my updated question is:
Is it possible to print a FULL EObject model without modifying the content if the model is used in the following code?

Related

Exception in Concurrency task.then.wait affects further call of ::ShellExecuteEx()

Following logic is implemented to open a file by a "filename.extension" in a C++ application using managed-C++:
try
{
CoInitialize(nullptr);
auto task = Concurrency::create_task(Windows::Storage::StorageFile::GetFileFromPathAsync(filePath));
// an excpetion is thrown in the next line
Concurrency::task_status status = task.then([&](Windows::Storage::StorageFile^ file){
if (file != nullptr)
{
concurrency::task<bool> launchFileOperation(Windows::System::Launcher::LaunchFileAsync(file));
launchFileOperation.then([&](bool success)
{
if (!success)
return 0;
}).wait();
}
}).wait();
}
catch (...)
{
CoUninitialize(); // an exeption is catched
return 0;
}
Since the above code throws an exception, we go further to an alternative file open approach via ::ShellExecuteEx
SHELLEXECUTEINFO exec_info = {0};
exec_info.cbSize = sizeof exec_info;
exec_info.fMask = SEE_MASK_NOCLOSEPROCESS
| SEE_MASK_DOENVSUBST;
exec_info.fMask &= ~SEE_MASK_NOASYNC;
exec_info.lpVerb = "open";
exec_info.lpFile = full_path_str;
exec_info.nShow = SW_SHOW;
bool result_b = ::ShellExecuteEx(&exec_info) ? true : false;
The ::ShellExecuteEx fails and ends up in Microsofts ppltasks.h
_REPORT_PPLTASK_UNOBSERVED_EXCEPTION();.
::ShellExecuteEx works correctly if the managed-C++ Concurrency::create_task approach is removed.
Why does Concurrency::create_task affect the further call of ::ShellExecuteEx?
This issue appears only in release build.
Adding try/catch-blocks to the innermost .wait()-block solved the issue
try {
concurrency::task<bool> launchFileOperation(Windows::System::Launcher::LaunchFileAsync(file));
launchFileOperation.then([&](bool success) {
// logic
}).wait();
}
catch (concurrency::invalid_operation& ex)
{
...
}
catch (concurrency::task_canceled& ex)
{
...
}

Correctly catching the CDatabase::Close exception

I thought I would do a little digging about cataching exceptions.
According to this question (C++ catching all exceptions) one of the answers states:
[catch(...)] will catch all C++ exceptions, but it should be considered bad design.
At the moment I have used this approach:
CPTSDatabase::~CPTSDatabase()
{
try
{
CloseDatabase();
}
catch(...)
{
}
}
void CPTSDatabase::CloseDatabase()
{
if (m_dbDatabase.IsOpen())
m_dbDatabase.Close();
}
I thought that this was the correct way because when I trace into CDatabase::Close() it does something similar:
// Disconnect connection
void CDatabase::Close()
{
ASSERT_VALID(this);
// Close any open recordsets
AfxLockGlobals(CRIT_ODBC);
TRY
{
while (!m_listRecordsets.IsEmpty())
{
CRecordset* pSet = (CRecordset*)m_listRecordsets.GetHead();
pSet->Close(); // will implicitly remove from list
pSet->m_pDatabase = NULL;
}
}
CATCH_ALL(e)
{
AfxUnlockGlobals(CRIT_ODBC);
THROW_LAST();
}
END_CATCH_ALL
AfxUnlockGlobals(CRIT_ODBC);
if (m_hdbc != SQL_NULL_HDBC)
{
RETCODE nRetCode;
AFX_SQL_SYNC(::SQLDisconnect(m_hdbc));
AFX_SQL_SYNC(::SQLFreeConnect(m_hdbc));
m_hdbc = SQL_NULL_HDBC;
_AFX_DB_STATE* pDbState = _afxDbState;
AfxLockGlobals(CRIT_ODBC);
ASSERT(pDbState->m_nAllocatedConnections != 0);
pDbState->m_nAllocatedConnections--;
AfxUnlockGlobals(CRIT_ODBC);
}
}
And the CDatabase::Close documentation does not even state anything about exceptions being thrown.
The linked answer does state:
You can use c++11's new current_exception mechanism.
It is not clear if we can use this approach given the CDatabase class we are using.
Since CDatabase::Close() is using THROW_LAST to throw CDBException, you have to use catch (CDBException* e). Even if you are not handling it, you still have to Delete the error. You might as well do this when CDatabase methods are called directly:
void CPTSDatabase::CloseDatabase()
{
try
{
if (m_dbDatabase.IsOpen())
m_dbDatabase.Close();
}
catch (CDBException* e)
{
//TRACE(L"DB error: " + e->m_strError);
e->Delete();
}
}
Or use
CPTSDatabase::~CPTSDatabase()
{
try { CloseDatabase(); }
catch (CDBException* e) { e->Delete(); }
catch(...) {}
}
Because in this code it's not clear where the exceptions are coming from. catch(...) {} will deal with other exceptions. In general catch(...) {} is not recommended because it doesn't give useful information, it just says "something went wrong..."
Use Standard Library exceptions only if you are adding throw in your own code, or when using std functions. Example:
try { std::stoi("wrong argument"); }
catch (const std::exception& e) { TRACE("%s\n", e.what()); }
try { throw 123; }
catch (int i) { TRACE("%d\n", i); }

ROS cv_bridge in a class leads to segfault when cv_ptr->image is accessed

I'm having an issue where when I get my const sensor_msgs::ImageConstPtr &msg in my callback function, and do a cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::RGB8); where cv_ptr is a cv_bridge::CvImagePtr, and try to do anything with the cv_ptr->image, the line where I do toCvCopy segfaults. When I leave the pointer alone and maybe access its contents or something elsewhere in my class, it's seemingly fine... I'm extremely confused.
Here's some of my real code:
void CNNLocalizer::imageCB(const sensor_msgs::ImageConstPtr &msg)
{
cv_bridge::CvImagePtr cv_ptr;
try
{
cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::RGB8);
ROS_INFO("Attempt!");
cv::Mat image = cv_ptr->image.clone();
ROS_INFO("Success!");
image.convertTo(g_most_recent_image_, CV_32FC3);
g_img_height_ = msg->height;
g_img_width_ = msg->width;
g_got_image_ = true;
}
catch (cv_bridge::Exception &e)
{
ROS_ERROR("Failed converting the received message: %s", e.what());
return;
}
}
If I get rid of the business where I try to clone the cv_ptr->image, there is no segfault... Any tips or tricks? Am I misunderstanding how things are working here...?
Edit: I am running my camera data through a looping rosbag with --clock enabled.
try debugging that using a try/catch block for "cv_bridge::toCvCopy"
cv_bridge::CvImagePtr cv_ptr;
try
{
cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8);
}
catch (cv_bridge::Exception& e)
{
ROS_ERROR("cv_bridge exception: %s", e.what());
return;
}
and add the exception description when it occurs.
A quick fix would be changing the line :
cv::Mat image = cv_ptr->image.clone();
to :
cv::Mat image = cv_ptr->image;
This should work just fine.

print error while null value for SQL safety

How can I print "Error" while the JTextfield is empty
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
String sn =jX1.getText();
if (sn==null){
System.out.println("Error");
System.out.println("T");
}
Thanks
Try using a fail-safe method. Also Expanding on the comments, you should be logging data, in a better format. Java hosts a huge array of different way to log certain data. look here
As for your error handling, try-catch-finally. This isn't tested code. Let me know if you run into any issues, documentation on try-catch and other statements here or here
public static void main(String[] args) {
while (String sn == null)
try {
String sn = JX1.getText();
} catch (Exception ex) {
System.out.println("Exception thrown!");
} finally {
if (sn != null) {
System.out.println("Closing PrintWriter");
sn.close();
} else {
System.out.println("PrintWriter not open");
}
}

Files locked after indexing

I have the following workflow in my (web)application:
download a pdf file from an archive
index the file
delete the file
My problem is that after indexing the file, it remains locked and the delete-part throws an exception.
Here is my code-snippet for indexing the file:
try
{
ContentStreamUpdateRequest req = new ContentStreamUpdateRequest("/update/extract");
req.addFile(file, type);
req.setAction(AbstractUpdateRequest.ACTION.COMMIT, true, true);
NamedList<Object> result = server.request(req);
Assert.assertEquals(0, ((NamedList<?>) result.get("responseHeader")).get("status"));
}
Do I miss something?
EDIT:
I tried this way too, but with the same result...
ContentStream contentStream = null;
try
{
contentStream = new ContentStreamBase.FileStream(document);
ContentStreamUpdateRequest req = new ContentStreamUpdateRequest(UPDATE_EXTRACT_REQUEST);
// req.addFile(document, context.getProperty(FTSConstants.CONTENT_TYPE_APPLICATION_PDF));
req.addContentStream(contentStream);
req.setAction(AbstractUpdateRequest.ACTION.COMMIT, true, true);
NamedList<Object> result = server.request(req);
if (!((NamedList<?>) result.get("responseHeader")).get("status").equals(0))
{
throw new IDSystemException(LOG, "Document could not be indexed. Status returned: " +
((NamedList<?>) result.get("responseHeader")).get("status"));
}
}
catch (FileNotFoundException fnfe)
{
throw new IDSystemException(LOG, fnfe.getMessage(), fnfe);
}
catch (IOException ioe)
{
throw new IDSystemException(LOG, ioe.getMessage(), ioe);
}
catch (SolrServerException sse)
{
throw new IDSystemException(LOG, sse.getMessage(), sse);
}
finally
{
try
{
if(contentStream != null && contentStream.getStream() != null)
{
contentStream.getStream().close();
}
}
catch (IOException ioe)
{
throw new IDSystemException(LOG, ioe.getMessage(), ioe);
}
}
This seems like a bug,
a patch is proposed here
https://issues.apache.org/jira/browse/SOLR-1744
Also checkout
http://lucene.472066.n3.nabble.com/ContentStreamUpdateRequest-addFile-fails-to-close-Stream-td485429.html
you can check if the stream is not null and close it.
It may be due to lock acquired by file system. Instead of addFile(), you can try the following.
ContentStreamUpdateRequest req = new ContentStreamUpdateRequest("/update/extract");
ContentStreamBase.FileStream fileStream = new FileStream(file);
req.addContentStream(fileStream);
Shishir