Exemple #1
0
 /**
  * Wait for sequence number to be assigned & return the assigned value.
  *
  * @param maxWaitForSeqId maximum time to wait in milliseconds for sequenceid
  * @return long the new assigned sequence number
  * @throws IOException
  */
 public long getSequenceId(final long maxWaitForSeqId) throws IOException {
   // TODO: This implementation waiting on a latch is problematic because if a higher level
   // determines we should stop or abort, there is no global list of all these blocked WALKeys
   // waiting on a sequence id; they can't be cancelled... interrupted. See getNextSequenceId.
   //
   // UPDATE: I think we can remove the timeout now we are stamping all walkeys with sequenceid,
   // even those that have failed (previously we were not... so they would just hang out...).
   // St.Ack 20150910
   try {
     if (maxWaitForSeqId < 0) {
       this.seqNumAssignedLatch.await();
     } else if (!this.seqNumAssignedLatch.await(maxWaitForSeqId, TimeUnit.MILLISECONDS)) {
       throw new TimeoutIOException(
           "Failed to get sequenceid after "
               + maxWaitForSeqId
               + "ms; WAL system stuck or has gone away?");
     }
   } catch (InterruptedException ie) {
     LOG.warn("Thread interrupted waiting for next log sequence number");
     InterruptedIOException iie = new InterruptedIOException();
     iie.initCause(ie);
     throw iie;
   }
   return this.logSeqNum;
 }
 /**
  * Returns the stream's response headers, blocking if necessary if they have not been received
  * yet.
  */
 public synchronized List<String> getResponseHeaders() throws IOException {
   long remaining = 0;
   long start = 0;
   if (readTimeoutMillis != 0) {
     start = (System.nanoTime() / 1000000);
     remaining = readTimeoutMillis;
   }
   try {
     while (responseHeaders == null && errorCode == null) {
       if (readTimeoutMillis == 0) { // No timeout configured.
         wait();
       } else if (remaining > 0) {
         wait(remaining);
         remaining = start + readTimeoutMillis - (System.nanoTime() / 1000000);
       } else {
         throw new SocketTimeoutException(
             "Read response header timeout. readTimeoutMillis: " + readTimeoutMillis);
       }
     }
     if (responseHeaders != null) {
       return responseHeaders;
     }
     throw new IOException("stream was reset: " + errorCode);
   } catch (InterruptedException e) {
     InterruptedIOException rethrow = new InterruptedIOException();
     rethrow.initCause(e);
     throw rethrow;
   }
 }
  @Override
  public Event intercept(Event event) {
    // TODO Auto-generated method stub
    Map<String, String> headers = event.getHeaders();
    String Filename = headers.get("file");
    String fileType = getFileType(new String(event.getBody()));
    Configuration conf = HBaseConfiguration.create();
    HTable table = null;
    try {
      table = new HTable(conf, "fs");
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    Put put = new Put(Bytes.toBytes(fileType + "_" + Filename));
    put.add(Bytes.toBytes("fn"), Bytes.toBytes("ST"), Bytes.toBytes("PICKED"));

    try {
      table.put(put);
    } catch (RetriesExhaustedWithDetailsException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InterruptedIOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    try {

      table.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return event;
  }
Exemple #4
0
  public static boolean sessionDeleteClient(SessionTable session, Server e) throws IOException {
    DatagramSocket rpcSocket = new DatagramSocket();
    rpcSocket.setSoTimeout(2000); // Timeout after 2 seconds
    String callID = UUID.randomUUID().toString(); // generate unique id for call
    byte[] outBuf = new byte[512];
    // fill outBuf with callId, operationSESSIONDelete, sessionID, sessionVersionNum
    String outStr = callID + "+2+" + session.getSid() + "+" + session.getVersion();
    outBuf = string2byte(outStr);
    //	for(Server e : s){
    DatagramPacket sendPkt = new DatagramPacket(outBuf, outBuf.length, e.ip, e.port);
    rpcSocket.send(sendPkt);
    //	}

    byte[] inBuf = new byte[512];
    DatagramPacket recvPkt = new DatagramPacket(inBuf, inBuf.length);
    try {
      do {
        recvPkt.setLength(inBuf.length);
        rpcSocket.receive(recvPkt);

      } while (!byte2string(recvPkt.getData())
          .equals("ok")); // the callId in inBuf is not the expected one
    } catch (InterruptedIOException iioe) {
      // timeout
      iioe.printStackTrace();
      return false;
    } catch (SocketException e0) {
      // TODO Auto-generated catch block
      e0.printStackTrace();
      return false;
    }

    rpcSocket.close();
    return true;
  }
  /**
   * Reads bytes from the socket.
   *
   * @param buf byte buffer receiving the bytes
   * @param offset offset into the buffer
   * @param length number of bytes to read
   * @return number of bytes read or -1
   * @exception throws ClientDisconnectException if the connection is dropped
   */
  @Override
  public int read(byte[] buf, int offset, int length) throws IOException {
    try {
      SocketChannel s = _s;

      if (s == null) {
        return -1;
      }

      int remaining = _readBuffer.remaining();
      if (remaining <= 0) {
        _readBuffer.clear();

        if (s.read(_readBuffer) < 0) {
          _readBuffer.flip();
          return -1;
        }

        _readBuffer.flip();

        remaining = _readBuffer.remaining();
      }

      int sublen = Math.min(remaining, length);

      _readBuffer.get(buf, offset, sublen);

      int readLength = sublen;

      if (readLength >= 0) {
        _totalReadBytes += readLength;
      }

      return readLength;
    } catch (InterruptedIOException e) {
      if (_throwReadInterrupts) throw e;

      log.log(Level.FINEST, e.toString(), e);
    } catch (IOException e) {
      if (_throwReadInterrupts) {
        throw e;
      }

      if (log.isLoggable(Level.FINEST)) {
        log.log(Level.FINEST, e.toString(), e);
      } else {
        log.finer(e.toString());
      }
      // server/0611
      /*
      try {
        close();
      } catch (IOException e1) {
      }
      */
    }

    return -1;
  }
 private void _checkCancelled() throws IOException {
   if (_isCanceled()) {
     InterruptedIOException exc = new InterruptedIOException("IO operation cancelled");
     exc.bytesTransferred = _nread;
     // System.out.println("throwing io exception");
     _interruptedIO();
     throw exc;
   }
 }
Exemple #7
0
    /** Thread to handle incoming requests. */
    @Override
    public void run() {
      // start message queue
      while (!Thread.interrupted()) {
        try {
          // wait for new message
          Message msg = mQueuedMessageConnection.readMessage();

          mPongFlag = true;
          if (msg.getRequest() == Instruction.PONG) {
            continue;
          }

          // notify listeners
          for (Receiver r : mReceivers) {
            r.OnNewMessage(msg);
          }
        }
        // The thread was interrupted
        catch (InterruptedIOException ex) {
          LOGGER.warning(ex.getMessage());
          mWorkerQueue.add(
              new Runnable() {
                public void run() {
                  _disconnect();
                  if (mConnectEnabled) {
                    _connect();
                  }
                }
              });
          return;
        }
        // The socket was close of any reason
        catch (IOException ex) {
          LOGGER.warning(ex.getMessage());
          mWorkerQueue.add(
              new Runnable() {
                public void run() {
                  _disconnect();
                  if (mConnectEnabled) {
                    _connect();
                  }
                }
              });
          return;
        }
      }
      LOGGER.log(Level.INFO, "[[MessageReceiver THREAD done]]");

      mWorkerQueue.add(
          new Runnable() {
            public void run() {
              _disconnect();
            }
          });
    }
 /**
  * Overrides <code>FilterInputStream.read</code> to update the progress monitor after the read.
  */
 public int read() throws IOException {
   int c = in.read();
   if (c >= 0) monitor.setProgress(++nread);
   if (monitor.isCanceled()) {
     InterruptedIOException exc = new InterruptedIOException("progress");
     exc.bytesTransferred = nread;
     throw exc;
   }
   return c;
 }
 /**
  * Overrides <code>FilterInputStream.read</code> to update the progress monitor after the read.
  */
 public int read(byte b[], int off, int len) throws IOException {
   int nr = in.read(b, off, len);
   if (nr > 0) monitor.setProgress(nread += nr);
   if (monitor.isCanceled()) {
     InterruptedIOException exc = new InterruptedIOException("progress");
     exc.bytesTransferred = nread;
     throw exc;
   }
   return nr;
 }
  public static void readMetaInfo(DicomSeriesProgressMonitor progress, byte[] b)
      throws IOException {
    if (b == null) {
      return;
    }
    int byteOffset = 0;
    if (b.length > 132 && new String(b, 128, 4).equals("DICM")) { // $NON-NLS-1$
      byteOffset = 132;
    } else {
      InterruptedIOException exc = new InterruptedIOException("Not a DICOM file"); // $NON-NLS-1$
      exc.bytesTransferred = progress.nread;
      progress.series.setFileSize(progress.series.getFileSize() - progress.nread);
      progress.nread = 0;
      throw exc;
    }
    if (!DicomImageUtils.hasPlatformNativeImageioCodecs()) {
      int endByteOffset = b.length - 1;
      while (byteOffset < endByteOffset) {
        int group = extractUnsigned16(b, byteOffset);
        int element = extractUnsigned16(b, byteOffset + 2);
        byteOffset += 4;
        if ((group == 0x0002 && element > 0x0010) || group > 0x0002) {
          break;
        }
        byte[] vr = {b[byteOffset], b[byteOffset + 1]};
        byteOffset += 2;

        int vl;
        if (isShortValueLengthVR(vr)) {
          vl = extractUnsigned16(b, byteOffset);
          byteOffset += 2;
        } else {
          // 2 reserved bytes
          // cast to int (should not be a big number in meta information)
          vl = (int) extractUnsigned32(b, byteOffset + 2);
          byteOffset += 6;
        }
        // (0x0002, 0x0010) Transfer Syntax UID
        if (element == 0x0010 && vl != 0 && byteOffset + vl < b.length) {
          String tsuid = new String(b, byteOffset, vl);
          if (TransferSyntax.requiresNativeImageioCodecs(tsuid)) {
            InterruptedIOException exc =
                new InterruptedIOException("TSUID not supported by OS"); // $NON-NLS-1$
            exc.bytesTransferred = Integer.MIN_VALUE;
            progress.series.setFileSize(progress.series.getFileSize() - progress.nread);
            progress.nread = 0;
            throw exc;
          }
        }
        byteOffset += vl;
      }
    }
  }
Exemple #11
0
 /**
  * Execute the passed <code>mutations</code> against <code>.META.</code> table.
  *
  * @param ct CatalogTracker on whose back we will ride the edit.
  * @param mutations Puts and Deletes to execute on .META.
  * @throws IOException
  */
 static void mutateMetaTable(final CatalogTracker ct, final List<Mutation> mutations)
     throws IOException {
   HTable t = MetaReader.getMetaHTable(ct);
   try {
     t.batch(mutations);
   } catch (InterruptedException e) {
     InterruptedIOException ie = new InterruptedIOException(e.getMessage());
     ie.initCause(e);
     throw ie;
   } finally {
     t.close();
   }
 }
Exemple #12
0
 /**
  * Will block until a write entry has been assigned by they WAL subsystem.
  *
  * @return A WriteEntry gotten from local WAL subsystem. Must be completed by calling {@link
  *     MultiVersionConcurrencyControl#complete(MultiVersionConcurrencyControl.WriteEntry)} or
  *     {@link MultiVersionConcurrencyControl#complete(MultiVersionConcurrencyControl.WriteEntry)}
  * @see {@link #setWriteEntry(MultiVersionConcurrencyControl.WriteEntry)}
  */
 @InterfaceAudience.Private // For internal use only.
 public MultiVersionConcurrencyControl.WriteEntry getWriteEntry() throws InterruptedIOException {
   try {
     this.seqNumAssignedLatch.await();
   } catch (InterruptedException ie) {
     // If interrupted... clear out our entry else we can block up mvcc.
     MultiVersionConcurrencyControl mvcc = getMvcc();
     LOG.debug("mvcc=" + mvcc + ", writeEntry=" + this.writeEntry);
     if (mvcc != null) {
       if (this.writeEntry != null) {
         mvcc.complete(this.writeEntry);
       }
     }
     InterruptedIOException iie = new InterruptedIOException();
     iie.initCause(ie);
     throw iie;
   }
   return this.writeEntry;
 }
 protected boolean execStreamAccept(Properties props) {
   boolean verbose = props.getProperty("SILENT", "false").equals("false");
   try {
     try {
       notifyStreamResult(verbose, "OK", null);
       streamSession.accept(this, verbose);
       return true;
     } catch (InterruptedIOException e) {
       _log.debug("STREAM ACCEPT failed: " + e.getMessage());
       notifyStreamResult(verbose, "TIMEOUT", e.getMessage());
     } catch (I2PException e) {
       _log.debug("STREAM ACCEPT failed: " + e.getMessage());
       notifyStreamResult(verbose, "I2P_ERROR", e.getMessage());
     } catch (SAMException e) {
       _log.debug("STREAM ACCEPT failed: " + e.getMessage());
       notifyStreamResult(verbose, "ALREADY_ACCEPTING", null);
     }
   } catch (IOException e) {
   }
   return false;
 }
  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;
  }
  @Override
  protected void accept(SocketImpl newImpl) throws IOException {
    if (NetUtil.usingSocks(proxy)) {
      ((PlainSocketImpl) newImpl).socksBind();
      ((PlainSocketImpl) newImpl).socksAccept();
      return;
    }

    try {
      if (newImpl instanceof PlainSocketImpl) {
        PlainSocketImpl newPlainSocketImpl = (PlainSocketImpl) newImpl;
        // BEGIN android-changed
        // call accept instead of acceptStreamImpl (native impl is identical)
        netImpl.accept(fd, newImpl, newPlainSocketImpl.getFileDescriptor(), receiveTimeout);
        // END android-changed
        newPlainSocketImpl.setLocalport(getLocalPort());
      } else {
        // if newImpl is not an instance of PlainSocketImpl, use
        // reflection to get/set protected fields.
        if (null == fdField) {
          fdField = getSocketImplField("fd"); // $NON-NLS-1$
        }
        FileDescriptor newFd = (FileDescriptor) fdField.get(newImpl);
        // BEGIN android-changed
        // call accept instead of acceptStreamImpl (native impl is identical)
        netImpl.accept(fd, newImpl, newFd, receiveTimeout);
        // END android-cahnged

        if (null == localportField) {
          localportField = getSocketImplField("localport"); // $NON-NLS-1$
        }
        localportField.setInt(newImpl, getLocalPort());
      }
    } catch (InterruptedIOException e) {
      throw new SocketTimeoutException(e.getMessage());
    } catch (IllegalAccessException e) {
      // empty
    }
  }
Exemple #16
0
  public void run() {
    while (!disposing.get()) {
      if (connector.isStarted() && !disposing.get()) {
        Socket socket = null;
        try {
          socket = serverSocket.accept();

          if (logger.isTraceEnabled()) {
            logger.trace("Accepted: " + serverSocket);
          }
        } catch (java.io.InterruptedIOException iie) {
          if (logger.isDebugEnabled()) {
            logger.debug("Interupted IO doing serverSocket.accept: " + iie.getMessage());
          }
        } catch (Exception e) {
          if (!connector.isDisposed() && !disposing.get()) {
            logger.warn("Accept failed on socket: " + e, e);
            handleException(new ConnectException(e, this));
          }
        }

        if (socket != null) {
          try {
            Work work = createWork(socket);
            try {
              getWorkManager().scheduleWork(work, WorkManager.INDEFINITE, null, connector);
            } catch (WorkException e) {
              logger.error("Tcp Server receiver Work was not processed: " + e.getMessage(), e);
            }
          } catch (IOException e) {
            handleException(e);
          }
        }
      }
    }
  }
Exemple #17
0
  // non-javadoc, see interface ClientRequestDirector
  public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context)
      throws HttpException, IOException {

    HttpRequest orig = request;
    RequestWrapper origWrapper = wrapRequest(orig);
    origWrapper.setParams(params);
    HttpRoute origRoute = determineRoute(target, origWrapper, context);

    RoutedRequest roureq = new RoutedRequest(origWrapper, origRoute);

    long timeout = ConnManagerParams.getTimeout(params);

    int execCount = 0;

    boolean reuse = false;
    HttpResponse response = null;
    boolean done = false;
    try {
      while (!done) {
        // In this loop, the RoutedRequest may be replaced by a
        // followup request and route. The request and route passed
        // in the method arguments will be replaced. The original
        // request is still available in 'orig'.

        RequestWrapper wrapper = roureq.getRequest();
        HttpRoute route = roureq.getRoute();

        // See if we have a user token bound to the execution context
        Object userToken = context.getAttribute(ClientContext.USER_TOKEN);

        // Allocate connection if needed
        if (managedConn == null) {
          ClientConnectionRequest connRequest = connManager.requestConnection(route, userToken);
          if (orig instanceof AbortableHttpRequest) {
            ((AbortableHttpRequest) orig).setConnectionRequest(connRequest);
          }

          try {
            managedConn = connRequest.getConnection(timeout, TimeUnit.MILLISECONDS);
          } catch (InterruptedException interrupted) {
            InterruptedIOException iox = new InterruptedIOException();
            iox.initCause(interrupted);
            throw iox;
          }

          if (HttpConnectionParams.isStaleCheckingEnabled(params)) {
            // validate connection
            this.log.debug("Stale connection check");
            if (managedConn.isStale()) {
              this.log.debug("Stale connection detected");
              // BEGIN android-changed
              try {
                managedConn.close();
              } catch (IOException ignored) {
                // SSLSocket's will throw IOException
                // because they can't send a "close
                // notify" protocol message to the
                // server. Just supresss any
                // exceptions related to closing the
                // stale connection.
              }
              // END android-changed
            }
          }
        }

        if (orig instanceof AbortableHttpRequest) {
          ((AbortableHttpRequest) orig).setReleaseTrigger(managedConn);
        }

        // Reopen connection if needed
        if (!managedConn.isOpen()) {
          managedConn.open(route, context, params);
        }
        // BEGIN android-added
        else {
          // b/3241899 set the per request timeout parameter on reused connections
          managedConn.setSocketTimeout(HttpConnectionParams.getSoTimeout(params));
        }
        // END android-added

        try {
          establishRoute(route, context);
        } catch (TunnelRefusedException ex) {
          if (this.log.isDebugEnabled()) {
            this.log.debug(ex.getMessage());
          }
          response = ex.getResponse();
          break;
        }

        // Reset headers on the request wrapper
        wrapper.resetHeaders();

        // Re-write request URI if needed
        rewriteRequestURI(wrapper, route);

        // Use virtual host if set
        target = (HttpHost) wrapper.getParams().getParameter(ClientPNames.VIRTUAL_HOST);

        if (target == null) {
          target = route.getTargetHost();
        }

        HttpHost proxy = route.getProxyHost();

        // Populate the execution context
        context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, target);
        context.setAttribute(ExecutionContext.HTTP_PROXY_HOST, proxy);
        context.setAttribute(ExecutionContext.HTTP_CONNECTION, managedConn);
        context.setAttribute(ClientContext.TARGET_AUTH_STATE, targetAuthState);
        context.setAttribute(ClientContext.PROXY_AUTH_STATE, proxyAuthState);

        // Run request protocol interceptors
        requestExec.preProcess(wrapper, httpProcessor, context);

        context.setAttribute(ExecutionContext.HTTP_REQUEST, wrapper);

        boolean retrying = true;
        while (retrying) {
          // Increment total exec count (with redirects)
          execCount++;
          // Increment exec count for this particular request
          wrapper.incrementExecCount();
          if (wrapper.getExecCount() > 1 && !wrapper.isRepeatable()) {
            throw new NonRepeatableRequestException(
                "Cannot retry request " + "with a non-repeatable request entity");
          }

          try {
            if (this.log.isDebugEnabled()) {
              this.log.debug("Attempt " + execCount + " to execute request");
            }
            response = requestExec.execute(wrapper, managedConn, context);
            retrying = false;

          } catch (IOException ex) {
            this.log.debug("Closing the connection.");
            managedConn.close();
            if (retryHandler.retryRequest(ex, execCount, context)) {
              if (this.log.isInfoEnabled()) {
                this.log.info(
                    "I/O exception ("
                        + ex.getClass().getName()
                        + ") caught when processing request: "
                        + ex.getMessage());
              }
              if (this.log.isDebugEnabled()) {
                this.log.debug(ex.getMessage(), ex);
              }
              this.log.info("Retrying request");
            } else {
              throw ex;
            }

            // If we have a direct route to the target host
            // just re-open connection and re-try the request
            if (route.getHopCount() == 1) {
              this.log.debug("Reopening the direct connection.");
              managedConn.open(route, context, params);
            } else {
              // otherwise give up
              throw ex;
            }
          }
        }

        // Run response protocol interceptors
        response.setParams(params);
        requestExec.postProcess(response, httpProcessor, context);

        // The connection is in or can be brought to a re-usable state.
        reuse = reuseStrategy.keepAlive(response, context);
        if (reuse) {
          // Set the idle duration of this connection
          long duration = keepAliveStrategy.getKeepAliveDuration(response, context);
          managedConn.setIdleDuration(duration, TimeUnit.MILLISECONDS);
        }

        RoutedRequest followup = handleResponse(roureq, response, context);
        if (followup == null) {
          done = true;
        } else {
          if (reuse) {
            this.log.debug("Connection kept alive");
            // Make sure the response body is fully consumed, if present
            HttpEntity entity = response.getEntity();
            if (entity != null) {
              entity.consumeContent();
            }
            // entity consumed above is not an auto-release entity,
            // need to mark the connection re-usable explicitly
            managedConn.markReusable();
          } else {
            managedConn.close();
          }
          // check if we can use the same connection for the followup
          if (!followup.getRoute().equals(roureq.getRoute())) {
            releaseConnection();
          }
          roureq = followup;
        }

        userToken = this.userTokenHandler.getUserToken(context);
        context.setAttribute(ClientContext.USER_TOKEN, userToken);
        if (managedConn != null) {
          managedConn.setState(userToken);
        }
      } // while not done

      // check for entity, release connection if possible
      if ((response == null)
          || (response.getEntity() == null)
          || !response.getEntity().isStreaming()) {
        // connection not needed and (assumed to be) in re-usable state
        if (reuse) managedConn.markReusable();
        releaseConnection();
      } else {
        // install an auto-release entity
        HttpEntity entity = response.getEntity();
        entity = new BasicManagedEntity(entity, managedConn, reuse);
        response.setEntity(entity);
      }

      return response;

    } catch (HttpException ex) {
      abortConnection();
      throw ex;
    } catch (IOException ex) {
      abortConnection();
      throw ex;
    } catch (RuntimeException ex) {
      abortConnection();
      throw ex;
    }
  } // execute
    @Override
    protected Result doRun(final BuildListener listener) throws Exception {
      PrintStream logger = listener.getLogger();
      try {
        EnvVars envVars = getEnvironment(listener);

        Config config = IvyConfig.provider.getConfigById(project.getSettings());
        if (config != null) {
          FilePath tmp = getWorkspace().createTextTempFile("ivy", "xml", config.content);
          settings = tmp.getRemote();
          addAction(new CleanTempFilesAction(settings));

        } else {
          String settingsFile = project.getIvySettingsFile();
          if (settingsFile != null) {
            settings = getWorkspace().child(settingsFile).getRemote();
          }
        }

        if (!project.isAggregatorStyleBuild()) {
          // start module builds
          parseIvyDescriptorFiles(listener, logger, envVars);
          Set<IvyModule> triggeredModules = new HashSet<IvyModule>();
          if (!project.isIncrementalBuild() || IvyModuleSetBuild.this.getChangeSet().isEmptySet()) {
            for (IvyModule module : project.sortedActiveModules) {
              // Don't trigger builds if we've already triggered
              // one
              // of their dependencies.
              // It's safe to just get the direct dependencies
              // since
              // the modules are sorted in dependency order.
              List<AbstractProject> ups = module.getUpstreamProjects();
              boolean triggerBuild = true;
              for (AbstractProject upstreamDep : ups) {
                if (triggeredModules.contains(upstreamDep)) {
                  triggerBuild = false;
                  break;
                }
              }

              if (triggerBuild) {
                logger.println("Triggering " + module.getModuleName());
                module.scheduleBuild(
                    new ParameterizedUpstreamCause(
                        ((Run<?, ?>) IvyModuleSetBuild.this),
                        IvyModuleSetBuild.this.getActions(ParametersAction.class)));
              }
              triggeredModules.add(module);
            }
          } else {
            for (IvyModule module : project.sortedActiveModules) {
              // If there are changes for this module, add it.
              // Also add it if we've never seen this module
              // before,
              // or if the previous build of this module
              // failed or was unstable.
              boolean triggerBuild = false;
              if ((module.getLastBuild() == null)
                  || (!getChangeSetFor(module).isEmpty())
                  || (module.getLastBuild().getResult().isWorseThan(Result.SUCCESS))) {
                triggerBuild = true;
                List<AbstractProject> ups = module.getUpstreamProjects();
                for (AbstractProject upstreamDep : ups) {
                  if (triggeredModules.contains(upstreamDep)) {
                    triggerBuild = false;
                    triggeredModules.add(module);
                    break;
                  }
                }
              }

              if (triggerBuild) {
                logger.println("Triggering " + module.getModuleName());
                module.scheduleBuild(
                    new ParameterizedUpstreamCause(
                        ((Run<?, ?>) IvyModuleSetBuild.this),
                        IvyModuleSetBuild.this.getActions(ParametersAction.class)));
                triggeredModules.add(module);
              }
            }
          }
        } else {
          // do builds here
          try {
            List<BuildWrapper> wrappers = new ArrayList<BuildWrapper>();
            for (BuildWrapper w : project.getBuildWrappersList()) wrappers.add(w);
            ParametersAction parameters = getAction(ParametersAction.class);
            if (parameters != null)
              parameters.createBuildWrappers(IvyModuleSetBuild.this, wrappers);

            for (BuildWrapper w : wrappers) {
              Environment e = w.setUp(IvyModuleSetBuild.this, launcher, listener);
              if (e == null) return Result.FAILURE;
              buildEnvironments.add(e);
              e.buildEnvVars(envVars); // #3502: too late for
              // getEnvironment to do
              // this
            }

            if (!preBuild(listener, project.getPublishers())) return Result.FAILURE;

            Properties additionalProperties = null;
            if (project.isIncrementalBuild()) {
              parseIvyDescriptorFiles(listener, logger, envVars);
              List<String> changedModules = new ArrayList<String>();
              for (IvyModule m : project.sortedActiveModules) {
                // Check if incrementalBuild is selected and that
                // there are changes -
                // we act as if incrementalBuild is not set if there
                // are no changes.
                if (!IvyModuleSetBuild.this.getChangeSet().isEmptySet()) {
                  // If there are changes for this module, add it.
                  if (!getChangeSetFor(m).isEmpty()) {
                    changedModules.add(m.getModuleName().name);
                  }
                }
              }

              if (project.isAggregatorStyleBuild()) {
                additionalProperties = new Properties();
                additionalProperties.put(
                    project.getChangedModulesProperty() == null
                        ? "hudson.ivy.changedModules"
                        : project.getChangedModulesProperty(),
                    StringUtils.join(changedModules, ','));
              }
            }

            IvyBuilderType ivyBuilderType = project.getIvyBuilderType();
            hudson.tasks.Builder builder =
                ivyBuilderType.getBuilder(additionalProperties, null, buildEnvironments);
            logger.println(
                "Building project with " + ivyBuilderType.getDescriptor().getDisplayName());

            if (builder.perform(IvyModuleSetBuild.this, launcher, listener)) return Result.SUCCESS;

            return Result.FAILURE;
          } finally {
            // tear down in reverse order
            boolean failed = false;
            for (int i = buildEnvironments.size() - 1; i >= 0; i--) {
              if (!buildEnvironments.get(i).tearDown(IvyModuleSetBuild.this, listener)) {
                failed = true;
              }
            }
            buildEnvironments = null;
            // WARNING The return in the finally clause will trump
            // any return before
            if (failed) return Result.FAILURE;
          }
        }

        return null;
      } catch (AbortException e) {
        if (e.getMessage() != null) listener.error(e.getMessage());
        return Result.FAILURE;
      } catch (InterruptedIOException e) {
        e.printStackTrace(listener.error("Aborted Ivy execution for InterruptedIOException"));
        return Result.ABORTED;
      } catch (InterruptedException e) {
        e.printStackTrace(listener.error("Aborted Ivy execution for InterruptedException"));
        return Result.ABORTED;
      } catch (IOException e) {
        e.printStackTrace(listener.error(Messages.IvyModuleSetBuild_FailedToParseIvyXml()));
        return Result.FAILURE;
      } catch (RunnerAbortedException e) {
        return Result.FAILURE;
      } catch (RuntimeException e) {
        // bug in the code.
        e.printStackTrace(
            listener.error(
                "Processing failed due to a bug in the code. Please report this to [email protected]"));
        logger.println("project=" + project);
        logger.println("project.getModules()=" + project.getModules());
        throw e;
      }
    }
