private void makeRequestWithRetries() throws ConnectException {
    // This is an additional layer of retry logic lifted from droid-fu
    // See:
    // https://github.com/kaeppler/droid-fu/blob/master/src/main/java/com/github/droidfu/http/BetterHttpRequestBase.java
    boolean retry = true;
    IOException cause = null;
    HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();
    while (retry) {
      try {
        makeRequest();
        return;
      } catch (IOException e) {
        cause = e;
        retry = retryHandler.retryRequest(cause, ++executionCount, context);
      } catch (NullPointerException e) {
        // there's a bug in HttpClient 4.0.x that on some occasions causes
        // DefaultRequestExecutor to throw an NPE, see
        // http://code.google.com/p/android/issues/detail?id=5255
        cause = new IOException("NPE in HttpClient" + e.getMessage());
        retry = retryHandler.retryRequest(cause, ++executionCount, context);
      }
    }

    // no retries left, crap out with exception
    ConnectException ex = new ConnectException();
    ex.initCause(cause);
    throw ex;
  }
Exemplo n.º 2
0
  int invokeOperation(String operation) {
    Authenticator.setDefault(getAuthenticator());

    String urlString = getInvokeUrl() + "&operation=" + operation;
    try {
      URL invoke = new URL(urlString);
      HttpURLConnection connection = (HttpURLConnection) invoke.openConnection();
      connection.setReadTimeout(getHttpRequestReadTimeout());
      InputStream in = connection.getInputStream();

      int ch;
      while ((ch = in.read()) != -1) {
        System.out.write((char) ch);
      }
      in.close();
      System.out.println("");
      System.out.flush();
    } catch (final ConnectException e) {
      LOG.error("error when attempting to fetch URL \"{}\"", urlString, e);
      if (isVerbose()) {
        System.out.println(e.getMessage() + " when attempting to fetch URL \"" + urlString + "\"");
      }
      return 1;
    } catch (final Throwable t) {
      LOG.error("error invoking {} operation", operation, t);
      System.out.println("error invoking " + operation + " operation");
      return 1;
    }

    return 0;
  }
