private static synchronized void retrieveTestAccountsForAppIfNeeded() {
    if (appTestAccounts != null) {
      return;
    }

    appTestAccounts = new HashMap<String, TestAccount>();

    // The data we need is split across two different FQL tables. We construct two queries, submit
    // them
    // together (the second one refers to the first one), then cross-reference the results.

    // Get the test accounts for this app.
    String testAccountQuery =
        String.format(
            "SELECT id,access_token FROM test_account WHERE app_id = %s", testApplicationId);
    // Get the user names for those accounts.
    String userQuery = "SELECT uid,name FROM user WHERE uid IN (SELECT id FROM #test_accounts)";

    Bundle parameters = new Bundle();

    // Build a JSON string that contains our queries and pass it as the 'q' parameter of the query.
    JSONObject multiquery;
    try {
      multiquery = new JSONObject();
      multiquery.put("test_accounts", testAccountQuery);
      multiquery.put("users", userQuery);
    } catch (JSONException exception) {
      throw new FacebookException(exception);
    }
    parameters.putString("q", multiquery.toString());

    // We need to authenticate as this app.
    parameters.putString("access_token", getAppAccessToken());

    Request request = new Request(null, "fql", parameters, null);
    Response response = request.executeAndWait();

    if (response.getError() != null) {
      throw response.getError().getException();
    }

    FqlResponse fqlResponse = response.getGraphObjectAs(FqlResponse.class);

    GraphObjectList<FqlResult> fqlResults = fqlResponse.getData();
    if (fqlResults == null || fqlResults.size() != 2) {
      throw new FacebookException("Unexpected number of results from FQL query");
    }

    // We get back two sets of results. The first is from the test_accounts query, the second from
    // the users query.
    Collection<TestAccount> testAccounts =
        fqlResults.get(0).getFqlResultSet().castToListOf(TestAccount.class);
    Collection<UserAccount> userAccounts =
        fqlResults.get(1).getFqlResultSet().castToListOf(UserAccount.class);

    // Use both sets of results to populate our static array of accounts.
    populateTestAccounts(testAccounts, userAccounts);

    return;
  }
  private Request createRequest(
      Location location,
      int radiusInMeters,
      int resultsLimit,
      String searchText,
      Set<String> extraFields,
      Session session) {
    Request request =
        Request.newPlacesSearchRequest(
            session, location, radiusInMeters, resultsLimit, searchText, null);

    Set<String> fields = new HashSet<String>(extraFields);
    String[] requiredFields = new String[] {ID, NAME, LOCATION, CATEGORY, WERE_HERE_COUNT};
    fields.addAll(Arrays.asList(requiredFields));

    String pictureField = adapter.getPictureFieldSpecifier();
    if (pictureField != null) {
      fields.add(pictureField);
    }

    Bundle parameters = request.getParameters();
    parameters.putString("fields", TextUtils.join(",", fields));
    request.setParameters(parameters);

    return request;
  }
  /**
   * maintains a list of last <i>committedLog</i> or so committed requests. This is used for fast
   * follower synchronization.
   *
   * @param request committed request
   */
  public void addCommittedProposal(Request request) {
    WriteLock wl = logLock.writeLock();
    try {
      wl.lock();
      if (committedLog.size() > commitLogCount) {
        committedLog.removeFirst();
        minCommittedLog = committedLog.getFirst().packet.getZxid();
      }
      if (committedLog.isEmpty()) {
        minCommittedLog = request.zxid;
        maxCommittedLog = request.zxid;
      }

      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      BinaryOutputArchive boa = BinaryOutputArchive.getArchive(baos);
      try {
        request.getHdr().serialize(boa, "hdr");
        if (request.getTxn() != null) {
          request.getTxn().serialize(boa, "txn");
        }
        baos.close();
      } catch (IOException e) {
        LOG.error("This really should be impossible", e);
      }
      QuorumPacket pp = new QuorumPacket(Leader.PROPOSAL, request.zxid, baos.toByteArray(), null);
      Proposal p = new Proposal();
      p.packet = pp;
      p.request = request;
      committedLog.add(p);
      maxCommittedLog = p.packet.getZxid();
    } finally {
      wl.unlock();
    }
  }