Exemple #19
0
  protected boolean execStreamConnect(Properties props) {
    if (props == null) {
      _log.debug("No parameters specified in STREAM CONNECT message");
      return false;
    }

    int id;
    {
      String strid = props.getProperty("ID");
      if (strid == null) {
        _log.debug("ID not specified in STREAM SEND message");
        return false;
      }
      try {
        id = Integer.parseInt(strid);
      } catch (NumberFormatException e) {
        _log.debug("Invalid STREAM CONNECT ID specified: " + strid);
        return false;
      }
      if (id < 1) {
        _log.debug("Invalid STREAM CONNECT ID specified: " + strid);
        return false;
      }
      props.remove("ID");
    }

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

    try {
      try {
        if (!getStreamSession().connect(id, dest, props)) {
          _log.debug("STREAM connection failed");
          return false;
        }
      } catch (DataFormatException e) {
        _log.debug("Invalid destination in STREAM CONNECT message");
        notifyStreamOutgoingConnection(id, "INVALID_KEY", null);
      } catch (SAMInvalidDirectionException e) {
        _log.debug("STREAM CONNECT failed: " + e.getMessage());
        notifyStreamOutgoingConnection(id, "INVALID_DIRECTION", null);
      } catch (ConnectException e) {
        _log.debug("STREAM CONNECT failed: " + e.getMessage());
        notifyStreamOutgoingConnection(id, "CONNECTION_REFUSED", null);
      } catch (NoRouteToHostException e) {
        _log.debug("STREAM CONNECT failed: " + e.getMessage());
        notifyStreamOutgoingConnection(id, "CANT_REACH_PEER", null);
      } catch (InterruptedIOException e) {
        _log.debug("STREAM CONNECT failed: " + e.getMessage());
        notifyStreamOutgoingConnection(id, "TIMEOUT", null);
      } catch (I2PException e) {
        _log.debug("STREAM CONNECT failed: " + e.getMessage());
        notifyStreamOutgoingConnection(id, "I2P_ERROR", null);
      }
    } catch (IOException e) {
      return false;
    }

    return true;
  }
  public void handle() {
    String msg = null;
    String domain = null;
    String opcode = null;
    boolean canContinue = false;
    StringTokenizer tok;
    Properties props;

    this.thread.setName("SAMv3Handler " + _id);
    _log.debug("SAM handling started");

    try {
      InputStream in = getClientSocket().socket().getInputStream();

      while (true) {
        if (shouldStop()) {
          _log.debug("Stop request found");
          break;
        }
        String line = DataHelper.readLine(in);
        if (line == null) {
          _log.debug("Connection closed by client (line read : null)");
          break;
        }
        msg = line.trim();

        if (_log.shouldLog(Log.DEBUG)) {
          _log.debug("New message received: [" + msg + "]");
        }

        if (msg.equals("")) {
          _log.debug("Ignoring newline");
          continue;
        }

        tok = new StringTokenizer(msg, " ");
        if (tok.countTokens() < 2) {
          // This is not a correct message, for sure
          _log.debug("Error in message format");
          break;
        }
        domain = tok.nextToken();
        opcode = tok.nextToken();
        if (_log.shouldLog(Log.DEBUG)) {
          _log.debug("Parsing (domain: \"" + domain + "\"; opcode: \"" + opcode + "\")");
        }
        props = SAMUtils.parseParams(tok);

        if (domain.equals("STREAM")) {
          canContinue = execStreamMessage(opcode, props);
        } else if (domain.equals("SESSION")) {
          if (i2cpProps != null) props.putAll(i2cpProps); // make sure we've got the i2cp settings
          canContinue = execSessionMessage(opcode, props);
        } else if (domain.equals("DEST")) {
          canContinue = execDestMessage(opcode, props);
        } else if (domain.equals("NAMING")) {
          canContinue = execNamingMessage(opcode, props);
        } else if (domain.equals("DATAGRAM")) {
          canContinue = execDatagramMessage(opcode, props);
        } else {
          _log.debug("Unrecognized message domain: \"" + domain + "\"");
          break;
        }

        if (!canContinue) {
          break;
        }
      }
    } catch (IOException e) {
      _log.debug("Caught IOException (" + e.getMessage() + ") for message [" + msg + "]", e);
    } catch (Exception e) {
      _log.error("Unexpected exception for message [" + msg + "]", e);
    } finally {
      _log.debug("Stopping handler");

      if (!this.stolenSocket) {
        try {
          closeClientSocket();
        } catch (IOException e) {
          _log.error("Error closing socket: " + e.getMessage());
        }
      }
      if (streamForwardingSocket) {
        if (this.getStreamSession() != null) {
          try {
            this.streamSession.stopForwardingIncoming();
          } catch (SAMException e) {
            _log.error("Error while stopping forwarding connections: " + e.getMessage());
          } catch (InterruptedIOException e) {
            _log.error("Interrupted while stopping forwarding connections: " + e.getMessage());
          }
        }
      }

      die();
    }
  }
