Java 类com.intellij.util.net.NetUtils 实例源码

项目:intellij-ce-playground    文件:ProcessProxyImpl.java   
@SuppressWarnings({"SocketOpenedButNotSafelyClosed", "IOResourceOpenedButNotSafelyClosed"})
private synchronized void writeLine(@NonNls final String s) {
  if (myWriter == null) {
    try {
      if (mySocket == null) {
        mySocket = new Socket(NetUtils.getLoopbackAddress(), myPortNumber);
      }
      myWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(mySocket.getOutputStream())));
    }
    catch (IOException e) {
      return;
    }
  }
  myWriter.println(s);
  myWriter.flush();
}
项目:intellij-ce-playground    文件:CompilerManagerImpl.java   
@Nullable
private ExternalJavacManager getJavacManager() throws IOException {
  ExternalJavacManager manager = myExternalJavacManager;
  if (manager == null) {
    synchronized (this) {
      manager = myExternalJavacManager;
      if (manager == null) {
        final File compilerWorkingDir = getJavacCompilerWorkingDir();
        if (compilerWorkingDir == null) {
          return null; // should not happen for real projects
        }
        final int listenPort = NetUtils.findAvailableSocketPort();
        manager = new ExternalJavacManager(compilerWorkingDir);
        manager.start(listenPort);
        myExternalJavacManager = manager;
      }
    }
  }
  return manager;
}
项目:intellij-ce-playground    文件:BuildManager.java   
private int startListening() throws Exception {
  final ServerBootstrap bootstrap = NettyUtil.nioServerBootstrap(new NioEventLoopGroup(1, PooledThreadExecutor.INSTANCE));
  bootstrap.childHandler(new ChannelInitializer() {
    @Override
    protected void initChannel(Channel channel) throws Exception {
      channel.pipeline().addLast(myChannelRegistrar,
                                 new ProtobufVarint32FrameDecoder(),
                                 new ProtobufDecoder(CmdlineRemoteProto.Message.getDefaultInstance()),
                                 new ProtobufVarint32LengthFieldPrepender(),
                                 new ProtobufEncoder(),
                                 myMessageDispatcher);
    }
  });
  Channel serverChannel = bootstrap.bind(NetUtils.getLoopbackAddress(), 0).syncUninterruptibly().channel();
  myChannelRegistrar.add(serverChannel);
  return ((InetSocketAddress)serverChannel.localAddress()).getPort();
}
项目:intellij-ce-playground    文件:ExternalSystemRunConfiguration.java   
public MyRunnableState(@NotNull ExternalSystemTaskExecutionSettings settings,
                       @NotNull Project project,
                       boolean debug,
                       @NotNull ExternalSystemRunConfiguration configuration,
                       @NotNull ExecutionEnvironment env) {
  mySettings = settings;
  myProject = project;
  myConfiguration = configuration;
  myEnv = env;
  int port;
  if (debug) {
    try {
      port = NetUtils.findAvailableSocketPort();
    }
    catch (IOException e) {
      LOG.warn("Unexpected I/O exception occurred on attempt to find a free port to use for external system task debugging", e);
      port = 0;
    }
  }
  else {
    port = 0;
  }
  myDebugPort = port;
}
项目:intellij-ce-playground    文件:UpdateSettingsConfigurable.java   
@Override
public void apply() throws ConfigurationException {
  if (myPanel.myUseSecureConnection.isSelected() && !NetUtils.isSniEnabled()) {
    boolean tooOld = !SystemInfo.isJavaVersionAtLeast("1.7");
    String message = IdeBundle.message(tooOld ? "update.sni.not.available.error" : "update.sni.disabled.error");
    throw new ConfigurationException(message);
  }

  boolean wasEnabled = mySettings.isCheckNeeded();
  mySettings.setCheckNeeded(myPanel.myCheckForUpdates.isSelected());
  if (wasEnabled != mySettings.isCheckNeeded()) {
    UpdateCheckerComponent checker = ApplicationManager.getApplication().getComponent(UpdateCheckerComponent.class);
    if (checker != null) {
      if (wasEnabled) {
        checker.cancelChecks();
      }
      else {
        checker.queueNextCheck();
      }
    }
  }

  mySettings.setUpdateChannelType(myPanel.getSelectedChannelType().getCode());
  mySettings.setSecureConnection(myPanel.myUseSecureConnection.isSelected());
}
项目:intellij-ce-playground    文件:ITNProxy.java   
private static HttpURLConnection post(URL url, byte[] bytes) throws IOException {
  HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();

  connection.setSSLSocketFactory(ourSslContext.getSocketFactory());
  if (!NetUtils.isSniEnabled()) {
    connection.setHostnameVerifier(new EaHostnameVerifier());
  }

  connection.setRequestMethod("POST");
  connection.setDoInput(true);
  connection.setDoOutput(true);
  connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=" + ENCODING);
  connection.setRequestProperty("Content-Length", Integer.toString(bytes.length));

  OutputStream out = connection.getOutputStream();
  try {
    out.write(bytes);
  }
  finally {
    out.close();
  }

  return connection;
}
项目:intellij-ce-playground    文件:SocketConnectionImpl.java   
@NotNull
private Socket createSocket() throws IOException {
  InetAddress host = myHost;
  if (host == null) {
    try {
      host = InetAddress.getLocalHost();
    }
    catch (UnknownHostException ignored) {
      host = NetUtils.getLoopbackAddress();
    }
  }

  IOException exc = null;
  for (int i = 0; i < myPortsNumberToTry; i++) {
    int port = myInitialPort + i;
    try {
      return new Socket(host, port);
    }
    catch (IOException e) {
      exc = e;
      LOG.debug(e);
    }
  }
  throw exc;
}
项目:tools-idea    文件:ExternalSystemRunConfiguration.java   
public MyRunnableState(@NotNull ExternalSystemTaskExecutionSettings settings, @NotNull Project project, boolean debug) {
  mySettings = settings;
  myProject = project;
  int port;
  if (debug) {
    try {
      port = NetUtils.findAvailableSocketPort();
    }
    catch (IOException e) {
      LOG.warn("Unexpected I/O exception occurred on attempt to find a free port to use for external system task debugging", e);
      port = 0;
    }
  }
  else {
    port = 0;
  }
  myDebugPort = port;
}
项目:consulo    文件:ExternalSystemRunConfiguration.java   
public MyRunnableState(@Nonnull ExternalSystemTaskExecutionSettings settings, @Nonnull Project project, boolean debug) {
  mySettings = settings;
  myProject = project;
  int port;
  if (debug) {
    try {
      port = NetUtils.findAvailableSocketPort();
    }
    catch (IOException e) {
      LOG.warn("Unexpected I/O exception occurred on attempt to find a free port to use for external system task debugging", e);
      port = 0;
    }
  }
  else {
    port = 0;
  }
  myDebugPort = port;
}
项目:intellij-ce-playground    文件:RemoteDebugConfiguration.java   
@NotNull
@Override
public InetSocketAddress computeDebugAddress() {
  if (host == null) {
    return new InetSocketAddress(NetUtils.getLoopbackAddress(), port);
  }
  else {
    return new InetSocketAddress(host, getPort());
  }
}
项目:intellij-ce-playground    文件:CommonProxy.java   
@Override
public List<Proxy> select(@Nullable URI uri) {
  isInstalledAssertion();
  if (uri == null) {
    return NO_PROXY_LIST;
  }
  LOG.debug("CommonProxy.select called for " + uri.toString());

  if (Boolean.TRUE.equals(ourReenterDefence.get())) {
    return NO_PROXY_LIST;
  }
  try {
    ourReenterDefence.set(Boolean.TRUE);
    String host = StringUtil.notNullize(uri.getHost());
    if (NetUtils.isLocalhost(host)) {
      return NO_PROXY_LIST;
    }

    final HostInfo info = new HostInfo(uri.getScheme(), host, correctPortByProtocol(uri));
    final Map<String, ProxySelector> copy;
    synchronized (myLock) {
      if (myNoProxy.contains(Pair.create(info, Thread.currentThread()))) {
        LOG.debug("CommonProxy.select returns no proxy (in no proxy list) for " + uri.toString());
        return NO_PROXY_LIST;
      }
      copy = new THashMap<String, ProxySelector>(myCustom);
    }
    for (Map.Entry<String, ProxySelector> entry : copy.entrySet()) {
      final List<Proxy> proxies = entry.getValue().select(uri);
      if (!ContainerUtil.isEmpty(proxies)) {
        LOG.debug("CommonProxy.select returns custom proxy for " + uri.toString() + ", " + proxies.toString());
        return proxies;
      }
    }
    return NO_PROXY_LIST;
  }
  finally {
    ourReenterDefence.remove();
  }
}
项目:intellij-ce-playground    文件:RequestBuilder.java   
@NotNull
public String readString(@Nullable final ProgressIndicator indicator) throws IOException {
  return connect(new HttpRequests.RequestProcessor<String>() {
    @Override
    public String process(@NotNull HttpRequests.Request request) throws IOException {
      int contentLength = request.getConnection().getContentLength();
      BufferExposingByteArrayOutputStream out = new BufferExposingByteArrayOutputStream(contentLength > 0 ? contentLength : 16 * 1024);
      NetUtils.copyStreamContent(indicator, request.getInputStream(), out, contentLength);
      return new String(out.getInternalBuffer(), 0, out.size(), HttpRequests.getCharset(request));
    }
  });
}
项目:intellij-ce-playground    文件:PydevXmlRpcClient.java   
/**
 * Constructor (see fields description)
 */