Example #4
0
 @Override
 public DbFuture<PreparedUpdate> prepareUpdate(String sql) {
   checkClosed();
   final Request request = requestCreator.executePrepareUpdate(sql);
   queRequest(request);
   return (DbFuture<PreparedUpdate>) request.getToComplete();
 }
Example #5
0
  private void onOK() {
    if (!isValidInput()) {
      return;
    }
    dispose();
    String firstName = firstNameField.getText().trim();
    String lastName = lastNameField.getText().trim();
    String emailAddress = emailAddressField.getText().trim();
    SexOfPerson sexOfPerson;
    if (femaleRadioButton.isSelected()) {
      sexOfPerson = SexOfPerson.FEMALE;
    } else {
      sexOfPerson = SexOfPerson.MALE;
    }
    String country = (String) countryComboBox.getSelectedObject();
    Integer birthdayYear = (Integer) birthdayYearComboBox.getSelectedItem();
    Month birthdayMonth = (Month) birthdayMonthComboBox.getSelectedItem();
    Integer birthdayDay = (Integer) birthdayDayComboBox.getSelectedItem();
    char[] passwordArr = passwordField.getPassword();
    String password = new String(passwordArr);
    Arrays.fill(passwordArr, (char) 0);
    Image profilePicture = null;
    if (imageFromFileRadioButton.isSelected()) {
      if (fileSelector.getFilePath() != null) {
        profilePicture = new FileImage(fileSelector.getFilePath());
      }
    }
    Request request =
        new CreateUserRequest(
            communicator.getHttpClient(),
            frame,
            firstName,
            lastName,
            emailAddress,
            sexOfPerson,
            country,
            birthdayYear,
            birthdayMonth,
            birthdayDay,
            password,
            profilePicture) {

          @Override
          protected void onCreateUser(String status, Person person) {
            if (status.equals("INVALID_PROFILE_PICTURE")) {
              communicator.promptForCreateAccount("Invalid profile picture");
            } else if (status.equals("ERROR_CREATING_USER")) {
              communicator.promptForCreateAccount("Error creating user");
            } else if (status.equals("CONNECTION_ERROR")) {
              communicator.promptForCreateAccount("Error connecting to Modeling Commons");
            } else if (status.equals("SUCCESS")) {
              communicator.setPerson(person);
              communicator.promptForUpload();
            } else {
              communicator.promptForCreateAccount("Unknown server error");
            }
          }
        };
    request.execute();
  }
  /**
   * 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);
    }
  }
Example #7
0
  public static void zhongbiao(Long id) {
    Toubiao toubiao = Toubiao.findById(id);
    toubiao.status = "1";
    toubiao.save();
    Request request = toubiao.request;
    request.status = 1;
    request.zb = true;
    request.save();
    List<Toubiao> toubiaos = Toubiao.find("request.id=? and id!=?", request.id, id).fetch();
    for (Toubiao tb : toubiaos) {
      tb.status = "2";
      tb.save();
    }
    Config config = Config.find("1=1").first();
    String message = "";
    SendMessage m = new SendMessage();
    message = "您已中标" + toubiao.request.name + "项目,请按时发货";
    if (config.msg_request_invite != null && !"".equals(config.msg_request_invite)) {
      message = config.msg_request_notification.replace("{request}", toubiao.request.name);
    }
    Profile p = toubiao.profile;
    if (p.contact_phone != null && !"".equals(p.contact_phone))
      m.sendSms(p.contact_phone, message, "0000003");
    if (p.contact_email != null && !"".equals(p.contact_email))
      m.sendMail(p.contact_email, "[" + Messages.get("application.name") + "]中标通知", message);

    redirect("/admin/requests");
  }
Example #8
0
  public static void logout(final Callback<Boolean> callback) {
    HashMap<String, String> parameter = new HashMap<>();
    parameter.put("token", getTokenAsString());

    Request<Boolean> request =
        new Request<>(
            HttpVerb.POST,
            serverUrl + "/public/logout",
            Boolean.class,
            parameter,
            new Callback<Boolean>() {
              @Override
              public void onCompletion(Boolean input) {
                if (input) {
                  token = null;
                }
                callback.onCompletion(input);
              }

              @Override
              public void onError(String message) {
                token = null;
                callback.onError(message);
              }
            });
    request.execute();
  }
Example #9
0
  public static void register(
      String mail,
      String password,
      String name,
      String studentenNumber,
      final Callback<Boolean> callback) {
    HashMap<String, String> parameter = new HashMap<>();
    parameter.put("email", mail);
    parameter.put("password", password);
    parameter.put("name", name);
    parameter.put("studentnumber", studentenNumber);

    Request<Boolean> request =
        new Request<>(
            HttpVerb.POST,
            serverUrl + "/public/register",
            Boolean.class,
            parameter,
            new Callback<Boolean>() {
              @Override
              public void onCompletion(Boolean input) {
                callback.onCompletion(input);
              }

              @Override
              public void onError(String message) {
                callback.onError(message);
              }
            });
    request.execute();
  }
Example #10
0
  public static void reserveGadget(Gadget toReserve, final Callback<Boolean> callback) {
    if (token == null) {
      throw new IllegalStateException("Not logged in");
    }
    HashMap<String, String> parameter = new HashMap<>();
    parameter.put("token", getTokenAsString());
    parameter.put("gadgetId", toReserve.getInventoryNumber());

    Request<Boolean> request =
        new Request<>(
            HttpVerb.POST,
            serverUrl + "/public/reservations",
            new TypeToken<Boolean>() {}.getType(),
            parameter,
            new Callback<Boolean>() {
              @Override
              public void onCompletion(Boolean success) {
                callback.onCompletion(success);
              }

              @Override
              public void onError(String message) {
                callback.onError(message);
              }
            });
    request.execute();
  }
Example #11
0
  public static void deleteReservation(Reservation toDelete, final Callback<Boolean> callback) {
    if (token == null) {
      throw new IllegalStateException("Not logged in");
    }
    HashMap<String, String> parameter = new HashMap<>();
    parameter.put("token", getTokenAsString());
    parameter.put("id", toDelete.getReservationId());
    Request<Boolean> request =
        new Request<>(
            HttpVerb.DELETE,
            serverUrl + "/public/reservations",
            Boolean.class,
            parameter,
            new Callback<Boolean>() {
              @Override
              public void onCompletion(Boolean input) {
                callback.onCompletion(input);
              }

              @Override
              public void onError(String message) {
                callback.onError(message);
              }
            });
    request.execute();
  }
 // Ensures that reply field is non-null
 //
 private void build() throws IOException {
   Request.Action action = request.action();
   if ((action != Request.Action.GET) && (action != Request.Action.HEAD)) {
     reply = new Reply(Reply.Code.METHOD_NOT_ALLOWED, new StringContent(request.toString()));
   }
   reply = new Reply(Reply.Code.OK, new FileContent(request.uri()), action);
 }
  /**
   * Writes an array of bytes on the stream. This method may not be used until this stream has been
   * passed to one of the methods in HTTPConnection (i.e. until it has been associated with a
   * request).
   *
   * @param buf an array containing the data to write
   * @param off the offset of the data whithin the buffer
   * @param len the number bytes (starting at <var>off</var>) to write
   * @exception IOException if any exception is thrown by the socket, or if writing <var>len</var>
   *     bytes would cause more bytes to be written than this stream is willing to accept.
   * @exception IllegalAccessError if this stream has not been associated with a request yet
   */
  public synchronized void write(byte[] buf, int off, int len)
      throws IOException, IllegalAccessError {
    if (req == null) throw new IllegalAccessError("Stream not associated with a request");

    if (ignore) return;

    if (length != -1 && rcvd + len > length) {
      IOException ioe =
          new IOException("Tried to write too many bytes (" + (rcvd + len) + " > " + length + ")");
      req.getConnection().closeDemux(ioe, false);
      req.getConnection().outputFinished();
      throw ioe;
    }

    try {
      if (bos != null) bos.write(buf, off, len);
      else if (length != -1) os.write(buf, off, len);
      else os.write(Codecs.chunkedEncode(buf, off, len, null, false));
    } catch (IOException ioe) {
      req.getConnection().closeDemux(ioe, true);
      req.getConnection().outputFinished();
      throw ioe;
    }

    rcvd += len;
  }
 public void handleRequest(Request request) {
   if (request.getValue() >= 0) {
     System.out.println("Zero values are handled by HandlerThree:");
     System.out.println(
         "HandlerThree.HandleRequest : " + request.getDescription() + request.getValue());
   }
 }
  private <X, Y extends AmazonWebServiceRequest> Response<X> invoke(
      Request<Y> request,
      HttpResponseHandler<AmazonWebServiceResponse<X>> responseHandler,
      ExecutionContext executionContext) {
    request.setEndpoint(endpoint);
    request.setTimeOffset(timeOffset);

    AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
    AWSCredentials credentials;
    awsRequestMetrics.startEvent(Field.CredentialsRequestTime);
    try {
      credentials = awsCredentialsProvider.getCredentials();
    } finally {
      awsRequestMetrics.endEvent(Field.CredentialsRequestTime);
    }

    AmazonWebServiceRequest originalRequest = request.getOriginalRequest();
    if (originalRequest != null && originalRequest.getRequestCredentials() != null) {
      credentials = originalRequest.getRequestCredentials();
    }

    executionContext.setCredentials(credentials);

    DefaultErrorResponseHandler errorResponseHandler =
        new DefaultErrorResponseHandler(exceptionUnmarshallers);

    return client.execute(request, responseHandler, errorResponseHandler, executionContext);
  }
