Esempio n. 1
1
  private void loop() {
    while (thread == Thread.currentThread()) {
      try {
        Request key = peekKey();
        if (key == null) throw new IOException("end of stream");
        synchronized (response_map) {
          Response response = (Response) response_map.get(key);
          if (response == null) {
            if (log.level >= 4) log.println("Invalid key, skipping message");
            doSkip();
          } else {
            doRecv(response);
            response.isReceived = true;
            response_map.notifyAll();
          }
        }
      } catch (Exception ex) {
        String msg = ex.getMessage();
        boolean timeout = msg != null && msg.equals("Read timed out");
        /* If just a timeout, try to disconnect gracefully
         */
        boolean hard = timeout == false;

        if (!timeout && log.level >= 3) ex.printStackTrace(log);

        try {
          disconnect(hard);
        } catch (IOException ioe) {
          ioe.printStackTrace(log);
        }
      }
    }
  }
  /**
   * Validates a specified template.
   *
   * @param validateTemplateRequest The input for <a>ValidateTemplate</a> action.
   * @return Result of the ValidateTemplate operation returned by the service.
   * @sample AmazonCloudFormation.ValidateTemplate
   */
  @Override
  public ValidateTemplateResult validateTemplate(ValidateTemplateRequest validateTemplateRequest) {
    ExecutionContext executionContext = createExecutionContext(validateTemplateRequest);
    AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
    awsRequestMetrics.startEvent(Field.ClientExecuteTime);
    Request<ValidateTemplateRequest> request = null;
    Response<ValidateTemplateResult> response = null;

    try {
      awsRequestMetrics.startEvent(Field.RequestMarshallTime);
      try {
        request =
            new ValidateTemplateRequestMarshaller()
                .marshall(super.beforeMarshalling(validateTemplateRequest));
        // Binds the request metrics to the current request.
        request.setAWSRequestMetrics(awsRequestMetrics);
      } finally {
        awsRequestMetrics.endEvent(Field.RequestMarshallTime);
      }

      StaxResponseHandler<ValidateTemplateResult> responseHandler =
          new StaxResponseHandler<ValidateTemplateResult>(
              new ValidateTemplateResultStaxUnmarshaller());
      response = invoke(request, responseHandler, executionContext);

      return response.getAwsResponse();

    } finally {

      endClientExecution(awsRequestMetrics, request, response);
    }
  }
Esempio n. 3
0
  public void doCall(String method, Object value) throws Exception {
    Call call = new Call();
    call.setTargetObjectURI("http://soapinterop.org/");
    call.setMethodName(method);
    call.setEncodingStyleURI(encodingStyleURI);

    Vector params = new Vector();
    params.addElement(new Parameter("in", value.getClass(), value, null));
    call.setParams(params);

    // make the call: note that the action URI is empty because the
    // XML-SOAP rpc router does not need this. This may change in the
    // future.
    Response resp = call.invoke(url, "");

    // Check the response.
    if (resp.generatedFault()) {
      Fault fault = resp.getFault();
      System.out.println("Ouch, the call failed: ");
      System.out.println("  Fault Code   = " + fault.getFaultCode());
      System.out.println("  Fault String = " + fault.getFaultString());
    } else {
      Parameter result = resp.getReturnValue();
      System.out.println("Call succeeded: ");
      System.out.println("Result = " + result.getValue());
    }
  }
