jndi can be null, in which case send to the same site
198067
public String invoke(String message, int timeoutSeconds)
    throws ProcessException {
        try {
            return JMSServices.getInstance().invoke(destination,
                    JMSDestinationNames.INTRA_MDW_EVENT_HANDLER_QUEUE, message, timeoutSeconds);
        } catch (Exception e) {
            throw new ProcessException(-1, e.getMessage(), e);
        }
    }
178285
private FullResponseHolder submitRequest(
      String taskId,
      @Nullable String mediaType, // nullable if content is empty
      HttpMethod method,
      String encodedPathSuffix,
      @Nullable String encodedQueryString,
      byte[] content,
      boolean retry
  ) throws IOException, ChannelException, NoTaskLocationException
  {
    final RetryPolicy retryPolicy = retryPolicyFactory.makeRetryPolicy();

    while (true) {
      String path = StringUtils.format("%s/%s/%s", BASE_PATH, StringUtils.urlEncode(taskId), encodedPathSuffix);

      Optional<TaskStatus> status = taskInfoProvider.getTaskStatus(taskId);
      if (!status.isPresent() || !status.get().isRunnable()) {
        throw new TaskNotRunnableException(
            StringUtils.format(
                "Aborting request because task [%s] is not runnable",
                taskId
            )
        );
      }

      final TaskLocation location = taskInfoProvider.getTaskLocation(taskId);
      if (location.equals(TaskLocation.unknown())) {
        throw new NoTaskLocationException(StringUtils.format("No TaskLocation available for task [%s]", taskId));
      }

      final Request request = createRequest(
          taskId,
          location,
          path,
          encodedQueryString,
          method,
          mediaType,
          content
      );

      FullResponseHolder response = null;
      try {
        // Netty throws some annoying exceptions if a connection can't be opened, which happens relatively frequently
        // for tasks that happen to still be starting up, so test the connection first to keep the logs clean.
        checkConnection(request.getUrl().getHost(), request.getUrl().getPort());

        response = submitRequest(request);

        int responseCode = response.getStatus().getCode();
        if (responseCode / 100 == 2) {
          return response;
        } else if (responseCode == 400) { // don't bother retrying if it's a bad request
          throw new IAE("Received 400 Bad Request with body: %s", response.getContent());
        } else {
          throw new IOE("Received status [%d] and content [%s]", responseCode, response.getContent());
        }
      }
      catch (IOException | ChannelException e) {

        // Since workers are free to move tasks around to different ports, there is a chance that a task may have been
        // moved but our view of its location has not been updated yet from ZK. To detect this case, we send a header
        // identifying our expected recipient in the request; if this doesn't correspond to the worker we messaged, the
        // worker will return an HTTP 404 with its ID in the response header. If we get a mismatching task ID, then
        // we will wait for a short period then retry the request indefinitely, expecting the task's location to
        // eventually be updated.

        final Duration delay;
        if (response != null && response.getStatus().equals(HttpResponseStatus.NOT_FOUND)) {
          String headerId = StringUtils.urlDecode(
              response.getResponse().headers().get(ChatHandlerResource.TASK_ID_HEADER)
          );
          if (headerId != null && !headerId.equals(taskId)) {
            log.warn(
                "Expected worker to have taskId [%s] but has taskId [%s], will retry in [%d]s",
                taskId, headerId, TASK_MISMATCH_RETRY_DELAY_SECONDS
            );
            delay = Duration.standardSeconds(TASK_MISMATCH_RETRY_DELAY_SECONDS);
          } else {
            delay = retryPolicy.getAndIncrementRetryDelay();
          }
        } else {
          delay = retryPolicy.getAndIncrementRetryDelay();
        }
        final String urlForLog = request.getUrl().toString();
        if (!retry) {
          // if retry=false, we probably aren't too concerned if the operation doesn't succeed (i.e. the request was
          // for informational purposes only) so don't log a scary stack trace
          log.info("submitRequest failed for [%s], with message [%s]", urlForLog, e.getMessage());
          throw e;
        } else if (delay == null) {
          log.warn(e, "Retries exhausted for [%s], last exception:", urlForLog);
          throw e;
        } else {
          try {
            final long sleepTime = delay.getMillis();
            log.debug(
                "Bad response HTTP [%s] from [%s]; will try again in [%s] (body/exception: [%s])",
                (response != null ? response.getStatus().getCode() : "no response"),
                urlForLog,
                new Duration(sleepTime).toString(),
                (response != null ? response.getContent() : e.getMessage())
            );
            Thread.sleep(sleepTime);
          }
          catch (InterruptedException e2) {
            Thread.currentThread().interrupt();
            e.addSuppressed(e2);
            throw new RuntimeException(e);
          }
        }
      }
      catch (NoTaskLocationException e) {
        log.info("No TaskLocation available for task [%s], this task may not have been assigned to a worker yet or "
                 + "may have already completed", taskId);
        throw e;
      }
      catch (Exception e) {
        log.warn(e, "Exception while sending request");
        throw e;
      }
    }
  }