Example #16
0
  /**
   * this action allows you to give the path of a track on disk, and it will be resolved to the
   * tracks internal ID. this can then be used normally for playing music. the path coming in is
   * assumed to have forward slashes to delimit path components, but this needs to be converted to
   * whatever the actual path separator is for the current system BEFORE we try and query the
   * database, otherwise, well, it just won't work.
   *
   * <p>NB! ATM, this feature is only here for the the folder browsing stuff, so if that's not
   * turned on this this won't work.
   */
  protected void resolvePath() throws BadRequestException, SQLException, IOException {

    // check folder browsing is enabled
    Utils.checkFeatureEnabled(getProperties(), "browse.folders.enabled");

    ResultSet rs = null;
    PreparedStatement st = null;

    try {

      final Database db = getDatabase();
      final Locale locale = getLocale();
      final Request req = getRequest();
      final String path = convertPath(req.getArgument("path"));
      final String sql = Track.getSelectFromSql() + " where t.path = ? ";

      st = db.prepare(sql);
      st.setString(1, path);
      rs = st.executeQuery();

      if (!rs.next())
        throw new BadRequestException(locale.getString("www.error.trackNotFound"), 404);

      final Track track = Track.createFromResultSet(rs);
      final TResolvePath tpl = new TResolvePath();

      tpl.setTrack(track);
      getResponse().showJson(tpl.makeRenderer());

    } finally {
      Utils.close(rs);
      Utils.close(st);
    }
  }
  /**
   * Sends a signal to the specified resource with a success or failure status. You can use the
   * SignalResource API in conjunction with a creation policy or update policy. AWS CloudFormation
   * doesn't proceed with a stack creation or update until resources receive the required number of
   * signals or the timeout period is exceeded. The SignalResource API is useful in cases where you
   * want to send signals from anywhere other than an Amazon EC2 instance.
   *
   * @param signalResourceRequest The input for the <a>SignalResource</a> action.
   * @sample AmazonCloudFormation.SignalResource
   */
  @Override
  public void signalResource(SignalResourceRequest signalResourceRequest) {
    ExecutionContext executionContext = createExecutionContext(signalResourceRequest);
    AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
    awsRequestMetrics.startEvent(Field.ClientExecuteTime);
    Request<SignalResourceRequest> request = null;
    Response<Void> response = null;

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

      StaxResponseHandler<Void> responseHandler = new StaxResponseHandler<Void>(null);
      invoke(request, responseHandler, executionContext);

    } finally {

      endClientExecution(awsRequestMetrics, request, response);
    }
  }
