code
stringlengths
73
34.1k
label
stringclasses
1 value
public boolean waitForConnectorFinished() throws InterruptedException { connectorStatusLock.lock(); try { if (connectorStatus == ConnectorStatus.ConnectorSuccesful) { return true; } return connectorSuccessfullyFinished.await(discoveryQos.getDiscoveryTimeoutMs(), TimeUnit.MILLISECONDS); } finally { connectorStatusLock.unlock(); } }
java
public boolean isConnectorReady() { connectorStatusLock.lock(); try { if (connectorStatus == ConnectorStatus.ConnectorSuccesful) { return true; } return false; } finally { connectorStatusLock.unlock(); } }
java
private void sendQueuedInvocations() { while (true) { MethodInvocation<?> currentRPC = queuedRpcList.poll(); if (currentRPC == null) { return; } try { connector.executeAsyncMethod(currentRPC.getProxy(), currentRPC.getMethod(), currentRPC.getArgs(), currentRPC.getFuture()); } catch (JoynrRuntimeException e) { currentRPC.getFuture().onFailure(e); } catch (Exception e) { currentRPC.getFuture().onFailure(new JoynrRuntimeException(e)); } } }
java
@Override public void createConnector(ArbitrationResult result) { connector = connectorFactory.create(proxyParticipantId, result, qosSettings, statelessAsyncParticipantId); connectorStatusLock.lock(); try { connectorStatus = ConnectorStatus.ConnectorSuccesful; connectorSuccessfullyFinished.signalAll(); if (connector != null) { sendQueuedInvocations(); sendQueuedSubscriptionInvocations(); sendQueuedUnsubscribeInvocations(); sendQueuedStatelessAsyncInvocations(); } } finally { connectorStatusLock.unlock(); } }
java
@GET @Produces({ MediaType.TEXT_PLAIN }) public String getTime() { return String.valueOf(System.currentTimeMillis()); }
java
public static int findFreePort() throws IOException { ServerSocket socket = null; try { socket = new ServerSocket(0); return socket.getLocalPort(); } finally { if (socket != null) { socket.close(); } } }
java
@DELETE @Path("/clusters/{clusterid: ([A-Z,a-z,0-9,_,\\-]+)}") public Response migrateCluster(@PathParam("clusterid") final String clusterId) { // as this is a long running task, this has to be asynchronous migrationService.startClusterMigration(clusterId); return Response.status(202 /* Accepted */).build(); }
java
public String buildReportStartupUrl(ControlledBounceProxyUrl controlledBounceProxyUrl) throws UnsupportedEncodingException { String url4cc = URLEncoder.encode(controlledBounceProxyUrl.getOwnUrlForClusterControllers(), "UTF-8"); String url4bpc = URLEncoder.encode(controlledBounceProxyUrl.getOwnUrlForBounceProxyController(), "UTF-8"); return baseUrl + // "?bpid=" + this.bounceProxyId + // "&url4cc=" + url4cc + // "&url4bpc=" + url4bpc; }
java
@POST @Consumes({ MediaType.APPLICATION_OCTET_STREAM }) public Response postMessageWithoutContentType(@PathParam("ccid") String ccid, byte[] serializedMessage) throws IOException { ImmutableMessage message; try { message = new ImmutableMessage(serializedMessage); } catch (EncodingException | UnsuppportedVersionException e) { log.error("Failed to deserialize SMRF message: {}", e.getMessage()); throw new WebApplicationException(e); } try { String msgId = message.getId(); log.debug("******POST message {} to cluster controller: {}", msgId, ccid); log.trace("******POST message {} to cluster controller: {} extended info: \r\n {}", ccid, message); response.setCharacterEncoding("UTF-8"); // the location that can be queried to get the message // status // TODO REST URL for message status? String path = longPollingDelegate.postMessage(ccid, serializedMessage); URI location = ui.getBaseUriBuilder().path(path).build(); // return the message status location to the sender. return Response.created(location).header("msgId", msgId).build(); } catch (WebApplicationException e) { log.error("Invalid request from host {}", request.getRemoteHost()); throw e; } catch (Exception e) { log.error("POST message for cluster controller: error: {}", e.getMessage()); throw new WebApplicationException(e); } }
java
public SubscriptionQos setValidityMs(final long validityMs) { if (validityMs == -1) { setExpiryDateMs(NO_EXPIRY_DATE); } else { long now = System.currentTimeMillis(); this.expiryDateMs = now + validityMs; } return this; }
java
public List<ChannelInformation> listChannels() { LinkedList<ChannelInformation> entries = new LinkedList<ChannelInformation>(); Collection<Broadcaster> broadcasters = BroadcasterFactory.getDefault().lookupAll(); String name; for (Broadcaster broadcaster : broadcasters) { if (broadcaster instanceof BounceProxyBroadcaster) { name = ((BounceProxyBroadcaster) broadcaster).getName(); } else { name = broadcaster.getClass().getSimpleName(); } Integer cachedSize = null; entries.add(new ChannelInformation(name, broadcaster.getAtmosphereResources().size(), cachedSize)); } return entries; }
java
public String createChannel(String ccid, String atmosphereTrackingId) { throwExceptionIfTrackingIdnotSet(atmosphereTrackingId); log.info("CREATE channel for cluster controller: {} trackingId: {} ", ccid, atmosphereTrackingId); Broadcaster broadcaster = null; // look for an existing broadcaster BroadcasterFactory defaultBroadcasterFactory = BroadcasterFactory.getDefault(); if (defaultBroadcasterFactory == null) { throw new JoynrHttpException(500, 10009, "broadcaster was null"); } broadcaster = defaultBroadcasterFactory.lookup(Broadcaster.class, ccid, false); // create a new one if none already exists if (broadcaster == null) { broadcaster = defaultBroadcasterFactory.get(BounceProxyBroadcaster.class, ccid); } // avoids error where previous long poll from browser got message // destined for new long poll // especially as seen in js, where every second refresh caused a fail for (AtmosphereResource resource : broadcaster.getAtmosphereResources()) { if (resource.uuid() != null && resource.uuid().equals(atmosphereTrackingId)) { resource.resume(); } } UUIDBroadcasterCache broadcasterCache = (UUIDBroadcasterCache) broadcaster.getBroadcasterConfig() .getBroadcasterCache(); broadcasterCache.activeClients().put(atmosphereTrackingId, System.currentTimeMillis()); // BroadcasterCacheInspector is not implemented corrected in Atmosphere // 1.1.0RC4 // broadcasterCache.inspector(new MessageExpirationInspector()); return "/channels/" + ccid + "/"; }
java
public boolean deleteChannel(String ccid) { log.info("DELETE channel for cluster controller: " + ccid); Broadcaster broadcaster = BroadcasterFactory.getDefault().lookup(Broadcaster.class, ccid, false); if (broadcaster == null) { return false; } BroadcasterFactory.getDefault().remove(ccid); broadcaster.resumeAll(); broadcaster.destroy(); // broadcaster.getBroadcasterConfig().forceDestroy(); return true; }
java
public String postMessage(String ccid, byte[] serializedMessage) { ImmutableMessage message; try { message = new ImmutableMessage(serializedMessage); } catch (EncodingException | UnsuppportedVersionException e) { throw new JoynrHttpException(Status.BAD_REQUEST, JOYNRMESSAGINGERROR_DESERIALIZATIONFAILED); } if (ccid == null) { log.error("POST message {} to cluster controller: NULL. Dropped because: channel Id was not set.", message.getId()); throw new JoynrHttpException(Status.BAD_REQUEST, JOYNRMESSAGINGERROR_CHANNELNOTSET); } // send the message to the receiver. if (message.getTtlMs() == 0) { log.error("POST message {} to cluster controller: {} dropped because: expiry date not set", ccid, message.getId()); throw new JoynrHttpException(Status.BAD_REQUEST, JOYNRMESSAGINGERROR_EXPIRYDATENOTSET); } // Relative TTLs are not supported yet. if (!message.isTtlAbsolute()) { throw new JoynrHttpException(Status.BAD_REQUEST, JOYNRMESSAGINGERROR_RELATIVE_TTL_UNSPORTED); } if (message.getTtlMs() < System.currentTimeMillis()) { log.warn("POST message {} to cluster controller: {} dropped because: TTL expired", ccid, message.getId()); throw new JoynrHttpException(Status.BAD_REQUEST, JOYNRMESSAGINGERROR_EXPIRYDATEEXPIRED); } // look for an existing broadcaster Broadcaster ccBroadcaster = BroadcasterFactory.getDefault().lookup(Broadcaster.class, ccid, false); if (ccBroadcaster == null) { // if the receiver has never registered with the bounceproxy // (or his registration has expired) then return 204 no // content. log.error("POST message {} to cluster controller: {} dropped because: no channel found", ccid, message.getId()); throw new JoynrHttpException(Status.BAD_REQUEST, JOYNRMESSAGINGERROR_CHANNELNOTFOUND); } if (ccBroadcaster.getAtmosphereResources().size() == 0) { log.debug("no poll currently waiting for channelId: {}", ccid); } ccBroadcaster.broadcast(message); return "messages/" + message.getId(); }
java
private void asyncGetGlobalCapabilitities(final String[] domains, final String interfaceName, Collection<DiscoveryEntryWithMetaInfo> localDiscoveryEntries2, long discoveryTimeout, final CapabilitiesCallback capabilitiesCallback) { final Collection<DiscoveryEntryWithMetaInfo> localDiscoveryEntries = localDiscoveryEntries2 == null ? new LinkedList<DiscoveryEntryWithMetaInfo>() : localDiscoveryEntries2; globalCapabilitiesDirectoryClient.lookup(new Callback<List<GlobalDiscoveryEntry>>() { @Override public void onSuccess(List<GlobalDiscoveryEntry> globalDiscoverEntries) { if (globalDiscoverEntries != null) { registerIncomingEndpoints(globalDiscoverEntries); globalDiscoveryEntryCache.add(globalDiscoverEntries); Collection<DiscoveryEntryWithMetaInfo> allDisoveryEntries = new ArrayList<DiscoveryEntryWithMetaInfo>(globalDiscoverEntries.size() + localDiscoveryEntries.size()); allDisoveryEntries.addAll(CapabilityUtils.convertToDiscoveryEntryWithMetaInfoList(false, globalDiscoverEntries)); allDisoveryEntries.addAll(localDiscoveryEntries); capabilitiesCallback.processCapabilitiesReceived(allDisoveryEntries); } else { capabilitiesCallback.onError(new NullPointerException("Received capabilities are null")); } } @Override public void onFailure(JoynrRuntimeException exception) { capabilitiesCallback.onError(exception); } }, domains, interfaceName, discoveryTimeout); }
java
public static boolean isSessionEncodedInUrl(String encodedUrl, String sessionIdName) { int sessionIdIndex = encodedUrl.indexOf(getSessionIdSubstring(sessionIdName)); return sessionIdIndex >= 0; }
java
public static String getUrlWithoutSessionId(String url, String sessionIdName) { if (isSessionEncodedInUrl(url, sessionIdName)) { return url.substring(0, url.indexOf(getSessionIdSubstring(sessionIdName))); } return url; }
java
public static String getSessionEncodedUrl(String url, String sessionIdName, String sessionId) { return url + getSessionIdSubstring(sessionIdName) + sessionId; }
java
private void stopPublicationByProviderId(String providerParticipantId) { for (PublicationInformation publicationInformation : subscriptionId2PublicationInformation.values()) { if (publicationInformation.getProviderParticipantId().equals(providerParticipantId)) { removePublication(publicationInformation.getSubscriptionId()); } } if (providerParticipantId != null && queuedSubscriptionRequests.containsKey(providerParticipantId)) { queuedSubscriptionRequests.removeAll(providerParticipantId); } }
java
private void restoreQueuedSubscription(String providerId, ProviderContainer providerContainer) { Collection<PublicationInformation> queuedRequests = queuedSubscriptionRequests.get(providerId); Iterator<PublicationInformation> queuedRequestsIterator = queuedRequests.iterator(); while (queuedRequestsIterator.hasNext()) { PublicationInformation publicationInformation = queuedRequestsIterator.next(); queuedRequestsIterator.remove(); if (!isExpired(publicationInformation)) { addSubscriptionRequest(publicationInformation.getProxyParticipantId(), publicationInformation.getProviderParticipantId(), publicationInformation.subscriptionRequest, providerContainer); } } }
java
public static URI createChannelLocation(ControlledBounceProxyInformation bpInfo, String ccid, URI location) { return URI.create(location.toString() + ";jsessionid=." + bpInfo.getInstanceId()); }
java
@GET @Produces("application/json") public GenericEntity<List<ChannelInformation>> listChannels() { try { return new GenericEntity<List<ChannelInformation>>(channelService.listChannels()) { }; } catch (Exception e) { log.error("GET channels listChannels: error: {}", e.getMessage(), e); throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } }
java
@GET @Path("/{ccid: [A-Z,a-z,0-9,_,\\-,\\.]+}") @Produces({ MediaType.APPLICATION_JSON }) @Suspend(resumeOnBroadcast = true, period = ChannelServiceConstants.EXPIRE_TIME_CONNECTION, timeUnit = TimeUnit.SECONDS, contentType = MediaType.APPLICATION_JSON) public Broadcastable open(@PathParam("ccid") String ccid, @HeaderParam("X-Cache-Index") Integer cacheIndex, @HeaderParam(ChannelServiceConstants.X_ATMOSPHERE_TRACKING_ID) String atmosphereTrackingId) { try { return channelService.openChannel(ccid, cacheIndex, atmosphereTrackingId); } catch (WebApplicationException e) { throw e; } catch (Exception e) { log.error("GET Channels open long poll ccid: error: {}", e.getMessage(), e); throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } }
java
@POST @Produces({ MediaType.TEXT_PLAIN }) public Response createChannel(@QueryParam("ccid") String ccid, @HeaderParam(ChannelServiceConstants.X_ATMOSPHERE_TRACKING_ID) String atmosphereTrackingId) { try { log.info("CREATE channel for channel ID: {}", ccid); if (ccid == null || ccid.isEmpty()) throw new JoynrHttpException(Status.BAD_REQUEST, JOYNRMESSAGINGERROR_CHANNELNOTSET); Channel channel = channelService.getChannel(ccid); if (channel != null) { String encodedChannelLocation = response.encodeURL(channel.getLocation().toString()); return Response.ok() .entity(encodedChannelLocation) .header("Location", encodedChannelLocation) .header("bp", channel.getBounceProxy().getId()) .build(); } // look for an existing bounce proxy handling the channel channel = channelService.createChannel(ccid, atmosphereTrackingId); String encodedChannelLocation = response.encodeURL(channel.getLocation().toString()); log.debug("encoded channel URL " + channel.getLocation() + " to " + encodedChannelLocation); return Response.created(URI.create(encodedChannelLocation)) .entity(encodedChannelLocation) .header("bp", channel.getBounceProxy().getId()) .build(); } catch (WebApplicationException ex) { throw ex; } catch (Exception e) { throw new WebApplicationException(e); } }
java
@DELETE @Path("/{ccid: [A-Z,a-z,0-9,_,\\-,\\.]+}") public Response deleteChannel(@PathParam("ccid") String ccid) { try { log.info("DELETE channel for cluster controller: {}", ccid); if (channelService.deleteChannel(ccid)) { return Response.ok().build(); } return Response.noContent().build(); } catch (WebApplicationException e) { throw e; } catch (Exception e) { log.error("DELETE channel for cluster controller: error: {}", e.getMessage(), e); throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } }
java
private synchronized boolean createChannel() { final String url = settings.getBounceProxyUrl().buildCreateChannelUrl(channelId); HttpPost postCreateChannel = httpRequestFactory.createHttpPost(URI.create(url.trim())); postCreateChannel.setConfig(defaultRequestConfig); postCreateChannel.addHeader(httpConstants.getHEADER_X_ATMOSPHERE_TRACKING_ID(), receiverId); postCreateChannel.addHeader(httpConstants.getHEADER_CONTENT_TYPE(), httpConstants.getAPPLICATION_JSON()); channelUrl = null; CloseableHttpResponse response = null; boolean created = false; try { response = httpclient.execute(postCreateChannel); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); String reasonPhrase = statusLine.getReasonPhrase(); switch (statusCode) { case HttpURLConnection.HTTP_OK: case HttpURLConnection.HTTP_CREATED: try { Header locationHeader = response.getFirstHeader(httpConstants.getHEADER_LOCATION()); channelUrl = locationHeader != null ? locationHeader.getValue() : null; } catch (Exception e) { throw new JoynrChannelMissingException("channel url was null"); } break; default: logger.error("createChannel channelId: {} failed. status: {} reason: {}", channelId, statusCode, reasonPhrase); throw new JoynrChannelMissingException("channel url was null"); } created = true; logger.info("createChannel channelId: {} returned channelUrl {}", channelId, channelUrl); } catch (ClientProtocolException e) { logger.error("createChannel ERROR reason: {}", e.getMessage()); } catch (IOException e) { logger.error("createChannel ERROR reason: {}", e.getMessage()); } finally { if (response != null) { try { response.close(); } catch (IOException e) { logger.error("createChannel ERROR reason: {}", e.getMessage()); } } } return created; }
java
public static List<List<Annotation>> findAndMergeParameterAnnotations(Method method) { List<List<Annotation>> res = new ArrayList<List<Annotation>>(method.getParameterTypes().length); for (int i = 0; i < method.getParameterTypes().length; i++) { res.add(new LinkedList<Annotation>()); } findAndMergeAnnotations(method.getDeclaringClass(), method, res); return res; }
java
private static boolean areMethodNameAndParameterTypesEqual(Method methodA, Method methodB) { if (!methodA.getName().equals(methodB.getName())) { return false; } Class<?>[] methodAParameterTypes = methodA.getParameterTypes(); Class<?>[] methodBParameterTypes = methodB.getParameterTypes(); if (methodAParameterTypes.length != methodBParameterTypes.length) { return false; } for (int i = 0; i < methodAParameterTypes.length; i++) { if (!methodAParameterTypes[i].equals(methodBParameterTypes[i])) { return false; } } return true; }
java
protected void arbitrationFinished(ArbitrationStatus arbitrationStatus, ArbitrationResult arbitrationResult) { this.arbitrationStatus = arbitrationStatus; this.arbitrationResult = arbitrationResult; // wait for arbitration listener to be registered if (arbitrationListenerSemaphore.tryAcquire()) { arbitrationListener.onSuccess(arbitrationResult); arbitrationListenerSemaphore.release(); } }
java
@Override public Future<Void> registerProvider(String domain, Object provider, ProviderQos providerQos, boolean awaitGlobalRegistration, final Class<?> interfaceClass) { if (interfaceClass == null) { throw new IllegalArgumentException("Cannot registerProvider: interfaceClass may not be NULL"); } registerInterfaceClassTypes(interfaceClass, "Cannot registerProvider"); return capabilitiesRegistrar.registerProvider(domain, provider, providerQos, awaitGlobalRegistration); }
java
public void setStatus(BounceProxyStatus status) throws IllegalStateException { // this checks if the transition is valid if (this.status.isValidTransition(status)) { this.status = status; } else { throw new IllegalStateException("Illegal status transition from " + this.status + " to " + status); } }
java
@POST @Produces({ MediaType.APPLICATION_OCTET_STREAM }) public Response postMessage(@PathParam("ccid") String ccid, byte[] serializedMessage) { ImmutableMessage message; try { message = new ImmutableMessage(serializedMessage); } catch (EncodingException | UnsuppportedVersionException e) { throw new JoynrHttpException(Status.BAD_REQUEST, JOYNRMESSAGINGERROR_DESERIALIZATIONFAILED); } try { log.debug("POST message to channel: {} message: {}", ccid, message); // TODO Can this happen at all with empty path parameter??? if (ccid == null) { log.error("POST message to channel: NULL. message: {} dropped because: channel Id was not set", message); throw new JoynrHttpException(Status.BAD_REQUEST, JOYNRMESSAGINGERROR_CHANNELNOTSET); } // send the message to the receiver. if (message.getTtlMs() == 0) { log.error("POST message to channel: {} message: {} dropped because: TTL not set", ccid, message); throw new JoynrHttpException(Status.BAD_REQUEST, JOYNRMESSAGINGERROR_EXPIRYDATENOTSET); } if (message.getTtlMs() < timestampProvider.getCurrentTime()) { log.warn("POST message {} to cluster controller: {} dropped because: TTL expired", ccid, message.getId()); throw new JoynrHttpException(Status.BAD_REQUEST, JOYNRMESSAGINGERROR_EXPIRYDATEEXPIRED, request.getRemoteHost()); } if (!messagingService.isAssignedForChannel(ccid)) { // scalability extensions: in case that other component should handle this channel log.debug("POST message {}: Bounce Proxy not assigned for channel: {}", message, ccid); if (messagingService.hasChannelAssignmentMoved(ccid)) { // scalability extension: in case that this component was responsible before but isn't any more log.debug("POST message {}: Bounce Proxy assignment moved for channel: {}", message, ccid); return Response.status(410 /* Gone */).build(); } else { log.debug("POST message {}: channel unknown: {}", message, ccid); return Response.status(404 /* Not Found */).build(); } } // if the receiver has never registered with the bounceproxy // (or his registration has expired) then return 204 no // content. if (!messagingService.hasMessageReceiver(ccid)) { log.debug("POST message {}: no receiver for channel: {}", message, ccid); return Response.noContent().build(); } messagingService.passMessageToReceiver(ccid, serializedMessage); // the location that can be queried to get the message // status // TODO REST URL for message status? URI location = ui.getBaseUriBuilder().path("messages/" + message.getId()).build(); // encode URL in case we use sessions String encodeURL = response.encodeURL(location.toString()); // return the message status location to the sender. return Response.created(URI.create(encodeURL)).header("msgId", message.getId()).build(); } catch (WebApplicationException e) { throw e; } catch (Exception e) { log.debug("POST message to channel: {} error: {}", ccid, e.getMessage()); throw new WebApplicationException(e, Status.INTERNAL_SERVER_ERROR); } }
java
public static Arbitrator create(final Set<String> domains, final String interfaceName, final Version interfaceVersion, final DiscoveryQos discoveryQos, DiscoveryAsync localDiscoveryAggregator) throws DiscoveryException { ArbitrationStrategyFunction arbitrationStrategyFunction; switch (discoveryQos.getArbitrationStrategy()) { case FixedChannel: arbitrationStrategyFunction = new FixedParticipantArbitrationStrategyFunction(); break; case Keyword: arbitrationStrategyFunction = new KeywordArbitrationStrategyFunction(); break; case HighestPriority: arbitrationStrategyFunction = new HighestPriorityArbitrationStrategyFunction(); break; case LastSeen: arbitrationStrategyFunction = new LastSeenArbitrationStrategyFunction(); break; case Custom: arbitrationStrategyFunction = discoveryQos.getArbitrationStrategyFunction(); break; default: throw new DiscoveryException("Arbitration failed: domain: " + domains + " interface: " + interfaceName + " qos: " + discoveryQos + ": unknown arbitration strategy or strategy not set!"); } return new Arbitrator(domains, interfaceName, interfaceVersion, discoveryQos, localDiscoveryAggregator, minimumArbitrationRetryDelay, arbitrationStrategyFunction, discoveryEntryVersionFilter); }
java
public static Properties loadProperties(String fileName) { LowerCaseProperties properties = new LowerCaseProperties(); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); URL url = classLoader.getResource(fileName); // try opening from classpath if (url != null) { InputStream urlStream = null; try { urlStream = url.openStream(); properties.load(urlStream); logger.info("Properties from classpath loaded file: " + fileName); } catch (IOException e) { logger.info("Properties from classpath not loaded because file not found: " + fileName); } finally { if (urlStream != null) { try { urlStream.close(); } catch (IOException e) { } } } } // Override properties found on the classpath with any found in a file // of the same name LowerCaseProperties propertiesFromFileSystem = loadProperties(new File(fileName)); properties.putAll(propertiesFromFileSystem); return properties; }
java
@GET @Produces({ MediaType.APPLICATION_JSON }) public GenericEntity<List<BounceProxyStatusInformation>> getBounceProxies() { return new GenericEntity<List<BounceProxyStatusInformation>>(monitoringService.getRegisteredBounceProxies()) { }; }
java
public URI createChannel(ControlledBounceProxyInformation bpInfo, String ccid, String trackingId) throws JoynrProtocolException { try { // Try to create a channel on a bounce proxy with maximum number of // retries. return createChannelLoop(bpInfo, ccid, trackingId, sendCreateChannelMaxRetries); } catch (JoynrProtocolException e) { logger.error("Unexpected bounce proxy behaviour: message: {}", e.getMessage()); throw e; } catch (JoynrRuntimeException e) { logger.error("Channel creation on bounce proxy failed: message: {}", e.getMessage()); throw e; } catch (Exception e) { logger.error("Uncaught exception in channel creation: message: {}", e.getMessage()); throw new JoynrRuntimeException("Unknown exception when creating channel '" + ccid + "' on bounce proxy '" + bpInfo.getId() + "'", e); } }
java
private URI createChannelLoop(ControlledBounceProxyInformation bpInfo, String ccid, String trackingId, int retries) throws JoynrProtocolException { while (retries > 0) { retries--; try { return sendCreateChannelHttpRequest(bpInfo, ccid, trackingId); } catch (IOException e) { // failed to establish communication with the bounce proxy logger.error("creating a channel on bounce proxy {} failed due to communication errors: message: {}", bpInfo.getId(), e.getMessage()); } // try again if creating the channel failed try { Thread.sleep(sendCreateChannelRetryIntervalMs); } catch (InterruptedException e) { throw new JoynrRuntimeException("creating a channel on bounce proxy " + bpInfo.getId() + " was interrupted."); } } // the maximum number of retries passed, so channel creation failed throw new JoynrRuntimeException("creating a channel on bounce proxy " + bpInfo.getId() + " failed."); }
java
public void cancelReporting() { if (startupReportFuture != null) { startupReportFuture.cancel(true); } if (execService != null) { // interrupt reporting loop execService.shutdownNow(); } }
java
private void reportEventAsHttpRequest() throws IOException { final String url = bounceProxyControllerUrl.buildReportStartupUrl(controlledBounceProxyUrl); logger.debug("Using monitoring service URL: {}", url); HttpPut putReportStartup = new HttpPut(url.trim()); CloseableHttpResponse response = null; try { response = httpclient.execute(putReportStartup); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); switch (statusCode) { case HttpURLConnection.HTTP_NO_CONTENT: // bounce proxy instance was already known at the bounce proxy // controller // nothing else to do logger.info("Bounce proxy was already registered with the controller"); break; case HttpURLConnection.HTTP_CREATED: // bounce proxy instance was registered for the very first time // TODO maybe read URL logger.info("Registered bounce proxy with controller"); break; default: logger.error("Failed to send startup notification: {}", response); throw new JoynrHttpException(statusCode, "Failed to send startup notification. Bounce Proxy won't get any channels assigned."); } } finally { if (response != null) { response.close(); } } }
java
private OnChangeSubscriptionQos setMinIntervalMsInternal(final long minIntervalMs) { if (minIntervalMs < MIN_MIN_INTERVAL_MS) { this.minIntervalMs = MIN_MIN_INTERVAL_MS; logger.warn("minIntervalMs < MIN_MIN_INTERVAL_MS. Using MIN_MIN_INTERVAL_MS: {}", MIN_MIN_INTERVAL_MS); } else if (minIntervalMs > MAX_MIN_INTERVAL_MS) { this.minIntervalMs = MAX_MIN_INTERVAL_MS; logger.warn("minIntervalMs > MAX_MIN_INTERVAL_MS. Using MAX_MIN_INTERVAL_MS: {}", MAX_MIN_INTERVAL_MS); } else { this.minIntervalMs = minIntervalMs; } return this; }
java
private boolean hasRoleMaster(String userId, String domain) { DomainRoleEntry domainRole = domainAccessStore.getDomainRole(userId, Role.MASTER); if (domainRole == null || !Arrays.asList(domainRole.getDomains()).contains(domain)) { return false; } return true; }
java
public void put(DelayableImmutableMessage delayableImmutableMessage) { if (messagePersister.persist(messageQueueId, delayableImmutableMessage)) { logger.trace("Message {} was persisted for messageQueueId {}", delayableImmutableMessage.getMessage(), messageQueueId); } else { logger.trace("Message {} was not persisted for messageQueueId {}", delayableImmutableMessage.getMessage(), messageQueueId); } delayableImmutableMessages.put(delayableImmutableMessage); }
java
public DelayableImmutableMessage poll(long timeout, TimeUnit unit) throws InterruptedException { DelayableImmutableMessage message = delayableImmutableMessages.poll(timeout, unit); if (message != null) { messagePersister.remove(messageQueueId, message); } return message; }
java
public void startReporting() { if (executorService == null) { throw new IllegalStateException("MonitoringServiceClient already shutdown"); } if (scheduledFuture != null) { logger.error("only one performance reporting thread can be started"); return; } Runnable performanceReporterCallable = new Runnable() { @Override public void run() { try { // only send a report if the bounce proxy is initialized if (bounceProxyLifecycleMonitor.isInitialized()) { // Don't do any retries here. If we miss on performance // report, we'll just wait for the next loop. sendPerformanceReportAsHttpRequest(); } } catch (Exception e) { logger.error("Uncaught exception in reportPerformance.", e); } } }; scheduledFuture = executorService.scheduleWithFixedDelay(performanceReporterCallable, performanceReportingFrequencyMs, performanceReportingFrequencyMs, TimeUnit.MILLISECONDS); }
java
private void sendPerformanceReportAsHttpRequest() throws IOException { final String url = bounceProxyControllerUrl.buildReportPerformanceUrl(); logger.debug("Using monitoring service URL: {}", url); Map<String, Integer> performanceMap = bounceProxyPerformanceMonitor.getAsKeyValuePairs(); String serializedMessage = objectMapper.writeValueAsString(performanceMap); HttpPost postReportPerformance = new HttpPost(url.trim()); // using http apache constants here because JOYNr constants are in // libjoynr which should not be included here postReportPerformance.addHeader(HttpHeaders.CONTENT_TYPE, "application/json"); postReportPerformance.setEntity(new StringEntity(serializedMessage, "UTF-8")); CloseableHttpResponse response = null; try { response = httpclient.execute(postReportPerformance); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode != HttpURLConnection.HTTP_NO_CONTENT) { logger.error("Failed to send performance report: {}", response); throw new JoynrHttpException(statusCode, "Failed to send performance report."); } } finally { if (response != null) { response.close(); } } }
java
public boolean stopReporting() { // quit the bounce proxy heartbeat but let a possibly running request // finish if (scheduledFuture != null) { return scheduledFuture.cancel(false); } executorService.shutdown(); executorService = null; return false; }
java
public void setArbitrationStrategy(ArbitrationStrategy arbitrationStrategy) { if (arbitrationStrategy.equals(ArbitrationStrategy.Custom)) { throw new IllegalStateException("A Custom strategy can only be set by passing an arbitration strategy function to the DiscoveryQos constructor"); } this.arbitrationStrategy = arbitrationStrategy; }
java
public void onSuccess(T result) { try { statusLock.lock(); value = result; status = new RequestStatus(RequestStatusCode.OK); statusLockChangedCondition.signalAll(); } catch (Exception e) { status = new RequestStatus(RequestStatusCode.ERROR); exception = new JoynrRuntimeException(e); } finally { statusLock.unlock(); } }
java
public void onFailure(JoynrException newException) { exception = newException; status = new RequestStatus(RequestStatusCode.ERROR); try { statusLock.lock(); statusLockChangedCondition.signalAll(); } finally { statusLock.unlock(); } }
java
public Set<Version> getDiscoveredVersionsForDomain(String domain) { Set<Version> result = new HashSet<>(); if (hasExceptionForDomain(domain)) { result.addAll(exceptionsByDomain.get(domain).getDiscoveredVersions()); } return result; }
java
@CheckForNull public ConnectorInvocationHandler create(final String fromParticipantId, final ArbitrationResult arbitrationResult, final MessagingQos qosSettings, String statelessAsyncParticipantId) { // iterate through arbitrationResult.getDiscoveryEntries() // check if there is at least one Globally visible // set isGloballyVisible = true. otherwise = false boolean isGloballyVisible = false; Set<DiscoveryEntryWithMetaInfo> entries = arbitrationResult.getDiscoveryEntries(); for (DiscoveryEntryWithMetaInfo entry : entries) { if (entry.getQos().getScope() == ProviderScope.GLOBAL) { isGloballyVisible = true; } messageRouter.setToKnown(entry.getParticipantId()); } messageRouter.addNextHop(fromParticipantId, libjoynrMessagingAddress, isGloballyVisible); return joynrMessagingConnectorFactory.create(fromParticipantId, arbitrationResult.getDiscoveryEntries(), qosSettings, statelessAsyncParticipantId); }
java
@Override public void registerAttributeListener(String attributeName, AttributeListener attributeListener) { attributeListeners.putIfAbsent(attributeName, new ArrayList<AttributeListener>()); List<AttributeListener> listeners = attributeListeners.get(attributeName); synchronized (listeners) { listeners.add(attributeListener); } }
java
@Override public void unregisterAttributeListener(String attributeName, AttributeListener attributeListener) { List<AttributeListener> listeners = attributeListeners.get(attributeName); if (listeners == null) { LOG.error("trying to unregister an attribute listener for attribute \"" + attributeName + "\" that was never registered"); return; } synchronized (listeners) { boolean success = listeners.remove(attributeListener); if (!success) { LOG.error("trying to unregister an attribute listener for attribute \"" + attributeName + "\" that was never registered"); return; } } }
java
@Override public void registerBroadcastListener(String broadcastName, BroadcastListener broadcastListener) { broadcastListeners.putIfAbsent(broadcastName, new ArrayList<BroadcastListener>()); List<BroadcastListener> listeners = broadcastListeners.get(broadcastName); synchronized (listeners) { listeners.add(broadcastListener); } }
java
@Override public void unregisterBroadcastListener(String broadcastName, BroadcastListener broadcastListener) { List<BroadcastListener> listeners = broadcastListeners.get(broadcastName); if (listeners == null) { LOG.error("trying to unregister a listener for broadcast \"" + broadcastName + "\" that was never registered"); return; } synchronized (listeners) { boolean success = listeners.remove(broadcastListener); if (!success) { LOG.error("trying to unregister a listener for broadcast \"" + broadcastName + "\" that was never registered"); return; } } }
java
@Override public void addBroadcastFilter(BroadcastFilterImpl filter) { if (broadcastFilters.containsKey(filter.getName())) { broadcastFilters.get(filter.getName()).add(filter); } else { ArrayList<BroadcastFilter> list = new ArrayList<BroadcastFilter>(); list.add(filter); broadcastFilters.put(filter.getName(), list); } }
java
@Override public void addBroadcastFilter(BroadcastFilterImpl... filters) { List<BroadcastFilterImpl> filtersList = Arrays.asList(filters); for (BroadcastFilterImpl filter : filtersList) { addBroadcastFilter(filter); } }
java
@CheckForNull public Object[] getValues(long timeout) throws InterruptedException { if (!isSettled()) { synchronized (this) { wait(timeout); } } if (values == null) { return null; } return Arrays.copyOf(values, values.length); }
java
private void getCapabilityEntry(ImmutableMessage message, CapabilityCallback callback) { long cacheMaxAge = Long.MAX_VALUE; DiscoveryQos discoveryQos = new DiscoveryQos(DiscoveryQos.NO_MAX_AGE, ArbitrationStrategy.NotSet, cacheMaxAge, DiscoveryScope.LOCAL_THEN_GLOBAL); String participantId = message.getRecipient(); localCapabilitiesDirectory.lookup(participantId, discoveryQos, callback); }
java
public static void copyDirectory(File sourceLocation, File targetLocation) throws IOException { if (sourceLocation.isDirectory()) { if (!targetLocation.exists()) { if (targetLocation.mkdir() == false) { logger.debug("Creating target directory " + targetLocation + " failed."); } } String[] children = sourceLocation.list(); if (children == null) { return; } for (int i = 0; i < children.length; i++) { copyDirectory(new File(sourceLocation, children[i]), new File(targetLocation, children[i])); } } else { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream(sourceLocation); out = new FileOutputStream(targetLocation); copyStream(in, out); } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } }
java
public boolean check(Version caller, Version provider) { if (caller == null || provider == null) { throw new IllegalArgumentException(format("Both caller (%s) and provider (%s) must be non-null.", caller, provider)); } if (caller.getMajorVersion() == null || caller.getMinorVersion() == null || provider.getMajorVersion() == null || provider.getMinorVersion() == null) { throw new IllegalArgumentException(format("Neither major nor minor version values can be null in either caller %s or provider %s.", caller, provider)); } int callerMajor = caller.getMajorVersion(); int callerMinor = caller.getMinorVersion(); int providerMajor = provider.getMajorVersion(); int providerMinor = provider.getMinorVersion(); return callerMajor == providerMajor && callerMinor <= providerMinor; }
java
public static GlobalDiscoveryEntry newGlobalDiscoveryEntry(Version providerVesion, String domain, String interfaceName, String participantId, ProviderQos qos, Long lastSeenDateMs, Long expiryDateMs, String publicKeyId, Address address) { // CHECKSTYLE ON return new GlobalDiscoveryEntry(providerVesion, domain, interfaceName, participantId, qos, lastSeenDateMs, expiryDateMs, publicKeyId, serializeAddress(address)); }
java
@Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (throwable != null) { throw throwable; } try { return invokeInternal(proxy, method, args); } catch (Exception e) { if (this.throwable != null) { logger.debug("exception caught: {} overridden by: {}", e.getMessage(), throwable.getMessage()); throw throwable; } else { throw e; } } }
java
public B error(String errorCode) { ErrorEventDefinition errorEventDefinition = createErrorEventDefinition(errorCode); element.getEventDefinitions().add(errorEventDefinition); return myself; }
java
public B addExtensionElement(BpmnModelElementInstance extensionElement) { ExtensionElements extensionElements = getCreateSingleChild(ExtensionElements.class); extensionElements.addChildElement(extensionElement); return myself; }
java
public B camundaFailedJobRetryTimeCycle(String retryTimeCycle) { CamundaFailedJobRetryTimeCycle failedJobRetryTimeCycle = createInstance(CamundaFailedJobRetryTimeCycle.class); failedJobRetryTimeCycle.setTextContent(retryTimeCycle); addExtensionElement(failedJobRetryTimeCycle); return myself; }
java
public B message(String messageName) { Message message = findMessageForName(messageName); return message(message); }
java
public B camundaOut(String source, String target) { CamundaOut param = modelInstance.newInstance(CamundaOut.class); param.setCamundaSource(source); param.setCamundaTarget(target); addExtensionElement(param); return myself; }
java
public B message(String messageName) { MessageEventDefinition messageEventDefinition = createMessageEventDefinition(messageName); element.getEventDefinitions().add(messageEventDefinition); return myself; }
java
public B signal(String signalName) { SignalEventDefinition signalEventDefinition = createSignalEventDefinition(signalName); element.getEventDefinitions().add(signalEventDefinition); return myself; }
java
public B timerWithDate(String timerDate) { TimeDate timeDate = createInstance(TimeDate.class); timeDate.setTextContent(timerDate); TimerEventDefinition timerEventDefinition = createInstance(TimerEventDefinition.class); timerEventDefinition.setTimeDate(timeDate); element.getEventDefinitions().add(timerEventDefinition); return myself; }
java
public B timerWithDuration(String timerDuration) { TimeDuration timeDuration = createInstance(TimeDuration.class); timeDuration.setTextContent(timerDuration); TimerEventDefinition timerEventDefinition = createInstance(TimerEventDefinition.class); timerEventDefinition.setTimeDuration(timeDuration); element.getEventDefinitions().add(timerEventDefinition); return myself; }
java
public B timerWithCycle(String timerCycle) { TimeCycle timeCycle = createInstance(TimeCycle.class); timeCycle.setTextContent(timerCycle); TimerEventDefinition timerEventDefinition = createInstance(TimerEventDefinition.class); timerEventDefinition.setTimeCycle(timeCycle); element.getEventDefinitions().add(timerEventDefinition); return myself; }
java
public SubProcessBuilder subProcessDone() { BpmnModelElementInstance lastSubProcess = element.getScope(); if (lastSubProcess != null && lastSubProcess instanceof SubProcess) { return ((SubProcess) lastSubProcess).builder(); } else { throw new BpmnModelException("Unable to find a parent subProcess."); } }
java
public B error() { ErrorEventDefinition errorEventDefinition = createInstance(ErrorEventDefinition.class); element.getEventDefinitions().add(errorEventDefinition); return myself; }
java
public ErrorEventDefinitionBuilder errorEventDefinition(String id) { ErrorEventDefinition errorEventDefinition = createEmptyErrorEventDefinition(); if (id != null) { errorEventDefinition.setId(id); } element.getEventDefinitions().add(errorEventDefinition); return new ErrorEventDefinitionBuilder(modelInstance, errorEventDefinition); }
java
public ErrorEventDefinitionBuilder errorEventDefinition() { ErrorEventDefinition errorEventDefinition = createEmptyErrorEventDefinition(); element.getEventDefinitions().add(errorEventDefinition); return new ErrorEventDefinitionBuilder(modelInstance, errorEventDefinition); }
java
public B escalation() { EscalationEventDefinition escalationEventDefinition = createInstance(EscalationEventDefinition.class); element.getEventDefinitions().add(escalationEventDefinition); return myself; }
java
public B escalation(String escalationCode) { EscalationEventDefinition escalationEventDefinition = createEscalationEventDefinition(escalationCode); element.getEventDefinitions().add(escalationEventDefinition); return myself; }
java
public CamundaUserTaskFormFieldBuilder camundaFormField() { CamundaFormData camundaFormData = getCreateSingleExtensionElement(CamundaFormData.class); CamundaFormField camundaFormField = createChild(camundaFormData, CamundaFormField.class); return new CamundaUserTaskFormFieldBuilder(modelInstance, element, camundaFormField); }
java
public B activationCondition(String conditionExpression) { ActivationCondition activationCondition = createInstance(ActivationCondition.class); activationCondition.setTextContent(conditionExpression); element.setActivationCondition(activationCondition); return myself; }
java
public B cardinality(String expression) { LoopCardinality cardinality = getCreateSingleChild(LoopCardinality.class); cardinality.setTextContent(expression); return myself; }
java
public B completionCondition(String expression) { CompletionCondition condition = getCreateSingleChild(CompletionCondition.class); condition.setTextContent(expression); return myself; }
java
@SuppressWarnings({ "rawtypes", "unchecked" }) public <T extends AbstractActivityBuilder> T multiInstanceDone() { return (T) ((Activity) element.getParentElement()).builder(); }
java
public B condition(String conditionText) { Condition condition = createInstance(Condition.class); condition.setTextContent(conditionText); element.setCondition(condition); return myself; }
java
@SuppressWarnings({ "rawtypes", "unchecked" }) public <T extends AbstractFlowNodeBuilder> T conditionalEventDefinitionDone() { return (T) ((Event) element.getParentElement()).builder(); }
java
@SuppressWarnings({ "rawtypes", "unchecked" }) public <T extends AbstractFlowNodeBuilder> T errorEventDefinitionDone() { return (T) ((Event) element.getParentElement()).builder(); }
java
public B camundaInputParameter(String name, String value) { CamundaInputOutput camundaInputOutput = getCreateSingleExtensionElement(CamundaInputOutput.class); CamundaInputParameter camundaInputParameter = createChild(camundaInputOutput, CamundaInputParameter.class); camundaInputParameter.setCamundaName(name); camundaInputParameter.setTextContent(value); return myself; }
java
public B camundaOutputParameter(String name, String value) { CamundaInputOutput camundaInputOutput = getCreateSingleExtensionElement(CamundaInputOutput.class); CamundaOutputParameter camundaOutputParameter = createChild(camundaInputOutput, CamundaOutputParameter.class); camundaOutputParameter.setCamundaName(name); camundaOutputParameter.setTextContent(value); return myself; }
java
public MessageEventDefinitionBuilder messageEventDefinition(String id) { MessageEventDefinition messageEventDefinition = createEmptyMessageEventDefinition(); if (id != null) { messageEventDefinition.setId(id); } element.getEventDefinitions().add(messageEventDefinition); return new MessageEventDefinitionBuilder(modelInstance, messageEventDefinition); }
java
public SignalEventDefinitionBuilder signalEventDefinition(String signalName) { SignalEventDefinition signalEventDefinition = createSignalEventDefinition(signalName); element.getEventDefinitions().add(signalEventDefinition); return new SignalEventDefinitionBuilder(modelInstance, signalEventDefinition); }
java
public B from(FlowNode source) { element.setSource(source); source.getOutgoing().add(element); return myself; }
java
public B to(FlowNode target) { element.setTarget(target); target.getIncoming().add(element); return myself; }
java
@SuppressWarnings({ "rawtypes", "unchecked" }) public <T extends AbstractFlowNodeBuilder> T messageEventDefinitionDone() { return (T) ((Event) element.getParentElement()).builder(); }
java
public B compensation() { CompensateEventDefinition compensateEventDefinition = createCompensateEventDefinition(); element.getEventDefinitions().add(compensateEventDefinition); return myself; }
java
public static void setSessionTicketKeys(long ctx, SessionTicketKey[] keys) { if (keys == null || keys.length == 0) { throw new IllegalArgumentException("Length of the keys should be longer than 0."); } byte[] binaryKeys = new byte[keys.length * SessionTicketKey.TICKET_KEY_SIZE]; for (int i = 0; i < keys.length; i++) { SessionTicketKey key = keys[i]; int dstCurPos = SessionTicketKey.TICKET_KEY_SIZE * i; System.arraycopy(key.name, 0, binaryKeys, dstCurPos, SessionTicketKey.NAME_SIZE); dstCurPos += SessionTicketKey.NAME_SIZE; System.arraycopy(key.hmacKey, 0, binaryKeys, dstCurPos, SessionTicketKey.HMAC_KEY_SIZE); dstCurPos += SessionTicketKey.HMAC_KEY_SIZE; System.arraycopy(key.aesKey, 0, binaryKeys, dstCurPos, SessionTicketKey.AES_KEY_SIZE); } setSessionTicketKeys0(ctx, binaryKeys); }
java
private static String calculatePackagePrefix() { String maybeShaded = Library.class.getName(); // Use ! instead of . to avoid shading utilities from modifying the string String expected = "io!netty!internal!tcnative!Library".replace('!', '.'); if (!maybeShaded.endsWith(expected)) { throw new UnsatisfiedLinkError(String.format( "Could not find prefix added to %s to get %s. When shading, only adding a " + "package prefix is supported", expected, maybeShaded)); } return maybeShaded.substring(0, maybeShaded.length() - expected.length()); }
java
public static boolean initialize(String libraryName, String engine) throws Exception { if (_instance == null) { _instance = libraryName == null ? new Library() : new Library(libraryName); if (aprMajorVersion() < 1) { throw new UnsatisfiedLinkError("Unsupported APR Version (" + aprVersionString() + ")"); } if (!aprHasThreads()) { throw new UnsatisfiedLinkError("Missing APR_HAS_THREADS"); } } return initialize0() && SSL.initialize(engine) == 0; }
java
public static <S, R> List<R> convert(List<S> source, Function<S, R> converter) { return (source == null) ? null : source .stream() .filter(Objects::nonNull) .map(converter) .filter(Objects::nonNull) .collect(Collectors.toList()); }
java
public static ProcessHandler getDefaultHandler(Logger logger) { return LegacyProcessHandler.builder() .addStdErrLineListener(logger::lifecycle) .addStdOutLineListener(logger::lifecycle) .setExitListener(new NonZeroExceptionExitListener()) .build(); }
java