Esempio n. 4
0
  public Integer handleResponse(ESXX esxx, Context cx, Response response) throws Exception {
    // Output HTTP headers
    final PrintWriter out = new PrintWriter(createWriter(outStream, "US-ASCII"));

    out.println("Status: " + response.getStatus());
    out.println("Content-Type: " + response.getContentType(true));

    response.enumerateHeaders(
        new Response.HeaderEnumerator() {
          public void header(String name, String value) {
            out.println(name + ": " + value);
          }
        });

    out.println();
    out.flush();

    response.writeResult(esxx, cx, outStream);

    getErrorWriter().flush();
    getDebugWriter().flush();
    outStream.flush();

    return 0;
  }
  /**
   * You use this operation to change the parameters specified in the original manifest file by
   * supplying a new manifest file. The manifest file attached to this request replaces the original
   * manifest file. You can only use the operation after a CreateJob request but before the data
   * transfer starts and you can only use it on jobs you own.
   *
   * @param updateJobRequest Container for the necessary parameters to execute the UpdateJob service
   *     method on AmazonImportExport.
   * @return The response from the UpdateJob service method, as returned by AmazonImportExport.
   * @throws MalformedManifestException
   * @throws BucketPermissionException
   * @throws InvalidAddressException
   * @throws InvalidParameterException
   * @throws UnableToUpdateJobIdException
   * @throws MultipleRegionsException
   * @throws InvalidVersionException
   * @throws MissingParameterException
   * @throws InvalidFileSystemException
   * @throws CanceledJobIdException
   * @throws MissingCustomsException
   * @throws NoSuchBucketException
   * @throws ExpiredJobIdException
   * @throws InvalidAccessKeyIdException
   * @throws InvalidCustomsException
   * @throws InvalidManifestFieldException
   * @throws MissingManifestFieldException
   * @throws InvalidJobIdException
   * @throws AmazonClientException If any internal errors are encountered inside the client while
   *     attempting to make the request or handle the response. For example if a network connection
   *     is not available.
   * @throws AmazonServiceException If an error response is returned by AmazonImportExport
   *     indicating either a problem with the data in the request, or a server side issue.
   */
  public UpdateJobResult updateJob(UpdateJobRequest updateJobRequest) {
    ExecutionContext executionContext = createExecutionContext(updateJobRequest);
    AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
    awsRequestMetrics.startEvent(Field.ClientExecuteTime);
    Request<UpdateJobRequest> request = null;
    Response<UpdateJobResult> response = null;

    try {
      awsRequestMetrics.startEvent(Field.RequestMarshallTime);
      try {
        request =
            new UpdateJobRequestMarshaller().marshall(super.beforeMarshalling(updateJobRequest));
        // Binds the request metrics to the current request.
        request.setAWSRequestMetrics(awsRequestMetrics);
      } finally {
        awsRequestMetrics.endEvent(Field.RequestMarshallTime);
      }

      response = invoke(request, new UpdateJobResultStaxUnmarshaller(), executionContext);
      return response.getAwsResponse();

    } finally {

      endClientExecution(awsRequestMetrics, request, response);
    }
  }
Esempio n. 6
0
 public void sendrecv(Request request, Response response, long timeout) throws IOException {
   synchronized (response_map) {
     makeKey(request);
     response.isReceived = false;
     try {
       response_map.put(request, response);
       doSend(request);
       response.expiration = System.currentTimeMillis() + timeout;
       while (!response.isReceived) {
         response_map.wait(timeout);
         timeout = response.expiration - System.currentTimeMillis();
         if (timeout <= 0) {
           throw new TransportException(name + " timedout waiting for response to " + request);
         }
       }
     } catch (IOException ioe) {
       if (log.level > 2) ioe.printStackTrace(log);
       try {
         disconnect(true);
       } catch (IOException ioe2) {
         ioe2.printStackTrace(log);
       }
       throw ioe;
     } catch (InterruptedException ie) {
       throw new TransportException(ie);
     } finally {
       response_map.remove(request);
     }
   }
 }
  public Response call(DB db, DBCollection coll, OutMessage m, int retries) throws MongoException {

    final MyPort mp = _threadPort.get();
    final DBPort port = mp.get(false);

    port.checkAuth(db);

    Response res = null;
    try {
      res = port.call(m, coll);
      mp.done(port);
    } catch (IOException ioe) {
      mp.error(ioe);
      if (_error(ioe) && retries > 0) {
        return call(db, coll, m, retries - 1);
      }
      throw new MongoException.Network("can't call something", ioe);
    } catch (RuntimeException re) {
      mp.error(re);
      throw re;
    }

    ServerError err = res.getError();

    if (err != null && err.isNotMasterError()) {
      _pickCurrent();
      if (retries <= 0) {
        throw new MongoException("not talking to master and retries used up");
      }
      return call(db, coll, m, retries - 1);
    }

    return res;
  }
