use of java.util.concurrent.atomic.AtomicReference in project jetty.project by eclipse.
the class FileSessionDataStore method load.
/**
* @see org.eclipse.jetty.server.session.SessionDataStore#load(java.lang.String)
*/
@Override
public SessionData load(String id) throws Exception {
final AtomicReference<SessionData> reference = new AtomicReference<SessionData>();
final AtomicReference<Exception> exception = new AtomicReference<Exception>();
Runnable r = new Runnable() {
public void run() {
File file = getFile(_storeDir, id);
if (file == null || !file.exists()) {
if (LOG.isDebugEnabled())
LOG.debug("No file: {}", file);
return;
}
try (FileInputStream in = new FileInputStream(file)) {
SessionData data = load(in);
data.setLastSaved(file.lastModified());
//delete restored file
file.delete();
reference.set(data);
} catch (UnreadableSessionDataException e) {
if (isDeleteUnrestorableFiles() && file.exists() && file.getParentFile().equals(_storeDir))
;
{
file.delete();
LOG.warn("Deleted unrestorable file for session {}", id);
}
exception.set(e);
} catch (Exception e) {
exception.set(e);
}
}
};
//ensure this runs with the context classloader set
_context.run(r);
if (exception.get() != null)
throw exception.get();
return reference.get();
}
use of java.util.concurrent.atomic.AtomicReference in project jetty.project by eclipse.
the class BaseBuilder method build.
/**
* Build out the Base directory (if needed)
*
* @return true if base directory was changed, false if left unchanged.
* @throws IOException if unable to build
*/
public boolean build() throws IOException {
Modules modules = startArgs.getAllModules();
// Select all the added modules to determine which ones are newly enabled
Set<String> newly_added = new HashSet<>();
if (!startArgs.getStartModules().isEmpty()) {
for (String name : startArgs.getStartModules()) {
newly_added.addAll(modules.enable(name, "--add-to-start"));
if (!newly_added.contains(name)) {
Set<String> sources = modules.get(name).getEnableSources();
sources.remove("--add-to-start");
StartLog.info("%s already enabled by %s", name, sources);
}
}
}
if (StartLog.isDebugEnabled())
StartLog.debug("added=%s", newly_added);
// Check the licenses
if (startArgs.isLicenseCheckRequired()) {
Licensing licensing = new Licensing();
for (String name : newly_added) licensing.addModule(modules.get(name));
if (licensing.hasLicenses()) {
if (startArgs.isApproveAllLicenses()) {
StartLog.info("All Licenses Approved via Command Line Option");
} else if (!licensing.acknowledgeLicenses()) {
StartLog.warn(EXITING_LICENSE_NOT_ACKNOWLEDGED);
System.exit(1);
}
}
}
// generate the files
List<FileArg> files = new ArrayList<FileArg>();
AtomicReference<BaseBuilder.Config> builder = new AtomicReference<>();
AtomicBoolean modified = new AtomicBoolean();
Path startd = getBaseHome().getBasePath("start.d");
Path startini = getBaseHome().getBasePath("start.ini");
if (startArgs.isCreateStartd() && !Files.exists(startd)) {
if (FS.ensureDirectoryExists(startd)) {
StartLog.log("MKDIR", baseHome.toShortForm(startd));
modified.set(true);
}
if (Files.exists(startini)) {
int ini = 0;
Path startd_startini = startd.resolve("start.ini");
while (Files.exists(startd_startini)) {
ini++;
startd_startini = startd.resolve("start" + ini + ".ini");
}
Files.move(startini, startd_startini);
modified.set(true);
}
}
if (!newly_added.isEmpty()) {
if (Files.exists(startini) && Files.exists(startd))
StartLog.warn("Use both %s and %s is deprecated", getBaseHome().toShortForm(startd), getBaseHome().toShortForm(startini));
boolean useStartD = Files.exists(startd);
builder.set(useStartD ? new StartDirBuilder(this) : new StartIniBuilder(this));
newly_added.stream().map(n -> modules.get(n)).forEach(module -> {
String ini = null;
try {
if (module.isSkipFilesValidation()) {
StartLog.debug("Skipping [files] validation on %s", module.getName());
} else {
if (startArgs.getStartModules().contains(module.getName())) {
ini = builder.get().addModule(module, startArgs.getProperties());
if (ini != null)
modified.set(true);
}
for (String file : module.getFiles()) files.add(new FileArg(module, startArgs.getProperties().expand(file)));
}
} catch (Exception e) {
throw new RuntimeException(e);
}
if (module.isDynamic()) {
for (String s : module.getEnableSources()) StartLog.info("%-15s %s", module.getName(), s);
} else if (module.isTransitive()) {
if (module.hasIniTemplate())
StartLog.info("%-15s transitively enabled, ini template available with --add-to-start=%s", module.getName(), module.getName());
else
StartLog.info("%-15s transitively enabled", module.getName());
} else
StartLog.info("%-15s initialized in %s", module.getName(), ini);
});
}
files.addAll(startArgs.getFiles());
if (!files.isEmpty() && processFileResources(files))
modified.set(Boolean.TRUE);
return modified.get();
}
use of java.util.concurrent.atomic.AtomicReference in project jetty.project by eclipse.
the class EventSourceServletTest method testBasicFunctionality.
@Test
public void testBasicFunctionality() throws Exception {
final AtomicReference<EventSource.Emitter> emitterRef = new AtomicReference<EventSource.Emitter>();
final CountDownLatch emitterLatch = new CountDownLatch(1);
final CountDownLatch closeLatch = new CountDownLatch(1);
class S extends EventSourceServlet {
@Override
protected EventSource newEventSource(HttpServletRequest request) {
return new EventSource() {
public void onOpen(Emitter emitter) throws IOException {
emitterRef.set(emitter);
emitterLatch.countDown();
}
public void onClose() {
closeLatch.countDown();
}
};
}
}
String servletPath = "/eventsource";
ServletHolder servletHolder = new ServletHolder(new S());
int heartBeatPeriod = 2;
servletHolder.setInitParameter("heartBeatPeriod", String.valueOf(heartBeatPeriod));
context.addServlet(servletHolder, servletPath);
Socket socket = new Socket("localhost", connector.getLocalPort());
writeHTTPRequest(socket, servletPath);
BufferedReader reader = readAndDiscardHTTPResponse(socket);
Assert.assertTrue(emitterLatch.await(1, TimeUnit.SECONDS));
EventSource.Emitter emitter = emitterRef.get();
Assert.assertNotNull(emitter);
String data = "foo";
emitter.data(data);
String line = reader.readLine();
String received = "";
while (line != null) {
received += line;
if (line.length() == 0)
break;
line = reader.readLine();
}
Assert.assertEquals("data: " + data, received);
socket.close();
Assert.assertTrue(closeLatch.await(heartBeatPeriod * 3, TimeUnit.SECONDS));
}
use of java.util.concurrent.atomic.AtomicReference in project jetty.project by eclipse.
the class EventSourceServletTest method testServerSideClose.
@Test
public void testServerSideClose() throws Exception {
final AtomicReference<EventSource.Emitter> emitterRef = new AtomicReference<EventSource.Emitter>();
final CountDownLatch emitterLatch = new CountDownLatch(1);
class S extends EventSourceServlet {
@Override
protected EventSource newEventSource(HttpServletRequest request) {
return new EventSource() {
public void onOpen(Emitter emitter) throws IOException {
emitterRef.set(emitter);
emitterLatch.countDown();
}
public void onClose() {
}
};
}
}
String servletPath = "/eventsource";
context.addServlet(new ServletHolder(new S()), servletPath);
Socket socket = new Socket("localhost", connector.getLocalPort());
writeHTTPRequest(socket, servletPath);
BufferedReader reader = readAndDiscardHTTPResponse(socket);
Assert.assertTrue(emitterLatch.await(1, TimeUnit.SECONDS));
EventSource.Emitter emitter = emitterRef.get();
Assert.assertNotNull(emitter);
String comment = "foo";
emitter.comment(comment);
String line = reader.readLine();
String received = "";
while (line != null) {
received += line;
if (line.length() == 0)
break;
line = reader.readLine();
}
Assert.assertEquals(": " + comment, received);
emitter.close();
line = reader.readLine();
Assert.assertNull(line);
socket.close();
}
use of java.util.concurrent.atomic.AtomicReference in project vert.x by eclipse.
the class Starter method startVertx.
private Vertx startVertx(boolean clustered, boolean ha, Args args) {
MetricsOptions metricsOptions;
ServiceLoader<VertxMetricsFactory> factories = ServiceLoader.load(VertxMetricsFactory.class);
if (factories.iterator().hasNext()) {
VertxMetricsFactory factory = factories.iterator().next();
metricsOptions = factory.newOptions();
} else {
metricsOptions = new MetricsOptions();
}
configureFromSystemProperties(metricsOptions, METRICS_OPTIONS_PROP_PREFIX);
options = new VertxOptions().setMetricsOptions(metricsOptions);
configureFromSystemProperties(options, VERTX_OPTIONS_PROP_PREFIX);
if (clustered) {
log.info("Starting clustering...");
int clusterPort = args.getInt("-cluster-port");
if (clusterPort == -1) {
// Default to zero - this means choose an ephemeral port
clusterPort = 0;
}
String clusterHost = args.map.get("-cluster-host");
if (clusterHost == null) {
clusterHost = getDefaultAddress();
if (clusterHost == null) {
log.error("Unable to find a default network interface for clustering. Please specify one using -cluster-host");
return null;
} else {
log.info("No cluster-host specified so using address " + clusterHost);
}
}
CountDownLatch latch = new CountDownLatch(1);
AtomicReference<AsyncResult<Vertx>> result = new AtomicReference<>();
options.setClusterHost(clusterHost).setClusterPort(clusterPort).setClustered(true);
if (ha) {
String haGroup = args.map.get("-hagroup");
int quorumSize = args.getInt("-quorum");
options.setHAEnabled(true);
if (haGroup != null) {
options.setHAGroup(haGroup);
}
if (quorumSize != -1) {
options.setQuorumSize(quorumSize);
}
}
beforeStartingVertx(options);
Vertx.clusteredVertx(options, ar -> {
result.set(ar);
latch.countDown();
});
try {
if (!latch.await(2, TimeUnit.MINUTES)) {
log.error("Timed out in starting clustered Vert.x");
return null;
}
} catch (InterruptedException e) {
log.error("Thread interrupted in startup");
return null;
}
if (result.get().failed()) {
log.error("Failed to form cluster");
result.get().cause().printStackTrace();
return null;
}
vertx = result.get().result();
} else {
beforeStartingVertx(options);
vertx = Vertx.vertx(options);
}
addShutdownHook();
afterStartingVertx();
return vertx;
}
Aggregations