本文整理汇总了Java中org.apache.lucene.util.Constants.WINDOWS属性的典型用法代码示例。如果您正苦于以下问题:Java Constants.WINDOWS属性的具体用法?Java Constants.WINDOWS怎么用?Java Constants.WINDOWS使用的例子?那么, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类org.apache.lucene.util.Constants
的用法示例。
在下文中一共展示了Constants.WINDOWS属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: init
/**
* Attempt to drop the capability to execute for the process.
* <p>
* This is best effort and OS and architecture dependent. It may throw any Throwable.
* @return 0 if we can do this for application threads, 1 for the entire process
*/
static int init(Path tmpFile) throws Exception {
if (Constants.LINUX) {
return linuxImpl();
} else if (Constants.MAC_OS_X) {
// try to enable both mechanisms if possible
bsdImpl();
macImpl(tmpFile);
return 1;
} else if (Constants.SUN_OS) {
solarisImpl();
return 1;
} else if (Constants.FREE_BSD || OPENBSD) {
bsdImpl();
return 1;
} else if (Constants.WINDOWS) {
windowsImpl();
return 1;
} else {
throw new UnsupportedOperationException("syscall filtering not supported for OS: '" + Constants.OS_NAME + "'");
}
}
示例2: isWritable
/**
* Returns true if the path is writable.
* Acts just like {@link Files#isWritable(Path)}, except won't
* falsely return false for paths on SUBST'd drive letters
* See https://bugs.openjdk.java.net/browse/JDK-8034057
* Note this will set the file modification time (to its already-set value)
* to test access.
*/
@SuppressForbidden(reason = "works around https://bugs.openjdk.java.net/browse/JDK-8034057")
public static boolean isWritable(Path path) throws IOException {
boolean v = Files.isWritable(path);
if (v || Constants.WINDOWS == false) {
return v;
}
// isWritable returned false on windows, the hack begins!!!!!!
// resetting the modification time is the least destructive/simplest
// way to check for both files and directories, and fails early just
// in getting the current value if file doesn't exist, etc
try {
Files.setLastModifiedTime(path, Files.getLastModifiedTime(path));
return true;
} catch (Throwable e) {
return false;
}
}
示例3: testMap
public void testMap() throws Exception {
Map<String, Map<String, ?>> maps = new HashMap<>();
maps.put("{'map':null}", (Map) null);
maps.put("{'map':{}}", Collections.emptyMap());
maps.put("{'map':{'key':'value'}}", singletonMap("key", "value"));
Map<String, Object> innerMap = new HashMap<>();
innerMap.put("string", "value");
innerMap.put("int", 42);
innerMap.put("long", 42L);
innerMap.put("long[]", new long[]{1L, 3L});
innerMap.put("path", PathUtils.get("path", "to", "file"));
innerMap.put("object", singletonMap("key", "value"));
final String path = Constants.WINDOWS ? "path\\\\to\\\\file" : "path/to/file";
maps.put("{'map':{'path':'" + path + "','string':'value','long[]':[1,3],'int':42,'long':42,'object':{'key':'value'}}}", innerMap);
for (Map.Entry<String, Map<String, ?>> m : maps.entrySet()) {
final String expected = m.getKey();
assertResult(expected, () -> builder().startObject().field("map", m.getValue()).endObject());
assertResult(expected, () -> builder().startObject().field("map").value(m.getValue()).endObject());
assertResult(expected, () -> builder().startObject().field("map").map(m.getValue()).endObject());
}
}
示例4: testIterable
public void testIterable() throws Exception {
Map<String, Iterable<?>> iterables = new HashMap<>();
iterables.put("{'iter':null}", (Iterable) null);
iterables.put("{'iter':[]}", Collections.emptyList());
iterables.put("{'iter':['a','b']}", Arrays.asList("a", "b"));
final String path = Constants.WINDOWS ? "{'iter':'path\\\\to\\\\file'}" : "{'iter':'path/to/file'}";
iterables.put(path, PathUtils.get("path", "to", "file"));
final String paths = Constants.WINDOWS ? "{'iter':['a\\\\b\\\\c','c\\\\d']}" : "{'iter':['a/b/c','c/d']}";
iterables.put(paths, Arrays.asList(PathUtils.get("a", "b", "c"), PathUtils.get("c", "d")));
for (Map.Entry<String, Iterable<?>> i : iterables.entrySet()) {
final String expected = i.getKey();
assertResult(expected, () -> builder().startObject().field("iter", i.getValue()).endObject());
assertResult(expected, () -> builder().startObject().field("iter").value(i.getValue()).endObject());
}
}
示例5: definitelyRunningAsRoot
/** Returns true if user is root, false if not, or if we don't know */
static boolean definitelyRunningAsRoot() {
if (Constants.WINDOWS) {
return false; // don't know
}
try {
return JNACLibrary.geteuid() == 0;
} catch (UnsatisfiedLinkError e) {
// this will have already been logged by Kernel32Library, no need to repeat it
return false;
}
}
示例6: addConsoleCtrlHandler
static void addConsoleCtrlHandler(ConsoleCtrlHandler handler) {
// The console Ctrl handler is necessary on Windows platforms only.
if (Constants.WINDOWS) {
try {
boolean result = JNAKernel32Library.getInstance().addConsoleCtrlHandler(handler);
if (result) {
logger.debug("console ctrl handler correctly set");
} else {
logger.warn("unknown error {} when adding console ctrl handler", Native.getLastError());
}
} catch (UnsatisfiedLinkError e) {
// this will have already been logged by Kernel32Library, no need to repeat it
}
}
}
示例7: windowsImpl
static void windowsImpl() {
if (!Constants.WINDOWS) {
throw new IllegalStateException("bug: should not be trying to initialize ActiveProcessLimit for an unsupported OS");
}
JNAKernel32Library lib = JNAKernel32Library.getInstance();
// create a new Job
Pointer job = lib.CreateJobObjectW(null, null);
if (job == null) {
throw new UnsupportedOperationException("CreateJobObject: " + Native.getLastError());
}
try {
// retrieve the current basic limits of the job
int clazz = JNAKernel32Library.JOBOBJECT_BASIC_LIMIT_INFORMATION_CLASS;
JNAKernel32Library.JOBOBJECT_BASIC_LIMIT_INFORMATION limits = new JNAKernel32Library.JOBOBJECT_BASIC_LIMIT_INFORMATION();
limits.write();
if (!lib.QueryInformationJobObject(job, clazz, limits.getPointer(), limits.size(), null)) {
throw new UnsupportedOperationException("QueryInformationJobObject: " + Native.getLastError());
}
limits.read();
// modify the number of active processes to be 1 (exactly the one process we will add to the job).
limits.ActiveProcessLimit = 1;
limits.LimitFlags = JNAKernel32Library.JOB_OBJECT_LIMIT_ACTIVE_PROCESS;
limits.write();
if (!lib.SetInformationJobObject(job, clazz, limits.getPointer(), limits.size())) {
throw new UnsupportedOperationException("SetInformationJobObject: " + Native.getLastError());
}
// assign ourselves to the job
if (!lib.AssignProcessToJobObject(job, lib.GetCurrentProcess())) {
throw new UnsupportedOperationException("AssignProcessToJobObject: " + Native.getLastError());
}
} finally {
lib.CloseHandle(job);
}
logger.debug("Windows ActiveProcessLimit initialization successful");
}
示例8: testShardStats
public void testShardStats() throws IOException {
IndexShard shard = newStartedShard();
ShardStats stats = new ShardStats(shard.routingEntry(), shard.shardPath(),
new CommonStats(new IndicesQueryCache(Settings.EMPTY), shard, new CommonStatsFlags()), shard.commitStats(), shard.seqNoStats());
assertEquals(shard.shardPath().getRootDataPath().toString(), stats.getDataPath());
assertEquals(shard.shardPath().getRootStatePath().toString(), stats.getStatePath());
assertEquals(shard.shardPath().isCustomDataPath(), stats.isCustomDataPath());
if (randomBoolean() || true) { // try to serialize it to ensure values survive the serialization
BytesStreamOutput out = new BytesStreamOutput();
stats.writeTo(out);
StreamInput in = out.bytes().streamInput();
stats = ShardStats.readShardStats(in);
}
XContentBuilder builder = jsonBuilder();
builder.startObject();
stats.toXContent(builder, EMPTY_PARAMS);
builder.endObject();
String xContent = builder.string();
StringBuilder expectedSubSequence = new StringBuilder("\"shard_path\":{\"state_path\":\"");
expectedSubSequence.append(shard.shardPath().getRootStatePath().toString());
expectedSubSequence.append("\",\"data_path\":\"");
expectedSubSequence.append(shard.shardPath().getRootDataPath().toString());
expectedSubSequence.append("\",\"is_custom_data_path\":").append(shard.shardPath().isCustomDataPath()).append("}");
if (Constants.WINDOWS) {
// Some path weirdness on windows
} else {
assertTrue(xContent.contains(expectedSubSequence));
}
closeShards(shard);
}
示例9: testProcessStats
public void testProcessStats() {
ProcessStats stats = probe.processStats();
assertNotNull(stats);
assertThat(stats.getTimestamp(), greaterThan(0L));
if (Constants.WINDOWS) {
// Open/Max files descriptors are not supported on Windows platforms
assertThat(stats.getOpenFileDescriptors(), equalTo(-1L));
assertThat(stats.getMaxFileDescriptors(), equalTo(-1L));
} else {
assertThat(stats.getOpenFileDescriptors(), greaterThan(0L));
assertThat(stats.getMaxFileDescriptors(), greaterThan(0L));
}
ProcessStats.Cpu cpu = stats.getCpu();
assertNotNull(cpu);
// CPU percent can be negative if the system recent cpu usage is not available
assertThat(cpu.getPercent(), anyOf(lessThan((short) 0), allOf(greaterThanOrEqualTo((short) 0), lessThanOrEqualTo((short) 100))));
// CPU time can return -1 if the platform does not support this operation, let's see which platforms fail
assertThat(cpu.getTotal().millis(), greaterThan(0L));
ProcessStats.Mem mem = stats.getMem();
assertNotNull(mem);
// Commited total virtual memory can return -1 if not supported, let's see which platforms fail
assertThat(mem.getTotalVirtual().getBytes(), greaterThan(0L));
}
示例10: runTestTook
private void runTestTook(boolean controlled) throws Exception {
String bulkAction = copyToStringFromClasspath("/org/elasticsearch/action/bulk/simple-bulk.json");
// translate Windows line endings (\r\n) to standard ones (\n)
if (Constants.WINDOWS) {
bulkAction = Strings.replace(bulkAction, "\r\n", "\n");
}
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.add(bulkAction.getBytes(StandardCharsets.UTF_8), 0, bulkAction.length(), null, null, XContentType.JSON);
AtomicLong expected = new AtomicLong();
TransportBulkAction action = createAction(controlled, expected);
action.doExecute(null, bulkRequest, new ActionListener<BulkResponse>() {
@Override
public void onResponse(BulkResponse bulkItemResponses) {
if (controlled) {
assertThat(
bulkItemResponses.getTook().getMillis(),
equalTo(TimeUnit.MILLISECONDS.convert(expected.get(), TimeUnit.NANOSECONDS)));
} else {
assertThat(
bulkItemResponses.getTook().getMillis(),
greaterThanOrEqualTo(TimeUnit.MILLISECONDS.convert(expected.get(), TimeUnit.NANOSECONDS)));
}
}
@Override
public void onFailure(Exception e) {
}
});
}
示例11: testConsoleCtrlHandler
public void testConsoleCtrlHandler() {
if (Constants.WINDOWS) {
assertNotNull(JNAKernel32Library.getInstance());
assertThat(JNAKernel32Library.getInstance().getCallbacks().size(), equalTo(1));
} else {
assertNotNull(JNAKernel32Library.getInstance());
assertThat(JNAKernel32Library.getInstance().getCallbacks().size(), equalTo(0));
}
}
示例12: open
/** Just like {@link #open(File)}, but allows you to
* also specify a custom {@link LockFactory}. */
public static FSDirectory open(File path, LockFactory lockFactory) throws IOException {
if (Constants.JRE_IS_64BIT && MMapDirectory.UNMAP_SUPPORTED) {
return new MMapDirectory(path, lockFactory);
} else if (Constants.WINDOWS) {
return new SimpleFSDirectory(path, lockFactory);
} else {
return new NIOFSDirectory(path, lockFactory);
}
}
示例13: addConsoleCtrlHandler
static void addConsoleCtrlHandler(ConsoleCtrlHandler handler) {
// The console Ctrl handler is necessary on Windows platforms only.
if (Constants.WINDOWS) {
try {
boolean result = JNAKernel32Library.getInstance().addConsoleCtrlHandler(handler);
if (result) {
logger.debug("console ctrl handler correctly set");
} else {
logger.warn("unknown error " + Native.getLastError() + " when adding console ctrl handler:");
}
} catch (UnsatisfiedLinkError e) {
// this will have already been logged by Kernel32Library, no need to repeat it
}
}
}
示例14: getMatchingFileStore
/**
* Files.getFileStore(Path) useless here! Don't complain, just try it yourself.
*/
@SuppressForbidden(reason = "works around the bugs")
static FileStore getMatchingFileStore(Path path, FileStore fileStores[]) throws IOException {
if (Constants.WINDOWS) {
return getFileStoreWindows(path, fileStores);
}
final FileStore store;
try {
store = Files.getFileStore(path);
} catch (IOException unexpected) {
// give a better error message if a filestore cannot be retrieved from inside a FreeBSD jail.
if (Constants.FREE_BSD) {
throw new IOException("Unable to retrieve mount point data for " + path +
". If you are running within a jail, set enforce_statfs=1. See jail(8)", unexpected);
} else {
throw unexpected;
}
}
try {
String mount = getMountPointLinux(store);
FileStore sameMountPoint = null;
for (FileStore fs : fileStores) {
if (mount.equals(getMountPointLinux(fs))) {
if (sameMountPoint == null) {
sameMountPoint = fs;
} else {
// more than one filesystem has the same mount point; something is wrong!
// fall back to crappy one we got from Files.getFileStore
return store;
}
}
}
if (sameMountPoint != null) {
// ok, we found only one, use it:
return sameMountPoint;
} else {
// fall back to crappy one we got from Files.getFileStore
return store;
}
} catch (Exception e) {
// ignore
}
// fall back to crappy one we got from Files.getFileStore
return store;
}
示例15: initializeNatives
/** initialize native resources */
public static void initializeNatives(Path tmpFile, boolean mlockAll, boolean seccomp, boolean ctrlHandler) {
final ESLogger logger = Loggers.getLogger(Bootstrap.class);
// check if the user is running as root, and bail
if (Natives.definitelyRunningAsRoot()) {
if (Boolean.parseBoolean(System.getProperty("es.insecure.allow.root"))) {
logger.warn("running as ROOT user. this is a bad idea!");
} else {
throw new RuntimeException("don't run elasticsearch as root.");
}
}
// enable secure computing mode
if (seccomp) {
Natives.trySeccomp(tmpFile);
}
// mlockall if requested
if (mlockAll) {
if (Constants.WINDOWS) {
Natives.tryVirtualLock();
} else {
Natives.tryMlockall();
}
}
// listener for windows close event
if (ctrlHandler) {
Natives.addConsoleCtrlHandler(new ConsoleCtrlHandler() {
@Override
public boolean handle(int code) {
if (CTRL_CLOSE_EVENT == code) {
logger.info("running graceful exit on windows");
Bootstrap.stop();
return true;
}
return false;
}
});
}
// force remainder of JNA to be loaded (if available).
try {
JNAKernel32Library.getInstance();
} catch (Throwable ignored) {
// we've already logged this.
}
// init lucene random seed. it will use /dev/urandom where available:
StringHelper.randomId();
}