Exemplo n.º 3
0
  @Override
  public Cursor query(
      Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {

    try {
      HttpUriRequest request = queryRequest(uri, projection, selection, selectionArgs, sortOrder);

      if (DEBUG) Log.i(TAG, "will query: " + request.getURI());

      Cursor cursor = getQueryHandler(uri).handleResponse(httpClient.execute(request));
      // httpClient.getConnectionManager().shutdown();
      return cursor;
    } catch (ConnectException e) {
      Log.w(TAG, "an error occured in query", e);
      return ErrorCursor.getCursor(0, e.getMessage());
    } catch (ClientProtocolException e) {
      Log.w(TAG, "an error occured in query", e);
      return ErrorCursor.getCursor(0, e.getMessage());
    } catch (IOException e) {
      Log.w(TAG, "an error occured in query", e);
      return ErrorCursor.getCursor(0, e.getMessage());
    } catch (IllegalArgumentException e) {
      Log.w(TAG, "an error occured in query", e);
      return ErrorCursor.getCursor(
          0,
          "Unknown URI (not in cache or not answerable by the implementator): " + uri.toString());
    }
  }
Exemplo n.º 4
0
 private boolean _connect() {
   try {
     trace.trace("client socket is connecting to server :" + this.getPeerAddr());
     lastConnectTime = System.currentTimeMillis();
     socket = new Socket();
     InetSocketAddress ar = new InetSocketAddress(hostIp, hostPort);
     socket.setSoTimeout(timeout * 1000);
     socket.connect(ar, timeout * 1000);
     connectWaitTime = 2;
   } catch (ConnectException e) {
     log.error(
         "Can't connect to:" + hostIp + "@" + hostPort + ",reason=" + e.getLocalizedMessage());
     socket = null;
     return false;
   } catch (Exception e) {
     log.error("Can't connect to:" + hostIp + "@" + hostPort);
     if (null != socket) {
       try {
         socket.close();
       } catch (Exception e1) {
       }
     }
     socket = null;
     return false;
   }
   log.info("client socket connect to server successfully:" + this.getPeerAddr());
   return true;
 }
Exemplo n.º 5
0
  public static ArrayList<String> trans(String url)
      throws FailingHttpStatusCodeException, MalformedURLException, IOException {

    ArrayList<String> hrefList = new ArrayList<String>();
    WebClient webClient = new WebClient(BrowserVersion.CHROME);
    webClient.getOptions().setJavaScriptEnabled(false);
    webClient.getOptions().setCssEnabled(false);
    try {
      HtmlPage page = null;
      try {
        page = (HtmlPage) webClient.getPage(url);
      } catch (ConnectException e) {
        System.out.println("Connect fails here:" + e.getMessage());
      }
      InputStream temp = new ByteArrayInputStream(page.asText().getBytes());
      InputStreamReader isr = new InputStreamReader(temp);
      BufferedReader br = new BufferedReader(isr);
      String str = null, rs = null;
      while ((str = br.readLine()) != null) {
        rs = str;
        // System.out.println(rs);
        if (rs != null) hrefList.add(rs);
      }
      System.out.println("从该网址查找的可能相关文本如下:");
      for (int i = 0; i < hrefList.size(); i++) {
        String string = hrefList.get(i);
        string = getTextFromHtml(string);
        if (string.length() >= 30) System.out.println("------" + i + ":" + string);
      }
    } catch (IOException e) {
    }
    return hrefList;
  }
Exemplo n.º 6
0
  public static void main(String[] args) {
    try {
      Socket s1 = new Socket("127.0.0.1", 57643);

      InputStream is = s1.getInputStream();
      DataInputStream dis = new DataInputStream(is);
      System.out.println(dis.readUTF());

      OutputStream os = s1.getOutputStream();
      DataOutputStream dos = new DataOutputStream(os);
      dos.writeUTF("Oh my gosh...");

      dis.close();
      is.close();
      dos.close();
      os.close();

      s1.close();
    } catch (ConnectException connExc) {
      connExc.printStackTrace();
      System.out.println("Server connection failed");
    } catch (IOException ioExc) {
      ioExc.printStackTrace();
    }
  }
Exemplo n.º 7
0
  /** Program Entry Point. */
  public static void main(String args[]) {

    // Set up log
    Log log = new Log();
    log.setLogName("Client");

    // Connection object listening on 4001
    Connection conn = new ConnectionImpl2(4001);
    InetAddress addr; // will hold address of host to connect to
    try {
      // get address of local host and connect
      addr = InetAddress.getLocalHost();
      conn.connect(addr, 5555);
      // send two messages to server
      conn.send("Client: Hello Server! Are you there?");
      conn.send("Client: Hi again!");
      // write a message in the log and close the connection
      Log.writeToLog("Client is now closing the connection!", "TestApplication");
      conn.close();
    } catch (ConnectException e) {
      Log.writeToLog(e.getMessage(), "TestApplication");
      e.printStackTrace();
    } catch (UnknownHostException e) {
      Log.writeToLog(e.getMessage(), "TestApplication");
      e.printStackTrace();
    } catch (IOException e) {
      Log.writeToLog(e.getMessage(), "TestApplication");
      e.printStackTrace();
    }

    System.out.println("CLIENT TEST FINISHED");
    Log.writeToLog("CLIENT TEST FINISHED", "TestApplication");
  }
Exemplo n.º 8
0
 /**
  * 方法名:httpRequest</br> 详述:发送http请求</br> 开发人员:souvc </br> 创建时间:2016-1-5 </br>
  *
  * @param requestUrl
  * @param requestMethod
  * @param outputStr
  * @return 说明返回值含义
  * @throws 说明发生此异常的条件
  */
 private static JsonNode httpRequest(String requestUrl, String requestMethod, String outputStr) {
   StringBuffer buffer = new StringBuffer();
   JsonNode josnNode = null;
   JSONObject jsonObject = null;
   try {
     URL url = new URL(requestUrl);
     HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
     httpUrlConn.setRequestMethod("GET");
     httpUrlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
     httpUrlConn.setDoOutput(true);
     httpUrlConn.setDoInput(true);
     httpUrlConn.setUseCaches(false);
     System.setProperty("sun.net.client.defaultConnectTimeout", "30000"); // 连接超时30秒
     System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
     httpUrlConn.connect();
     InputStream inputStream = httpUrlConn.getInputStream();
     InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
     BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
     String str = null;
     while ((str = bufferedReader.readLine()) != null) {
       buffer.append(str);
     }
     josnNode = new ObjectMapper().readTree(buffer.toString());
     bufferedReader.close();
     inputStreamReader.close();
     inputStream.close();
     inputStream = null;
     httpUrlConn.disconnect();
   } catch (ConnectException ce) {
     ce.printStackTrace();
   } catch (Exception e) {
     e.printStackTrace();
   }
   return josnNode;
 }
 private boolean txt2Pdf(File inputFile, File outputFile, Charset inputFileCharset) {
   // // 先将txt转成odt
   // String fileName = inputFile.getAbsolutePath();
   // if (fileName.endsWith(".txt")) {
   BufferedReader bufferedReader = null;
   try {
     // 判断原始txt文件的编码格式,获取响应的文件读入
     bufferedReader =
         new BufferedReader(
             new InputStreamReader(new FileInputStream(inputFile), inputFileCharset));
     // 将txt内容直接生成pdf
     Document document = new Document();
     BaseFont bfChinese =
         BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
     Font font_normal = new Font(bfChinese, 10, Font.NORMAL); // 设置字体大小
     document.setPageSize(PageSize.A4); // 设置页面大小
     if (!outputFile.exists()) {
       outputFile.createNewFile();
     }
     try {
       PdfWriter.getInstance(document, new FileOutputStream(outputFile));
       document.open();
     } catch (Exception e) {
       e.printStackTrace();
     }
     String content = null;
     while ((content = bufferedReader.readLine()) != null) {
       document.add(new Paragraph(content, font_normal));
     }
     document.close();
     bufferedReader.close();
     return true;
   } catch (ConnectException cex) {
     cex.printStackTrace();
     // System.out.println("转换失败!");
     return false;
   } catch (FileNotFoundException e) {
     e.printStackTrace();
     return false;
   } catch (IOException e) {
     e.printStackTrace();
     return false;
   } catch (DocumentException e) {
     e.printStackTrace();
     return false;
   } finally {
     // close the connection
     if (bufferedReader != null) {
       try {
         bufferedReader.close();
       } catch (IOException e) {
         e.printStackTrace();
       }
     }
   }
   // }
 }
Exemplo n.º 10
0
    public void run() {
      Log.v(TAG, "entering client thread --> ");
      String message = null;
      try {
        Log.v(TAG, "server IP:" + mServerIP + ", SERVER_PORT" + SERVER_PORT);
        mSocket = new Socket(mServerIP, SERVER_PORT);
        mReader = new BufferedReader(new InputStreamReader(mSocket.getInputStream()));
        mWriter =
            new PrintWriter(
                new BufferedWriter(new OutputStreamWriter(mSocket.getOutputStream())), true);

        if (mHandler != null) {
          mHandler.sendMessage(Message.obtain(null, MSG_ON_SERVER_CONNECTED, message));
        }
        while (true) {
          Log.v(TAG, "try to read from socket --> ");
          if (mSocket.isConnected() && !mSocket.isInputShutdown()) {
            message = mReader.readLine();
            Log.v(TAG, "Read Message: " + message);
            if (message == null) {
              Log.v(TAG, "remote socket closed");
              break;
            } else {
              if (mHandler != null) {
                mHandler.sendMessage(Message.obtain(null, MSG_ON_MESSAGE_ARRIVED, message));
              }
            }
          } else {
            Log.v(TAG, "disconnected ir input shutdown, so quit!: ");
            break;
          }
        }
      } catch (UnknownHostException e) {
        e.printStackTrace();
      } catch (ConnectException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }

      try {
        if (mReader != null) {
          mReader.close();
          mReader = null;
        }
        if (mWriter != null) {
          mWriter.close();
          mWriter = null;
        }
        mSocket = null;
      } catch (IOException e) {
        e.printStackTrace();
      }
      Log.v(TAG, "exit client thread --> ");
    }
Exemplo n.º 11
0
  /** Program Entry Point. */
  public static void main(String args[]) {

    // Set up log
    Log log = new Log();

    log.setLogName("Client");

    // Connection object listening on 4001
    Connection conn = new ConnectionImpl(4001);
    InetAddress addr; // will hold address of host to connect to
    try {
      // get address of local host and connect
      addr = InetAddress.getLocalHost(); // 78.91.16.205
      // addr = InetAddress.getByAddress(new byte[] { (byte) 78,(byte)  91, (byte) 23, (byte) 32 }
      // );
      conn.connect(addr, 5555);

      // send two messages to server

      String[] msgs = new String[20];

      for (int i = 0; i < msgs.length; i++) {
        msgs[i] = "m" + i;
      }

      for (String msg : msgs) {
        conn.send(msg);
      }

      // conn.send("Client: Hello Server! Are you there?");
      // conn.send("Client: Hi again!");
      // write a message in the log and close the connection
      Log.writeToLog("Client is now closing the connection!", "TestApplication");

      // System.out.println("##### close()");

      conn.close();

      // System.out.println("#### close();");
    } catch (ConnectException e) {
      // Log.writeToLog(e.getMessage(),"TestApplication");
      e.printStackTrace();
    } catch (UnknownHostException e) {
      // Log.writeToLog(e.getMessage(),"TestApplication");
      e.printStackTrace();
    } catch (IOException e) {
      Log.writeToLog(e.getMessage(), "TestApplication");
      e.printStackTrace();
    }

    System.out.println("CLIENT TEST FINISHED");
    Log.writeToLog("CLIENT TEST FINISHED", "TestApplication");
  }
  private void makeRequestWithRetries() throws ConnectException {
    // This is an additional layer of retry logic lifted from droid-fu
    // See:
    // https://github.com/kaeppler/droid-fu/blob/master/src/main/java/com/github/droidfu/http/BetterHttpRequestBase.java
    boolean retry = true;
    IOException cause = null;
    HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();
    while (retry) {
      try {
        makeRequest();
        return;
      } catch (ClientProtocolException e) {
        if (responseHandler != null) {
          responseHandler.sendFailureMessage(e, "cannot repeat the request");
        }
        return;
      } catch (UnknownHostException e) {
        if (responseHandler != null) {
          responseHandler.sendFailureMessage(e, "can't resolve host");
        }
        return;
      } catch (ConnectTimeoutException e) {
        if (responseHandler != null) {
          responseHandler.sendFailureMessage(e, "connection timed out");
        }
      } catch (SocketException e) {
        // Added to detect host unreachable
        if (responseHandler != null) {
          responseHandler.sendFailureMessage(e, "can't resolve host");
        }
        return;
      } catch (SocketTimeoutException e) {
        if (responseHandler != null) {
          responseHandler.sendFailureMessage(e, "socket time out");
        }
        return;
      } catch (IOException e) {
        cause = e;
        retry = retryHandler.retryRequest(cause, ++executionCount, context);
      } catch (NullPointerException e) {
        // there's a bug in HttpClient 4.0.x that on some occasions causes
        // DefaultRequestExecutor to throw an NPE, see
        // http://code.google.com/p/android/issues/detail?id=5255
        cause = new IOException("NPE in HttpClient" + e.getMessage());
        retry = retryHandler.retryRequest(cause, ++executionCount, context);
      }
    }

    // no retries left, crap out with exception
    ConnectException ex = new ConnectException();
    ex.initCause(cause);
    throw ex;
  }
  public Bucket openBucketConnectionNoPass() {
    try {
      randomConnectionUtility = randomConnectionBuilder.constructRandomConnection();

      bucket = randomConnectionUtility.getCluster().openBucket(bucketid, 5, TimeUnit.SECONDS);

    } catch (ConnectException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return bucket;
  }
Exemplo n.º 14
0
  /**
   * Аутентификация пользователя по паролю.
   *
   * @param answer ссылка на JSONObject ответа для клиента
   * @param user логин
   * @param pass пароль
   * @throws Exception
   */
  private void authenticationByPassword(
      HttpServletRequest request,
      HttpServletResponse response,
      JSONObject answer,
      String user,
      String pass)
      throws Exception {
    Mongo myMongoServ = new Mongo();
    myMongoServ.initMongoConnect();
    if (user.length() > 0) {
      try {
        List<UsersEntity> users =
            (List<UsersEntity>) myMongoServ.find(new UsersEntity(), "username", user);
        if (users.size() > 0) {
          if (users.get(0).getPassword().equals(pass)) {
            String session = UUID.randomUUID().toString();
            // System.out.println("session = "+session);
            myMongoServ.update(users.get(0), "session", session);
            myMongoServ.update(users.get(0), "last_login", new Date().getTime() + "");
            Cookie cuk = new Cookie("JSESSIONID", session);
            cuk.setPath("/phonebk");
            cuk.setHttpOnly(true);
            cuk.setMaxAge(UpdateCookie.COOKIE_MAX_AGE);
            response.addCookie(cuk);

            answer.put("answer", "Auth by pass is correct!");
            answer.put("code", 200);
          } else {
            answer.put("answer", "Password is invalid!");
            answer.put("code", 401);
          }
        } else {
          answer.put("answer", "Username or password is invalid!");
          answer.put("code", 401);
        }
      } catch (MongoSocketOpenException e) {
        System.out.println("Mongo ex");
        System.out.println(e.getMessage());
      } catch (ConnectException e) {
        System.out.println("Connect ex");
        System.out.println(e.getMessage());
      } catch (MongoTimeoutException e) {
        answer.put("answer", "Server is unavailable!");
        answer.put("code", 503);
      }

    } else {
      answer.put("answer", "Username is empty!");
      answer.put("code", 401);
    }
  }
Exemplo n.º 15
0
 public static boolean isPortOpen(final String ip, final int port, final int timeout) {
   try {
     Socket socket = new Socket();
     socket.connect(new InetSocketAddress(ip, port), timeout);
     socket.close();
     return true;
   } catch (ConnectException ce) {
     ce.printStackTrace();
     return false;
   } catch (Exception ex) {
     ex.printStackTrace();
     return false;
   }
 }
Exemplo n.º 16
0
  @Override
  public Socket establishConnection() {
    try {
      Socket sock = new Socket(server, port);
      return sock;
    } catch (ConnectException cex) {
      getImplementation().fireError(cex.getMessage());
    } catch (Exception ex) {
      ex.printStackTrace();
      getImplementation().fireError(ex.getMessage());
    }

    return null;
  }
Exemplo n.º 17
0
 public void setup() {
   size(640, 480);
   ThinkGearSocket neuroSocket = new ThinkGearSocket(this);
   try {
     neuroSocket.start();
   } catch (ConnectException e) {
     e.printStackTrace();
   }
   smooth();
   font = loadFont("MyriadPro-Regular-24.vlw");
   textFont(font);
   frameRate(25);
   cap = new Capture(this, width, height);
   noStroke();
 }
Exemplo n.º 18
0
 protected void send(Message message, long timestamp) {
   if (isDisabled()) {
     return;
   }
   try {
     transport.send(message.encoded(), timestamp);
   } catch (ConnectException e) {
     LOG.log(Level.SEVERE, e.getMessage(), e);
     // TODO Add backing off in case of errors
   } catch (FileNotFoundException e) {
     LOG.log(Level.SEVERE, e.getMessage(), e);
     // TODO Add backing off in case of errors
   } catch (IOException e) {
     LOG.log(Level.SEVERE, e.getMessage(), e);
   }
 }
Exemplo n.º 19
0
 public static CommandMinaClient getCommandMinaClient() {
   if (commandMinaClient == null) {
     synchronized (CommandMinaClient.class) {
       if (commandMinaClient == null) {
         try {
           commandMinaClient = new CommandMinaClient();
         } catch (java.net.ConnectException msg) {
           log.error("服务器没有开启,错误信息为:" + msg.getMessage().toString());
         } catch (Exception msg) {
           log.error("客户端连接服务器是发生错误,错误信息为:" + msg.getMessage().toString());
         }
       }
     }
   }
   return commandMinaClient;
 }
Exemplo n.º 20
0
 /** Should only be invoked by the IOLoop */
 @Override
 public void handleConnect(SelectionKey key) throws IOException {
   logger.debug("handle connect...");
   SocketChannel sc = (SocketChannel) channel;
   if (sc.isConnectionPending()) {
     try {
       sc.finishConnect();
       invokeConnectSuccessfulCallback();
       interestOps &= ~SelectionKey.OP_CONNECT;
       IOLoop.INSTANCE.updateHandler(channel, interestOps |= SelectionKey.OP_READ);
     } catch (ConnectException e) {
       logger.warn("Connect failed: {}", e.getMessage());
       invokeConnectFailureCallback(e);
     }
   }
 }
Exemplo n.º 21
0
  @Test
  public void testTypes() throws IOException, NoSuchElementException {
    if (url == null) return;
    WFS_1_0_0_DataStore wfs;
    try {
      wfs = WFSDataStoreReadTest.getDataStore(url);
    } catch (ConnectException e) {
      e.printStackTrace(System.err);
      return;
    } catch (UnknownHostException e) {
      e.printStackTrace(System.err);
      return;
    } catch (NoRouteToHostException e) {
      e.printStackTrace(System.err);
      return;
    }
    String types[] = wfs.getTypeNames();
    String typeName = "unknown";
    for (int i = 0; i < types.length; i++) {
      typeName = types[i];
      if (typeName.equals("topp:geometrytype")) continue;
      SimpleFeatureType type = wfs.getSchema(typeName);
      type.getTypeName();
      type.getName().getNamespaceURI();

      SimpleFeatureSource source = wfs.getFeatureSource(typeName);
      source.getBounds();

      SimpleFeatureCollection features = source.getFeatures();
      features.getBounds();
      features.getSchema();
      // features.getFeatureType();

      Query query = new Query(typeName, Filter.INCLUDE, 20, Query.ALL_NAMES, "work already");
      features = source.getFeatures(query);
      features.size();
      SimpleFeatureIterator iterator = features.features();
      try {
        while (iterator.hasNext()) {
          SimpleFeature feature = (SimpleFeature) iterator.next();
        }
      } finally {
        iterator.close();
      }
    }
  }
Exemplo n.º 22
0
  /** Program Entry Point. */
  public static void main(String args[]) {

    // Set up log
    Log log = new Log();
    log.setLogName("Client");

    // Connection object listening on 4001
    Connection conn = new ConnectionImpl(4001);
    InetAddress addr; // will hold address of host to connect to
    try {
      // get address of local host and connect
      addr = InetAddress.getLocalHost();
      conn.connect(addr, 5555);
      // send two messages to server
      for (int i = 0; i < 20; i++) {
        conn.send("Packet " + i);
      }
      int rec = 0;
      try {
        while (rec < 20) {
          String msg = conn.receive();
          Log.writeToLog("Message got through to client: " + msg, "TestClient");
          rec++;
        }
      } catch (EOFException e) {
        Log.writeToLog("Got close request (EOFException), closing.", "TestClient");
        conn.close();
      }

      // write a message in the log and close the connection
      Log.writeToLog("Client is now closing the connection!", "TestApplication");
      conn.close();
    } catch (ConnectException e) {
      Log.writeToLog(e.getMessage(), "TestApplication");
      e.printStackTrace();
    } catch (UnknownHostException e) {
      Log.writeToLog(e.getMessage(), "TestApplication");
      e.printStackTrace();
    } catch (IOException e) {
      Log.writeToLog(e.getMessage(), "TestApplication");
      e.printStackTrace();
    }

    System.out.println("CLIENT TEST FINISHED");
    Log.writeToLog("CLIENT TEST FINISHED", "TestApplication");
  }
Exemplo n.º 23
0
  public void connect() throws IOException {
    try {
      connection = new Socket(host, port);
      connection.setSoTimeout(timeout);

      out = new BufferedOutputStream(connection.getOutputStream());
      in = new BufferedInputStream(connection.getInputStream());
    } catch (UnknownHostException e) {
      logger.error("Ha ocurrido un error:", e);
      throw new UnknownHostException(e.getMessage());
    } catch (java.net.ConnectException e) {
      logger.error("Ha ocurrido un error:", e);
      throw new java.net.ConnectException(e.getMessage());
    } catch (IOException e) {
      logger.error("Ha ocurrido un error:", e);
      throw new IOException(e.getMessage());
    }
  }
Exemplo n.º 24
0
  /**
   * 执行http get请求
   *
   * @param url
   * @return HttpResult
   */
  public HttpResult invoke(String url) {
    GetMethod get = null;
    HttpResult result = null;
    try {
      get = new GetMethod(url);
      getClient().executeMethod(get);
      int statusCode = get.getStatusCode();
      String statusText = get.getStatusText();
      result = new HttpResult(statusCode, statusText);

      if (statusCode == 200) {
        StringBuffer buf = new StringBuffer();
        BufferedReader br =
            new BufferedReader(new InputStreamReader(get.getResponseBodyAsStream()));
        String line;
        while ((line = br.readLine()) != null) {
          buf.append(line).append('\n');
        }
        result.setBody(buf.toString());
      }

    } catch (SocketTimeoutException e) {
      result = new HttpResult(408, "REQUEST TIMEOUT. " + e.getMessage());
    } catch (java.net.ConnectException e) {
      result = new HttpResult(321, "Connection refused. " + e.getMessage());
    } catch (Exception e) {
      LOG.error(e);
      result = new HttpResult(123, e.getMessage());
    } finally {
      if (get != null) {
        try {
          // byte[] bytes = get.getResponseBody();
          get.releaseConnection();
        } catch (Exception e) {
          LOG.error(e);
        }
      }
    }

    return result;
  }
Exemplo n.º 25
0
  /**
   * Initialize a server on the given port. This server will not listen until it is launched with
   * the start() method.
   *
   * @param port
   * @throws IOException
   */
  public Server(int port, int botPort, Retriever ret, Map<String, Double> traffic)
      throws IOException {
    if (port <= 1024 || botPort <= 1024) {
      throw new IllegalArgumentException("Ports under 1024 are reserved!");
    }

    _port = port;
    _clients = new ClientPool();
    _socket = new ServerSocket(port);
    try {
      _botSocket = new Socket("localhost", botPort);
      _botConnectionSuccess = true;
      _trafficInput = new BufferedReader(new InputStreamReader(_botSocket.getInputStream()));
      _trafficData = traffic;
    } catch (ConnectException e) {
      System.out.println("unable to connect");
      System.out.println(e.getMessage());
      _botConnectionSuccess = false;
    }
    r = ret;
  }
  public void run() {
    try {
      GuiConnecting.setNetClientHandler(
          this.connectingGui, new NetClientHandler(this.mc, this.ip, this.port));

      if (GuiConnecting.isCancelled(this.connectingGui)) {
        return;
      }

      GuiConnecting.getNetClientHandler(this.connectingGui)
          .addToSendQueue(new Packet2Handshake(this.mc.session.username, this.ip, this.port));
    } catch (UnknownHostException var2) {
      if (GuiConnecting.isCancelled(this.connectingGui)) {
        return;
      }

      this.mc.displayGuiScreen(
          new GuiDisconnected(
              "connect.failed",
              "disconnect.genericReason",
              new Object[] {"Unknown host \'" + this.ip + "\'"}));
    } catch (ConnectException var3) {
      if (GuiConnecting.isCancelled(this.connectingGui)) {
        return;
      }

      this.mc.displayGuiScreen(
          new GuiDisconnected(
              "connect.failed", "disconnect.genericReason", new Object[] {var3.getMessage()}));
    } catch (Exception var4) {
      if (GuiConnecting.isCancelled(this.connectingGui)) {
        return;
      }

      var4.printStackTrace();
      this.mc.displayGuiScreen(
          new GuiDisconnected(
              "connect.failed", "disconnect.genericReason", new Object[] {var4.toString()}));
    }
  }
Exemplo n.º 27
0
  protected boolean execStreamConnect(Properties props) {
    try {
      if (props == null) {
        notifyStreamResult(true, "I2P_ERROR", "No parameters specified in STREAM CONNECT message");
        _log.debug("No parameters specified in STREAM CONNECT message");
        return false;
      }
      boolean verbose = props.getProperty("SILENT", "false").equals("false");

      String dest = props.getProperty("DESTINATION");
      if (dest == null) {
        notifyStreamResult(verbose, "I2P_ERROR", "Destination not specified in RAW SEND message");
        _log.debug("Destination not specified in RAW SEND message");
        return false;
      }
      props.remove("DESTINATION");

      try {
        streamSession.connect(this, dest, props);
        return true;
      } catch (DataFormatException e) {
        _log.debug("Invalid destination in STREAM CONNECT message");
        notifyStreamResult(verbose, "INVALID_KEY", null);
      } catch (ConnectException e) {
        _log.debug("STREAM CONNECT failed: " + e.getMessage());
        notifyStreamResult(verbose, "CONNECTION_REFUSED", null);
      } catch (NoRouteToHostException e) {
        _log.debug("STREAM CONNECT failed: " + e.getMessage());
        notifyStreamResult(verbose, "CANT_REACH_PEER", null);
      } catch (InterruptedIOException e) {
        _log.debug("STREAM CONNECT failed: " + e.getMessage());
        notifyStreamResult(verbose, "TIMEOUT", null);
      } catch (I2PException e) {
        _log.debug("STREAM CONNECT failed: " + e.getMessage());
        notifyStreamResult(verbose, "I2P_ERROR", e.getMessage());
      }
    } catch (IOException e) {
    }
    return false;
  }
Exemplo n.º 28
0
  @Test
  public void testSingleType() throws IOException, NoSuchElementException {
    if (url == null) return;
    WFS_1_0_0_DataStore wfs;
    try {
      wfs = WFSDataStoreReadTest.getDataStore(url);
    } catch (ConnectException e) {
      e.printStackTrace(System.err);
      return;
    } catch (UnknownHostException e) {
      e.printStackTrace(System.err);
      return;
    } catch (NoRouteToHostException e) {
      e.printStackTrace(System.err);
      return;
    }
    String typeName = "tiger:poi";
    SimpleFeatureType type = wfs.getSchema(typeName);
    type.getTypeName();
    type.getName().getNamespaceURI();

    SimpleFeatureSource source = wfs.getFeatureSource(typeName);
    source.getBounds();

    SimpleFeatureCollection features = source.getFeatures();
    features.getBounds();
    features.getSchema();
    // features.getFeatureType();

    Query query = new Query(typeName, Filter.INCLUDE, 20, Query.ALL_NAMES, "work already");
    features = source.getFeatures(query);
    features.size();

    SimpleFeatureIterator iterator = features.features();
    while (iterator.hasNext()) {
      SimpleFeature feature = iterator.next();
    }
    iterator.close();
  }
  /**
   * Connects this socket to the specified remote host address/port.
   *
   * @param anAddr the remote host address to connect to
   * @param aPort the remote port to connect to
   * @param timeout a timeout where supported. 0 means no timeout
   * @throws IOException if an error occurs while connecting
   */
  private void connect(InetAddress anAddr, int aPort, int timeout) throws IOException {

    InetAddress normalAddr = anAddr.isAnyLocalAddress() ? InetAddress.getLocalHost() : anAddr;
    try {
      if (streaming) {
        if (NetUtil.usingSocks(proxy)) {
          socksConnect(anAddr, aPort, 0);
        } else {
          if (timeout == 0) {
            netImpl.connect(fd, trafficClass, normalAddr, aPort);
          } else {
            netImpl.connectStreamWithTimeoutSocket(fd, aPort, timeout, trafficClass, normalAddr);
          }
        }
      } else {
        netImpl.connectDatagram(fd, aPort, trafficClass, normalAddr);
      }
    } catch (ConnectException e) {
      throw new ConnectException(anAddr + ":" + aPort + " - " + e.getMessage());
    }
    super.address = normalAddr;
    super.port = aPort;
  }
  private static String getSearchedAnime(String animeToSearch) {
    if (token == null) {
      try {
        ConnectAndGetToken();
      } catch (ConnectException e) {
        MAMUtil.writeLog(e);
        e.printStackTrace();
      } catch (UnknownHostException e) {
        MAMUtil.writeLog(e);
        e.printStackTrace();
      }
    }
    URL url; // The URL to read
    HttpURLConnection conn = null; // The actual connection to the web page
    BufferedReader rr; // Used to read results from the web page
    String line; // An individual line of the web page HTML
    String result = ""; // A long string containing all the HTML
    try {
      String animeQuery =
          URLEncoder.encode(
              animeToSearch
                  .replace(".", "\\.")
                  .replace("/", "\\ ")
                  .replace("-", "\\-")
                  .replace("!", "\\!"),
              "UTF-8");

      url = new URL(ANI_BASEURL + SEARCH + animeQuery + "?access_token=" + ConnectionManager.token);

      conn = (HttpURLConnection) url.openConnection();
      conn.setDoOutput(true);
      conn.setRequestMethod("GET");
      conn.setRequestProperty("User-Agent", "My Anime Manager");
      conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      rr = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
      while ((line = rr.readLine()) != null) result += line + "\r\n";
      rr.close();
    } catch (Exception e) {
      try {
        if (conn.getResponseCode() == 401) {
          System.out.println("Errore 401");
          System.out.println("Token scaduto, richiesta nuovo token");
          ConnectionManager.tokenExpired = true;
          attempts++;
          if (attempts > 5) {
            ConnectAndGetToken();
            AnimeSearch(animeToSearch);
            attempts = 0;
          } else
            JOptionPane.showMessageDialog(
                AnimeIndex.frame,
                "Errore durante la connessione! Potrebbe dipendere dalla tua connessione o dal sito di Anilist.",
                "Errore!",
                JOptionPane.ERROR_MESSAGE);
        } else {
          e.printStackTrace();
          MAMUtil.writeLog(e);
        }

      } catch (IOException e1) {
        MAMUtil.writeLog(e1);
        e1.printStackTrace();
      }
    }
    result = StringEscapeUtils.unescapeJava(result);
    return result;
  }