1311804
protected void sendMessage(String xml) {
    byte[] bytes = null;
    try {
      bytes = xml.getBytes("UTF-8");
      writeBytes(bytes);
    } catch (SocketException se) {
      // when we get a socket exception, let's try to re-establish
      stop();
      start();
      try {
        writeBytes(bytes);
      } catch (IOException e) {
        throw new WebDriverException(e);
      }
    } catch (IOException e) {
      throw new WebDriverException(e);
    }
  }
999019
public void onModuleLoad() {
        RestRequestBuilder.setDefaultApplicationPath( "rest" );

        final Button sendGetButton = new Button( "GET" );
        final Button sendPostButton = new Button( "POST" );
        final Button sendPostPathButton = new Button( "POST + Path" );
        final TextBox nameField = new TextBox();
        nameField.setText( "GWT User" );
        final Label errorLabel = new Label();

        // We can add style names to widgets
        sendGetButton.addStyleName( "sendButton" );
        sendPostButton.addStyleName( "sendButton" );
        sendPostPathButton.addStyleName( "sendButton" );

        // Add the nameField and sendButton to the RootPanel
        // Use RootPanel.get() to get the entire body element
        RootPanel.get( "nameFieldContainer" ).add( nameField );
        RootPanel.get( "sendButtonContainer" ).add( sendGetButton );
        RootPanel.get( "sendButtonContainer" ).add( sendPostButton );
        RootPanel.get( "sendButtonContainer" ).add( sendPostPathButton );
        RootPanel.get( "errorLabelContainer" ).add( errorLabel );

        // Focus the cursor on the name field when the app loads
        nameField.setFocus( true );
        nameField.selectAll();

        // Create the popup dialog box
        final DialogBox dialogBox = new DialogBox();
        dialogBox.setText( "Remote Procedure Call" );
        dialogBox.setAnimationEnabled( true );
        final Button closeButton = new Button( "Close" );
        // We can set the id of a widget by accessing its Element
        closeButton.getElement().setId( "closeButton" );
        final Label textToServerLabel = new Label();
        final HTML serverResponseLabel = new HTML();
        VerticalPanel dialogVPanel = new VerticalPanel();
        dialogVPanel.addStyleName( "dialogVPanel" );
        dialogVPanel.add( new HTML( "<b>Sending name to the server:</b>" ) );
        dialogVPanel.add( textToServerLabel );
        dialogVPanel.add( new HTML( "<br><b>Server replies:</b>" ) );
        dialogVPanel.add( serverResponseLabel );
        dialogVPanel.setHorizontalAlignment( VerticalPanel.ALIGN_RIGHT );
        dialogVPanel.add( closeButton );
        dialogBox.setWidget( dialogVPanel );

        // Add a handler to close the DialogBox
        closeButton.addClickHandler( new ClickHandler() {
            public void onClick( ClickEvent event ) {
                dialogBox.hide();
                sendGetButton.setEnabled( true );
                sendPostButton.setEnabled( true );
                sendPostPathButton.setEnabled( true );
            }
        } );

        // Create a handler for the sendButton and nameField
        class MyHandler implements ClickHandler, KeyUpHandler {

            private final int req;

            MyHandler( int req ) {
                this.req = req;
            }

            /**
             * Fired when the user clicks on the sendButton.
             */
            public void onClick( ClickEvent event ) {
                sendNameToServer();
            }

            /**
             * Fired when the user types in the nameField.
             */
            public void onKeyUp( KeyUpEvent event ) {
                if ( event.getNativeKeyCode() == KeyCodes.KEY_ENTER ) {
                    sendNameToServer();
                }
            }

            /**
             * Send the name from the nameField to the server and wait for a response.
             */
            private void sendNameToServer() {
                // First, we validate the input.
                errorLabel.setText( "" );
                String textToServer = nameField.getText();
                if ( !FieldVerifier.isValidName( textToServer ) ) {
                    errorLabel.setText( "Please enter at least four characters" );
                    return;
                }

                // Then, we send the input to the server.
                sendGetButton.setEnabled( false );
                sendPostButton.setEnabled( false );
                sendPostPathButton.setEnabled( false );
                textToServerLabel.setText( textToServer );
                serverResponseLabel.setText( "" );

                RestCallback<GreetingResponse> callback = new RestCallback<GreetingResponse>() {
                    @Override
                    public void onSuccess( GreetingResponse result ) {
                        dialogBox.setText( "Remote Procedure Call" );
                        serverResponseLabel.removeStyleName( "serverResponseLabelError" );
                        serverResponseLabel.setHTML( new SafeHtmlBuilder().appendEscaped( result.getGreeting() )
                                .appendHtmlConstant( "<br><br>I am running " ).appendEscaped( result.getServerInfo() )
                                .appendHtmlConstant( ".<br><br>It looks like you are using:<br>" ).appendEscaped( result
                                        .getUserAgent() ).toSafeHtml() );
                        dialogBox.center();
                        closeButton.setFocus( true );
                    }

                    @Override
                    public void onError( Response response ) {
                        onRequestFailure();
                    }

                    @Override
                    public void onFailure( Throwable throwable ) {
                        onRequestFailure();
                    }
                };

                if ( req == 0 ) {
                    GreetingResourceBuilder.hello( textToServer ).callback( callback ).send();
                } else {
                    if ( req == 1 ) {
                        GreetingResourceBuilder.greet( new GreetingRequest( textToServer ) )
                                .callback( callback )
                                .send();
                    } else if ( req == 2 ) {
                        GreetingResourceBuilder.greet( "someId", null, new GreetingRequest( textToServer ) )
                                .addQueryParam( "other" )
                                .callback( callback )
                                .send();
                    } else {
                        GreetingResourceBuilder.greetWithCustomHTTPCode( "someId", null, new GreetingRequest( textToServer ) )
                                .addQueryParam( "other" )
                                .callback( callback )
                                .send();
                    }
                }
            }

            private void onRequestFailure() {
                // Show the RPC error message to the user
                dialogBox.setText( "Remote Procedure Call - Failure" );
                serverResponseLabel.addStyleName( "serverResponseLabelError" );
                serverResponseLabel.setHTML( SERVER_ERROR );
                dialogBox.center();
                closeButton.setFocus( true );
            }
        }

        // Add a handler to send the name to the server
        MyHandler handler = new MyHandler( 0 );
        sendGetButton.addClickHandler( handler );
        nameField.addKeyUpHandler( handler );

        sendPostButton.addClickHandler( new MyHandler( 1 ) );
        sendPostPathButton.addClickHandler( new MyHandler( 2 ) );
    }