Example #18
0
  /**
   * saves a playlist to the database for the current user. outputs a single integer which is the
   * playlist ID if all goes well, otherwise you'll get a description of the problem.
   *
   * @throws IOException
   */
  protected void savePlaylist() throws IOException, SQLException, BadRequestException {

    final Request req = getRequest();
    final User user = getUser();
    final Locale locale = getLocale();
    final String name = req.getUrlParam(2).trim();
    final String[] args = req.getPlayParams(2);

    String result = locale.getString("www.json.error.unknown");

    // make sure data is ok first
    if (name.equals("")) result = locale.getString("www.json.error.noName");
    else if (args.length == 0) result = locale.getString("www.json.error.noArguments");
    else if (user == null) result = locale.getString("www.json.error.notLoggedIn");
    else {

      final Database db = getDatabase();
      final List<Track> vTracks = Track.getTracksFromPlayArgs(db, args);
      final Track[] tracks = new Track[vTracks.size()];

      for (int i = 0; i < vTracks.size(); i++) tracks[i] = vTracks.get(i);

      result = Integer.toString(cm.savePlaylist(name, tracks, user));
    }

    final TString tpl = new TString();
    tpl.setResult(result);
    getResponse().showJson(tpl.makeRenderer());
  }
Example #19
0
 /**
  * Aborts the connection in response to an error.
  *
  * @param e The error that caused the connection to be aborted. Never null.
  */
 @java.lang.SuppressWarnings("ToArrayCallWithZeroLengthArrayArgument")
 @SuppressWarnings(
     "ITA_INEFFICIENT_TO_ARRAY") // intentionally; race condition on listeners otherwise
 protected void terminate(IOException e) {
   try {
     synchronized (this) {
       if (e == null) throw new IllegalArgumentException();
       outClosed = inClosed = e;
       try {
         transport.closeRead();
       } catch (IOException x) {
         logger.log(Level.WARNING, "Failed to close down the reader side of the transport", x);
       }
       try {
         synchronized (pendingCalls) {
           for (Request<?, ?> req : pendingCalls.values()) req.abort(e);
           pendingCalls.clear();
         }
         synchronized (executingCalls) {
           for (Request<?, ?> r : executingCalls.values()) {
             java.util.concurrent.Future<?> f = r.future;
             if (f != null) f.cancel(true);
           }
           executingCalls.clear();
         }
       } finally {
         notifyAll();
       }
     } // JENKINS-14909: leave synch block
   } finally {
     if (e instanceof OrderlyShutdown) e = null;
     for (Listener l : listeners.toArray(new Listener[0])) l.onClosed(this, e);
   }
 }
