/** * Starts the web server. */ public boolean startServer() { listen = true; if (!(new File(serverConfig. getDocumentRootPath()) .isDirectory())) { LOGGER.log(Level.WARNING, "DocumentRoot does not exist! PATH {0}", new Object[]{ serverConfig.getDocumentRootPath() }); } if (!isNumberOfThreadsSufficient() || !isTempPathWritable() || !bindSocket()) { listen = false; return false; } LOGGER.log(Level.INFO, "Server has been started. Listening on port {0}", new Object[]{ serverConfig.getListenPort() }); FileUtilities.clearDirectory(serverConfig.getTempPath()); start(); return true; }
/** * {@inheritDoc} */ @Override protected Set<ResourceProvider> getAdditionalResourceProviders(final ServerConfig serverConfig) { Set<ResourceProvider> resourceProviders = new HashSet<>(); resourceProviders.add(getAssetsResourceProvider(serverConfig.getMimeTypeMapping())); return resourceProviders; }
/** * Logs the user in if the login and password match. * * @param login * @param password * @return */ public boolean doLogin(final String login, final String password) { if (serverConfig.getAttribute("admin.login").equals(login) && serverConfig.getAttribute("admin.password").equals(password)) { session.setAttribute(ATTR_LOGGEDIN, "1"); return true; } else { LOGGER.fine("Not logging in - wrong password"); } return false; } }
private ServerConfig getDefaultServerConfig() throws IOException { ServerConfig serverConfig = mock(ServerConfig.class); when(serverConfig.getDocumentRootPath()).thenReturn("/tmp/SomePathThatDoesNotExist"); when(serverConfig.getTempPath()).thenReturn(FileUtils.createTempDirectory()); when(serverConfig.getMaxServerThreads()).thenReturn(99); return serverConfig; } }
@Test public void shouldCreateFromPath() throws IOException { writeFiles(DEFAULT_CONFIG_DATA + "DefaultMimeType mime/text\n"); ServerConfig serverConfig = ServerConfigImpl.createFromPath(workingDirectory, tempDirectory); assertThat(serverConfig.getTempPath(), is(tempDirectory)); assertThat(serverConfig.getBasePath(), is(workingDirectory)); assertThat(serverConfig.getDocumentRootPath(), is(workingDirectory + "wwwx")); assertThat(serverConfig.getDirectoryIndex(), hasItem("index.php")); assertThat(serverConfig.getDirectoryIndex(), hasItem("index.html")); assertThat(serverConfig.getDirectoryIndex().size(), is(2)); assertThat(serverConfig.getErrorDocument403Path(), is(workingDirectory + "error403.html")); assertThat(serverConfig.getErrorDocument404Path(), is(workingDirectory + "error404.html")); assertThat(serverConfig.getListenPort(), is(8090)); assertThat(serverConfig.getMaxServerThreads(), is(3)); assertThat(serverConfig.isKeepAlive(), is(true)); assertThat(serverConfig.getMimeTypeMapping().getMimeTypeByExtension("ANY"), is("mime/text")); assertThat(serverConfig.getAttribute(ADDITIONAL_ATTRIBUTE_NAME), is(ORIGINAL_VALUE)); }
@Test public void shouldReadSystemPropertiesWhenNoFileIsPresent() throws IOException { System.setProperty("server.port", "9090"); System.setProperty("server.static.path", "path"); System.setProperty("server.static.directoryIndex", "i.php,i.html"); System.setProperty("server.maxThreads", "66"); System.setProperty("server.keepAlive.enabled", "false"); System.setProperty("server.errorDocument.404", "ERROR404.html"); System.setProperty("server.errorDocument.403", "ERROR403.html"); System.setProperty(ADDITIONAL_ATTRIBUTE_NAME, "YET_ANOTHER_VALUE"); ServerConfig serverConfig = new ServerConfigImpl("/tmp/", "/tmp/", new Properties()); assertThat(serverConfig.getDocumentRootPath(), is("/tmp/path")); assertThat(serverConfig.getDirectoryIndex(), hasItem("i.php")); assertThat(serverConfig.getDirectoryIndex(), hasItem("i.html")); assertThat(serverConfig.getDirectoryIndex().size(), is(2)); assertThat(serverConfig.getErrorDocument403Path(), is("/tmp/ERROR403.html")); assertThat(serverConfig.getErrorDocument404Path(), is("/tmp/ERROR404.html")); assertThat(serverConfig.getListenPort(), is(9090)); assertThat(serverConfig.getMaxServerThreads(), is(66)); assertThat(serverConfig.isKeepAlive(), is(false)); // assertThat(serverConfig.getMimeTypeMapping().getMimeTypeByExtension("ANY"), is("mime/text")); assertThat(serverConfig.getAttribute(ADDITIONAL_ATTRIBUTE_NAME), is("YET_ANOTHER_VALUE")); } }
private FileResourceProvider getFileResourceProvider(final ServerConfig serverConfig) { return new FileResourceProvider(new RangeParser(), new RangeHelper(), new RangePartHeaderSerializer(), serverConfig.getMimeTypeMapping(), serverConfig.getDocumentRootPath()); }
private void doFirstRunChecks(final ServerConfigFactory serverConfigFactory) { ServerConfig serverConfig = serverConfigFactory.getServerConfig(); String basePath = Environment.getExternalStorageDirectory() + serverConfig.getBasePath(); String staticDirPath = Environment.getExternalStorageDirectory() + serverConfig.getDocumentRootPath();
private boolean isTempPathWritable() { File tempPath = new File(serverConfig.getTempPath()); if (!tempPath.exists()) { boolean successCreatedMissingDirectory = tempPath.mkdirs(); if (!successCreatedMissingDirectory) { LOGGER.log(Level.SEVERE, "TempPath does not exist and can not be created! PATH {0}", new Object[]{ serverConfig.getTempPath() }); return false; } } if (!tempPath.canWrite()) { LOGGER.log(Level.SEVERE, "TempPath is not writable! PATH {0}", new Object[]{ serverConfig.getTempPath() }); return false; } return true; }
public ServiceContainer(final ServerConfig serverConfig) { HeadersParser headersParser = new HeadersParser(); requestWrapperFactory = new HttpServletRequestImplFactory(headersParser, new QueryStringParser(), new RequestStatusParser(), new CookieParser(), new MultipartHeadersPartParser(headersParser), serverConfig.getTempPath() ); responseFactory = new HttpServletResponseImplFactory( new HeadersSerializer(), new CookieHeaderSerializer(new DateProvider()), new StreamHelper( new RangeHelper(), new RangePartHeaderSerializer() ) ); threadPoolExecutor = new ThreadPoolExecutor(1, serverConfig.getMaxServerThreads(), DEFAULT_TIME_UNITS, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(serverConfig.getMaxServerThreads() * MAX_THREADS_MULTIPLIER), Executors.defaultThreadFactory(), new ServiceUnavailableHandler(responseFactory) ); httpErrorHandlerResolver = new HttpErrorHandlerResolverImpl(serverConfig); pathHelper = new PathHelper(); }
private static void handleFile(ServerConfig serverConfig, String relativePath, String contents) throws IOException { File documentRoot = new File(serverConfig.getDocumentRootPath()); if (!documentRoot.exists() && !documentRoot.mkdir()) { throw new IOException("Unable to mkdir " + documentRoot.getAbsolutePath()); } File file = new File(serverConfig.getDocumentRootPath() + relativePath); if (file.exists() && !file.delete()) { throw new IOException("Unable to delete " + file.getAbsolutePath()); } if (!file.createNewFile()) { throw new IOException("Unable to create " + file.getAbsolutePath()); } PrintWriter writer = new PrintWriter(file, StandardCharsets.UTF_8.name()); writer.print(contents); writer.close(); }
/** * Returns resolved handler for given exception. * * @param e * @return */ @Override public HttpErrorHandler getHandler(final RuntimeException e) { Throwable fallbackException; try { if (e instanceof ProtocolException) { return getProtocolExceptionHandler((ProtocolException) e); } else if (e instanceof AccessDeniedException) { return new HttpError403Handler(serverConfig.getErrorDocument403Path()); } else if (e instanceof NotFoundException) { Statistics.incrementError404(); return new HttpError404Handler(serverConfig.getErrorDocument404Path()); } else if (e instanceof MethodNotAllowedException) { return new HttpError405Handler(getAllowedMethods()); } else { fallbackException = e; } } catch (Throwable handlingException) { fallbackException = handlingException; } Statistics.incrementError500(); return new HttpError500Handler().setReason(fallbackException); }
private boolean bindSocket() { try { serverSocket.bind(new InetSocketAddress(serverConfig.getListenPort())); } catch (IOException e) { LOGGER.log(Level.SEVERE, "Unable to start server: unable to listen on port " + serverConfig.getListenPort(), e); return false; } return true; }
private boolean isNumberOfThreadsSufficient() { if (serverConfig.getMaxServerThreads() < 1) { LOGGER.log(Level.SEVERE, "MaxThreads should be greater or equal to 1! {0} is given.", new Object[]{serverConfig.getMaxServerThreads()}); return false; } return true; }
private DirectoryIndexDescriptor loadDirectoryIndexResource(final String path) { String normalizedDirectoryPath = pathHelper.getNormalizedDirectoryPath(path); for (String index : serverConfig.getDirectoryIndex()) { String directoryIndexPath = normalizedDirectoryPath + index; ResourceProvider resourceProvider = getResourceProvider(directoryIndexPath); if (resourceProvider != null) { return new DirectoryIndexDescriptor(resourceProvider, directoryIndexPath); } } return null; }
@Before public void setUp() throws IOException { serverConfig = mock(ServerConfig.class); serverConfigFactory = mock(ServerConfigFactory.class); serverSocketFactory = mock(ServerSocketFactory.class); ServerSocket serverSocket = mock(ServerSocket.class); when(serverSocket.accept()).thenCallRealMethod(); // Avoid NPE when(serverConfigFactory.getServerConfig()).thenReturn(serverConfig); when(serverConfig.getMaxServerThreads()).thenReturn(1); when(serverConfig.getDocumentRootPath()).thenReturn("/somepath"); when(serverConfig.getTempPath()).thenReturn(FileUtils.createTempDirectory()); when(serverSocketFactory.createServerSocket()).thenReturn(serverSocket); serverGui = mock(ServerGui.class); }
private List<ServletContextImpl> getServletContexts(final ServerConfig serverConfig) { DeploymentDescriptorBuilder deploymentDescriptorBuilder = getDeploymentDescriptorBuilder(new FileSessionStorage(serverConfig.getTempPath()), serverConfig); List<ServletContextImpl> servletContexts = deploymentDescriptorBuilder.build(); for (ServletContextImpl servletContextImpl : servletContexts) { for (Map.Entry<String, Object> entry : getAdditionalServletContextAttributes().entrySet()) { servletContextImpl.setAttribute(entry.getKey(), entry.getValue()); } } return servletContexts; }
/** * Returns current service state. * * @return */ public ServiceStateDTO getServiceState() { String accessUrl = "Initializing"; if (controller != null && controller.getWebServer() != null) { accessUrl = "http://" + getLocalIpAddress() + getPort(controller.getWebServer().getServerConfig().getListenPort()) + '/'; } boolean isWebserverStarted = controller != null && controller.getWebServer() != null && controller.getWebServer().isRunning(); return new ServiceStateDTO(isServiceStarted, isWebserverStarted, accessUrl); }
@Test public void shouldNotStartServerOnTooLessThreadsAvailable() throws IOException { ServerSocket serverSocket = mock(ServerSocket.class); ServerConfig serverConfig = getDefaultServerConfig(); when(serverConfig.getMaxServerThreads()).thenReturn(0); WebServer webServer = new WebServer(serverSocket, serverConfig); assertThat(webServer.startServer(), is(false)); assertThat(webServer.isRunning(), is(false)); }
/** * {@inheritDoc} */ @Override public String getMimeType(final String file) { return serverConfig.getMimeTypeMapping(). getMimeTypeByExtension(FileUtilities.getExtension(file)); }