Exemple #21
0
  public static void main(String[] args) {

    int retry = 2;
    int port = 123;
    int timeout = 3000;

    // get the address and NTP address request
    InetAddress ipv4Addr = null;
    try {
      ipv4Addr = InetAddress.getByName("133.100.11.8");
    } catch (UnknownHostException e1) {
      e1.printStackTrace();
      return;
    }

    int serviceStatus = -1;
    DatagramSocket socket = null;
    long responseTime = -1;
    try {
      socket = new DatagramSocket();
      socket.setSoTimeout(timeout); // will force the InterruptedIOException

      for (int attempts = 0; attempts <= retry && serviceStatus != 1; attempts++) {
        try {
          // Send NTP request
          byte[] data = new NtpMessage().toByteArray();
          DatagramPacket outgoing = new DatagramPacket(data, data.length, ipv4Addr, port);
          long sentTime = System.currentTimeMillis();
          socket.send(outgoing);

          // Get NTP Response
          // byte[] buffer = new byte[512];
          DatagramPacket incoming = new DatagramPacket(data, data.length);
          socket.receive(incoming);
          responseTime = System.currentTimeMillis() - sentTime;
          double destinationTimestamp = (System.currentTimeMillis() / 1000.0) + 2208988800.0;
          // 这里要加2208988800,是因为获得到的时间是格林尼治时间,所以要变成东八区的时间,否则会与与北京时间有8小时的时差

          // Validate NTP Response
          // IOException thrown if packet does not decode as expected.
          NtpMessage msg = new NtpMessage(incoming.getData());
          double localClockOffset =
              ((msg.receiveTimestamp - msg.originateTimestamp)
                      + (msg.transmitTimestamp - destinationTimestamp))
                  / 2;

          System.out.println(
              "poll: valid NTP request received the local clock offset is "
                  + localClockOffset
                  + ", responseTime= "
                  + responseTime
                  + "ms");
          System.out.println("poll: NTP message : " + msg.toString());
          serviceStatus = 1;
        } catch (InterruptedIOException ex) {
          // Ignore, no response received.
          System.out.println("InterruptedIOException: " + ex.getMessage());
        }
      }
    } catch (NoRouteToHostException e) {
      System.out.println("No route to host exception for address: " + ipv4Addr);
    } catch (ConnectException e) {
      // Connection refused. Continue to retry.
      e.fillInStackTrace();
      System.out.println("Connection exception for address: " + ipv4Addr);
    } catch (IOException ex) {
      ex.fillInStackTrace();
      System.out.println("IOException while polling address: " + ipv4Addr);
    } finally {
      if (socket != null) socket.close();
    }

    // Store response time if available
    if (serviceStatus == 1) {
      System.out.println("responsetime==" + responseTime);
    }
  }