Example #20
0
  /**
   * given some url arguments (ar123, al456, etc...) queries for the tracks that belong to these
   * items
   *
   * @throws java.io.IOException
   * @throws java.sql.SQLException
   * @throws com.pugh.sockso.web.BadRequestException
   */
  protected void tracks() throws IOException, SQLException, BadRequestException {

    final Request req = getRequest();
    final List<Track> tracks = Track.getTracksFromPlayArgs(getDatabase(), req.getPlayParams(true));

    showTracks(tracks);
  }
Example #21
0
 @Override
 public DbFuture<Result> executeUpdate(String sql) {
   checkClosed();
   final Request request = requestCreator.executeUpdate(sql);
   queRequest(request);
   return (DbFuture) request.getToComplete();
 }
Example #22
0
  @Override
  public void checkRecycled(org.apache.coyote.Request req, org.apache.coyote.Response res) {
    Request request = (Request) req.getNote(ADAPTER_NOTES);
    Response response = (Response) res.getNote(ADAPTER_NOTES);
    String messageKey = null;
    if (request != null && request.getHost() != null) {
      messageKey = "coyoteAdapter.checkRecycled.request";
    } else if (response != null && response.getContentWritten() != 0) {
      messageKey = "coyoteAdapter.checkRecycled.response";
    }
    if (messageKey != null) {
      // Log this request, as it has probably skipped the access log.
      // The log() method will take care of recycling.
      log(req, res, 0L);

      if (connector.getState().isAvailable()) {
        if (log.isInfoEnabled()) {
          log.info(sm.getString(messageKey), new RecycleRequiredException());
        }
      } else {
        // There may be some aborted requests.
        // When connector shuts down, the request and response will not
        // be reused, so there is no issue to warn about here.
        if (log.isDebugEnabled()) {
          log.debug(sm.getString(messageKey), new RecycleRequiredException());
        }
      }
    }
  }