Esempio n. 8
0
 public void setErrResponse(Exception ex, Response response) {
   if (ex instanceof java.sql.SQLException
       || ex instanceof com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException
       || ex instanceof org.springframework.jdbc.BadSqlGrammarException
       || ex instanceof org.springframework.dao.InvalidDataAccessApiUsageException
       || ex instanceof org.springframework.dao.DataAccessException
       || ex instanceof org.springframework.web.util.NestedServletException
       || ex
           instanceof com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException) {
     response.setResponseMsg(ex.getMessage());
     response.setResponseStatus(ConstException.ERR_CODE_DB_ERROR);
   } else if (ex instanceof java.lang.NullPointerException) {
     response.setResponseMsg(ex.getMessage());
     response.setResponseStatus(ConstException.ERR_CODE_UNKNOWN);
   } else if (ex instanceof ConstException) {
     ConstException constException = (ConstException) ex;
     response.setResponseMsg(constException.getMessage());
     response.setResponseStatus(constException.getCode());
   } else if (ex instanceof java.lang.IllegalThreadStateException) {
     response.setResponseMsg(ex.getMessage());
     response.setResponseStatus(ConstException.ERR_CODE_INVALID_THREAD_STOP);
   } else {
     setErrResponse(ex, response, ConstException.ERR_CODE_UNKNOWN);
   }
 }
Esempio n. 9
0
  /**
   * Receives options requests and replies with an OK response containing methods that we support.
   *
   * @param requestEvent the incoming options request.
   * @return <tt>true</tt> if request has been successfully processed, <tt>false</tt> otherwise
   */
  @Override
  public boolean processRequest(RequestEvent requestEvent) {
    Response optionsOK = null;
    try {
      optionsOK =
          provider.getMessageFactory().createResponse(Response.OK, requestEvent.getRequest());

      // add to the allows header all methods that we support
      for (String method : provider.getSupportedMethods()) {
        // don't support REGISTERs
        if (!method.equals(Request.REGISTER))
          optionsOK.addHeader(provider.getHeaderFactory().createAllowHeader(method));
      }

      Iterable<String> knownEventsList = provider.getKnownEventsList();

      synchronized (knownEventsList) {
        for (String event : knownEventsList)
          optionsOK.addHeader(provider.getHeaderFactory().createAllowEventsHeader(event));
      }
    } catch (ParseException ex) {
      // What else could we do apart from logging?
      logger.warn("Failed to create an incoming OPTIONS request", ex);
      return false;
    }

    try {
      SipStackSharing.getOrCreateServerTransaction(requestEvent).sendResponse(optionsOK);
    } catch (TransactionUnavailableException ex) {
      // this means that we received an OPTIONS request outside the scope
      // of a transaction which could mean that someone is simply sending
      // us b****hit to keep a NAT connection alive, so let's not get too
      // excited.
      if (logger.isInfoEnabled())
        logger.info("Failed to respond to an incoming " + "transactionless OPTIONS request");
      if (logger.isTraceEnabled()) logger.trace("Exception was:", ex);
      return false;
    } catch (InvalidArgumentException ex) {
      // What else could we do apart from logging?
      logger.warn("Failed to send an incoming OPTIONS request", ex);
      return false;
    } catch (SipException ex) {
      // What else could we do apart from logging?
      logger.warn("Failed to send an incoming OPTIONS request", ex);
      return false;
    }

    return true;
  }
 /**
  * Creates a stack as specified in the template. After the call completes successfully, the stack
  * creation starts. You can check the status of the stack via the DescribeStacks API.
  *
  * @param createStackRequest Container for the necessary parameters to execute the CreateStack
  *     service method on AmazonCloudFormation.
  * @return The response from the CreateStack service method, as returned by AmazonCloudFormation.
  * @throws AlreadyExistsException
  * @throws LimitExceededException
  * @throws InsufficientCapabilitiesException
  * @throws AmazonClientException If any internal errors are encountered inside the client while
  *     attempting to make the request or handle the response. For example if a network connection
  *     is not available.
  * @throws AmazonServiceException If an error response is returned by AmazonCloudFormation
  *     indicating either a problem with the data in the request, or a server side issue.
  */
 public CreateStackResult createStack(CreateStackRequest createStackRequest) {
   ExecutionContext executionContext = createExecutionContext(createStackRequest);
   AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
   Request<CreateStackRequest> request = null;
   Response<CreateStackResult> response = null;
   awsRequestMetrics.startEvent(Field.ClientExecuteTime);
   try {
     request = new CreateStackRequestMarshaller().marshall(createStackRequest);
     // Binds the request metrics to the current request.
     request.setAWSRequestMetrics(awsRequestMetrics);
     response = invoke(request, new CreateStackResultStaxUnmarshaller(), executionContext);
     return response.getAwsResponse();
   } finally {
     endClientExecution(awsRequestMetrics, request, response);
   }
 }