Exemple #22
0
    public void run() {

      try {
        // 1.建立客户端socket连接,指定服务器位置及端口
        socket = new Socket("s.doit.am", 8810);
        socket.setSoTimeout(5000);
        // 2.得到socket读写流
        OutputStream os = socket.getOutputStream();
        PrintWriter pw = new PrintWriter(os);
        // 输入流
        is = socket.getInputStream();
        br = new BufferedReader(new InputStreamReader(is));
        // 3.利用流按照一定的操作,对socket进行读写操作

        String info =
            "cmd=m2m_chat&device_id=" + id + "&device_key=" + key + "&topic=" + id + "_chat\r\n";
        pw.write(info);
        pw.flush();
        //    		            socket.shutdownOutput();

        String reply = null;
        while (!((reply = br.readLine()) == null)) {
          int index = reply.indexOf("res=");
          if (index != -1) {
            String res = reply.substring(index + 4, index + 5);
            if (res.equals("1")) {

              Message msg = new Message();
              msg.what = 1;
              myHandler.sendMessage(msg);

              keep_run = true;

              break;
            } else {
              Message msg = new Message();
              msg.what = -1;
              myHandler.sendMessage(msg);

              keep_run = false;
            }
          }
        }

        //    		            socket.close();
      } catch (InterruptedIOException e) {
        e.printStackTrace();
      } catch (IOException e) {
        keep_run = false;
        e.printStackTrace();
      }

      if (keep_run) {
        while (bRun) {
          try {
            Thread.sleep(1000);
          } catch (Exception e) {
            e.printStackTrace();
          }

          try {
            //      		     			    InputStream is=socket.getInputStream();
            //      	    		            BufferedReader br=new BufferedReader(new
            // InputStreamReader(is));
            String reply = null;
            while (!((reply = br.readLine()) == null)) {
              int index = reply.indexOf("message=");
              if (index != -1) {
                he_text = reply.substring(index + 8);
                Message msg2 = new Message();
                msg2.what = 2;
                myHandler.sendMessage(msg2);
              }
            }
          } catch (InterruptedIOException e) {
            e.printStackTrace();
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      }
    }