public PydevXmlRpcClient(Process process, int port) throws MalformedURLException {
  XmlRpc.setDefaultInputEncoding("UTF8"); //even though it uses UTF anyway
  impl = new XmlRpcClientLite(NetUtils.getLocalHostString(), port);
  //this.impl = new XmlRpcClient(url, new CommonsXmlRpcTransportFactory(url));
  this.process = process;
}
项目:intellij-ce-playground    文件:PydevConsoleRunner.java   
private static int[] findAvailablePorts(Project project, PyConsoleType consoleType) {
  final int[] ports;
  try {
    // File "pydev/console/pydevconsole.py", line 223, in <module>
    // port, client_port = sys.argv[1:3]
    ports = NetUtils.findAvailableSocketPorts(2);
  }
  catch (IOException e) {
    ExecutionHelper.showErrors(project, Arrays.<Exception>asList(e), consoleType.getTitle(), null);
    return null;
  }
  return ports;
}
项目:intellij-ce-playground    文件:BrowserStarter.java   
private void checkAndOpenPage(@NotNull final HostAndPort hostAndPort, final int attemptNumber) {
  if (NetUtils.canConnectToRemoteSocket(hostAndPort.getHostText(), hostAndPort.getPort())) {
    openPageNow();
  }
  else {
    LOG.info("[attempt#" + attemptNumber + "] Checking " + hostAndPort + " failed");
    if (!isOutdated()) {
      int delayMillis = getDelayMillis(attemptNumber);
      checkAndOpenPageLater(hostAndPort, attemptNumber + 1, delayMillis);
    }
  }
}
项目:intellij-ce-playground    文件:TestNGRunnableState.java   
@Override
protected JavaParameters createJavaParameters() throws ExecutionException {
  final JavaParameters javaParameters = super.createJavaParameters();
  javaParameters.setupEnvs(getConfiguration().getPersistantData().getEnvs(), getConfiguration().getPersistantData().PASS_PARENT_ENVS);
  javaParameters.setMainClass("org.testng.RemoteTestNGStarter");

  try {
    port = NetUtils.findAvailableSocketPort();
  }
  catch (IOException e) {
    throw new ExecutionException("Unable to bind to port " + port, e);
  }

  final TestData data = getConfiguration().getPersistantData();

  javaParameters.getProgramParametersList().add(supportSerializationProtocol(getConfiguration()) ? RemoteArgs.PORT : CommandLineArgs.PORT, String.valueOf(port));

  if (data.getOutputDirectory() != null && !data.getOutputDirectory().isEmpty()) {
    javaParameters.getProgramParametersList().add(CommandLineArgs.OUTPUT_DIRECTORY, data.getOutputDirectory());
  }

  javaParameters.getProgramParametersList().add(CommandLineArgs.USE_DEFAULT_LISTENERS, String.valueOf(data.USE_DEFAULT_REPORTERS));

  @NonNls final StringBuilder buf = new StringBuilder();
  if (data.TEST_LISTENERS != null && !data.TEST_LISTENERS.isEmpty()) {
    buf.append(StringUtil.join(data.TEST_LISTENERS, ";"));
  }
  collectListeners(javaParameters, buf, IDEATestNGListener.EP_NAME, ";");
  if (buf.length() > 0) javaParameters.getProgramParametersList().add(CommandLineArgs.LISTENER, buf.toString());

  createServerSocket(javaParameters);
  createTempFiles(javaParameters);
  return javaParameters;
}
项目:intellij-ce-playground    文件:SnapShooterConfigurationExtension.java   
@Override
public void updateJavaParameters(RunConfigurationBase configuration, JavaParameters params, RunnerSettings runnerSettings) {
  if (!isApplicableFor(configuration)) {
    return;
  }
  ApplicationConfiguration appConfiguration = (ApplicationConfiguration) configuration;
  SnapShooterConfigurationSettings settings = appConfiguration.getUserData(SnapShooterConfigurationSettings.SNAP_SHOOTER_KEY);
  if (settings == null) {
    settings = new SnapShooterConfigurationSettings();
    appConfiguration.putUserData(SnapShooterConfigurationSettings.SNAP_SHOOTER_KEY, settings);
  }
  if (appConfiguration.ENABLE_SWING_INSPECTOR) {
    settings.setLastPort(NetUtils.tryToFindAvailableSocketPort());
  }

  if (appConfiguration.ENABLE_SWING_INSPECTOR && settings.getLastPort() != -1) {
    params.getProgramParametersList().prepend(appConfiguration.MAIN_CLASS_NAME);
    params.getProgramParametersList().prepend(Integer.toString(settings.getLastPort()));
    // add +1 because idea_rt.jar will be added as the last entry to the classpath
    params.getProgramParametersList().prepend(Integer.toString(params.getClassPath().getPathList().size() + 1));
    Set<String> paths = new TreeSet<String>();
    paths.add(PathUtil.getJarPathForClass(SnapShooter.class));         // ui-designer-impl
    paths.add(PathUtil.getJarPathForClass(BaseComponent.class));       // appcore-api
    paths.add(PathUtil.getJarPathForClass(ProjectComponent.class));    // openapi
    paths.add(PathUtil.getJarPathForClass(LwComponent.class));         // UIDesignerCore
    paths.add(PathUtil.getJarPathForClass(GridConstraints.class));     // forms_rt
    paths.add(PathUtil.getJarPathForClass(PaletteGroup.class));        // openapi
    paths.add(PathUtil.getJarPathForClass(LafManagerListener.class));  // ui-impl
    paths.add(PathUtil.getJarPathForClass(DataProvider.class));        // action-system-openapi
    paths.add(PathUtil.getJarPathForClass(XmlStringUtil.class));       // idea
    paths.add(PathUtil.getJarPathForClass(Navigatable.class));         // pom
    paths.add(PathUtil.getJarPathForClass(AreaInstance.class));        // extensions
    paths.add(PathUtil.getJarPathForClass(FormLayout.class));          // jgoodies
    paths.addAll(PathManager.getUtilClassPath());
    for(String path: paths) {
      params.getClassPath().addFirst(path);
    }
    params.setMainClass("com.intellij.uiDesigner.snapShooter.SnapShooter");
  }
}
项目:intellij-ce-playground    文件:OutputTabAdapter.java   
@Nullable
private InputStream connect(int port) throws IOException {
    final long s = System.currentTimeMillis();
    final InetSocketAddress endpoint = new InetSocketAddress(NetUtils.getLoopbackAddress(), port);

    myStartedProcess.notifyTextAvailable("Connecting to XSLT runner on " + endpoint + "\n", ProcessOutputTypes.SYSTEM);

    int tries = 0;
    IOException ex;
    do {
        final int d = (int)(System.currentTimeMillis() - s);
        try {
            @SuppressWarnings({"SocketOpenedButNotSafelyClosed"})
            final Socket socket = new Socket();
            socket.connect(endpoint, Math.max(CONNECT_TIMEOUT - d, 100));

            myStartedProcess.notifyTextAvailable("Connected to XSLT runner." + "\n", ProcessOutputTypes.SYSTEM);
            return socket.getInputStream();
        } catch (ConnectException e) {
            ex = e;
            try { Thread.sleep(500); } catch (InterruptedException ignored) { break; }
        }
        if (myStartedProcess.isProcessTerminated() || myStartedProcess.isProcessTerminating()) {
            return null;
        }
    } while (tries++ < 10);

    throw ex;
}
项目:tools-idea    文件:SubServer.java   
public boolean bind(int port) {
  if (port == BuiltInServerManager.getInstance().getPort()) {
    return true;
  }

  try {
    openChannels.add(bootstrap.bind(user.isAvailableExternally() ? new InetSocketAddress(port) : new InetSocketAddress(NetUtils.getLoopbackAddress(), port)));
    return true;
  }
  catch (Exception e) {
    NettyUtil.log(e, BuiltInServer.LOG);
    user.cannotBind(e, port);
    return false;
  }
}
项目:tools-idea    文件:OutputTabAdapter.java   
@Nullable
private InputStream connect(int port) throws IOException {
    final long s = System.currentTimeMillis();
    final InetSocketAddress endpoint = new InetSocketAddress(NetUtils.getLoopbackAddress(), port);

    myStartedProcess.notifyTextAvailable("Connecting to XSLT runner on " + endpoint + "\n", ProcessOutputTypes.SYSTEM);

    int tries = 0;
    IOException ex;
    do {
        final int d = (int)(System.currentTimeMillis() - s);
        try {
            @SuppressWarnings({"SocketOpenedButNotSafelyClosed"})
            final Socket socket = new Socket();
            socket.connect(endpoint, Math.max(CONNECT_TIMEOUT - d, 100));

            myStartedProcess.notifyTextAvailable("Connected to XSLT runner." + "\n", ProcessOutputTypes.SYSTEM);
            return socket.getInputStream();
        } catch (ConnectException e) {
            ex = e;
            try { Thread.sleep(500); } catch (InterruptedException ignored) { break; }
        }
        if (myStartedProcess.isProcessTerminated() || myStartedProcess.isProcessTerminating()) {
            return null;
        }
    } while (tries++ < 10);

    throw ex;
}
项目:consulo-javaee    文件:TomcatLocalModel.java   
public int[] getFreePorts() throws ExecutionException
{
    if(myFreePorts == null)
    {
        try
        {
            myFreePorts = NetUtils.findAvailableSocketPorts(2);
        }
        catch(IOException e)
        {
            throw new ExecutionException("Unable to find free ports", e);
        }
    }
    return myFreePorts;
}
项目:consulo-dotnet    文件:DebugConnectionInfo.java   
public DebugConnectionInfo(String host, int port, boolean server)
{
    myHost = host;
    myServer = server;
    if(port == -1)
    {
        myPort = NetUtils.tryToFindAvailableSocketPort();
    }
    else
    {
        myPort = port;
    }
}
项目:consulo    文件:BuiltInServerManagerImpl.java   
public static boolean isOnBuiltInWebServerByAuthority(@Nonnull String authority) {
  int portIndex = authority.indexOf(':');
  if (portIndex < 0 || portIndex == authority.length() - 1) {
    return false;
  }

  int port = StringUtil.parseInt(authority.substring(portIndex + 1), -1);
  if (port == -1) {
    return false;
  }

  BuiltInServerOptions options = BuiltInServerOptions.getInstance();
  int idePort = BuiltInServerManager.getInstance().getPort();
  if (options.builtInServerPort != port && idePort != port) {
    return false;
  }

  String host = authority.substring(0, portIndex);
  if (NetUtils.isLocalhost(host)) {
    return true;
  }

  try {
    InetAddress inetAddress = InetAddress.getByName(host);
    return inetAddress.isLoopbackAddress() ||
           inetAddress.isAnyLocalAddress() ||
           (options.builtInServerAvailableExternally && idePort != port && NetworkInterface.getByInetAddress(inetAddress) != null);
  }
  catch (IOException e) {
    return false;
  }
}
项目:consulo    文件:CommonProxy.java   
@Override
public List<Proxy> select(@Nullable URI uri) {
  isInstalledAssertion();
  if (uri == null) {
    return NO_PROXY_LIST;
  }
  LOG.debug("CommonProxy.select called for " + uri.toString());

  if (Boolean.TRUE.equals(ourReenterDefence.get())) {
    return NO_PROXY_LIST;
  }
  try {
    ourReenterDefence.set(Boolean.TRUE);
    String host = StringUtil.notNullize(uri.getHost());
    if (NetUtils.isLocalhost(host)) {
      return NO_PROXY_LIST;
    }

    final HostInfo info = new HostInfo(uri.getScheme(), host, correctPortByProtocol(uri));
    final Map<String, ProxySelector> copy;
    synchronized (myLock) {
      if (myNoProxy.contains(Pair.create(info, Thread.currentThread()))) {
        LOG.debug("CommonProxy.select returns no proxy (in no proxy list) for " + uri.toString());
        return NO_PROXY_LIST;
      }
      copy = new THashMap<>(myCustom);
    }
    for (Map.Entry<String, ProxySelector> entry : copy.entrySet()) {
      final List<Proxy> proxies = entry.getValue().select(uri);
      if (!ContainerUtil.isEmpty(proxies)) {
        LOG.debug("CommonProxy.select returns custom proxy for " + uri.toString() + ", " + proxies.toString());
        return proxies;
      }
    }
    return NO_PROXY_LIST;
  }
  finally {
    ourReenterDefence.remove();
  }
}
项目:consulo    文件:HttpRequests.java   
@Override
@Nonnull
public byte[] readBytes(@Nullable ProgressIndicator indicator) throws IOException {
  int contentLength = getConnection().getContentLength();
  BufferExposingByteArrayOutputStream out = new BufferExposingByteArrayOutputStream(contentLength > 0 ? contentLength : BLOCK_SIZE);
  NetUtils.copyStreamContent(indicator, getInputStream(), out, contentLength);
  return ArrayUtil.realloc(out.getInternalBuffer(), out.size());
}
项目:consulo    文件:HttpRequests.java   
@Override
@Nonnull
public File saveToFile(@Nonnull File file, @Nullable ProgressIndicator indicator) throws IOException {
  FileUtilRt.createParentDirs(file);

  boolean deleteFile = true;
  try {
    OutputStream out = new FileOutputStream(file);
    try {
      NetUtils.copyStreamContent(indicator, getInputStream(), out, getConnection().getContentLength());
      deleteFile = false;
    }
    catch (IOException e) {
      throw new IOException(createErrorMessage(e, this, false), e);
    }
    finally {
      out.close();
    }
  }
  finally {
    if (deleteFile) {
      FileUtilRt.delete(file);
    }
  }

  return file;
}
项目:consulo    文件:NettyKt.java   
public static boolean isLocalHost(String host, boolean onlyAnyOrLoopback, boolean hostsOnly) {
  if (NetUtils.isLocalhost(host)) {
    return true;
  }

  // if IP address, it is safe to use getByName (not affected by DNS rebinding)
  if (onlyAnyOrLoopback && !InetAddresses.isInetAddress(host)) {
    return false;
  }

  ThrowableNotNullFunction<InetAddress, Boolean, SocketException> isLocal =
          inetAddress -> inetAddress.isAnyLocalAddress() || inetAddress.isLoopbackAddress() || NetworkInterface.getByInetAddress(inetAddress) != null;

  try {
    InetAddress address = InetAddress.getByName(host);
    if (!isLocal.fun(address)) {
      return false;
    }
    // be aware - on windows hosts file doesn't contain localhost
    // hosts can contain remote addresses, so, we check it
    if (hostsOnly && !InetAddresses.isInetAddress(host)) {
      InetAddress hostInetAddress = HostsFileEntriesResolver.DEFAULT.address(host, ResolvedAddressTypes.IPV4_PREFERRED);
      return hostInetAddress != null && isLocal.fun(hostInetAddress);
    }
    else {
      return true;
    }
  }
  catch (IOException ignored) {
    return false;
  }
}
项目:intellij-ce-playground    文件:SubServer.java   
public boolean bind(int port) {
  if (port == server.getPort() || port == -1) {
    return true;
  }

  if (channelRegistrar == null) {
    Disposer.register(server, this);
    channelRegistrar = new ChannelRegistrar();
  }

  ServerBootstrap bootstrap = NettyUtil.nioServerBootstrap(server.getEventLoopGroup());
  Map<String, Object> xmlRpcHandlers = user.createXmlRpcHandlers();
  if (xmlRpcHandlers == null) {
    BuiltInServer.configureChildHandler(bootstrap, channelRegistrar, null);
  }
  else {
    final XmlRpcDelegatingHttpRequestHandler handler = new XmlRpcDelegatingHttpRequestHandler(xmlRpcHandlers);
    bootstrap.childHandler(new ChannelInitializer() {
      @Override
      protected void initChannel(Channel channel) throws Exception {
        channel.pipeline().addLast(channelRegistrar);
        NettyUtil.addHttpServerCodec(channel.pipeline());
        channel.pipeline().addLast(handler);
      }
    });
  }

  try {
    bootstrap.localAddress(user.isAvailableExternally() ? new InetSocketAddress(port) : new InetSocketAddress(NetUtils.getLoopbackAddress(), port));
    channelRegistrar.add(bootstrap.bind().syncUninterruptibly().channel());
    return true;
  }
  catch (Exception e) {
    try {
      NettyUtil.log(e, Logger.getInstance(BuiltInServer.class));
    }
    finally {
      user.cannotBind(e, port);
    }
    return false;
  }
}
项目:intellij-ce-playground    文件:UpdateSettings.java   
public boolean canUseSecureConnection() {
  return myState.SECURE_CONNECTION && NetUtils.isSniEnabled();
}
项目:intellij-ce-playground    文件:DebugAttachDetector.java   
public DebugAttachDetector() {
  ApplicationEx app = ApplicationManagerEx.getApplicationEx();
  if (!app.isInternal()
      || app.isUnitTestMode()
      || app.isHeadlessEnvironment()
      || "true".equals(System.getProperty("idea.debug.mode"))) return;

  for (String argument : ManagementFactory.getRuntimeMXBean().getInputArguments()) {
    if (argument.startsWith("-agentlib:jdwp") && argument.contains("transport=dt_socket")) {
      String[] params = argument.split(",");
      for (String param : params) {
        if (param.startsWith("address")) {
          try {
            String[] address = param.split("=")[1].split(":");
            if (address.length == 1) {
              myPort = Integer.parseInt(address[0]);
            }
            else {
              myHost = address[0];
              myPort = Integer.parseInt(address[1]);
            }
          }
          catch (Exception e) {
            LOG.error(e);
            return;
          }
          break;
        }
      }
      break;
    }
  }

  if (myPort < 0) return;

  myAlarm = new SingleAlarm(new Runnable() {
    @Override
    public void run() {
      boolean attached = !NetUtils.canConnectToRemoteSocket(myHost, myPort);
      if (!myReady) {
        myAttached = attached;
        myReady = true;
      }
      else if (attached != myAttached) {
        myAttached = attached;
        Notifications.Bus.notify(new Notification(Notifications.SYSTEM_MESSAGES_GROUP_ID,
                                                  "Remote debugger",
                                                  myAttached ? "attached" : "detached",
                                                  NotificationType.WARNING));
      }
      myAlarm.request();
    }
  }, 5000, Alarm.ThreadToUse.POOLED_THREAD, null);
  myAlarm.request();
}
项目:intellij-ce-playground    文件:RemotelyConfigurableStatServiceTest.java   
@BeforeClass
public static void init() throws Exception {
  int port = NetUtils.findAvailableSocketPort();
  STAT_URL = "http://localhost:" + port + "/stat.jsp";
  STAT_CONFIG_URL = "http://localhost:" + port + "/config.jsp";
}
项目:js-graphql-intellij-plugin    文件:JSGraphQLNodeLanguageServiceInstance.java   
private void createProcessHandler() {

        // Make sure we have a node interpreter
        final String nodeInterpreter = getNodeInterpreter(project);
        if (nodeInterpreter == null) {
            if(log.isDebugEnabled()) {
                log.debug("Can't create process handler: No Node.js interpreter configured.");
            }
            return;
        }

        try {

            if(log.isDebugEnabled()) {
                log.debug("Resolving node.js file...");
            }

            final File jsGraphQLNodeFile = getOrCreateJSGraphQLLanguageServiceFileName();
            if(jsGraphQLNodeFile == null) {
                if(log.isDebugEnabled()) {
                    log.debug("Can't create process handler: Got null from getOrCreateJSGraphQLLanguageServiceFileName.");
                }
                return;
            }

            final int socketPort = NetUtils.findAvailableSocketPort();
            final GeneralCommandLine commandLine = new GeneralCommandLine(nodeInterpreter);

            commandLine.withWorkDirectory(jsGraphQLNodeFile.getParent());
            commandLine.addParameter(jsGraphQLNodeFile.getAbsolutePath());

            commandLine.addParameter("--port=" + socketPort);

            if(log.isDebugEnabled()) {
                log.debug("Creating processHandler using command line " + commandLine.toString());
            }

            processHandler = new OSProcessHandler(commandLine);
            JSGraphQLLanguageUIProjectService languageService = JSGraphQLLanguageUIProjectService.getService(project);
            final Runnable onInitialized = languageService.connectToProcessHandler(processHandler);

            if (waitForListeningNotification(processHandler, project)) {
                url = new URL("http", NetUtils.getLocalHostString(), socketPort, JSGRAPHQL_LANGUAGE_SERVICE_MAPPING);
                onInitialized.run();
            } else {
                log.error("Unable to start JS GraphQL Language Service using Node.js with commandline " + commandLine.toString());
            }



        } catch (IOException | ExecutionException e) {
            if (e instanceof ProcessNotCreatedException) {
                Notifications.Bus.notify(new Notification("GraphQL", "Unable to start JS GraphQL Language Service", "Node.js was not started: " + e.getMessage(), NotificationType.ERROR));
            } else {
                log.error("Error running JS GraphQL Language Service using Node.js", e);
            }
        }
    }