1084492
private static String getJmxResult(MBeanServerConnection connetion, String url) throws Exception {
        ObjectName name = new ObjectName(DruidStatService.MBEAN_NAME);

        return (String) conn.invoke(name, "service", new String[]{url},
                new String[]{String.class.getName()});
    }
290534
@SuppressWarnings("unchecked")
    @Override
    public void onEnd(PortletInvocationEvent event) {
        final PortletRequest portletRequest = event.getPortletRequest();
        final PortletSession portletSession = portletRequest.getPortletSession(false);
        if (portletSession == null) {
            return;
        }

        final HttpServletRequest portalRequest =
                this.portalRequestUtils.getPortletHttpRequest(portletRequest);
        final HttpSession portalSession = portalRequest.getSession();

        if (portalSession != null) {
            NonSerializableMapHolder<String, PortletSession> portletSessions;
            synchronized (WebUtils.getSessionMutex(portalSession)) {
                portletSessions =
                        (NonSerializableMapHolder<String, PortletSession>)
                                portalSession.getAttribute(PORTLET_SESSIONS_MAP);
                if (portletSessions == null || !portletSessions.isValid()) {
                    portletSessions =
                            new NonSerializableMapHolder(
                                    new ConcurrentHashMap<String, PortletSession>());
                    portalSession.setAttribute(PORTLET_SESSIONS_MAP, portletSessions);
                }
            }

            final String contextPath = portletRequest.getContextPath();
            portletSessions.put(contextPath, portletSession);
        }
    }
