I'm trying to call SearchFactory optimize to run a scheduled index maintenance job (compacting segments - the application is a write intensive). But it does not seem to invoke immediately until I shutdown the Tomcat. My code is calling simply like this.
public synchronized void optimizeIndexes() {
getFullTextEntityManager().flushToIndexes(); //apply any changes before optimizing
getFullTextEntityManager().getSearchFactory().optimize();
logger.info("[Lucene] optimization has performed on all the indexes...");
}
I got it to work around by loaning IndexWriter from HSearch backend.
private synchronized void optimizeBareMetal() {
try {
LuceneBackendQueueProcessor backend = (LuceneBackendQueueProcessor) getIndexManager().getBackendQueueProcessor();
LuceneBackendResources resources = backend.getIndexResources();
AbstractWorkspaceImpl workspace = resources.getWorkspace();
IndexWriter indexWriter = workspace.getIndexWriter();
indexWriter.forceMerge(1, true);
indexWriter.commit();
} catch (LockObtainFailedException e) {
e.printStackTrace();
} catch (CorruptIndexException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private synchronized DirectoryBasedIndexManager getIndexManager() {
SearchFactoryImplementor searchFactory = (SearchFactoryImplementor) getFullTextEntityManager().getSearchFactory();
IndexManagerHolder indexManagerHolder = searchFactory.getIndexManagerHolder();
return (DirectoryBasedIndexManager) indexManagerHolder.getIndexManager(getEntityClass().getName());
}
Related
My test method looks like this:
private static System.Timers.Timer _myTimer;
static void Main(string[] args)
{
using (_myTimer = new System.Timers.Timer(1000))
{
_myTimer.Elapsed += (o, e) => Console.WriteLine($"timer elapsed");
_myTimer.AutoReset = true;
_myTimer.Enabled = true;
Thread.Sleep(4000); // let the timer fire a couple of times
} // dispose timer?
Thread.Sleep(2000); // timer won't fire here
try
{
Console.WriteLine($"no problem accessing _myTimer: {_myTimer.Interval}"); // this won't throw an ObjectDisposedException on _myTimer
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex}");
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
try
{
Console.WriteLine($"no problem accessing _myTimer: {_myTimer.Interval}"); // still no ObjectDisposedException
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex}");
}
try
{
//_myTimer.Start(); // throws the ObjectDisposedException
_myTimer.Dispose(); // does not throw the ObjectDisposedException
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex}");
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
try
{
Console.WriteLine($"no problem accessing _myTimer: {_myTimer.Interval}"); // still no ObjectDisposedException
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex}");
}
Console.WriteLine("Press any key to continue...");
Console.ReadLine();
}
I would expect to get the ObjectDisposedException after leaving the using block.
Accessing the _myTimer.Interval works all the way to the end of the program. Also, I can call _myTimer.Dispose() anytime. Even waiting for the GarbageCollector does not help to get the ObjectDisposedException.
However, I do get the ObjectDisposedException if I call _myTimer.Start() after leaving the using block.
How can _myTimer be around for the entire lifetime of my program?
Calling Dispose doesn't remove the object or references to it. It will not be GCed as long as there are references to it. Dispose releases unmanaged resources within the object, which is likely but by no means guaranteed to cause at least some of its methods to stop working and start throwing ObjectDisposedException.
I have looked at the examples for subscribing to a NodeId and im wondering how I could stop/delete a subscription afterward.
Eclipse Milo v0.3.8 Client.
Here's what I've tried.
protected boolean unsubscribe(TransactionDefinition transactionDefinition) {
// Finds the mathing TransactionDefinition from the map where all subscriptions
// are stored, together with the clientHandle.
// private Map<UInteger, TransactionDefinition> subscriptions = new HashMap<>();
try {
UInteger subscriptionClientHandle = null;
for (Map.Entry<UInteger, TransactionDefinition> entry : subscriptions.entrySet()) {
if (entry.getValue().equals(transactionDefinition))
subscriptionClientHandle = entry.getKey();
}
if (subscriptionClientHandle == null) return false;
try {
client.getSubscriptionManager().deleteSubscription(subscriptionClientHandle).get();
return true;
} catch (Exception e) {
log.error("Subscription not found: {}", e.getMessage(), e.getCause());
e.printStackTrace();
}
} catch (ClassCastException e) {
log.error("TransactionDefinition trigger not found. {}", e.getMessage(), e.getCause());
e.printStackTrace();
}
return false;
}
UaSubscription has a deleteMonitoredItems method on it.
UaSubscriptionManager has a deleteSubscription method on it.
You could also call either of these services "manually" by invoking the "raw" service methods on the UaClient instance.
public static void write(byte[] aInput, String aOutputFileName, String dirName) {
(new File(dirName)).mkdir();
try {
OutputStream output = null;
try {
output = new BufferedOutputStream(new FileOutputStream(dirName + "/" + aOutputFileName));
output.write(aInput);
} finally {
output.close();
}
} catch (FileNotFoundException ex) {
System.out.println("File not found.");
} catch (IOException ex) {
System.out.println(ex);
}
}
The code above is from a library i'm using and it is supposed to create an output file and write a byte array to it. I checked logcat and saw the Strict Mode Policy violation Write.toDisk. I understand what it is supposed to be for my questions are: (1) Does Strict mode prevent you from doing disk reads and write on the main thread? (2) Does that mean that the file or folder were not actually created? (3) How then would I go about creating a folder or file within my App that doesn't trigger this? (4) What is the recommended way to handle disk read / write off the main ui thread, a real world example would be appreciated
Thanks in Advance
(1) It turns out that Strict mode doesn't actually prevent you from making writes to the disk it just gives a warning. From Android Developer "StrictMode is a developer tool which detects things you might be doing by accident and brings them to your attention so you can fix them". https://developer.android.com/reference/android/os/StrictMode
(2) The files were actually being created it's just that I was just not familiar with writing and reading from disk
(3) There are numerous ways to go about creating files (i) first you get a hold of a file directory to write the file to:
context.getFilesDir()
(ii) then you get an outputstream writer (iii) then you write out the data with the writer
public void makeFile(String filename){
//Create temp file for filename
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File(filename));
fos.write(filename.getBytes());//Write the contents of the file to app folder
fos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
(iv) finally you close the outputstream writer
(4) The recommended way is to use either an AsyncTask or some other background running class like FutureTask or to use Threads or Runnable:
public class DownloadFileThread implements Runnable{
public void run(){
//your code here
}
}
I want to use java nio in java ee.
But I don't know how to do it right.
I need to after server has deploy java.nio.selector always listens the port and processing socket connection.
I try do it there:
#Singleton
#Lock(LockType.READ)
public class TaskManager {
private static final int LISTENINGPORT;
static {
LISTENINGPORT = ConfigurationSettings.getConfigureSettings().getListeningPort();
}
private ArrayList<ServerCalculationInfo> serverList;
public TaskManager() {
serverList = new ArrayList<ServerCalculationInfo>();
select();
}
#Asynchronous
public void select() {
try {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
Selector selector = Selector.open();
serverSocketChannel.configureBlocking(false);
serverSocketChannel.socket().bind(new InetSocketAddress(LISTENINGPORT));
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
try {
selector.select();
} catch (IOException ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
break;
}
Iterator it = selector.selectedKeys().iterator();
while (it.hasNext()) {
SelectionKey selKey = (SelectionKey) it.next();
it.remove();
try {
processSelectionKey(serverSocketChannel, selKey);
} catch (IOException e) {
serverList.remove(serverCalculationInfo);
}
}
}
} catch (IOException e) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, e);
} catch (Exception e) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, e);
}
}
}
It don't work correctly. The process hangs during deploy and redeploy application possible only after restart Glassfish.
How can I do right it?
It works correctly if invoke #Asynchronous method from the #PostConstructor:
#PostConstruct
public void postTaskManager() {
serverList = new ArrayList<ServerCalculationInfo>();
select();
}
instead of invoke it from constructor.
But class must be without #Startup annotation.
I have tried in many different ways to send my xml document over a socket connection between a server and a client without closing the socket after sending (keep the outputstream open, for sending another document). I have found several sites who claimed that it should work, so I tried it in all the ways they sugested, but I did not found a way which works.
(that describes the same what I would like to do: http://jaxb.java.net/guide/Designing_a_client_server_protocol_in_XML.html)
The follwing code works perfectly if I am closing the socket after sending (#code marsh.marshal(element, xsw);), but it stucks on unmarshaling on the server side, if I try to keep the socket open.
Client Side....
public void sendMessage(String message){
JAXBContext jaxbContext;
try {
jaxbContext = JAXBContext.newInstance("cdl.wizard.library");
Marshaller marsh = jaxbContext.createMarshaller();
marsh.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marsh.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "http://www.example.org/WizardShema WizardsSchema.xsd");
ObjectFactory of = new ObjectFactory();
// the Dataset is the root element of the xml document
Dataset set = new Dataset("CONN01", "CONTR", "MCL01#localhost", "SV01#localhost:32000");
CommandSet cmdSet = new CommandSet();
Command cmd = new Command();
cmd.setFunctionName("RegisterAs");
Param p = new Param();
p.setString("RemoteClient");
cmd.addParameter(p);
cmdSet.addCommand(cmd);
set.setInstruction(cmdSet);
// creates a valid xml dataset, with startDocument, startElement...
JAXBElement<Dataset> element = of.createData(set);
XMLStreamWriter xsw = XMLOutputFactory.newInstance().createXMLStreamWriter(mOOS);
marsh.marshal(element, xsw);
xsw.flush();
} catch (JAXBException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XMLStreamException e) {
e.printStackTrace();
} catch (FactoryConfigurationError e) {
e.printStackTrace();
}
SERVER Side....
private void handleMessage() {
JAXBContext jaxbContext;
try {
jaxbContext = JAXBContext.newInstance("cdl.wizard.library") ;
Unmarshaller um = jaxbContext.createUnmarshaller();
XMLInputFactory xmlif = XMLInputFactory.newInstance();
// XMLEventReader xmlr = xmlif.createXMLEventReader(mOIS);
XMLStreamReader xmlr = xmlif.createXMLStreamReader(mOIS, "UTF8");
// move to the root element and check its name.
xmlr.nextTag();
System.out.println("TagName:" + xmlr.getLocalName());
xmlr.require(START_ELEMENT, null, "Data");
JAXBElement<Dataset> obj = um.unmarshal(xmlr, Dataset.class);
Dataset set = obj.getValue();
System.out.println("ID:"+ set.getID());
} catch (JAXBException e) {
e.printStackTrace();
} catch (XMLStreamException e) {
e.printStackTrace();
} catch (FactoryConfigurationError e) {
e.printStackTrace();
}
}