Hi I have the Below Code which giving me error at line :
uuidGenerator = Generators.timeBasedGenerator(nic, new UUIDTimer(new Random(), TimestampSynchronizer));
Like TimestampSynchronizer could not resolve as variable.
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Random;
import java.util.UUID;
import javax.crypto.KeyGenerator;
import com.fasterxml.uuid.EthernetAddress;
import com.fasterxml.uuid.Generators;
import com.fasterxml.uuid.TimestampSynchronizer;
import com.fasterxml.uuid.UUIDTimer;
import com.fasterxml.uuid.ext.FileBasedTimestampSynchronizer;
import com.fasterxml.uuid.impl.TimeBasedGenerator;
import com.google.common.base.Charsets;
import com.google.common.io.BaseEncoding;
import com.google.gdata.util.common.util.*;
public class UUID_Test {
public static void main(String[] args) {
for (int i = 0; i < 10000; i++) {
try {
UUID_Test.uuidToBase32();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static String uuidToBase32() throws IOException
{
EthernetAddress nic = EthernetAddress.fromInterface();
TimeBasedGenerator uuidGenerator;
uuidGenerator = Generators.timeBasedGenerator(nic, new UUIDTimer(new Random(), TimestampSynchronizer));
ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
bb.putLong(uuidGenerator.generate().getMostSignificantBits());
bb.putLong(uuidGenerator.generate().getLeastSignificantBits());
return BaseEncoding.base32().encode(bb.array());
}
}
How to solve this?
And when i use
uuidGenerator = Generators.timeBasedGenerator(nic, new UUIDTimer(new Random(), new FileBasedTimestampSynchronizer()));
Getting Exception
Exception in thread "main" java.nio.channels.OverlappingFileLockException
OR If I write
uuidGenerator = Generators.timeBasedGenerator(nic,new FileBasedTimestampSynchronizer(new File("d://abc"), new File("d://def")));
Getting Exception
WARNING: (file 'd:\abc') Missing or empty file, can not read timestamp value
WARNING: (file 'd:\def') Missing or empty file, can not read timestamp value
WARNING: Could not determine safe timer starting point: assuming current system time is acceptable
GNKOP7JVWII6HMAJ2S7NSZXSYE
Exception in thread "main" java.nio.channels.OverlappingFileLockException
at sun.nio.ch.SharedFileLockTable.checkList(FileLockTable.java:255)
Thanks
Edit
Code copied from comment to answer:
I place the code in static block
static EthernetAddress nic = EthernetAddress.fromInterface();
static File f = new File("D://a.txt");
static File f1 = new File("D://f.txt");
static TimeBasedGenerator uuidGenerator;
static {
try {
uuidGenerator = Generators.timeBasedGenerator(nic, new UUIDTimer(new Random(), new FileBasedTimestampSynchronizer(f, f1)));
}
catch (IOException e) {
e.printStackTrace();
}
}
Its giving Exception
java.io.IOException: Failed to lock 'd://a.txt' (another JVM running UUIDGenerator?)
TimestampSynchronizer is a non-public class, you can not use that in your code.
The problem with your overlapping lock comes from this line
uuidGenerator = Generators.timeBasedGenerator(nic, new UUIDTimer(new Random(), TimestampSynchronizer));
You are creating a new generator each time - to ensure the uniqueness of time based UUIDs this uses a lock file. The lock file can only be used for one generator.
Solution: Create just one timer, or even one generator and re-use that inside your loop.
Related
I need to copy all of the contents of a stream of VectorSchemaRoots into a single object:
Stream<VectorSchemaRoot> data = fetchStream();
VectorSchemaRoot finalResult = VectorSchemaRoot.create(schema, allocator);
VectorLoader = new VectorLoader(finalResult);
data.forEach(current -> {
VectorUnloader unloader = new VectorUnloader(current);
ArrowRecordBatch batch = unloader.getRecordBatch();
loader.load(batch);
current.close();
})
However, I am getting the following error:
java.lang.IllegalStateException: Memory was leaked by query. Memory was leaked.
Also getting this further down the stack track:
Could not load buffers for field date: Timetamp(MILLISECOND, null) not null. error message: A buffer can only be associated between two allocators that shame the same root
I use the same allocator for everything, does anyone know why I am getting this issue?
The "leak" is probably just a side effect of the exception, because the code as written is not exception-safe. Use try-with-resources to manage the ArrowRecordBatch instead of manually calling close():
try (ArrowRecordBatch batch = unloader.getRecordBatch()) {
loader.load(batch);
}
(though, depending on what load does, this may not be enough).
I can't say much else about why you're getting the exception without seeing more code and the full stack trace.
Could you try with something like this:
import org.apache.arrow.memory.BufferAllocator;
import org.apache.arrow.memory.RootAllocator;
import org.apache.arrow.vector.IntVector;
import org.apache.arrow.vector.VectorLoader;
import org.apache.arrow.vector.VectorSchemaRoot;
import org.apache.arrow.vector.VectorUnloader;
import org.apache.arrow.vector.ipc.message.ArrowRecordBatch;
import org.apache.arrow.vector.types.pojo.ArrowType;
import org.apache.arrow.vector.types.pojo.Field;
import org.apache.arrow.vector.types.pojo.FieldType;
import org.apache.arrow.vector.types.pojo.Schema;
import java.util.Arrays;
import java.util.Collections;
import java.util.stream.Stream;
public class StackOverFlowSolved {
public static void main(String[] args) {
try(BufferAllocator allocator = new RootAllocator()){
// load data
IntVector ageColumn = new IntVector("age", allocator);
ageColumn.allocateNew();
ageColumn.set(0, 1);
ageColumn.set(1, 2);
ageColumn.set(2, 3);
ageColumn.setValueCount(3);
Stream<VectorSchemaRoot> streamOfVSR = Collections.singletonList(VectorSchemaRoot.of(ageColumn)).stream();
// transfer data
streamOfVSR.forEach(current -> {
Field ageLoad = new Field("age",
FieldType.nullable(new ArrowType.Int(32, true)), null);
Schema schema = new Schema(Arrays.asList(ageLoad));
try (VectorSchemaRoot root = VectorSchemaRoot.create(schema,
allocator.newChildAllocator("loaddata", 0, Integer.MAX_VALUE))) {
VectorUnloader unload = new VectorUnloader(current);
try (ArrowRecordBatch recordBatch = unload.getRecordBatch()) {
VectorLoader loader = new VectorLoader(root);
loader.load(recordBatch);
}
System.out.println(root.contentToTSVString());
}
current.close();
});
}
}
}
age
1
2
3
In my application I have a method which I cant execute without main method. It only runs inside the main method. When I call that method inside my servlet class. It show an exception
My class with Main Method
package com.books.servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.HashSet;
import java.util.Set;
import opennlp.tools.cmdline.parser.ParserTool;
import opennlp.tools.parser.Parse;
import opennlp.tools.parser.Parser;
import opennlp.tools.parser.ParserFactory;
import opennlp.tools.parser.ParserModel;
public class ParserTest {
// download
public void download(String url, File destination) throws IOException, Exception {
URL website = new URL(url);
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
public static Set<String> nounPhrases = new HashSet<>();
private static String line = "The Moon is a barren, rocky world ";
public void getNounPhrases(Parse p) {
if (p.getType().equals("NN") || p.getType().equals("NNS") || p.getType().equals("NNP")
|| p.getType().equals("NNPS")) {
nounPhrases.add(p.getCoveredText());
}
for (Parse child : p.getChildren()) {
getNounPhrases(child);
}
}
public void parserAction() throws Exception {
// InputStream is = new FileInputStream("en-parser-chunking.bin");
File modelFile = new File("en-parser-chunking.bin");
if (!modelFile.exists()) {
System.out.println("Downloading model.");
download("https://drive.google.com/uc?export=download&id=0B4uQtYVPbChrY2ZIWmpRQ1FSVVk", modelFile);
}
ParserModel model = new ParserModel(modelFile);
Parser parser = ParserFactory.create(model);
Parse topParses[] = ParserTool.parseLine(line, parser, 1);
for (Parse p : topParses) {
// p.show();
getNounPhrases(p);
}
}
public static void main(String[] args) throws Exception {
new ParserTest().parserAction();
System.out.println("List of Noun Parse : " + nounPhrases);
}
}
It gives me below output
List of Noun Parse : [barren,, world, Moon]
Then I commented the main method and. Called the ParserAction() method in my servlet class
if (name.equals("bkDescription")) {
bookDes = value;
try {
new ParserTest().parserAction();
System.out.println("Nouns Are"+ParserTest.nounPhrases);
} catch (Exception e) {
}
It gives me the below exceptions
And below error in my Browser
Why is this happening ? I can run this with main method. But when I remove main method and called in my servlet. it gives an exception. Is there any way to fix this issue ?
NOTE - I have read below instructions in OpenNLP documentation , but I have no clear idea about it. Please help me to fix his issue.
Unlike the other components to instantiate the Parser a factory method
should be used instead of creating the Parser via the new operator.
The parser model is either trained for the chunking parser or the tree
insert parser the parser implementation must be chosen correctly. The
factory method will read a type parameter from the model and create an
instance of the corresponding parser implementation.
Either create an object of ParserTest class or remove new keyword in this line new ParserTest().parserAction();
I'm attempting to run an Access function through Java using Jacob using Application.Run (https://msdn.microsoft.com/en-us/library/office/ff193559.aspx). I am able to open and close an Access database, but not run a function. I suspect the run call actually does go through but that I have opened the file read-only (maybe? not sure I did) which then causes the Access error: Run-time error 3073: Operation must use an updatable query. The query simply appends two strings onto a test table I created, and that query works by hand, but so far not through Java.
If the error is that I've opened it read-only, how can I open it not read-only? If it's something else, how do I call a function (or a macro, either will work) using Jacob? Or you may know some other Java technique besides using Jacob, I'd take that too.
Minimum example:
Java program
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.LibraryLoader;
import com.jacob.com.Variant;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author evans
*/
public class Test {
public static void main(String[] args) {
// Load library/.dll
try {
String libFile = System.getProperty("os.arch").equals("amd64") ? "jacob-1.18-x64.dll" : "jacob-1.18-x86.dll";
FileInputStream inputStream = new FileInputStream(new File(libFile));
File temporaryDll = File.createTempFile("jacob", ".dll");
try (FileOutputStream outputStream = new FileOutputStream(temporaryDll)) {
byte[] array = new byte[8192];
for (int i = inputStream.read(array); i != -1; i = inputStream.read(array)) {
outputStream.write(array, 0, i);
}
}
System.setProperty(LibraryLoader.JACOB_DLL_PATH, temporaryDll.getAbsolutePath());
LibraryLoader.loadJacobLibrary();
temporaryDll.deleteOnExit();
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
// Open thread
ComThread.InitSTA(true);
// New application
ActiveXComponent ComBridge = new ActiveXComponent("Access.Application");
// Open database
Dispatch.put(ComBridge, "Visible", new Variant(true));
ComBridge.invoke("OpenCurrentDatabase", new Variant("C:/Users/evans/Documents/Book Business/Building Reports/Book Business.accdb"));
// Run function
ComBridge.invoke("Run", new Variant("Test"));
// Shutdown
ComBridge.invoke("Quit");
ComThread.quitMainSTA();
ComThread.Release();
}
}
Access query:
INSERT INTO tblTest ( Test, Test2 )
SELECT "a" AS Expr1, "B" AS Expr2;
I'm trying to add new XParameter for standard Status property with this code
import net.fortuna.ical4j.model.Calendar;
import net.fortuna.ical4j.model.Component;
import net.fortuna.ical4j.model.Property;
import net.fortuna.ical4j.model.parameter.XParameter;
import org.apache.commons.io.IOUtils;
import com.example.common.util.ical.ICalUtil;
import java.io.FileInputStream;
import java.io.IOException;
public class TestICal {
public static void main(String[] args) throws IOException {
String content = IOUtils.toString(new FileInputStream("/tmp/taskA.ics"));
Calendar task = ICalUtil.parse(content);
Component vtodo = task.getComponent(Component.VTODO);
Property prop = vtodo.getProperty(Property.STATUS);
prop.getParameters().add(new XParameter("X-TEST-PARAM", "TEST-VALUE")); // java.lang.UnsupportedOperationException
}
}
but following exception is thrown during its execution
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableCollection.add(Collections.java:1016)
at net.fortuna.ical4j.model.ParameterList.add(ParameterList.java:157)
at TestICal.main(TestICal.java:18)
In a debugger I can see that inside ical4j package add() method is called on java.util.Collections$UnmodifiableRandomAccessList which, actually I can't find in API doc for some reason, and which implements java.util.List
The property can't be deleted or replaced and I can't see a method which would allow to replace or add another parameter list.
So now I think the field can't have parameters, at least if using ical4j.
Any idea?
Answering myself: it can be done by searching required property index and calling set() method of ArrayList which PropertyList extends
import net.fortuna.ical4j.model.*;
import net.fortuna.ical4j.model.parameter.XParameter;
import org.apache.commons.io.IOUtils;
import com.example.common.util.ical.ICalUtil;
import java.io.FileInputStream;
import java.util.Iterator;
public class TestICal {
public static void main(String[] args) throws Exception {
// reading and parsing ICS
String content = IOUtils.toString(new FileInputStream("/tmp/taskA.ics"));
Calendar task = ICalUtil.parse(content);
Component vtodo = task.getComponent(Component.VTODO);
Property prop = vtodo.getProperty(Property.STATUS);
// checking the prop before
System.out.println(prop);
// preparing new param list and adding it to new created prop
ParameterList paramList = new ParameterList();
paramList.add(new XParameter("X-TEST-PARAM", "TEST-VALUE"));
PropertyFactoryImpl propFactory = PropertyFactoryImpl.getInstance();
Property myprop = propFactory.createProperty(Property.STATUS, paramList, "COMPLETED");
// and finally
PropertyList propList = vtodo.getProperties();
int index = propList.indexOf(prop);
propList.set(index, myprop);
// checking
System.out.println(vtodo.getProperties().getProperty(Property.STATUS));
}
}
result
STATUS:IN-PROCESS
STATUS;X-TEST-PARAM=TEST-VALUE:COMPLETED
I implemented the example from docs of this plugin, but I have an exception stating that a parameter Initiator is missed. I don't see this parameter at all.
My code is:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.logging.Level;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.core.framework.Platform;
import org.eclipse.birt.report.engine.api.EngineConfig;
import org.eclipse.birt.report.engine.api.IReportEngine;
import org.eclipse.birt.report.engine.api.IReportEngineFactory;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.engine.api.IRunAndRenderTask;
import org.eclipse.birt.report.engine.emitter.csv.CSVRenderOption;
public class RunExport {
static void runReport() throws FileNotFoundException, BirtException {
String resourcePath = "C:\\Users\\hpsa\\workspace\\My Reports\\";
FileInputStream fs = new FileInputStream(resourcePath + "new_report_1.rptdesign");
IReportEngine engine = null;
EngineConfig config = new EngineConfig();
config.setLogConfig("C:\\birtre\\", Level.FINE);
config.setResourcePath(resourcePath);
Platform.startup(config);
IReportEngineFactory factory = (IReportEngineFactory) Platform.createFactoryObject(IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY);
engine = factory.createReportEngine(config);
engine.changeLogLevel(Level.FINE);
IReportRunnable design = engine.openReportDesign(fs);
IRunAndRenderTask task = engine.createRunAndRenderTask(design);
CSVRenderOption csvOption = new CSVRenderOption();
String format = CSVRenderOption.OUTPUT_FORMAT_CSV;
csvOption.setOutputFormat(format);
csvOption.setOutputFileName("newBIRTcsv.csv");
csvOption.setShowDatatypeInSecondRow(true);
csvOption.setExportTableByName("SecondTable");
csvOption.setDelimiter("\t");
csvOption.setReplaceDelimiterInsideTextWith("-");
task.setRenderOption(csvOption);
task.setEmitterID("org.eclipse.birt.report.engine.emitter.csv");
task.run();
task.close();
Platform.shutdown();
System.out.println("Report Generated Successfully!!");
}
public static void main(String[] args) {
try {
runReport();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I have an exception:
org.eclipse.birt.report.engine.api.impl.ParameterValidationException: Required parameter Initiator is not set.
at org.eclipse.birt.report.engine.api.impl.EngineTask.validateAbstractScalarParameter(EngineTask.java:803)
at org.eclipse.birt.report.engine.api.impl.EngineTask.access$0(EngineTask.java:789)
at org.eclipse.birt.report.engine.api.impl.EngineTask$ParameterValidationVisitor.visitScalarParameter(EngineTask.java:706)
at org.eclipse.birt.report.engine.api.impl.EngineTask$ParameterVisitor.visit(EngineTask.java:1531)
at org.eclipse.birt.report.engine.api.impl.EngineTask.doValidateParameters(EngineTask.java:692)
at org.eclipse.birt.report.engine.api.impl.RunAndRenderTask.doRun(RunAndRenderTask.java:95)
at org.eclipse.birt.report.engine.api.impl.RunAndRenderTask.run(RunAndRenderTask.java:77)
at com.demshin.RunExport.runReport(RunExport.java:44)
at com.demshin.RunExport.main(RunExport.java:54)
[1]: https://code.google.com/a/eclipselabs.org/p/csv-emitter-birt-plugin/
I tried to find this parameter in csvOption, but there is nothing like that.
What am I doing wrong?
It is not a parameter of the emitter. This exception means a report parameter named "Initiator" is defined in the report "new_report_1.rptdesign", and its property "required" is checked.
For example edit the report design, disable "required" for this parameter and set a default value instead.