929920
SocketAddress getRemoteSocketAddress() {
        // a lot could go wrong here, so rather than put in a bunch of code
        // to check for nulls all down the chain let's do it the simple
        // yet bulletproof way
        try {
            return ((SocketChannel) sendThread.sockKey.channel()).socket()
                    .getRemoteSocketAddress();
        } catch (NullPointerException e) {
            return null;
        }
    }
521490
public void sendData(HttpServletRequest req, HttpServletResponse res) 
        throws ServletException, IOException
    {
//        res.setContentType("application/x-java-jnlp-file");
//x        PrintWriter out = new PrintWriter(res.getOutputStream());
//        PrintWriter out = res.getWriter();

//        this.printXML(req, out);
//        out.flush();
        
        ClassService classService = ClassServiceUtility.getClassService();
        if (classService == null)
            return;    // Never
        ClassFinder classFinder = classService.getClassFinder(null);
        if (classFinder == null)
            return;
        HttpServiceTracker tracker = (HttpServiceTracker)classFinder.getClassBundleService(null, WEB_START_ACTIVATOR_CLASS, null, null, -1);
        if (tracker == null)
            return;
        Servlet servlet = tracker.getServlet();
        if (servlet == null)
            return;
        servlet.service((HttpServletRequest)req, (HttpServletResponse)res);
    }
434816
static function sendXmlHttpResponseHeaders($contenttype = "application/json", $charset = 'utf-8')
	{
		if ( is_null($charset) )
			$charset = mb_internal_encoding();
			
		// charset
		header("Content-Type: $contenttype; charset=$charset");
		
		// no cache
		header("Expires: Sat, 1 Jan 2005 00:00:00 GMT");
		header("Last-Modified: ".gmdate( "D, d M Y H:i:s")." GMT");
		header("Cache-Control: no-cache, must-revalidate");
		header("Pragma: no-cache");	
	}
225104
private static <T> T nullForNotFound(IOException exception) {
    ComputeException serviceException = translate(exception);
    if (serviceException.getCode() == HTTP_NOT_FOUND) {
      return null;
    }
    throw serviceException;
  }
18421
public void onReceiveSitemapPreloadData(CmsSitemapEntryBean sitemapPreloadData) {

        fillWithPreloadInfo(Collections.singletonList(sitemapPreloadData));
        String siteRoot = sitemapPreloadData.getSiteRoot();
        if (siteRoot != null) {
            selectSite(siteRoot);
        }
    }