Example #23
0
 public void forceQueRequest(Request request) {
   synchronized (lock) {
     if (blockingRequest == null) {
       requestQueue.add(request);
       channel.writeAndFlush(request.getRequest());
       if (request.isBlocking()) {
         blockingRequest = new BlockingRequestInProgress(request);
         request
             .getToComplete()
             .addListener(
                 new DbListener<Object>() {
                   @Override
                   public void onCompletion(DbFuture<Object> future) {
                     blockingRequest.continueWithRequests();
                   }
                 });
       }
     } else {
       if (blockingRequest.unblockBy(request)) {
         requestQueue.add(request);
         channel.writeAndFlush(request.getRequest());
       } else {
         blockingRequest.add(request);
       }
     }
   }
 }
 public IRequestHandler mapRequest(final Request request) {
   final Url url = this.decryptUrl(request, request.getUrl());
   if (url == null) {
     return this.wrappedMapper.mapRequest(request);
   }
   return this.wrappedMapper.mapRequest(request.cloneWithUrl(url));
 }
    @Override
    public void messageReceived(Request request, final TransportChannel channel) throws Exception {
      // we just send back a response, no need to fork a listener
      request.listenerThreaded(false);
      // we don't spawn, so if we get a request with no threading, change it to single threaded
      if (request.operationThreading() == BroadcastOperationThreading.NO_THREADS) {
        request.operationThreading(BroadcastOperationThreading.SINGLE_THREAD);
      }
      execute(
          request,
          new ActionListener<Response>() {
            @Override
            public void onResponse(Response response) {
              try {
                channel.sendResponse(response);
              } catch (Throwable e) {
                onFailure(e);
              }
            }

            @Override
            public void onFailure(Throwable e) {
              try {
                channel.sendResponse(e);
              } catch (Exception e1) {
                logger.warn("Failed to send response", e1);
              }
            }
          });
    }
 private void fetchUserInfo() {
   if (fetchUserInfo) {
     final Session currentSession = sessionTracker.getOpenSession();
     if (currentSession != null) {
       if (currentSession != userInfoSession) {
         Request request =
             Request.newMeRequest(
                 currentSession,
                 new Request.GraphUserCallback() {
                   @Override
                   public void onCompleted(GraphUser me, Response response) {
                     if (currentSession == sessionTracker.getOpenSession()) {
                       user = me;
                       if (userInfoChangedCallback != null) {
                         userInfoChangedCallback.onUserInfoFetched(user);
                       }
                     }
                     if (response.getError() != null) {
                       handleError(response.getError().getException());
                     }
                   }
                 });
         Request.executeBatchAsync(request);
         userInfoSession = currentSession;
       }
     } else {
       user = null;
       if (userInfoChangedCallback != null) {
         userInfoChangedCallback.onUserInfoFetched(user);
       }
     }
   }
 }
  public static final void main(String[] args) {
    try {
      // load up the knowledge base
      KnowledgeBase kbase = readKnowledgeBase();
      StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
      KnowledgeRuntimeLogger logger =
          KnowledgeRuntimeLoggerFactory.newThreadedFileLogger(ksession, "test", 1000);
      ksession.getWorkItemManager().registerWorkItemHandler("Human Task", new WSHumanTaskHandler());

      // start a new process instance by setup of a Person and Request.
      Person person = new Person("erics", "Eric D. Schabell");
      person.setAge(43);
      Request request = new Request("1");
      request.setPersonId("erics");
      request.setAmount(1999);
      ksession.insert(person);

      // put them in the Map to be passed to the startProcess.
      Map<String, Object> params = new HashMap<String, Object>();
      params.put("person", person);
      params.put("request", request);

      // Fire it up!
      WorkflowProcessInstance processInstance =
          (WorkflowProcessInstance) ksession.startProcess("org.jbpm.demo.rulenode", params);
      ksession.insert(processInstance);
      ksession.fireAllRules();

      // Finished, clean up the logger.
      System.out.println("Process Ended.");
      logger.close();
    } catch (Throwable t) {
      t.printStackTrace();
    }
  }
