How to use Session class of org.openqa.selenium.grid.data package

Best Selenium code snippet using org.openqa.selenium.grid.data.Session

Run Selenium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

copy
1// Licensed to the Software Freedom Conservancy (SFC) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The SFC licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18package org.openqa.selenium.grid.graphql;
19
20import com.google.common.base.Suppliers;
21import graphql.schema.DataFetcher;
22import graphql.schema.DataFetchingEnvironment;
23import org.openqa.selenium.grid.data.DistributorStatus;
24import org.openqa.selenium.grid.data.NodeStatus;
25import org.openqa.selenium.grid.data.Slot;
26import org.openqa.selenium.grid.distributor.Distributor;
27import org.openqa.selenium.internal.Require;
28
29import java.util.Optional;
30import java.util.Set;
31import java.util.function.Supplier;
32
33public class SessionData implements DataFetcher {
34
35  private final Supplier<DistributorStatus> distributorStatus;
36
37  public SessionData(Distributor distributor) {
38    distributorStatus = Suppliers.memoize(Require.nonNull("Distributor", distributor)::getStatus);
39  }
40
41  @Override
42  public Object get(DataFetchingEnvironment environment) {
43    String sessionId = environment.getArgument("id");
44
45    if (sessionId.isEmpty()) {
46      throw new SessionNotFoundException("Session id is empty. A valid session id is required.");
47    }
48
49    Set<NodeStatus> nodeStatuses = distributorStatus.get().getNodes();
50
51    SessionInSlot currentSession = findSession(sessionId, nodeStatuses);
52
53    if (currentSession != null) {
54      org.openqa.selenium.grid.data.Session session = currentSession.session;
55
56      return new org.openqa.selenium.grid.graphql.Session(
57        session.getId().toString(),
58        session.getCapabilities(),
59        session.getStartTime(),
60        session.getUri(),
61        currentSession.node.getId().toString(),
62        currentSession.node.getUri(),
63        currentSession.slot);
64    } else {
65      throw new SessionNotFoundException("No ongoing session found with the requested session id.",
66                                         sessionId);
67    }
68  }
69
70  private SessionInSlot findSession(String sessionId, Set<NodeStatus> nodeStatuses) {
71    for (NodeStatus status : nodeStatuses) {
72      for (Slot slot : status.getSlots()) {
73        Optional<org.openqa.selenium.grid.data.Session> session = slot.getSession();
74
75        if (session.isPresent() && sessionId.equals(session.get().getId().toString())) {
76          return new SessionInSlot(session.get(), status, slot);
77        }
78      }
79    }
80    return null;
81  }
82
83  private static class SessionInSlot {
84    private final org.openqa.selenium.grid.data.Session session;
85    private final NodeStatus node;
86    private final Slot slot;
87
88    SessionInSlot(org.openqa.selenium.grid.data.Session session, NodeStatus node, Slot slot) {
89      this.session = session;
90      this.node = node;
91      this.slot = slot;
92    }
93  }
94}
95
Full Screen
copy
1// Licensed to the Software Freedom Conservancy (SFC) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The SFC licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18package org.openqa.selenium.grid.distributor.local;
19
20import com.google.common.collect.ImmutableSet;
21import org.openqa.selenium.Beta;
22import org.openqa.selenium.Capabilities;
23import org.openqa.selenium.ImmutableCapabilities;
24import org.openqa.selenium.SessionNotCreatedException;
25import org.openqa.selenium.concurrent.Regularly;
26import org.openqa.selenium.events.EventBus;
27import org.openqa.selenium.grid.config.Config;
28import org.openqa.selenium.grid.data.CreateSessionRequest;
29import org.openqa.selenium.grid.data.CreateSessionResponse;
30import org.openqa.selenium.grid.data.DistributorStatus;
31import org.openqa.selenium.grid.data.NodeAddedEvent;
32import org.openqa.selenium.grid.data.NodeDrainComplete;
33import org.openqa.selenium.grid.data.NodeId;
34import org.openqa.selenium.grid.data.NodeRemovedEvent;
35import org.openqa.selenium.grid.data.NodeStatus;
36import org.openqa.selenium.grid.data.NodeStatusEvent;
37import org.openqa.selenium.grid.data.Slot;
38import org.openqa.selenium.grid.data.SlotId;
39import org.openqa.selenium.grid.distributor.Distributor;
40import org.openqa.selenium.grid.distributor.selector.DefaultSlotSelector;
41import org.openqa.selenium.grid.log.LoggingOptions;
42import org.openqa.selenium.grid.node.HealthCheck;
43import org.openqa.selenium.grid.node.Node;
44import org.openqa.selenium.grid.node.remote.RemoteNode;
45import org.openqa.selenium.grid.security.Secret;
46import org.openqa.selenium.grid.server.BaseServerOptions;
47import org.openqa.selenium.grid.server.EventBusOptions;
48import org.openqa.selenium.grid.server.NetworkOptions;
49import org.openqa.selenium.grid.sessionmap.SessionMap;
50import org.openqa.selenium.grid.sessionmap.config.SessionMapOptions;
51import org.openqa.selenium.internal.Require;
52import org.openqa.selenium.remote.http.HttpClient;
53import org.openqa.selenium.remote.tracing.Tracer;
54import org.openqa.selenium.status.HasReadyState;
55
56import java.time.Duration;
57import java.util.ArrayList;
58import java.util.HashMap;
59import java.util.List;
60import java.util.Map;
61import java.util.Optional;
62import java.util.Set;
63import java.util.concurrent.locks.Lock;
64import java.util.concurrent.locks.ReadWriteLock;
65import java.util.concurrent.locks.ReentrantReadWriteLock;
66import java.util.function.Supplier;
67import java.util.logging.Level;
68import java.util.logging.Logger;
69
70import static com.google.common.collect.ImmutableSet.toImmutableSet;
71import static org.openqa.selenium.grid.data.Availability.DOWN;
72import static org.openqa.selenium.grid.data.Availability.DRAINING;
73
74public class LocalDistributor extends Distributor {
75
76  private static final Logger LOG = Logger.getLogger(LocalDistributor.class.getName());
77
78  private final Tracer tracer;
79  private final EventBus bus;
80  private final HttpClient.Factory clientFactory;
81  private final SessionMap sessions;
82  private final Secret registrationSecret;
83  private final Regularly hostChecker = new Regularly("distributor host checker");
84  private final Map<NodeId, Runnable> allChecks = new HashMap<>();
85
86  private final ReadWriteLock lock = new ReentrantReadWriteLock(/* fair */ true);
87  private final GridModel model;
88  private final Map<NodeId, Node> nodes;
89
90  public LocalDistributor(
91      Tracer tracer,
92      EventBus bus,
93      HttpClient.Factory clientFactory,
94      SessionMap sessions,
95      Secret registrationSecret) {
96    super(tracer, clientFactory, new DefaultSlotSelector(), sessions, registrationSecret);
97    this.tracer = Require.nonNull("Tracer", tracer);
98    this.bus = Require.nonNull("Event bus", bus);
99    this.clientFactory = Require.nonNull("HTTP client factory", clientFactory);
100    this.sessions = Require.nonNull("Session map", sessions);
101    this.model = new GridModel(bus, registrationSecret);
102    this.nodes = new HashMap<>();
103
104    this.registrationSecret = Require.nonNull("Registration secret", registrationSecret);
105
106    bus.addListener(NodeStatusEvent.listener(this::register));
107    bus.addListener(NodeStatusEvent.listener(model::refresh));
108    bus.addListener(NodeDrainComplete.listener(this::remove));
109  }
110
111  public static Distributor create(Config config) {
112    Tracer tracer = new LoggingOptions(config).getTracer();
113    EventBus bus = new EventBusOptions(config).getEventBus();
114    HttpClient.Factory clientFactory = new NetworkOptions(config).getHttpClientFactory(tracer);
115    SessionMap sessions = new SessionMapOptions(config).getSessionMap();
116    BaseServerOptions serverOptions = new BaseServerOptions(config);
117
118    return new LocalDistributor(tracer, bus, clientFactory, sessions, serverOptions.getRegistrationSecret());
119  }
120
121  @Override
122  public boolean isReady() {
123    try {
124      return ImmutableSet.of(bus, sessions).parallelStream()
125        .map(HasReadyState::isReady)
126        .reduce(true, Boolean::logicalAnd);
127    } catch (RuntimeException e) {
128      return false;
129    }
130  }
131
132  private void register(NodeStatus status) {
133    Require.nonNull("Node", status);
134
135    Lock writeLock = lock.writeLock();
136    writeLock.lock();
137    try {
138      if (nodes.containsKey(status.getId())) {
139        return;
140      }
141
142      Set<Capabilities> capabilities = status.getSlots().stream()
143        .map(Slot::getStereotype)
144        .map(ImmutableCapabilities::copyOf)
145        .collect(toImmutableSet());
146
147      // A new node! Add this as a remote node, since we've not called add
148      RemoteNode remoteNode = new RemoteNode(
149        tracer,
150        clientFactory,
151        status.getId(),
152        status.getUri(),
153        registrationSecret,
154        capabilities);
155
156      add(remoteNode);
157    } finally {
158      writeLock.unlock();
159    }
160  }
161
162  @Override
163  public LocalDistributor add(Node node) {
164    Require.nonNull("Node", node);
165
166    LOG.info(String.format("Added node %s at %s.", node.getId(), node.getUri()));
167
168    nodes.put(node.getId(), node);
169    model.add(node.getStatus());
170
171    // Extract the health check
172    Runnable runnableHealthCheck = asRunnableHealthCheck(node);
173    allChecks.put(node.getId(), runnableHealthCheck);
174    hostChecker.submit(runnableHealthCheck, Duration.ofMinutes(5), Duration.ofSeconds(30));
175
176    bus.fire(new NodeAddedEvent(node.getId()));
177
178    return this;
179  }
180
181  private Runnable asRunnableHealthCheck(Node node) {
182    HealthCheck healthCheck = node.getHealthCheck();
183    NodeId id = node.getId();
184    return () -> {
185      HealthCheck.Result result;
186      try {
187        result = healthCheck.check();
188      } catch (Exception e) {
189        LOG.log(Level.WARNING, "Unable to process node " + id, e);
190        result = new HealthCheck.Result(DOWN, "Unable to run healthcheck. Assuming down");
191      }
192
193      Lock writeLock = lock.writeLock();
194      writeLock.lock();
195      try {
196        model.setAvailability(id, result.getAvailability());
197      } finally {
198        writeLock.unlock();
199      }
200    };
201  }
202
203  @Override
204  public boolean drain(NodeId nodeId) {
205    Node node = nodes.get(nodeId);
206    if (node == null) {
207      LOG.info("Asked to drain unregistered node " + nodeId);
208      return false;
209    }
210
211    Lock writeLock = lock.writeLock();
212    writeLock.lock();
213    try {
214      node.drain();
215      model.setAvailability(nodeId, DRAINING);
216    } finally {
217      writeLock.unlock();
218    }
219
220    return node.isDraining();
221  }
222
223  public void remove(NodeId nodeId) {
224    Lock writeLock = lock.writeLock();
225    writeLock.lock();
226    try {
227      model.remove(nodeId);
228      Runnable runnable = allChecks.remove(nodeId);
229      if (runnable != null) {
230        hostChecker.remove(runnable);
231      }
232    } finally {
233      writeLock.unlock();
234      bus.fire(new NodeRemovedEvent(nodeId));
235    }
236  }
237
238  @Override
239  public DistributorStatus getStatus() {
240    Lock readLock = this.lock.readLock();
241    readLock.lock();
242    try {
243      return new DistributorStatus(model.getSnapshot());
244    } finally {
245      readLock.unlock();
246    }
247  }
248
249  @Beta
250  public void refresh() {
251    List<Runnable> allHealthChecks = new ArrayList<>();
252
253    Lock readLock = this.lock.readLock();
254    readLock.lock();
255    try {
256      allHealthChecks.addAll(allChecks.values());
257    } finally {
258      readLock.unlock();
259    }
260
261    allHealthChecks.parallelStream().forEach(Runnable::run);
262  }
263
264  @Override
265  protected Set<NodeStatus> getAvailableNodes() {
266    Lock readLock = this.lock.readLock();
267    readLock.lock();
268    try {
269      return model.getSnapshot().stream()
270        .filter(node -> !DOWN.equals(node.getAvailability()))
271        .collect(toImmutableSet());
272    } finally {
273      readLock.unlock();
274    }
275  }
276
277  @Override
278  protected Supplier<CreateSessionResponse> reserve(SlotId slotId, CreateSessionRequest request) {
279    Require.nonNull("Slot ID", slotId);
280    Require.nonNull("New Session request", request);
281
282    Lock writeLock = this.lock.writeLock();
283    writeLock.lock();
284    try {
285      Node node = nodes.get(slotId.getOwningNodeId());
286      if (node == null) {
287        return () -> {
288          throw new SessionNotCreatedException("Unable to find node");
289        };
290      }
291
292      model.reserve(slotId);
293
294      return () -> {
295        Optional<CreateSessionResponse> response = node.newSession(request);
296
297        if (!response.isPresent()) {
298          model.setSession(slotId, null);
299          throw new SessionNotCreatedException("Unable to create session for " + request);
300        }
301
302        model.setSession(slotId, response.get().getSession());
303
304        return response.get();
305      };
306
307    } finally {
308      writeLock.unlock();
309    }
310  }
311}
312
Full Screen
copy
1// Licensed to the Software Freedom Conservancy (SFC) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The SFC licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18package org.openqa.selenium.grid.distributor.local;
19
20import com.google.common.collect.ImmutableSet;
21import org.openqa.selenium.events.EventBus;
22import org.openqa.selenium.grid.data.Availability;
23import org.openqa.selenium.grid.data.NodeDrainComplete;
24import org.openqa.selenium.grid.data.NodeDrainStarted;
25import org.openqa.selenium.grid.data.NodeId;
26import org.openqa.selenium.grid.data.NodeRemovedEvent;
27import org.openqa.selenium.grid.data.NodeStatus;
28import org.openqa.selenium.grid.data.NodeStatusEvent;
29import org.openqa.selenium.grid.data.Session;
30import org.openqa.selenium.grid.data.SessionClosedEvent;
31import org.openqa.selenium.grid.data.Slot;
32import org.openqa.selenium.grid.data.SlotId;
33import org.openqa.selenium.grid.security.Secret;
34import org.openqa.selenium.internal.Require;
35import org.openqa.selenium.remote.SessionId;
36
37import java.time.Instant;
38import java.util.HashSet;
39import java.util.Iterator;
40import java.util.Map;
41import java.util.Optional;
42import java.util.Set;
43import java.util.concurrent.ConcurrentHashMap;
44import java.util.concurrent.locks.Lock;
45import java.util.concurrent.locks.ReadWriteLock;
46import java.util.concurrent.locks.ReentrantReadWriteLock;
47import java.util.logging.Logger;
48
49import static org.openqa.selenium.grid.data.Availability.DOWN;
50import static org.openqa.selenium.grid.data.Availability.DRAINING;
51import static org.openqa.selenium.grid.data.Availability.UP;
52
53public class GridModel {
54
55  private static final Logger LOG = Logger.getLogger(GridModel.class.getName());
56  private static final SessionId RESERVED = new SessionId("reserved");
57  private final ReadWriteLock lock = new ReentrantReadWriteLock(/* fair */ true);
58  private final Map<Availability, Set<NodeStatus>> nodes = new ConcurrentHashMap<>();
59  private final EventBus events;
60
61  public GridModel(EventBus events, Secret registrationSecret) {
62    this.events = Require.nonNull("Event bus", events);
63    Require.nonNull("Registration secret", registrationSecret);
64
65    events.addListener(NodeDrainStarted.listener(nodeId -> setAvailability(nodeId, DRAINING)));
66    events.addListener(NodeDrainComplete.listener(this::remove));
67    events.addListener(NodeRemovedEvent.listener(this::remove));
68    events.addListener(NodeStatusEvent.listener(status -> refresh(status)));
69
70    events.addListener(SessionClosedEvent.listener(this::release));
71  }
72
73  public GridModel add(NodeStatus node) {
74    Require.nonNull("Node", node);
75
76    Lock writeLock = lock.writeLock();
77    writeLock.lock();
78    try {
79      // If we've already added the node, remove it.
80      for (Set<NodeStatus> nodes : nodes.values()) {
81        Iterator<NodeStatus> iterator = nodes.iterator();
82        while (iterator.hasNext()) {
83          NodeStatus next = iterator.next();
84
85          // If the ID is the same, we're re-adding a node. If the URI is the same a node probably restarted
86          if (next.getId().equals(node.getId()) || next.getUri().equals(node.getUri())) {
87            LOG.info(String.format("Re-adding node with id %s and URI %s.", node.getId(), node.getUri()));
88            iterator.remove();
89          }
90        }
91      }
92
93      // Nodes are initially added in the "down" state until something changes their availability
94      nodes(DOWN).add(node);
95    } finally {
96      writeLock.unlock();
97    }
98
99    return this;
100  }
101
102  public GridModel refresh(NodeStatus status) {
103    Require.nonNull("Node status", status);
104
105    Lock writeLock = lock.writeLock();
106    writeLock.lock();
107    try {
108      AvailabilityAndNode availabilityAndNode = findNode(status.getId());
109
110      if (availabilityAndNode == null) {
111        return this;
112      }
113
114      // if the node was marked as "down", keep it down until a healthcheck passes:
115      // just because the node can hit the event bus doesn't mean it's reachable
116      if (DOWN.equals(availabilityAndNode.availability)) {
117        nodes(DOWN).remove(availabilityAndNode.status);
118        nodes(DOWN).add(status);
119        return this;
120      }
121
122      // But do trust the node if it tells us it's draining
123      nodes(availabilityAndNode.availability).remove(availabilityAndNode.status);
124      nodes(status.getAvailability()).add(status);
125      return this;
126    } finally {
127      writeLock.unlock();
128    }
129  }
130
131  public GridModel remove(NodeId id) {
132    Require.nonNull("Node ID", id);
133
134    Lock writeLock = lock.writeLock();
135    writeLock.lock();
136    try {
137      AvailabilityAndNode availabilityAndNode = findNode(id);
138      if (availabilityAndNode == null) {
139        return this;
140      }
141
142      nodes(availabilityAndNode.availability).remove(availabilityAndNode.status);
143      return this;
144    } finally {
145      writeLock.unlock();
146    }
147  }
148
149  public Availability setAvailability(NodeId id, Availability availability) {
150    Require.nonNull("Node ID", id);
151    Require.nonNull("Availability", availability);
152
153    Lock writeLock = lock.writeLock();
154    writeLock.lock();
155    try {
156      AvailabilityAndNode availabilityAndNode = findNode(id);
157
158      if (availabilityAndNode == null) {
159        return DOWN;
160      }
161
162      if (availability.equals(availabilityAndNode.availability)) {
163        return availability;
164      }
165
166      nodes(availabilityAndNode.availability).remove(availabilityAndNode.status);
167      nodes(availability).add(availabilityAndNode.status);
168
169      LOG.info(String.format(
170        "Switching node %s (uri: %s) from %s to %s",
171        id,
172        availabilityAndNode.status.getUri(),
173        availabilityAndNode.availability,
174        availability));
175      return availabilityAndNode.availability;
176    } finally {
177      writeLock.unlock();
178    }
179  }
180
181  public boolean reserve(SlotId slotId) {
182    Lock writeLock = lock.writeLock();
183    writeLock.lock();
184    try {
185      AvailabilityAndNode node = findNode(slotId.getOwningNodeId());
186      if (node == null) {
187        LOG.warning(String.format("Asked to reserve slot on node %s, but unable to find node", slotId.getOwningNodeId()));
188        return false;
189      }
190
191      if (!UP.equals(node.availability)) {
192        LOG.warning(String.format(
193          "Asked to reserve a slot on node %s, but not is %s",
194          slotId.getOwningNodeId(),
195          node.availability));
196        return false;
197      }
198
199      Optional<Slot> maybeSlot = node.status.getSlots().stream()
200        .filter(slot -> slotId.equals(slot.getId()))
201        .findFirst();
202
203      if (!maybeSlot.isPresent()) {
204        LOG.warning(String.format(
205          "Asked to reserve slot on node %s, but no slot with id %s found",
206          node.status.getId(),
207          slotId));
208        return false;
209      }
210
211      reserve(node.status, maybeSlot.get());
212      return true;
213    } finally {
214      writeLock.unlock();
215    }
216  }
217
218  public Set<NodeStatus> getSnapshot() {
219    Lock readLock = this.lock.readLock();
220    readLock.lock();
221    try {
222      ImmutableSet.Builder<NodeStatus> snapshot = ImmutableSet.builder();
223      for (Map.Entry<Availability, Set<NodeStatus>> entry : nodes.entrySet()) {
224        entry.getValue().stream()
225          .map(status -> rewrite(status, entry.getKey()))
226          .forEach(snapshot::add);
227      }
228      return snapshot.build();
229    } finally {
230      readLock.unlock();
231    }
232  }
233
234  private Set<NodeStatus> nodes(Availability availability) {
235    return nodes.computeIfAbsent(availability, ignored -> new HashSet<>());
236  }
237
238  private AvailabilityAndNode findNode(NodeId id) {
239    for (Map.Entry<Availability, Set<NodeStatus>> entry : nodes.entrySet()) {
240      for (NodeStatus nodeStatus : entry.getValue()) {
241        if (id.equals(nodeStatus.getId())) {
242          return new AvailabilityAndNode(entry.getKey(), nodeStatus);
243        }
244      }
245    }
246    return null;
247  }
248
249  private NodeStatus rewrite(NodeStatus status, Availability availability) {
250    return new NodeStatus(
251      status.getId(),
252      status.getUri(),
253      status.getMaxSessionCount(),
254      status.getSlots(),
255      availability);
256  }
257
258  private void release(SessionId id) {
259    if (id == null) {
260      return;
261    }
262
263    Lock writeLock = lock.writeLock();
264    writeLock.lock();
265    try {
266      for (Map.Entry<Availability, Set<NodeStatus>> entry : nodes.entrySet()) {
267        for (NodeStatus node : entry.getValue()) {
268          for (Slot slot : node.getSlots()) {
269            if (!slot.getSession().isPresent()) {
270              continue;
271            }
272
273            if (id.equals(slot.getSession().get().getId())) {
274              Slot released = new Slot(
275                slot.getId(),
276                slot.getStereotype(),
277                slot.getLastStarted(),
278                Optional.empty());
279              amend(entry.getKey(), node, released);
280              return;
281            }
282          }
283        }
284      }
285    } finally {
286      writeLock.unlock();
287    }
288  }
289
290  private void reserve(NodeStatus status, Slot slot) {
291    Instant now = Instant.now();
292
293    Slot reserved = new Slot(
294      slot.getId(),
295      slot.getStereotype(),
296      now,
297      Optional.of(new Session(
298        RESERVED,
299        status.getUri(),
300        slot.getStereotype(),
301        slot.getStereotype(),
302        now)));
303
304    amend(UP, status, reserved);
305  }
306
307  public void setSession(SlotId slotId, Session session) {
308    Require.nonNull("Slot ID", slotId);
309
310    AvailabilityAndNode node = findNode(slotId.getOwningNodeId());
311    if (node == null) {
312      LOG.warning("Grid model and reality have diverged. Unable to find node " + slotId.getOwningNodeId());
313      return;
314    }
315
316    Optional<Slot> maybeSlot = node.status.getSlots().stream()
317      .filter(slot -> slotId.equals(slot.getId()))
318      .findFirst();
319
320    if (!maybeSlot.isPresent()) {
321      LOG.warning("Grid model and reality have diverged. Unable to find slot " + slotId);
322      return;
323    }
324
325    Slot slot = maybeSlot.get();
326    Optional<Session> maybeSession = slot.getSession();
327    if (!maybeSession.isPresent()) {
328      LOG.warning("Grid model and reality have diverged. Slot is not reserved. " + slotId);
329      return;
330    }
331
332    Session current = maybeSession.get();
333    if (!RESERVED.equals(current.getId())) {
334      LOG.warning("Gid model and reality have diverged. Slot has session and is not reserved. " + slotId);
335      return;
336    }
337
338    Slot updated = new Slot(
339      slot.getId(),
340      slot.getStereotype(),
341      session == null ? slot.getLastStarted() : session.getStartTime(),
342      Optional.ofNullable(session));
343
344    amend(node.availability, node.status, updated);
345  }
346
347  private void amend(Availability availability, NodeStatus status, Slot slot) {
348    Set<Slot> newSlots = new HashSet<>(status.getSlots());
349    newSlots.removeIf(s -> s.getId().equals(slot.getId()));
350    newSlots.add(slot);
351
352    nodes(availability).remove(status);
353    nodes(availability).add(new NodeStatus(
354      status.getId(),
355      status.getUri(),
356      status.getMaxSessionCount(),
357      newSlots,
358      status.getAvailability()));
359  }
360
361  private static class AvailabilityAndNode {
362    public final Availability availability;
363    public final NodeStatus status;
364
365    public AvailabilityAndNode(Availability availability, NodeStatus status) {
366      this.availability = availability;
367      this.status = status;
368    }
369  }
370}
371
Full Screen
copy
1var uri = URI.create("https://httpbin.org/get?age=26&isHappy=true");
2var client = HttpClient.newHttpClient();
3var request = HttpRequest
4        .newBuilder()
5        .uri(uri)
6        .header("accept", "application/json")
7        .GET()
8        .build();
9var response = client.send(request, HttpResponse.BodyHandlers.ofString());
10System.out.println(response.statusCode());
11System.out.println(response.body());
12
Full Screen
copy
1var responseAsync = client
2        .sendAsync(request, HttpResponse.BodyHandlers.ofString())
3        .thenApply(HttpResponse::body)
4        .thenAccept(System.out::println);
5// responseAsync.join(); // Wait for completion
6
Full Screen
copy
1var request = HttpRequest
2        .newBuilder()
3        .uri(uri)
4        .version(HttpClient.Version.HTTP_2)
5        .timeout(Duration.ofMinutes(1))
6        .header("Content-Type", "application/json")
7        .header("Authorization", "Bearer fake")
8        .POST(BodyPublishers.ofString("{ title: 'This is cool' }"))
9        .build();
10var response = client.send(request, HttpResponse.BodyHandlers.ofString());
11
Full Screen
copy
1String html = new JdkRequest("http://www.google.com").fetch().body();
2
Full Screen
copy
1OkHttpClient client = new OkHttpClient();
2
Full Screen
copy
1Request request = new Request.Builder()
2      .url(url)
3      .build();
4
Full Screen
copy
1Response response = client.newCall(request).execute();
2
Full Screen
copy
1package org.boon.utils;
2
3import java.io.IOException;
4import java.io.InputStream;
5import java.net.HttpURLConnection;
6import java.net.URL;
7import java.net.URLConnection;
8import java.util.Map;
9
10import static org.boon.utils.IO.read;
11
12public class HTTP {
13
Full Screen
copy
1public static String get(
2        final String url) {
3
4    Exceptions.tryIt(() -> {
5        URLConnection connection;
6        connection = doGet(url, null, null, null);
7        return extractResponseString(connection);
8    });
9    return null;
10}
11
12public static String getWithHeaders(
13        final String url,
14        final Map<String, ? extends Object> headers) {
15    URLConnection connection;
16    try {
17        connection = doGet(url, headers, null, null);
18        return extractResponseString(connection);
19    } catch (Exception ex) {
20        Exceptions.handle(ex);
21        return null;
22    }
23}
24
25public static String getWithContentType(
26        final String url,
27        final Map<String, ? extends Object> headers,
28        String contentType) {
29    URLConnection connection;
30    try {
31        connection = doGet(url, headers, contentType, null);
32        return extractResponseString(connection);
33    } catch (Exception ex) {
34        Exceptions.handle(ex);
35        return null;
36    }
37}
38public static String getWithCharSet(
39        final String url,
40        final Map<String, ? extends Object> headers,
41        String contentType,
42        String charSet) {
43    URLConnection connection;
44    try {
45        connection = doGet(url, headers, contentType, charSet);
46        return extractResponseString(connection);
47    } catch (Exception ex) {
48        Exceptions.handle(ex);
49        return null;
50    }
51}
52
Full Screen
copy
1public static String postBody(
2        final String url,
3        final String body) {
4    URLConnection connection;
5    try {
6        connection = doPost(url, null, "text/plain", null, body);
7        return extractResponseString(connection);
8    } catch (Exception ex) {
9        Exceptions.handle(ex);
10        return null;
11    }
12}
13
14public static String postBodyWithHeaders(
15        final String url,
16        final Map<String, ? extends Object> headers,
17        final String body) {
18    URLConnection connection;
19    try {
20        connection = doPost(url, headers, "text/plain", null, body);
21        return extractResponseString(connection);
22    } catch (Exception ex) {
23        Exceptions.handle(ex);
24        return null;
25    }
26}
27
28
29public static String postBodyWithContentType(
30        final String url,
31        final Map<String, ? extends Object> headers,
32        final String contentType,
33        final String body) {
34
35    URLConnection connection;
36    try {
37        connection = doPost(url, headers, contentType, null, body);
38
39        return extractResponseString(connection);
40
41    } catch (Exception ex) {
42        Exceptions.handle(ex);
43        return null;
44    }
45
46}
47
48
49public static String postBodyWithCharset(
50        final String url,
51        final Map<String, ? extends Object> headers,
52        final String contentType,
53        final String charSet,
54        final String body) {
55
56    URLConnection connection;
57    try {
58        connection = doPost(url, headers, contentType, charSet, body);
59
60        return extractResponseString(connection);
61
62    } catch (Exception ex) {
63        Exceptions.handle(ex);
64        return null;
65    }
66}
67
68private static URLConnection doPost(String url, Map<String, ? extends Object> headers,
69                                    String contentType, String charset, String body
70                                    ) throws IOException {
71    URLConnection connection;/* Handle output. */
72    connection = new URL(url).openConnection();
73    connection.setDoOutput(true);
74    manageContentTypeHeaders(contentType, charset, connection);
75
76    manageHeaders(headers, connection);
77
78    IO.write(connection.getOutputStream(), body, IO.CHARSET);
79    return connection;
80}
81
82private static void manageHeaders(Map<String, ? extends Object> headers, URLConnection connection) {
83    if (headers != null) {
84        for (Map.Entry<String, ? extends Object> entry : headers.entrySet()) {
85            connection.setRequestProperty(entry.getKey(), entry.getValue().toString());
86        }
87    }
88}
89
90private static void manageContentTypeHeaders(String contentType, String charset, URLConnection connection) {
91    connection.setRequestProperty("Accept-Charset", charset == null ? IO.CHARSET : charset);
92    if (contentType!=null && !contentType.isEmpty()) {
93        connection.setRequestProperty("Content-Type", contentType);
94    }
95}
96
97private static URLConnection doGet(String url, Map<String, ? extends Object> headers,
98                                    String contentType, String charset) throws IOException {
99    URLConnection connection;/* Handle output. */
100    connection = new URL(url).openConnection();
101    manageContentTypeHeaders(contentType, charset, connection);
102
103    manageHeaders(headers, connection);
104
105    return connection;
106}
107
108private static String extractResponseString(URLConnection connection) throws IOException {
109/* Handle input. */
110    HttpURLConnection http = (HttpURLConnection)connection;
111    int status = http.getResponseCode();
112    String charset = getCharset(connection.getHeaderField("Content-Type"));
113
114    if (status==200) {
115        return readResponseBody(http, charset);
116    } else {
117        return readErrorResponseBody(http, status, charset);
118    }
119}
120
121private static String readErrorResponseBody(HttpURLConnection http, int status, String charset) {
122    InputStream errorStream = http.getErrorStream();
123    if ( errorStream!=null ) {
124        String error = charset== null ? read( errorStream ) :
125            read( errorStream, charset );
126        throw new RuntimeException("STATUS CODE =" + status + "\n\n" + error);
127    } else {
128        throw new RuntimeException("STATUS CODE =" + status);
129    }
130}
131
132private static String readResponseBody(HttpURLConnection http, String charset) throws IOException {
133    if (charset != null) {
134        return read(http.getInputStream(), charset);
135    } else {
136        return read(http.getInputStream());
137    }
138}
139
140private static String getCharset(String contentType) {
141    if (contentType==null)  {
142        return null;
143    }
144    String charset = null;
145    for (String param : contentType.replace(" ", "").split(";")) {
146        if (param.startsWith("charset=")) {
147            charset = param.split("=", 2)[1];
148            break;
149        }
150    }
151    charset = charset == null ? IO.CHARSET : charset;
152
153    return charset;
154}
155
Full Screen
copy
1static class MyHandler implements HttpHandler {
2    public void handle(HttpExchange t) throws IOException {
3
4        InputStream requestBody = t.getRequestBody();
5        String body = IO.read(requestBody);
6        Headers requestHeaders = t.getRequestHeaders();
7        body = body + "\n" + copy(requestHeaders).toString();
8        t.sendResponseHeaders(200, body.length());
9        OutputStream os = t.getResponseBody();
10        os.write(body.getBytes());
11        os.close();
12    }
13}
14
15
16@Test
17public void testHappy() throws Exception {
18
19    HttpServer server = HttpServer.create(new InetSocketAddress(9212), 0);
20    server.createContext("/test", new MyHandler());
21    server.setExecutor(null); // creates a default executor
22    server.start();
23
24    Thread.sleep(10);
25
26    Map<String,String> headers = map("foo", "bar", "fun", "sun");
27
28    String response = HTTP.postBodyWithContentType("http://localhost:9212/test", headers, "text/plain", "hi mom");
29
30    System.out.println(response);
31
32    assertTrue(response.contains("hi mom"));
33    assertTrue(response.contains("Fun=[sun], Foo=[bar]"));
34
35    response = HTTP.postBodyWithCharset("http://localhost:9212/test", headers, "text/plain", "UTF-8", "hi mom");
36
37    System.out.println(response);
38
39    assertTrue(response.contains("hi mom"));
40    assertTrue(response.contains("Fun=[sun], Foo=[bar]"));
41
42    response = HTTP.postBodyWithHeaders("http://localhost:9212/test", headers, "hi mom");
43
44    System.out.println(response);
45
46    assertTrue(response.contains("hi mom"));
47    assertTrue(response.contains("Fun=[sun], Foo=[bar]"));
48
49    response = HTTP.get("http://localhost:9212/test");
50
51    System.out.println(response);
52
53    response = HTTP.getWithHeaders("http://localhost:9212/test", headers);
54
55    System.out.println(response);
56
57    assertTrue(response.contains("Fun=[sun], Foo=[bar]"));
58
59    response = HTTP.getWithContentType("http://localhost:9212/test", headers, "text/plain");
60
61    System.out.println(response);
62
63    assertTrue(response.contains("Fun=[sun], Foo=[bar]"));
64
65    response = HTTP.getWithCharSet("http://localhost:9212/test", headers, "text/plain", "UTF-8");
66
67    System.out.println(response);
68
69    assertTrue(response.contains("Fun=[sun], Foo=[bar]"));
70
71    Thread.sleep(10);
72
73    server.stop(0);
74}
75
76@Test
77public void testPostBody() throws Exception {
78
79    HttpServer server = HttpServer.create(new InetSocketAddress(9220), 0);
80    server.createContext("/test", new MyHandler());
81    server.setExecutor(null); // creates a default executor
82    server.start();
83
84    Thread.sleep(10);
85
86    Map<String,String> headers = map("foo", "bar", "fun", "sun");
87
88    String response = HTTP.postBody("http://localhost:9220/test", "hi mom");
89
90    assertTrue(response.contains("hi mom"));
91
92    Thread.sleep(10);
93
94    server.stop(0);
95}
96
97@Test(expected = RuntimeException.class)
98public void testSad() throws Exception {
99
100    HttpServer server = HttpServer.create(new InetSocketAddress(9213), 0);
101    server.createContext("/test", new MyHandler());
102    server.setExecutor(null); // creates a default executor
103    server.start();
104
105    Thread.sleep(10);
106
107    Map<String,String> headers = map("foo", "bar", "fun", "sun");
108
109    String response = HTTP.postBodyWithContentType("http://localhost:9213/foo", headers, "text/plain", "hi mom");
110
111    System.out.println(response);
112
113    assertTrue(response.contains("hi mom"));
114    assertTrue(response.contains("Fun=[sun], Foo=[bar]"));
115
116    Thread.sleep(10);
117
118    server.stop(0);
119}
120
Full Screen
copy
1HttpURLConnection.setFollowRedirects(true); // Defaults to true
2
3String url = "https://name_of_the_url";
4URL request_url = new URL(url);
5HttpURLConnection http_conn = (HttpURLConnection)request_url.openConnection();
6http_conn.setConnectTimeout(100000);
7http_conn.setReadTimeout(100000);
8http_conn.setInstanceFollowRedirects(true);
9System.out.println(String.valueOf(http_conn.getResponseCode()));
10
Full Screen
copy
1HttpURLConnection.setFollowRedirects(true); // Defaults to true
2
3String url = "https://name_of_the_url"
4URL request_url = new URL(url);
5HttpURLConnection http_conn = (HttpURLConnection)request_url.openConnection();
6http_conn.setConnectTimeout(100000);
7http_conn.setReadTimeout(100000);
8http_conn.setInstanceFollowRedirects(true);
9http_conn.setDoOutput(true);
10PrintWriter out = new PrintWriter(http_conn.getOutputStream());
11if (urlparameter != null) {
12   out.println(urlparameter);
13}
14out.close();
15out = null;
16System.out.println(String.valueOf(http_conn.getResponseCode()));
17
Full Screen
copy
1// GET
2HttpResponse response = HttpRequest
3    .create(new URI("http://www.stackoverflow.com"))
4    .headers("Foo", "foovalue", "Bar", "barvalue")
5    .GET()
6    .response();
7
Full Screen
copy
1int statusCode = response.statusCode();
2String responseBody = response.body(HttpResponse.asString());
3
Full Screen
copy
1module com.foo.bar {
2    requires jdk.incubator.httpclient;
3}
4
Full Screen
copy
1// GET http://google.com?q=baseball%20gloves&size=100
2String response = HttpRequest.get("http://google.com", true, "q", "baseball gloves", "size", 100)
3        .accept("application/json")
4        .body();
5System.out.println("Response was: " + response);
6
Full Screen
copy
1int responseCode = httpURLConnection.getResponseCode();
2
3if (responseCode == HttpURLConnection.HTTP_OK) {
4
Full Screen
copy
1String url = "http://example.com";
2String charset = "UTF-8";  // Or in Java 7 and later, use the constant: java.nio.charset.StandardCharsets.UTF_8.name()
3String param1 = "value1";
4String param2 = "value2";
5// ...
6
7String query = String.format("param1=%s&param2=%s",
8    URLEncoder.encode(param1, charset),
9    URLEncoder.encode(param2, charset));
10
Full Screen
copy
1URLConnection connection = new URL(url + "?" + query).openConnection();
2connection.setRequestProperty("Accept-Charset", charset);
3InputStream response = connection.getInputStream();
4// ...
5
Full Screen
copy
1InputStream response = new URL(url).openStream();
2// ...
3
Full Screen
copy
1try (Scanner scanner = new Scanner(response)) {
2    String responseBody = scanner.useDelimiter("\\A").next();
3    System.out.println(responseBody);
4}
5
Full Screen
copy
1URLConnection connection = new URL(url).openConnection();
2connection.setDoOutput(true); // Triggers POST.
3connection.setRequestProperty("Accept-Charset", charset);
4connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
5
6try (OutputStream output = connection.getOutputStream()) {
7    output.write(query.getBytes(charset));
8}
9
10InputStream response = connection.getInputStream();
11// ...
12
Full Screen
copy
1HttpURLConnection httpConnection = (HttpURLConnection) new URL(url).openConnection();
2httpConnection.setRequestMethod("POST");
3// ...
4
Full Screen
copy
1    int status = httpConnection.getResponseCode();
2
Full Screen
copy
1    String contentType = connection.getHeaderField("Content-Type");
2    String charset = null;
3
4    for (String param : contentType.replace(" ", "").split(";")) {
5        if (param.startsWith("charset=")) {
6            charset = param.split("=", 2)[1];
7            break;
8        }
9    }
10
11    if (charset != null) {
12        try (BufferedReader reader = new BufferedReader(new InputStreamReader(response, charset))) {
13            for (String line; (line = reader.readLine()) != null;) {
14                // ... System.out.println(line)?
15            }
16        }
17    } else {
18        // It's likely binary content, use InputStream/OutputStream.
19    }
20
Full Screen
copy
1// First set the default cookie manager.
2CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
3
4// All the following subsequent URLConnections will use the same cookie manager.
5URLConnection connection = new URL(url).openConnection();
6// ...
7
8connection = new URL(url).openConnection();
9// ...
10
11connection = new URL(url).openConnection();
12// ...
13
Full Screen
copy
1// Gather all cookies on the first request.
2URLConnection connection = new URL(url).openConnection();
3List<String> cookies = connection.getHeaderFields().get("Set-Cookie");
4// ...
5
6// Then use the same cookies on all subsequent requests.
7connection = new URL(url).openConnection();
8for (String cookie : cookies) {
9    connection.addRequestProperty("Cookie", cookie.split(";", 2)[0]);
10}
11// ...
12
Full Screen
copy
1httpConnection.setFixedLengthStreamingMode(contentLength);
2
Full Screen
copy
1httpConnection.setChunkedStreamingMode(1024);
2
Full Screen
copy
1connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"); // Do as if you're using Chrome 41 on Windows 7.
2
Full Screen
copy
1InputStream error = ((HttpURLConnection) connection).getErrorStream();
2
Full Screen
copy
1System.setProperty("http.keepAlive", "false");
2
Full Screen
copy
1String param = "value";
2File textFile = new File("/path/to/file.txt");
3File binaryFile = new File("/path/to/file.bin");
4String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
5String CRLF = "\r\n"; // Line separator required by multipart/form-data.
6URLConnection connection = new URL(url).openConnection();
7connection.setDoOutput(true);
8connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
9
10try (
11    OutputStream output = connection.getOutputStream();
12    PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
13) {
14    // Send normal param.
15    writer.append("--" + boundary).append(CRLF);
16    writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF);
17    writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);
18    writer.append(CRLF).append(param).append(CRLF).flush();
19
20    // Send text file.
21    writer.append("--" + boundary).append(CRLF);
22    writer.append("Content-Disposition: form-data; name=\"textFile\"; filename=\"" + textFile.getName() + "\"").append(CRLF);
23    writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); // Text file itself must be saved in this charset!
24    writer.append(CRLF).flush();
25    Files.copy(textFile.toPath(), output);
26    output.flush(); // Important before continuing with writer!
27    writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.
28
29    // Send binary file.
30    writer.append("--" + boundary).append(CRLF);
31    writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"").append(CRLF);
32    writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName())).append(CRLF);
33    writer.append("Content-Transfer-Encoding: binary").append(CRLF);
34    writer.append(CRLF).flush();
35    Files.copy(binaryFile.toPath(), output);
36    output.flush(); // Important before continuing with writer!
37    writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.
38
39    // End of multipart/form-data.
40    writer.append("--" + boundary + "--").append(CRLF).flush();
41}
42
Full Screen
copy
1static {
2    TrustManager[] trustAllCertificates = new TrustManager[] {
3        new X509TrustManager() {
4            @Override
5            public X509Certificate[] getAcceptedIssuers() {
6                return null; // Not relevant.
7            }
8            @Override
9            public void checkClientTrusted(X509Certificate[] certs, String authType) {
10                // Do nothing. Just allow them all.
11            }
12            @Override
13            public void checkServerTrusted(X509Certificate[] certs, String authType) {
14                // Do nothing. Just allow them all.
15            }
16        }
17    };
18
19    HostnameVerifier trustAllHostnames = new HostnameVerifier() {
20        @Override
21        public boolean verify(String hostname, SSLSession session) {
22            return true; // Just allow them all.
23        }
24    };
25
26    try {
27        System.setProperty("jsse.enableSNIExtension", "false");
28        SSLContext sc = SSLContext.getInstance("SSL");
29        sc.init(null, trustAllCertificates, new SecureRandom());
30        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
31        HttpsURLConnection.setDefaultHostnameVerifier(trustAllHostnames);
32    }
33    catch (GeneralSecurityException e) {
34        throw new ExceptionInInitializerError(e);
35    }
36}
37
Full Screen
copy
1public Synchronized class service(ServletRequest request,ServletResponse response)throws ServletException,IOException
2
Full Screen
copy
1Synchronized(Object)
2
3{
4
5----Instructions-----
6
7}
8
copy
1public class ExampleServlet extends HttpServlet {
2
3    private Object thisIsNOTThreadSafe;
4
5    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
6        Object thisIsThreadSafe;
7
8        thisIsNOTThreadSafe = request.getParameter("foo"); // BAD!! Shared among all requests!
9        thisIsThreadSafe = request.getParameter("foo"); // OK, this is thread safe.
10    } 
11}
12
Full Screen
copy
1public static String getRandomString(int length)
2{
3    String randomStr = UUID.randomUUID().toString();
4    while(randomStr.length() < length) {
5        randomStr += UUID.randomUUID().toString();
6    }
7    return randomStr.substring(0, length);
8}
9
Full Screen
copy
1 public String generateRandomString(int length) {
2    String randomString = "";
3
4    final char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567890".toCharArray();
5    final Random random = new Random();
6    for (int i = 0; i < length; i++) {
7        randomString = randomString + chars[random.nextInt(chars.length)];
8    }
9
10    return randomString;
11}
12
Full Screen
copy
1public static String randomSeriesForThreeCharacter() {
2    Random r = new Random();
3    String value = "";
4    char random_Char ;
5    for(int i=0; i<10; i++)
6    {
7        random_Char = (char) (48 + r.nextInt(74));
8        value = value + random_char;
9    }
10    return value;
11}
12
Full Screen
copy
1import org.apache.commons.lang.RandomStringUtils;
2RandomStringUtils.randomAlphanumeric(64);
3
Full Screen
copy
1(for (i <- 0 until rnd.nextInt(64)) yield { 
2  ('0' + rnd.nextInt(64)).asInstanceOf[Char] 
3}) mkString("")
4
Full Screen
copy
1String.valueOf(CharStream.random('0', 'z').filter(c -> N.isLetterOrDigit(c)).limit(12).toArray())
2
Full Screen
copy
1N.uuid() // E.g.: "e812e749-cf4c-4959-8ee1-57829a69a80f". length is 36.
2N.guid() // E.g.: "0678ce04e18945559ba82ddeccaabfcd". length is 32 without '-'
3
Full Screen
copy
1Long.toString(Math.abs( UUID.randomUUID().getLeastSignificantBits(), 36));
2
Full Screen
copy
1private static final String NUMBERS = "0123456789";
2private static final String UPPER_ALPHABETS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
3private static final String LOWER_ALPHABETS = "abcdefghijklmnopqrstuvwxyz";
4private static final String SPECIALCHARACTERS = "@#$%&*";
5private static final int MINLENGTHOFPASSWORD = 8;
6
7public static String getRandomPassword() {
8    StringBuilder password = new StringBuilder();
9    int j = 0;
10    for (int i = 0; i < MINLENGTHOFPASSWORD; i++) {
11        password.append(getRandomPasswordCharacters(j));
12        j++;
13        if (j == 3) {
14            j = 0;
15        }
16    }
17    return password.toString();
18}
19
20private static String getRandomPasswordCharacters(int pos) {
21    Random randomNum = new Random();
22    StringBuilder randomChar = new StringBuilder();
23    switch (pos) {
24        case 0:
25            randomChar.append(NUMBERS.charAt(randomNum.nextInt(NUMBERS.length() - 1)));
26            break;
27        case 1:
28            randomChar.append(UPPER_ALPHABETS.charAt(randomNum.nextInt(UPPER_ALPHABETS.length() - 1)));
29            break;
30        case 2:
31            randomChar.append(SPECIALCHARACTERS.charAt(randomNum.nextInt(SPECIALCHARACTERS.length() - 1)));
32            break;
33        case 3:
34            randomChar.append(LOWER_ALPHABETS.charAt(randomNum.nextInt(LOWER_ALPHABETS.length() - 1)));
35            break;
36    }
37    return randomChar.toString();
38}
39
Full Screen
copy
1import java.util.*;
2import javax.swing.*;
3
4public class alphanumeric {
5    public static void main(String args[]) {
6        String nval, lenval;
7        int n, len;
8
9        nval = JOptionPane.showInputDialog("Enter number of codes you require: ");
10        n = Integer.parseInt(nval);
11
12        lenval = JOptionPane.showInputDialog("Enter code length you require: ");
13        len = Integer.parseInt(lenval);
14
15        find(n, len);
16    }
17
18    public static void find(int n, int length) {
19        String str1 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
20        StringBuilder sb = new StringBuilder(length);
21        Random r = new Random();
22
23        System.out.println("\n\t Unique codes are \n\n");
24        for(int i=0; i<n; i++) {
25            for(int j=0; j<length; j++) {
26                sb.append(str1.charAt(r.nextInt(str1.length())));
27            }
28            System.out.println("  " + sb.toString());
29            sb.delete(0, length);
30        }
31    }
32}
33
Full Screen
copy
1import org.apache.commons.lang3.RandomStringUtils;
2
3String keyLength = 20;
4RandomStringUtils.randomAlphanumeric(keylength);
5
Full Screen
copy
1public String randomString(int length, String characterSet) {
2    return IntStream.range(0, length).map(i -> new SecureRandom().nextInt(characterSet.length())).mapToObj(randomInt -> characterSet.substring(randomInt, randomInt + 1)).collect(Collectors.joining());
3}
4
5@Test
6public void buildFiveRandomStrings() {
7    for (int q = 0; q < 5; q++) {
8        System.out.println(randomString(10, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")); // The character set can basically be anything
9    }
10}
11
Full Screen
copy
1public String randomString(int length, String characterSet) {
2    StringBuilder sb = new StringBuilder(); // Consider using StringBuffer if needed
3    for (int i = 0; i < length; i++) {
4        int randomInt = new SecureRandom().nextInt(characterSet.length());
5        sb.append(characterSet.substring(randomInt, randomInt + 1));
6    }
7    return sb.toString();
8}
9
10@Test
11public void buildFiveRandomStrings() {
12    for (int q = 0; q < 5; q++) {
13        System.out.println(randomString(10, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")); // The character set can basically be anything
14    }
15}
16
Full Screen
copy
1UUID.randomUUID().toString().replace("-", "")
2
Full Screen
copy
1import java.util.Date;
2import java.util.Random;
3
4public class RandomGenerator {
5
6  private static Random random = new Random((new Date()).getTime());
7
8    public static String generateRandomString(int length) {
9      char[] values = {'a','b','c','d','e','f','g','h','i','j',
10               'k','l','m','n','o','p','q','r','s','t',
11               'u','v','w','x','y','z','0','1','2','3',
12               '4','5','6','7','8','9'};
13
14      String out = "";
15
16      for (int i=0;i<length;i++) {
17          int idx=random.nextInt(values.length);
18          out += values[idx];
19      }
20      return out;
21    }
22}
23
Full Screen
copy
1public static String getRandomString(int length) {
2    final String characters = "[email protected]#$%^&*()_+";
3    StringBuilder result = new StringBuilder();
4
5    while(length > 0) {
6        Random rand = new Random();
7        result.append(characters.charAt(rand.nextInt(characters.length())));
8        length--;
9    }
10    return result.toString();
11}
12
Full Screen
copy
1/**
2 * Generate a random hex encoded string token of the specified length
3 *  
4 * @param length
5 * @return random hex string
6 */
7public static synchronized String generateUniqueToken(Integer length){ 
8    byte random[] = new byte[length];
9    Random randomGenerator = new Random();
10    StringBuffer buffer = new StringBuffer();
11
12    randomGenerator.nextBytes(random);
13
14    for (int j = 0; j < random.length; j++) {
15        byte b1 = (byte) ((random[j] & 0xf0) >> 4);
16        byte b2 = (byte) (random[j] & 0x0f);
17        if (b1 < 10)
18            buffer.append((char) ('0' + b1));
19        else
20            buffer.append((char) ('A' + (b1 - 10)));
21        if (b2 < 10)
22            buffer.append((char) ('0' + b2));
23        else
24            buffer.append((char) ('A' + (b2 - 10)));
25    }
26    return (buffer.toString());
27}
28
29@Test
30public void testGenerateUniqueToken(){
31    Set set = new HashSet();
32    String token = null;
33    int size = 16;
34
35    /* Seems like we should be able to generate 500K tokens 
36     * without a duplicate 
37     */
38    for (int i=0; i<500000; i++){
39        token = Utility.generateUniqueToken(size);
40
41        if (token.length() != size * 2){
42            fail("Incorrect length");
43        } else if (set.contains(token)) {
44            fail("Duplicate token generated");
45        } else{
46            set.add(token);
47        }
48    }
49}
50
Full Screen
copy
1/*
2 * The random generator used by this class to create random keys.
3 * In a holder class to defer initialization until needed.
4 */
5private static class RandomHolder {
6    static final Random random = new SecureRandom();
7    public static String randomKey(int length) {
8        return String.format("%"+length+"s", new BigInteger(length*5/*base 32,2^5*/, random)
9            .toString(32)).replace('\u0020', '0');
10    }
11}
12
Full Screen
copy
1import java.util.Random;
2
3public class passGen{
4    // Version 1.0
5    private static final String dCase = "abcdefghijklmnopqrstuvwxyz";
6    private static final String uCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
7    private static final String sChar = "[email protected]#$%^&*";
8    private static final String intChar = "0123456789";
9    private static Random r = new Random();
10    private static StringBuilder pass = new StringBuilder();
11
12    public static void main (String[] args) {
13        System.out.println ("Generating pass...");
14        while (pass.length () != 16){
15            int rPick = r.nextInt(4);
16            if (rPick == 0){
17                int spot = r.nextInt(26);
18                pass.append(dCase.charAt(spot));
19            } else if (rPick == 1) {
20                int spot = r.nextInt(26);
21                pass.append(uCase.charAt(spot));
22            } else if (rPick == 2) {
23                int spot = r.nextInt(8);
24                pass.append(sChar.charAt(spot));
25            } else {
26                int spot = r.nextInt(10);
27                pass.append(intChar.charAt(spot));
28            }
29        }
30        System.out.println ("Generated Pass: " + pass.toString());
31    }
32}
33
Full Screen
copy
1public static String generateSessionKey(int length){
2    String alphabet =
3        new String("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"); // 9
4
5    int n = alphabet.length(); // 10
6
7    String result = new String();
8    Random r = new Random(); // 11
9
10    for (int i=0; i<length; i++) // 12
11        result = result + alphabet.charAt(r.nextInt(n)); //13
12
13    return result;
14}
15
Full Screen
copy
1static final Random random = new Random(); // Or SecureRandom
2static final int startChar = (int) '!';
3static final int endChar = (int) '~';
4
5static String randomString(final int maxLength) {
6  final int length = random.nextInt(maxLength + 1);
7  return random.ints(length, startChar, endChar + 1)
8        .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
9        .toString();
10}
11
Full Screen
copy
1import java.util.UUID
2
3UUID.randomUUID().toString();
4
Full Screen
copy
1Random r = new java.util.Random ();
2String s = Long.toString (r.nextLong () & Long.MAX_VALUE, 36);
3
Full Screen
copy
1import static java.lang.Math.round;
2import static java.lang.Math.random;
3import static java.lang.Math.pow;
4import static java.lang.Math.abs;
5import static java.lang.Math.min;
6import static org.apache.commons.lang.StringUtils.leftPad
7
8public class RandomAlphaNum {
9  public static String gen(int length) {
10    StringBuffer sb = new StringBuffer();
11    for (int i = length; i > 0; i -= 12) {
12      int n = min(12, abs(i));
13      sb.append(leftPad(Long.toString(round(random() * pow(36, n)), 36), n, '0'));
14    }
15    return sb.toString();
16  }
17}
18
Full Screen
copy
1scala> RandomAlphaNum.gen(42)
2res3: java.lang.String = uja6snx21bswf9t89s00bxssu8g6qlu16ffzqaxxoy
3
Full Screen
copy
1// "0123456789" + "ABCDE...Z"
2String validCharacters = $('0', '9').join() + $('A', 'Z').join();
3
4String randomString(int length) {
5    return $(validCharacters).shuffle().slice(length).toString();
6}
7
8@Test
9public void buildFiveRandomStrings() {
10    for (int i : $(5)) {
11        System.out.println(randomString(12));
12    }
13}
14
Full Screen
copy
1DKL1SBH9UJWC
2JH7P0IT21EA5
35DTI72EO6SFU
4HQUMJTEBNF7Y
51HCR6SKYWGT7
6
Full Screen
copy
1SecureRandom rnd = new SecureRandom();
2byte[] token = new byte[byteLength];
3rnd.nextBytes(token);
4
Full Screen
copy
1public static String generateRandomHexToken(int byteLength) {
2    SecureRandom secureRandom = new SecureRandom();
3    byte[] token = new byte[byteLength];
4    secureRandom.nextBytes(token);
5    return new BigInteger(1, token).toString(16); // Hexadecimal encoding
6}
7
8//generateRandomHexToken(16) -> 2189df7475e96aa3982dbeab266497cd
9
Full Screen
copy
1public static String generateRandomBase64Token(int byteLength) {
2    SecureRandom secureRandom = new SecureRandom();
3    byte[] token = new byte[byteLength];
4    secureRandom.nextBytes(token);
5    return Base64.getUrlEncoder().withoutPadding().encodeToString(token); //base64 encoding
6}
7
8//generateRandomBase64Token(16) -> EEcCCAYuUcQk7IuzdaPzrg
9
Full Screen
copy
1IdMask<Long> idMask = IdMasks.forLongIds(Config.builder(key).build());
2String maskedId = idMask.mask(id);
3// Example: NPSBolhMyabUBdTyanrbqT8
4long originalId = idMask.unmask(maskedId);
5
Full Screen
copy
1Long.toHexString(Double.doubleToLongBits(Math.random()));
2
Full Screen
copy
1RandomStringUtils.randomAlphanumeric(20).toUpperCase();
2
Full Screen
copy
1RandomStringGenerator randomStringGenerator =
2        new RandomStringGenerator.Builder()
3                .withinRange('0', 'z')
4                .filteredBy(CharacterPredicates.LETTERS, CharacterPredicates.DIGITS)
5                .build();
6randomStringGenerator.generate(12); // toUpperCase() if you want
7
Full Screen
copy
1static final String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2static SecureRandom rnd = new SecureRandom();
3
4String randomString(int len){
5   StringBuilder sb = new StringBuilder(len);
6   for(int i = 0; i < len; i++)
7      sb.append(AB.charAt(rnd.nextInt(AB.length())));
8   return sb.toString();
9}
10
Full Screen
copy
1import java.util.UUID;
2
3public class randomStringGenerator {
4    public static void main(String[] args) {
5        System.out.println(generateString());
6    }
7
8    public static String generateString() {
9        String uuid = UUID.randomUUID().toString();
10        return "uuid = " + uuid;
11    }
12}
13
Full Screen
copy
1uuid = 2d7428a6-b58c-4008-8575-f05549f16316
2
Full Screen
copy
1public class RandomString {
2
3    /**
4     * Generate a random string.
5     */
6    public String nextString() {
7        for (int idx = 0; idx < buf.length; ++idx)
8            buf[idx] = symbols[random.nextInt(symbols.length)];
9        return new String(buf);
10    }
11
12    public static final String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
13
14    public static final String lower = upper.toLowerCase(Locale.ROOT);
15
16    public static final String digits = "0123456789";
17
18    public static final String alphanum = upper + lower + digits;
19
20    private final Random random;
21
22    private final char[] symbols;
23
24    private final char[] buf;
25
26    public RandomString(int length, Random random, String symbols) {
27        if (length < 1) throw new IllegalArgumentException();
28        if (symbols.length() < 2) throw new IllegalArgumentException();
29        this.random = Objects.requireNonNull(random);
30        this.symbols = symbols.toCharArray();
31        this.buf = new char[length];
32    }
33
34    /**
35     * Create an alphanumeric string generator.
36     */
37    public RandomString(int length, Random random) {
38        this(length, random, alphanum);
39    }
40
41    /**
42     * Create an alphanumeric strings from a secure generator.
43     */
44    public RandomString(int length) {
45        this(length, new SecureRandom());
46    }
47
48    /**
49     * Create session identifiers.
50     */
51    public RandomString() {
52        this(21);
53    }
54
55}
56
Full Screen
copy
1RandomString gen = new RandomString(8, ThreadLocalRandom.current());
2
Full Screen
copy
1RandomString session = new RandomString();
2
Full Screen
copy
1String easy = RandomString.digits + "ACEFGHJKLMNPQRUVWXYabcdefhijkprstuvwx";
2RandomString tickets = new RandomString(23, new SecureRandom(), easy);
3
Full Screen