项目:tools-idea    文件:PluginDownloader.java   
private File downloadPlugin(final ProgressIndicator pi) throws IOException {
  final File pluginsTemp = new File(PathManager.getPluginTempPath());
  if (!pluginsTemp.exists() && !pluginsTemp.mkdirs()) {
    throw new IOException(IdeBundle.message("error.cannot.create.temp.dir", pluginsTemp));
  }
  final File file = FileUtil.createTempFile(pluginsTemp, "plugin_", "_download", true, false);

  pi.setText(IdeBundle.message("progress.connecting"));

  URLConnection connection = null;
  try {
    connection = openConnection(myPluginUrl);

    final InputStream is = UrlConnectionUtil.getConnectionInputStream(connection, pi);
    if (is == null) {
      throw new IOException("Failed to open connection");
    }

    pi.setText(IdeBundle.message("progress.downloading.plugin", getPluginName()));
    final int contentLength = connection.getContentLength();
    pi.setIndeterminate(contentLength == -1);

    try {
      final OutputStream fos = new BufferedOutputStream(new FileOutputStream(file, false));
      try {
        NetUtils.copyStreamContent(pi, is, fos, contentLength);
      }
      finally {
        fos.close();
      }
    }
    finally {
      is.close();
    }

    if (myFileName == null) {
      myFileName = guessFileName(connection, file);
    }

    final File newFile = new File(file.getParentFile(), myFileName);
    FileUtil.rename(file, newFile);
    return newFile;
  }
  finally {
    if (connection instanceof HttpURLConnection) {
      ((HttpURLConnection)connection).disconnect();
    }
  }
}
项目:tools-idea    文件:RemotelyConfigurableStatServiceTest.java   
@BeforeClass
public static void init() throws Exception {
  int port = NetUtils.findAvailableSocketPort();
  STAT_URL = "http://localhost:" + port + "/stat.jsp";
  STAT_CONFIG_URL = "http://localhost:" + port + "/config.jsp";
}
项目:tools-idea    文件:FetchExtResourceAction.java   
@Nullable
private static FetchResult fetchData(final Project project, final String dtdUrl, ProgressIndicator indicator) throws IOException {

  try {
    URL url = new URL(dtdUrl);
    HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
    urlConnection.addRequestProperty("accept", "text/xml,application/xml,text/html,*/*");
    int contentLength = urlConnection.getContentLength();

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    InputStream in = urlConnection.getInputStream();
    String contentType;
    try {
      contentType = urlConnection.getContentType();
      NetUtils.copyStreamContent(indicator, in, out, contentLength);
    }
    finally {
      in.close();
    }

    FetchResult result = new FetchResult();
    result.bytes = out.toByteArray();
    result.contentType = contentType;

    return result;
  }
  catch (MalformedURLException e) {
    if (!ApplicationManager.getApplication().isUnitTestMode()) {
      ApplicationManager.getApplication().invokeLater(new Runnable() {
        public void run() {
          Messages.showMessageDialog(project,
                                     XmlBundle.message("invalid.url.message", dtdUrl),
                                     XmlBundle.message("invalid.url.title"),
                                     Messages.getErrorIcon());
        }
      }, indicator.getModalityState());
    }
  }

  return null;
}
项目:tools-idea    文件:SnapShooterConfigurationExtension.java   
@Override
public void updateJavaParameters(RunConfigurationBase configuration, JavaParameters params, RunnerSettings runnerSettings) {
  if (!isApplicableFor(configuration)) {
    return;
  }
  ApplicationConfiguration appConfiguration = (ApplicationConfiguration) configuration;
  SnapShooterConfigurationSettings settings = appConfiguration.getUserData(SnapShooterConfigurationSettings.SNAP_SHOOTER_KEY);
  if (settings == null) {
    settings = new SnapShooterConfigurationSettings();
    appConfiguration.putUserData(SnapShooterConfigurationSettings.SNAP_SHOOTER_KEY, settings);
  }
  if (appConfiguration.ENABLE_SWING_INSPECTOR) {
    try {
      settings.setLastPort(NetUtils.findAvailableSocketPort());
    }
    catch(IOException ex) {
      settings.setLastPort(-1);
    }
  }

  if (appConfiguration.ENABLE_SWING_INSPECTOR && settings.getLastPort() != -1) {
    params.getProgramParametersList().prepend(appConfiguration.MAIN_CLASS_NAME);
    params.getProgramParametersList().prepend(Integer.toString(settings.getLastPort()));
    // add +1 because idea_rt.jar will be added as the last entry to the classpath
    params.getProgramParametersList().prepend(Integer.toString(params.getClassPath().getPathList().size() + 1));
    Set<String> paths = new TreeSet<String>();
    paths.add(PathUtil.getJarPathForClass(SnapShooter.class));         // ui-designer-impl
    paths.add(PathUtil.getJarPathForClass(BaseComponent.class));       // appcore-api
    paths.add(PathUtil.getJarPathForClass(ProjectComponent.class));    // openapi
    paths.add(PathUtil.getJarPathForClass(LwComponent.class));         // UIDesignerCore
    paths.add(PathUtil.getJarPathForClass(GridConstraints.class));     // forms_rt
    paths.add(PathUtil.getJarPathForClass(LafManagerListener.class));  // ui-impl
    paths.add(PathUtil.getJarPathForClass(DataProvider.class));        // action-system-openapi
    paths.add(PathUtil.getJarPathForClass(XmlStringUtil.class));       // idea
    paths.add(PathUtil.getJarPathForClass(Navigatable.class));         // pom
    paths.add(PathUtil.getJarPathForClass(AreaInstance.class));        // extensions
    paths.add(PathUtil.getJarPathForClass(FormLayout.class));          // jgoodies
    paths.addAll(PathManager.getUtilClassPath());
    for(String path: paths) {
      params.getClassPath().addFirst(path);
    }
    params.setMainClass("com.intellij.uiDesigner.snapShooter.SnapShooter");
  }
}
项目:tools-idea    文件:AbstractAttachSourceProvider.java   
@Override
public ActionCallback perform(List<LibraryOrderEntry> orderEntriesContainingFile) {

  final ActionCallback callback = new ActionCallback();

  Task task = new Task.Backgroundable(myProject, "Downloading sources...", true) {
    @Override
    public void run(@NotNull ProgressIndicator indicator) {
      final ByteArrayOutputStream out;

      try {
        LOG.info("Downloading sources jar: " + myUrl);

        indicator.checkCanceled();

        HttpURLConnection urlConnection = HttpConfigurable.getInstance().openHttpConnection(myUrl);

        int contentLength = urlConnection.getContentLength();

        out = new ByteArrayOutputStream(contentLength > 0 ? contentLength : 100 * 1024);

        InputStream in = urlConnection.getInputStream();

        try {
          NetUtils.copyStreamContent(indicator, in, out, contentLength);
        }
        finally {
          in.close();
        }
      }
      catch (IOException e) {
        LOG.warn(e);
        ApplicationManager.getApplication().invokeLater(new Runnable() {
          @Override
          public void run() {
            new Notification(myMessageGroupId,
                             "Downloading failed",
                             "Failed to download sources: " + myUrl,
                             NotificationType.ERROR)
              .notify(getProject());

            callback.setDone();
          }
        });
        return;
      }

      ApplicationManager.getApplication().invokeLater(new Runnable() {
        @Override
        public void run() {
          AccessToken accessToken = WriteAction.start();
          try {
            storeFile(out.toByteArray());
          }
          finally {
            accessToken.finish();
            callback.setDone();
          }
        }
      });
    }

    @Override
    public void onCancel() {
      callback.setRejected();
    }
  };

  task.queue();

  return callback;
}
项目:intellij-xquery    文件:XQueryDebuggerRunner.java   
private int getAvailablePort() {
    return NetUtils.tryToFindAvailableSocketPort(9000);
}
项目:consulo-ui-designer    文件:SnapShooterConfigurationExtension.java   
@Override
public void updateJavaParameters(RunConfigurationBase configuration, OwnJavaParameters params, RunnerSettings runnerSettings) {
  if (!isApplicableFor(configuration)) {
    return;
  }
  ApplicationConfiguration appConfiguration = (ApplicationConfiguration) configuration;
  SnapShooterConfigurationSettings settings = appConfiguration.getUserData(SnapShooterConfigurationSettings.SNAP_SHOOTER_KEY);
  if (settings == null) {
    settings = new SnapShooterConfigurationSettings();
    appConfiguration.putUserData(SnapShooterConfigurationSettings.SNAP_SHOOTER_KEY, settings);
  }
  if (appConfiguration.ENABLE_SWING_INSPECTOR) {
    try {
      settings.setLastPort(NetUtils.findAvailableSocketPort());
    }
    catch(IOException ex) {
      settings.setLastPort(-1);
    }
  }

  if (appConfiguration.ENABLE_SWING_INSPECTOR && settings.getLastPort() != -1) {
    params.getProgramParametersList().prepend(appConfiguration.MAIN_CLASS_NAME);
    params.getProgramParametersList().prepend(Integer.toString(settings.getLastPort()));
    // add +1 because idea_rt.jar will be added as the last entry to the classpath
    params.getProgramParametersList().prepend(Integer.toString(params.getClassPath().getPathList().size() + 1));
    Set<String> paths = new TreeSet<String>();
    paths.add(PathUtil.getJarPathForClass(SnapShooter.class));         // ui-designer-impl
    paths.add(PathUtil.getJarPathForClass(BaseComponent.class));       // appcore-api
    paths.add(PathUtil.getJarPathForClass(ProjectComponent.class));    // openapi
    paths.add(PathUtil.getJarPathForClass(LwComponent.class));         // UIDesignerCore
    paths.add(PathUtil.getJarPathForClass(GridConstraints.class));     // forms_rt
    paths.add(PathUtil.getJarPathForClass(LafManagerListener.class));  // ui-impl
    paths.add(PathUtil.getJarPathForClass(DataProvider.class));        // action-system-openapi
    paths.add(PathUtil.getJarPathForClass(XmlStringUtil.class));       // idea
    paths.add(PathUtil.getJarPathForClass(Navigatable.class));         // pom
    paths.add(PathUtil.getJarPathForClass(AreaInstance.class));        // extensions
    paths.add(PathUtil.getJarPathForClass(FormLayout.class));          // jgoodies
    paths.addAll(PathManager.getUtilClassPath());
    for(String path: paths) {
      params.getClassPath().addFirst(path);
    }
    params.setMainClass("com.intellij.uiDesigner.snapShooter.SnapShooter");
  }
}
项目:consulo    文件:SubServer.java   
public boolean bind(int port) {
  if (port == server.getPort() || port == -1) {
    return true;
  }

  if (channelRegistrar == null) {
    Disposer.register(server, this);
    channelRegistrar = new ChannelRegistrar();
  }

  ServerBootstrap bootstrap = serverBootstrap(server.getEventLoopGroup());
  Map<String, Object> xmlRpcHandlers = user.createXmlRpcHandlers();
  if (xmlRpcHandlers == null) {
    BuiltInServer.configureChildHandler(bootstrap, channelRegistrar, null);
  }
  else {
    final XmlRpcDelegatingHttpRequestHandler handler = new XmlRpcDelegatingHttpRequestHandler(xmlRpcHandlers);
    bootstrap.childHandler(new ChannelInitializer() {
      @Override
      protected void initChannel(Channel channel) throws Exception {
        channel.pipeline().addLast(channelRegistrar);
        NettyUtil.addHttpServerCodec(channel.pipeline());
        channel.pipeline().addLast(handler);
      }
    });
  }

  try {
    bootstrap.localAddress(user.isAvailableExternally() ? new InetSocketAddress(port) : NetUtils.loopbackSocketAddress(port));
    channelRegistrar.setServerChannel(bootstrap.bind().syncUninterruptibly().channel(), false);
    return true;
  }
  catch (Exception e) {
    try {
      NettyUtil.log(e, Logger.getInstance(BuiltInServer.class));
    }
    finally {
      user.cannotBind(e, port);
    }
    return false;
  }
}