Example #28
0
 public static void checkmtime(Request req, long mtime) {
   /* Since the HTTP time format is (reasonably enough) precise
    * only to seconds, any extra milliseconds must be trimmed
    * off, or the mtime will almost certainly not match. */
   final Date mdate = new Date((mtime / 1000) * 1000);
   String ims = req.inheaders().get("If-Modified-Since");
   if (ims != null) {
     Date cldate;
     try {
       cldate = Http.parsedate(ims);
     } catch (java.text.ParseException e) {
       throw (new ClientError("The If-Modified-Since header is not parseable."));
     }
     if (mdate.compareTo(cldate) <= 0) {
       throw (new RequestRestart() {
         public void respond(Request req) {
           req.status(304);
           req.outheaders().put("Content-Length", "0");
           req.outheaders().put("Last-Modified", Http.fmtdate(mdate));
         }
       });
     }
   }
   req.outheaders().put("Last-Modified", Http.fmtdate(mdate));
 }
Example #29
0
  /*
   *  An analysis, experiment, or data track can be part of many topics.  This convenience method
   *  allows the caller to send in the list of parent topics and it will generate XML nodes showing the
   *  topic with its contents.  This methods is used the GetAnalysis, GetRequest, and GetDataTrack to
   *  fill in the XML structure for "related" topics.
   */
  public static void appendParentTopicsXML(
      SecurityAdvisor secAdvisor, Element parentNode, Set topics)
      throws UnknownPermissionException {

    for (Topic topic : (Set<Topic>) topics) {
      Element topicNode = new Element("Topic");
      topicNode.setAttribute("idTopic", topic.getIdTopic().toString());
      topicNode.setAttribute(
          "label",
          (secAdvisor.canRead(topic)
              ? (topic.getName() != null ? topic.getName() : "")
              : "(Not authorized)"));
      topicNode.setAttribute("codeVisibility", topic.getCodeVisibility());
      parentNode.addContent(topicNode);

      for (Request r : (Set<Request>) topic.getRequests()) {
        Element rNode = new Element("Request");
        r.appendBasicXML(secAdvisor, topicNode);
      }
      for (Analysis a : (Set<Analysis>) topic.getAnalyses()) {
        Element aNode = new Element("Analysis");
        a.appendBasicXML(secAdvisor, topicNode);
      }
      for (DataTrack dt : (Set<DataTrack>) topic.getDataTracks()) {

        Element dtNode = new Element("DataTrack");
        dt.appendBasicXML(secAdvisor, topicNode);
      }
    }
  }
Example #30
0
 public <T> Request<T> add(Request<T> request) {
   request.setRequestQueue(this);
   // 给request编序号
   request.setSequence(getSequenceNumber());
   mNetworkQueue.add(request);
   return request;
 }