682756
@Override
	public CEMILData request(final KNXAddress dst, final Configuration c)
	{
		final Cache cache = c.getCache();
		if (cache == null || !(dst instanceof GroupAddress))
			return null;
		final LDataObject o = (LDataObject) cache.get(dst);
		if (o == null)
			return null;
		// check if there is an expiration timeout for a state based value
		final Datapoint dp;
		final DatapointModel<?> m = c.getDatapointModel();
		if (m != null && (dp = m.get((GroupAddress) dst)) != null && dp.isStateBased()) {
			final int t = ((StateDP) dp).getExpirationTimeout() * 1000;
			if (t != 0 && System.currentTimeMillis() > o.getTimestamp() + t)
				return null;
		}
		return o.getFrame();
	}
825863
private <T> void bindIfNotNull(final Class<T> interfaceType, @Nullable final Class<? extends T> implementationType, final Scope scope) {
        if (implementationType != null) {
            bind(interfaceType).to(implementationType).in(scope);
        }
    }
1163347
@OverrideOnDemand
  protected boolean linkNeedsContextPath (@Nullable final String sHref)
  {
    if (sHref == null)
      return false;

    // If prefix is defined and already present no need to change something
    // Or if the server prefix path is just "/" and the links starts with "/"
    // it's also fine
    if (sHref.startsWith (m_sServerPrefixPath))
      return false;

    // javascript: and mailto: are handled by URLProtocolRegistry
    if (URLProtocolRegistry.getInstance ().hasKnownProtocol (sHref) || sHref.startsWith ("#"))
      return false;

    // Prefix is needed
    return true;
  }
351672
public static final <T extends JavaScriptObject> T checkNull(T js) {
    if (!GWT.isProdMode() && js == null) {
      throw new NullPointerException();
    }
    return js;
  }
1070631
@Override
  public void sendRegistrationTerminationRequest(JRegistrationTerminationRequest request)
      throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
    send(Event.Type.SEND_MESSAGE, request, null);
  }
804401
private void initSite() {

        Object o = null;
        if (CmsStringUtil.isEmpty(getParamAction()) || CmsDialog.DIALOG_INITIAL.equals(getParamAction())) {
            // this is the initial dialog call
            if (CmsStringUtil.isNotEmpty(m_paramSites)) {
                // edit an existing site, get it from manager
                o = OpenCms.getSiteManager().getSiteForSiteRoot(m_paramSites);
            }
        } else {
            // this is not the initial call, get site from session
            o = getDialogObject();
        }
        if (o instanceof CmsSite) {
            // reuse site stored in session
            m_site = new CmsSiteBean((CmsSite)o);
        } else if (o instanceof CmsSiteBean) {
            // create a new site
            m_site = (CmsSiteBean)o;
        } else if (DIALOG_NEW.equals(getParamEditaction())) {
            m_site = new CmsSiteBean();
        } else {
            try {
                getToolManager().jspForwardTool(this, "/sites", new HashMap<String, String[]>());
            } catch (Exception e) {
                // noop
            }
        }

        if (!m_site.hasSecureServer()) {
            m_site.setSecureUrl("");
        }
        try {
            CmsObject clone = OpenCms.initCmsObject(getCms());
            clone.getRequestContext().setSiteRoot("");
            String iconPath = m_site.getSiteRoot() + "/" + CmsSiteFaviconDialog.ICON_NAME;
            if (clone.existsResource(iconPath)) {
                m_site.setFavicon(iconPath);
            }
        } catch (Throwable t) {
            // noop
        }

        if (m_site.getSiteRoot() != null) {
            setSitename(CmsResource.getName(m_site.getSiteRoot()));
        }

        CmsModule module = OpenCms.getModuleManager().getModule(MODULE_NAME);
        m_createou = Boolean.valueOf(module.getParameter(PARAM_CREATE_OU, Boolean.FALSE.toString())).booleanValue();
        m_ouDescription = module.getParameter(PARAM_OU_DESCRIPTION, "OU for: %(site)");
        setDialogObject(m_site);
    }