/** * Sets the node height used for drawing. * <p> * Also updates the font size used for drawing sequences within nodes. * * @param nodeHeight the node height */ public final void setNodeHeight(final double nodeHeight) { this.nodeHeight = nodeHeight; this.snpHeight = nodeHeight * SNP_HEIGHT_FACTOR; final Text text = new Text("X"); text.setFont(new Font(DEFAULT_NODE_FONT, 1)); final double font1PHeight = text.getLayoutBounds().getHeight(); final String font; if (SystemUtils.IS_OS_MAC) { font = DEFAULT_MAC_NODE_FONT; } else { font = DEFAULT_NODE_FONT; } final double fontSize = DEFAULT_NODE_FONT_HEIGHT_SCALAR * nodeHeight / font1PHeight; this.nodeFont = new Font(font, fontSize); text.setFont(nodeFont); this.charWidth = text.getLayoutBounds().getWidth(); this.charHeight = text.getLayoutBounds().getHeight(); }
private void doStart() { try { String[] command; if (SystemUtils.IS_OS_WINDOWS) { // for windows test command = new String[] { "C:/Program Files/Java/jdk1.8.0_91/bin/java", "-version" }; } else { // real use Assert.notNull(file); command = new String[] { this.command, argf, calculateFileName() }; } process = new ProcessBuilder(command).redirectErrorStream(true).start(); BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream())); String line = null; while ((line = input.readLine()) != null) { content.add(String.format("%s : %s", name, line)); this.checkForEviction(); } int exitVal = process.waitFor(); log.info("Exited with error code " + exitVal); } catch (Exception e) { log.error("Error", e); throw new RuntimeException(e); } }
/** * Creates a static {@code Logger} instance. * * @return a static {@code Logger} with properties: * <ul> * <li>Name: {@code "DefaultDatabaseConfigurator"}.</li> * <li>Output file pattern: * {@code user.home/.kawansoft/log/AceQL.log}.</li> * <li>Formatter: {@code SimpleFormatter}.</li> * <li>Limit: 200Mb.</li> * <li>Count (number of files to use): 2.</li> * </ul> */ @Override public Logger getLogger() throws IOException { if (ACEQL_LOGGER != null) { return ACEQL_LOGGER; } File logDir = new File(SystemUtils.USER_HOME + File.separator + ".kawansoft" + File.separator + "log"); logDir.mkdirs(); String pattern = logDir.toString() + File.separator + "AceQL.log"; ACEQL_LOGGER = Logger.getLogger(DefaultDatabaseConfigurator.class.getName()); Handler fh = new FileHandler(pattern, 200 * 1024 * 1024, 2, true); fh.setFormatter(new SimpleFormatter()); ACEQL_LOGGER.addHandler(fh); return ACEQL_LOGGER; }
/** * * @return the product file that contains the product name */ private static File getProductFile() { // Use absolute directory: client side and Tomcat side don'ts have same // user.home value! String exchangeDir = null; if (SystemUtils.IS_OS_WINDOWS) { exchangeDir = "c:\\temp\\"; } else { if (FrameworkSystemUtil.isAndroid()) { // exchangeDir = "/sdcard/"; exchangeDir = System.getProperty("java.io.tmpdir"); if (!exchangeDir.endsWith(System.getProperty("file.separator"))) { exchangeDir += System.getProperty("file.separator"); } } else { exchangeDir = "/tmp/"; } } File productFile = new File(exchangeDir + "aceql-database-to-use.txt"); return productFile; }
public static void read(File file, Consumer<File> handle) throws IOException { Path temp; if (SystemUtils.IS_OS_LINUX) { temp = Files.createTempFile(SHARED_MEMORY, TEMP_PREFIX, null); } else { temp = Files.createTempFile(TEMP_PREFIX, null); } try ( InputStream is = new FileInputStream(file); GZIPInputStream gis = new GZIPInputStream(is); OutputStream os = Files.newOutputStream(temp); ) { byte[] buffer = new byte[1024]; int length; while ((length = gis.read(buffer, 0, 1024)) != -1) { os.write(buffer, 0, length); } handle.accept(temp.toFile()); } finally { Files.delete(temp); } }
/** * Delete a file or directory and its contents recursively. * Don't follow directories if they are symlinks. * * @param file Input file / dir to be deleted * @throws IOException if deletion is unsuccessful */ public static void deleteRecursively(File file) throws IOException { if (file == null) { return; } // On Unix systems, use operating system command to run faster // If that does not work out, fallback to the Java IO way if (SystemUtils.IS_OS_UNIX) { try { deleteRecursivelyUsingUnixNative(file); return; } catch (IOException e) { logger.warn("Attempt to delete using native Unix OS command failed for path = {}. " + "Falling back to Java IO way", file.getAbsolutePath(), e); } } deleteRecursivelyUsingJavaIO(file); }
public List<CarnotzetModule> getModules() { if (modules == null) { modules = resolver.resolve(config.getTopLevelModuleId(), failOnDependencyCycle); if (SystemUtils.IS_OS_LINUX || !getResourcesFolder().resolve("expanded-jars").toFile().exists()) { resourceManager.extractResources(modules); modules = computeServiceIds(modules); resourceManager.resolveResources(modules); } log.debug("configuring modules"); modules = configureModules(modules); if (config.getExtensions() != null) { for (CarnotzetExtension feature : config.getExtensions()) { log.debug("Extension [{}] enabled", feature.getClass().getSimpleName()); modules = feature.apply(this); } } assertNoDuplicateArtifactId(modules); modules = selectModulesForUniqueServiceId(modules); } return modules; }
public static Sensor getSensor() { if (SystemUtils.IS_OS_WINDOWS) { return new WindowsSensor(); } else if (SystemUtils.IS_OS_LINUX) { return new LMSensor(); } else { System.err.println(SystemUtils.OS_NAME + " is not a supported operating system."); return new Sensor() { @Override public void poll() throws IOException { temperatures.put("Fake 0", 0d); temperatures.put("Fake 100", 100d); } }; } }
@Override public Solution solve(final Board board, final Configuration configuration) throws SolutionException { LOG.traceEntry("solve(board={}, configuration={})", board, configuration); LOG.debug("Attempting serial solve for board:{}{}", SystemUtils.LINE_SEPARATOR, board); for (final Move move : board.getAvailableMoves()) { try { final Solution solution = new SolutionSearch(configuration, move).search(); LOG.debug("Found solution:{}{}", SystemUtils.LINE_SEPARATOR, solution); return LOG.traceExit(solution); } catch (SolutionException e) { // Ignore failed solution } } LOG.debug("No solution found"); return LOG.traceExit(new Solution(configuration)); }
public Solution solve(final Board board) throws BrickPopSolverException { LOG.traceEntry("solve(board={})", board); Objects.requireNonNull(board, "board"); LOG.info("Solving board: {}", board); final SolutionService solutionService = configuration.getSolutionService(); final Instant start = Instant.now(); final Solution solution = solutionService.solve(board, configuration); final Instant end = Instant.now(); if (solution.isEmpty()) { throw new SolutionException("No solution could be found"); } LOG.info("Found a solution in {} seconds:{}{}", () -> Duration.between(start, end).getSeconds(), () -> SystemUtils.LINE_SEPARATOR, () -> solution); return LOG.traceExit(solution); }
@PostConstruct public void init() { if (SystemUtils.IS_OS_LINUX) { usersPath = environment.getProperty("image.path.linux.users"); formsPath = environment.getProperty("image.path.linux.forms"); } else if (SystemUtils.IS_OS_MAC) { usersPath = environment.getProperty("image.path.mac.users"); formsPath = environment.getProperty("image.path.mac.forms"); } else if (SystemUtils.IS_OS_WINDOWS) { usersPath = environment.getProperty("image.path.windows.users"); formsPath = environment.getProperty("image.path.windows.forms"); } userContext = environment.getProperty("image.context.user"); formContext = environment.getProperty("image.context.form"); }
/** * Enables handling of scroll and mouse wheel events for the node. * This type of events has a peculiarity on Windows. See the javadoc of notifyScrollEvents for more information. * @see #notifyScrollEvent * @param intersectionTestFunc a function that takes an event object and must return boolean * @return itself to let you use a chain of calls */ MouseEventNotificator setOnScrollListener(Function<NativeMouseWheelEvent, Boolean> intersectionTestFunc) { if (SystemUtils.IS_OS_WINDOWS) { if (!GlobalScreen.isNativeHookRegistered()) { try { GlobalScreen.registerNativeHook(); } catch (NativeHookException | UnsatisfiedLinkError e) { e.printStackTrace(); Main.log("Failed to initialize the native hooking. Rolling back to using JavaFX events..."); sender.addEventFilter(ScrollEvent.SCROLL, this::notifyScrollEvent); return this; } } mouseWheelListener = event -> notifyScrollEvent(event, intersectionTestFunc); GlobalScreen.addNativeMouseWheelListener(mouseWheelListener); } else { sender.addEventFilter(ScrollEvent.SCROLL, this::notifyScrollEvent); } return this; }
public static File getSteamDir() throws RegistryException, IOException { if (null == steamDir) { if(SystemUtils.IS_OS_WINDOWS) { steamDir = test(new File(WindowsRegistry.getInstance().readString(HKey.HKCU, "Software\\Valve\\Steam", "SteamPath"))); } else if(SystemUtils.IS_OS_MAC) { steamDir = test(new File(SystemUtils.getUserHome()+"/Library/Application Support/Steam")); } else if(SystemUtils.IS_OS_LINUX) { ArrayList<File> fl = new ArrayList<>(); fl.add(new File(SystemUtils.getUserHome()+"/.steam/steam")); fl.add(new File(SystemUtils.getUserHome()+"/.steam/Steam")); fl.add(new File(SystemUtils.getUserHome()+"/.local/share/steam")); fl.add(new File(SystemUtils.getUserHome()+"/.local/share/Steam")); steamDir = test(fl); } } return steamDir; }
private void diaplayWarnForDetach(JFrame parent) { if (Config.instance().to().getBoolean(Config.Entry.WARN_ON_OSX_TO_DETACH.key(), SystemUtils.IS_OS_MAC_OSX)) { if (planTowerSensor.isConnected()) { JOptionPane.showMessageDialog(parent, "<html>The sensor is still attached.<br><br>" + "This instance or the next start of the application may <b>hang</b><br>" + "when the device is still attached while app or port is being closed.<br>" + "<b>In such a case only reboot helps.</b><br><br>" + "This behavior is being observed when using some cheap PL2303<br>" + "uart-to-usb and their drivers.<br><br>" + "You can now forcibly detach the device now.<br><br>" + "Press OK to continue closing.</html>", "Warning", JOptionPane.WARNING_MESSAGE); } } }
private static void setLookAndFeel() { if (SystemUtils.IS_OS_MAC_OSX) { // must be before any AWT interaction System.setProperty("apple.laf.useScreenMenuBar", "true"); // place menubar (if any) in native menu bar System.setProperty("apple.awt.application.name", Constants.PROJECT_NAME); if (Config.instance().to().getBoolean(Config.Entry.SYSTEM_TRAY.key(), Constants.SYSTEM_TRAY)) { logger.debug("Hiding dock icon since system-tray integration is enabled"); System.setProperty("apple.awt.UIElement", "true"); } } try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { logger.error("Ooops, problem setting system L&F", e); } }
private void initControlPanel(Config config) { portField.setTextFormatter(new TextFormatter<>(change -> { change.setText(change.getText().replaceAll("[^0-9.,]", "")); return change; })); if (SystemUtils.IS_OS_UNIX) { // change web-cache dir // from: $HOME/.com.gitlab.anlar.lunatic.gui.LunaticApplication/webview // to: $HOME/.cache/lunatic-smtp/webview/ this.emailText.getEngine().setUserDataDirectory(new File( SystemUtils.USER_HOME + File.separator + ".cache" + File.separator + "lunatic-smtp", "webview")); } portField.setText(String.valueOf(config.getPort())); messagesField.setText("0"); setStartButtonText(false); dirField.setText(config.getDirectory()); saveDirCheck.setSelected(config.isWrite()); }
public void initializeDefaultPreferences() { IPreferenceStore store = IDEUtil.getPreferences().getPreferenceStore(); EGradleCallType defaultCallType = null; if (SystemUtils.IS_OS_WINDOWS){ defaultCallType = EGradleCallType.WINDOWS_GRADLE_WRAPPER; }else{ defaultCallType = EGradleCallType.LINUX_GRADLE_WRAPPER; } store.setDefault(P_OUTPUT_VALIDATION_ENABLED.getId(), true); store.setDefault(P_FILEHANDLING_AUTOMATICALLY_DERIVE_BUILDFOLDERS.getId(), false); store.setDefault(P_IMPORT__EXECUTE_ASSEMBLE_TASK.getId(), true); store.setDefault(P_IMPORT__DO_CLEAN_PROJECTS.getId(),true); store.setDefault(P_SHOW_CONSOLE_VIEW_ON_BUILD_FAILED_ENABLED.getId(), true); store.setDefault(P_DECORATION_SUBPROJECTS_WITH_ICON_ENABLED.getId(), true); store.setDefault(P_GRADLE_CALL_TYPE.getId(),defaultCallType.getId()); store.setDefault(P_GRADLE_SHELL.getId(), defaultCallType.getDefaultShell().getId()); store.setDefault(P_GRADLE_INSTALL_BIN_FOLDER.getId(), defaultCallType.getDefaultGradleBinFolder()); store.setDefault(P_GRADLE_CALL_COMMAND.getId(), defaultCallType.getDefaultGradleCommand()); store.setDefault(P_MIGRATE_IDE_STATE.getId(), MigrationState.NOT_MIGRATED.name()); }
@SuppressFBWarnings("PRMC_POSSIBLY_REDUNDANT_METHOD_CALLS") @Test public void searchContent() throws ProcessConfigurationException, IOException, InterruptedException, JsonArrayReaderException { final Output response = ProcessRunnerFactory.startProcess( new ConfigurationBuilder(getDefaultInterpreter(), getInterPreterVersion()) .setWorkigDir(Constants.DEFAULT_CURRENT_DIR_PATH) .setMasterLogFile(Utilities.createTempLogDump(), true) .build()); assertThat("Validating process return code : ", response.getReturnCode(), is(0)); if (SystemUtils.IS_OS_LINUX) { assertThat( "Validating searchMasterLog result for content in the output in UNIX : ", response.searchMasterLog(".*GNU.*"), is(true)); } else if (SystemUtils.IS_OS_WINDOWS) { assertThat( "Validating searchMasterLog result for content in the output in Windows : ", response.searchMasterLog("Microsoft Windows.*"), is(true)); } }
@Nonnull public String getOs() { String result = this.os; if (isSafeEmpty(result)) { if (SystemUtils.IS_OS_WINDOWS) { result = "windows"; } else if (SystemUtils.IS_OS_LINUX) { result = "linux"; } else if (SystemUtils.IS_OS_FREE_BSD) { result = "freebsd"; } else { result = "darwin"; } } return result; }
private List<String> buildCmd() { List<String> cmd = new ArrayList<>(); File logicbin = null; if(SystemUtils.IS_OS_WINDOWS) { logicbin = LogicRunMain.LOGIC_BIN_WIN; } else if(SystemUtils.IS_OS_UNIX) { logicbin = LogicRunMain.LOGIC_BIN_UNIX; } if(logicbin == null) { logger.error("Unsupported operating system"); return null; } cmd.add(logicbin.getAbsolutePath()); addGeneralParams(cmd); addAdvancedParams(cmd); addDebugParams(cmd); cmd.add(params.getTextValue(TextParam.GFile)); return cmd; }
/** * 获得自定义的空心字体 STCAIYUN.TTF,该字体已经制成为 jar,需要加入项目的 classpath * 经过测试,该空心字体作为 pdf 的水印,不会遮挡 pdf 原文,支持中文 * 需要注意的是,空心字体不能太小,否则会看不清楚 * * @return * @throws IOException */ private static PdfFont getPdfFont() throws IOException { //空心字体 String fontName = "/STCAIYUN.TTF"; String fontPath = SystemUtils.getJavaIoTmpDir() + File.separator + MyConstants.JarTempDir + File.separator + fontName; //如果已经拷贝过,就不用再拷贝了 if (!Files.exists(Paths.get(fontPath))) { MyFileUtils.copyResourceFileFromJarLibToTmpDir(fontName); } return PdfFontFactory.createFont(fontPath, PdfEncodings.IDENTITY_H); }
/** * 获取 pdfdecrypt.exe 文件路径 * * @return * @throws IOException */ private static String getPdfPdfdecryptExec() { //命令行模式,只需要两个文件即可 String exec1 = "/pdfdecrypt.exe"; String exec2 = "/license.dat"; String tempPath = SystemUtils.getJavaIoTmpDir() + File.separator + MyConstants.JarTempDir + File.separator; String exec1Path = tempPath + exec1; String exec2Path = tempPath + exec2; //如果已经拷贝过,就不用再拷贝了 if (!Files.exists(Paths.get(exec1Path))) MyFileUtils.copyResourceFileFromJarLibToTmpDir(exec1); if (!Files.exists(Paths.get(exec2Path))) MyFileUtils.copyResourceFileFromJarLibToTmpDir(exec2); return exec1Path; }
/** * 获得全平台的基础路径<br> * 真正的跨平台! * @author Administrator * @return */ public static String getConfigBasePathForAll() { String ret = ""; //根据操作系统决定真正的配置路径 if (SystemUtils.IS_OS_WINDOWS) { ret = FileKit.getMyConfigBasePathForWindows(); } else if (SystemUtils.IS_OS_LINUX) { ret = CONFIG_BASEPATH_LINUX; } else if (SystemUtils.IS_OS_MAC) { ret = CONFIG_BASEPATH_MAC; } else { //其他情况下,都是类Unix的系统,因此均采用Linux的路径设置 ret = CONFIG_BASEPATH_LINUX; } return ret; }
/** * Initializes the API and starts mod loading. Called from * {@link Minecraft#startGame()} and {@link DedicatedServer#startServer()}. * * @param sidedHandler the sided handler */ public static void minecraftConstruction(SidedHandler sidedHandler) { OpenModLoader.sidedHandler = sidedHandler; getLogger().info("Loading OpenModLoader " + getVersion()); getLogger().info("Running Minecraft %s on %s using Java %s", mcversion, SystemUtils.OS_NAME, SystemUtils.JAVA_VERSION); GameRegistry.init(); Dictionaries.init(); ModLoader.loadMods(); UpdateManager.checkForUpdates(); getSidedHandler().onInitialize(); channel = ChannelManager.create("oml") .createPacket("snackbar") .with("component", DataTypes.TEXT_COMPONENT) .handle((context, packet) -> getSidedHandler().openSnackbar(packet.get("component", DataTypes.TEXT_COMPONENT))) .build(); }
public static void validateJdkVersion() { boolean warn = false; if (SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_1_8)) { // We need 1.8.0_111 at least String version = SystemUtils.JAVA_VERSION; int ix = version.lastIndexOf('_'); if (ix > 0) { int patch = Integer.valueOf(version.substring(ix + 1)); if (patch < 111) { warn = true; } } } else { // Not even Java 1.8 warn = true; } if (warn) { new Log(VersionUtils.class).info(Style.yellow( "Please update your Java™ Runtime Environment (JRE) from %s to version 1.8.0_111 or newer.", SystemUtils.JAVA_VERSION)); } }
private String prompt(ArtifactDescriptor artifact) { if (artifact != null && !(artifact.group().equals(Constants.GROUP) && artifact.artifact().equals(Constants.RUG_ARTIFACT))) { log.info(Style.yellow("%s:%s", artifact.group(), artifact.artifact()) + Style.gray(" (%s%s%s%s%s)", artifact.version(), Constants.DOT, (artifact instanceof LocalArtifactDescriptor ? "local" : artifact.extension().toString().toLowerCase()), Constants.DOT, rugVersion)); } else { log.info(Style.yellow("%s", FileUtils.relativize(SystemUtils.getUserDir())) + Style.gray(" (%s)", rugVersion)); } // reset interrupt signal interrupt = false; return ShellUtils.DEFAULT_PROMPT; }
/** * Construct a Gremlin Server instance from the {@link ServerGremlinExecutor} which internally carries some * pre-constructed objects used by the server as well as the {@link Settings} object itself. This constructor * is useful when Gremlin Server is being used in an embedded style and there is a need to share thread pools * with the hosting application. * * @deprecated As of release 3.1.1-incubating, not replaced. * @see <a href="https://issues.apache.org/jira/browse/TINKERPOP-912">TINKERPOP-912</a> */ @Deprecated public GremlinServer(final ServerGremlinExecutor<EventLoopGroup> serverGremlinExecutor) { this.serverGremlinExecutor = serverGremlinExecutor; this.settings = serverGremlinExecutor.getSettings(); this.isEpollEnabled = settings.useEpollEventLoop && SystemUtils.IS_OS_LINUX; if(settings.useEpollEventLoop && !SystemUtils.IS_OS_LINUX){ logger.warn("cannot use epoll in non-linux env, falling back to NIO"); } Runtime.getRuntime().addShutdownHook(new Thread(() -> this.stop().join(), SERVER_THREAD_PREFIX + "shutdown")); final ThreadFactory threadFactoryBoss = ThreadFactoryUtil.create("boss-%d"); if(isEpollEnabled) { bossGroup = new EpollEventLoopGroup(settings.threadPoolBoss, threadFactoryBoss); } else{ bossGroup = new NioEventLoopGroup(settings.threadPoolBoss, threadFactoryBoss); } workerGroup = serverGremlinExecutor.getScheduledExecutorService(); gremlinExecutorService = serverGremlinExecutor.getGremlinExecutorService(); }
public TabCloser(final TabHolder pane) { super(new FlowLayout(FlowLayout.LEFT, 0, 0)); setOpaque(false); JLabel label = new JLabel() { @Override public String getText() { int i = pane.indexOfTabComponent(TabCloser.this); if (i != -1) { setText(pane.getTitleAt(i)); return super.getText(); } return null; } }; add(label); label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5)); mButton = new TabButton(); int buttonPos = SystemUtils.IS_OS_WINDOWS ? 1 : 0; add(mButton, buttonPos); setBorder(BorderFactory.createEmptyBorder(2, 0, 0, 0)); }
public static JvmInfo create() { JvmInfo jvmInfo = new JvmInfo(); jvmInfo.specVersion = SystemUtils.JAVA_SPECIFICATION_VERSION; jvmInfo.classVersion = SystemUtils.JAVA_CLASS_VERSION; jvmInfo.jreVersion = SystemUtils.JAVA_VERSION; jvmInfo.jreVendor = SystemUtils.JAVA_VENDOR; jvmInfo.vmName = SystemUtils.JAVA_VM_NAME; jvmInfo.vmVendor = SystemUtils.JAVA_VM_VENDOR; jvmInfo.vmVersion = SystemUtils.JAVA_VM_VERSION; RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean(); jvmInfo.inputArguments = new ArrayList<>(runtimeMXBean.getInputArguments()); jvmInfo.startedTimestamp = new Date(runtimeMXBean.getStartTime()); jvmInfo.defaultTimeZone = TimeZone.getDefault().getID(); jvmInfo.defaultCharset = Charset.defaultCharset().displayName(); return jvmInfo; }
/** * Opens a browser for the given {@code URI}. It is supposed to avoid issues with KDE systems. * * @param uri URI to browse */ public static void browse(URI uri) { try { if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) { Desktop.getDesktop().browse(uri); return; } else if (SystemUtils.IS_OS_UNIX && (new File("/usr/bin/xdg-open").exists() || new File("/usr/local/bin/xdg-open").exists())) { new ProcessBuilder("xdg-open", uri.toString()).start(); return; } throw new UnsupportedOperationException("Your operating system does not support launching browser from Net2Plan"); } catch (IOException | UnsupportedOperationException e) { throw new RuntimeException(e); } }
@Test public void can_access_host_networked_ports() throws Exception { // On linux the docker host is running on localhost, so host ports are accessible through localhost. // On Windows and Mac however, docker is being run in a linux VM. As such the docker host is the running // VM, not localhost, and the ports are inaccessible from outside the VM. // As such, this test will only run on linux. assumeTrue("Host ports are only accessible on linux", SystemUtils.IS_OS_LINUX); DockerComposeRule docker = DockerComposeRule.builder() .file("src/test/resources/host-networked-docker-compose.yaml") .waitingForHostNetworkedPort(5432, toBeOpen()) .build(); try { docker.before(); assertThat(docker.hostNetworkedPort(5432).getInternalPort(), is(5432)); assertThat(docker.hostNetworkedPort(5432).getExternalPort(), is(5432)); } finally { docker.after(); } }
@Override protected void doBuildDestContext() { DestTemplateParameterContext destContext = contextProvider.getDestContext(); // set interlaced to false if not specified String interlaced = destContext.getParameterValue(INTERLACED); destContext.addParameter(INTERLACED, interlaced == null ? Boolean.FALSE.toString() : interlaced); // define is dar provided destContext.addParameter(DEST_PARAM_VIDEO_IS_DAR_SPECIFIED, Boolean.toString(destContext.getParameterValue(DAR) != null)); // set frame rate for interlaced scan // for ffmpeg iFrameRate=frameRate*2 // for prenc iFrameRate=frameRate BigFraction iFrameRate = ConversionHelper.parseEditRate(destContext.getParameterValue(FRAME_RATE)); if (!SystemUtils.IS_OS_MAC_OSX) { iFrameRate = iFrameRate.multiply(2); } destContext.addParameter(DEST_PARAM_VIDEO_IFRAME_RATE, ConversionHelper.toREditRate(iFrameRate)); }
@Override public Object apply(WarpScriptStack stack) throws WarpScriptException { Object top = stack.pop(); long instant; if (top instanceof String) { if (SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_1_8)) { instant = io.warp10.script.unary.TOTIMESTAMP.parseTimestamp(top.toString()); } else { instant = fmt.parseDateTime((String) top).getMillis() * Constants.TIME_UNITS_PER_MS; } } else if (!(top instanceof Long)) { throw new WarpScriptException(getName() + " expects a timestamp or ISO8601 datetime string on top of the stack."); } else { instant = ((Number) top).longValue(); } long now = TimeSource.getTime(); if (now < instant) { throw new WarpScriptException("Current time is before '" + top + "'"); } return stack; }
@Override public Object apply(WarpScriptStack stack) throws WarpScriptException { Object top = stack.pop(); long instant; if (top instanceof String) { if (SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_1_8)) { instant = io.warp10.script.unary.TOTIMESTAMP.parseTimestamp(top.toString()); } else { instant = fmt.parseDateTime((String) top).getMillis() * Constants.TIME_UNITS_PER_MS; } } else if (!(top instanceof Long)) { throw new WarpScriptException(getName() + " expects a timestamp or ISO8601 datetime string on top of the stack."); } else { instant = ((Number) top).longValue(); } long now = TimeSource.getTime(); if (now > instant) { throw new WarpScriptException("Current time is after '" + top + "'"); } return stack; }
@Override public LocalResourceId resolve(String other, ResolveOptions resolveOptions) { checkState( isDirectory, "Expected the path is a directory, but had [%s].", pathString); checkArgument( resolveOptions.equals(StandardResolveOptions.RESOLVE_FILE) || resolveOptions.equals(StandardResolveOptions.RESOLVE_DIRECTORY), "ResolveOptions: [%s] is not supported.", resolveOptions); checkArgument( !(resolveOptions.equals(StandardResolveOptions.RESOLVE_FILE) && other.endsWith("/")), "The resolved file: [%s] should not end with '/'.", other); if (SystemUtils.IS_OS_WINDOWS) { return resolveLocalPathWindowsOS(other, resolveOptions); } else { return resolveLocalPath(other, resolveOptions); } }
@Test public void testMatchInDirectory() throws Exception { List<String> expected = ImmutableList.of(temporaryFolder.newFile("a").toString()); temporaryFolder.newFile("aa"); temporaryFolder.newFile("ab"); String expectedFile = expected.get(0); int slashIndex = expectedFile.lastIndexOf('/'); if (SystemUtils.IS_OS_WINDOWS) { slashIndex = expectedFile.lastIndexOf('\\'); } String directory = expectedFile.substring(0, slashIndex); String relative = expectedFile.substring(slashIndex + 1); System.setProperty("user.dir", directory); List<MatchResult> results = localFileSystem.match(ImmutableList.of(relative)); assertThat( toFilenames(results), containsInAnyOrder(expected.toArray(new String[expected.size()]))); }
@Test public void testResolveInWindowsOS() throws Exception { if (!SystemUtils.IS_OS_WINDOWS) { // Skip tests return; } assertEquals( toResourceIdentifier("C:\\my home\\out put"), toResourceIdentifier("C:\\my home\\") .resolve("out put", StandardResolveOptions.RESOLVE_FILE)); assertEquals( toResourceIdentifier("C:\\out put"), toResourceIdentifier("C:\\my home\\") .resolve("..", StandardResolveOptions.RESOLVE_DIRECTORY) .resolve(".", StandardResolveOptions.RESOLVE_DIRECTORY) .resolve("out put", StandardResolveOptions.RESOLVE_FILE)); assertEquals( toResourceIdentifier("C:\\my home\\**\\*"), toResourceIdentifier("C:\\my home\\") .resolve("**", StandardResolveOptions.RESOLVE_DIRECTORY) .resolve("*", StandardResolveOptions.RESOLVE_FILE)); }
private static void initLocalLpSolve() throws Exception { // Find or create the jopt-lib-lpsolve directory in temp File lpSolveTempDir = NativeUtils.createTempDir("jopt-lib-lpsolve"); lpSolveTempDir.deleteOnExit(); // Add this directory to the java library path NativeUtils.addLibraryPath(lpSolveTempDir.getAbsolutePath()); // Add the right files to this directory if (SystemUtils.IS_OS_WINDOWS) { if (SystemUtils.OS_ARCH.contains("64")) { NativeUtils.loadLibraryFromJar("/lib/64_lpsolve55.dll", lpSolveTempDir); NativeUtils.loadLibraryFromJar("/lib/64_lpsolve55j.dll", lpSolveTempDir); } else { NativeUtils.loadLibraryFromJar("/lib/32_lpsolve55.dll", lpSolveTempDir); NativeUtils.loadLibraryFromJar("/lib/32_lpsolve55j.dll", lpSolveTempDir); } } else if (SystemUtils.IS_OS_UNIX) { if (SystemUtils.OS_ARCH.contains("64")) { NativeUtils.loadLibraryFromJar("/lib/64_liblpsolve55.so", lpSolveTempDir); NativeUtils.loadLibraryFromJar("/lib/64_liblpsolve55j.so", lpSolveTempDir); } else { NativeUtils.loadLibraryFromJar("/lib/32_liblpsolve55.so", lpSolveTempDir); NativeUtils.loadLibraryFromJar("/lib/32_liblpsolve55j.so", lpSolveTempDir); } } }
/** * Returns a {@link File} instance for the given data file name. * * @param fileName the file name * @return the application data {@link File} object */ public static File getFile(final String fileName) { String baseDirectory = System.getProperty("user.home"); // Use the AppData directory if on Windows if (SystemUtils.IS_OS_WINDOWS) { baseDirectory = System.getenv("AppData"); } return new File(String.format("%s/%s", baseDirectory, APPLICATION_FOLDER_NAME), fileName); }
private static LocalCommandExecutor getLocalCommandExecutor() { if (SystemUtils.IS_OS_WINDOWS) { return new WindowsLocalCommandExecutor(); } else if (SystemUtils.IS_OS_UNIX) { return new UnixLocalCommandExecutor(); } else { throw new UnsupportedOperationException("OS not supported for local execution"); } }