Esempio n. 11
0
 /**
  * * sendResponse checks for the mode of the server and sends a Response object to the client with
  * the appropriate string stored and the client's Cookie.
  *
  * @param clientCookie - Cookie object received by client
  * @param responseToClient - Response object that will be sent to client
  * @param outputObject - Used to write serialized version of object back to client
  * @throws IOException - Thrown if outputObject is interrupted while processing or fails to
  *     process
  */
 static void sendResponse(
     Cookie clientCookie, Response responseToClient, ObjectOutputStream outputObject)
     throws IOException {
   if (mode.getMode() == ServerMode.JOKE) { // If the mode of the server is set to JOKE, send joke
     responseToClient.addResponse(
         joke.say(
             clientCookie
                 .getJokeKey())); // gets joke from Database and stores string in responseToClient
     clientCookie.nextJoke(); // clientCookie increments the index of the joke to be accessed later
     responseToClient.setCookie(clientCookie); // stores clientCookie in responseToClient
     System.out.println("Sending joke response..."); // notify server joke is being sent
     outputObject.writeObject(
         responseToClient); // send a serialized version of Response object to client
   } else if (mode.getMode()
       == ServerMode.PROVERB) { // If the mode of the server is set to PROVERB, send proverb
     responseToClient.addResponse(proverb.say(clientCookie.getProverbKey()));
     clientCookie.nextProverb();
     responseToClient.setCookie(clientCookie);
     System.out.println("Sending proverb response...");
     outputObject.writeObject(
         responseToClient); // send Response object with proverb and client's Cookie to the client
   } else if (mode.getMode()
       == ServerMode
           .MAINTENANCE) { // If the mode of the server is set to MAINTENANCE, notify clients
                           // server is down for maintenance
     responseToClient.addResponse("Joke server temporarily down for maintenance.\n");
     responseToClient.setCookie(clientCookie);
     System.out.println("Sending maintenance response...");
     outputObject.writeObject(
         responseToClient); // send Response object with maintenance message and client's Cookie to
                            // the client
   }
 }
Esempio n. 12
0
 public void setSuccessResponse(Response response, Object data) {
   response.setResponseStatus(ConstException.ERR_CODE_SUCCESS);
   response.setResponseMsg(ConstException.ERR_MSG_SUCCESS);
   response.setResponseData(data);
 }
Esempio n. 13
0
 public void setErrResponse(Exception ex, Response response, int errCode) {
   ConstException constException = (ConstException) ex;
   response.setResponseMsg(constException.getMessage());
   response.setResponseStatus(constException.getCode());
 }