Exemple #1
0
    @SuppressWarnings({"UnusedDeclaration"})
    @PUT
    @Path("{pId}/{tId}/volatile-participant")
    public Response synchronizations(
        @PathParam("pId") @DefaultValue("") String pId,
        @PathParam("tId") @DefaultValue("") String tId,
        String content) {
      Work work = faults.get(pId);
      TxStatus txStatus;
      int vStatus;

      if (work == null) return Response.ok().build();

      txStatus = content != null ? TxStatus.fromStatus(content) : TxStatus.TransactionStatusUnknown;

      vStatus = txStatus.equals(TxStatus.TransactionStatusUnknown) ? 1 : 2;

      if (vStatus == 2 && work.vStatus == 0) {
        // afterCompletion but coordinator never called beforeCompletion
        return Response.status(HttpURLConnection.HTTP_BAD_REQUEST).build();
      }

      work.vStatus = vStatus;
      work.syncCount += 1;

      if (vStatus == 1 && "V_PREPARE".equals(work.fault))
        return Response.status(HttpURLConnection.HTTP_CONFLICT).build();
      else if (vStatus == 2 && "V_COMMIT".equals(work.fault))
        return Response.status(HttpURLConnection.HTTP_CONFLICT).build();

      return Response.ok().build();
    }
Exemple #2
0
 /** @param args */
 public static void main(String[] args) {
   // TODO Auto-generated method stub
   Work work = new Work(Week.MON);
   Work work2 = new Work(Week.FRI);
   work.descript();
   work2.descript();
 }
 public void onReceive(Object message) {
   if (message instanceof Work) {
     Work work = (Work) message;
     double result = calculatePiFor(work.getStart(), work.getNrOfElements());
     getSender().tell(new Result(result), getSelf());
   } else {
     unhandled(message);
   }
 }
Exemple #4
0
 @PUT
 @Path("{pId}/{tId}/prepare")
 public Response prepare(
     @PathParam("pId") @DefaultValue("") String pId,
     @PathParam("tId") @DefaultValue("") String tId,
     String content) {
   Work work = faults.get(pId);
   if (work != null) work.prepareCnt += 1;
   return terminate(pId, tId, TxStatusMediaType.TX_PREPARED);
 }
Exemple #5
0
 @PUT
 @Path("{pId}/{tId}/rollback")
 public Response rollback(
     @PathParam("pId") @DefaultValue("") String pId,
     @PathParam("tId") @DefaultValue("") String tId,
     String content) {
   Work work = faults.get(pId);
   if (work != null) work.rollbackCnt += 1;
   return terminate(pId, tId, TxStatusMediaType.TX_ROLLEDBACK);
 }
Exemple #6
0
 @PUT
 @Path("{pId}/{tId}/commit-one-phase")
 public Response commmitOnePhase(
     @PathParam("pId") @DefaultValue("") String pId,
     @PathParam("tId") @DefaultValue("") String tId,
     String content) {
   Work work = faults.get(pId);
   if (work != null) work.commmitOnePhaseCnt += 1;
   return terminate(pId, tId, TxStatusMediaType.TX_COMMITTED_ONE_PHASE);
 }
  public String getWorkListTextually() {
    String ret = "";

    if (work != null) {
      for (Work work1 : work) {
        ret += (work1.toString() + "," + '\'');
      }
    }

    return ret;
  }
Exemple #8
0
    /**
     * Executes a {@link Work} instance wrapped in two layers of AOP. The first is intended to
     * acquire the proper arguments for {@link Work#doWork(TransactionStatus, Session,
     * ServiceFactory)} for the {@link OmeroContext}, and the second performs all the standard
     * service actions for any normal method call.
     *
     * <p>If the {@link Principal} argument is not null, then additionally, a login/logout sequence
     * will be performed in a try/finally block.
     *
     * @param callContext Possibly null key-value map. See #3529
     * @param p
     * @param work
     */
    public Object execute(
        final Map<String, String> callContext, final Principal p, final Work work) {

      if (work instanceof SimpleWork) {
        ((SimpleWork) work).setSqlAction(sqlAction);
      }

      Interceptor i = new Interceptor(factory);
      ProxyFactory factory = new ProxyFactory();
      factory.setTarget(work);
      factory.setInterfaces(new Class[] {Work.class});

      for (Advice advice : advices) {
        factory.addAdvice(advice);
      }
      factory.addAdvice(i);

      Work wrapper = (Work) factory.getProxy();

      // First we guarantee that this will cause one and only
      // login to take place.
      if (p == null && principalHolder.size() == 0) {
        throw new IllegalStateException("Must provide principal");
      } else if (p != null && principalHolder.size() > 0) {
        throw new IllegalStateException("Already logged in. Use Executor.submit() and .get().");
      }

      // Don't need to worry about the login stack below since
      // already checked.
      if (p != null) {
        this.principalHolder.login(p);
      }
      if (callContext != null) {
        this.principalHolder.setContext(callContext);
      }

      try {
        // Arguments will be replaced after hibernate is in effect
        return wrapper.doWork(null, isf);
      } finally {
        if (callContext != null) {
          this.principalHolder.setContext(null);
        }
        if (p != null) {
          int left = this.principalHolder.logout();
          if (left > 0) {
            log.warn("Logins left: " + left);
            for (int j = 0; j < left; j++) {
              this.principalHolder.logout();
            }
          }
        }
      }
    }
 public void run() {
   while (running) {
     try {
       Work w = mQueue.take();
       if (w != null && w.contactId == null) {
         w.contactId = queryContact(w.url);
       }
       update(w.contactId, w.url);
     } catch (InterruptedException e) {
       Log.d(TAG, "INTERRUPTED!");
     }
   }
 }
 private void doTransaction(Session session, Work... works) {
   Transaction tx = session.beginTransaction();
   try {
     for (Work work : works) {
       work.doWork(session);
     }
     tx.commit();
   } catch (Exception e) {
     errorCounter.incrementAndGet();
     System.err.println(e.getMessage());
     tx.rollback();
   }
 }
Exemple #11
0
  protected void returnThread(PooledThread thread) {
    synchronized (this.freeList) {
      this.busyList.remove(thread);
      if (!this.workOverflowQueue.isEmpty()) {
        Work queuedWork = (Work) this.workOverflowQueue.remove(0);

        queuedWork.setExitQueueTime(System.currentTimeMillis());
        this.busyList.add(thread);
        thread.assignWork(queuedWork);
      } else {
        this.freeList.add(thread);

        this.freeList.notify();
      }
    }
  }
  @Override
  public void onReceive(Object message) throws Exception {
    if (message instanceof Work) {

      Work work = (Work) message;
      // SumSingleton sum = SumSingleton.getInstance();
      Collection<Integer> result = sum(work.getListHolder().getList(), work.getNumber());
      /*for(int i: work.getListHolder().getList()){
          result.add(sum.compute(i, work.getNumber()));
      }*/
      getSender().tell(result, getSelf());
      logger.tell(result, getSelf());
    } else {
      unhandled(message);
    }
  }
  private static void perform(Calculator.Client client) throws TException {
    client.ping();
    System.out.println("ping()");

    int sum = client.add(1, 1);
    System.out.println("1+1=" + sum);

    Work work = new Work();

    work.op = Operation.DIVIDE;
    work.num1 = 1;
    work.num2 = 0;
    try {
      int quotient = client.calculate(1, work);
      System.out.println("Whoa we can divide by 0");
    } catch (InvalidOperation io) {
      System.out.println("Invalid operation: " + io.why);
    }

    work.op = Operation.SUBTRACT;
    work.num1 = 15;
    work.num2 = 10;
    try {
      int diff = client.calculate(1, work);
      System.out.println("15-10=" + diff);
    } catch (InvalidOperation io) {
      System.out.println("Invalid operation: " + io.why);
    }

    SharedStruct log = client.getStruct(1);
    System.out.println("Check log: " + log.value);
  }
 @Override
 @Transactional
 public <T, E extends Exception> T consistentRead(Work<T, E> work) throws StorageException, E {
   try {
     return work.apply(storeProvider);
   } catch (PersistenceException e) {
     throw new StorageException(e.getMessage(), e);
   }
 }
 /*
  * Overrides the run method.
  */
 public void run() {
   workStarted(workItem, decoratedWork);
   try {
     decoratedWork.run();
     workCompleted(workItem, decoratedWork);
   } catch (Throwable th) {
     workCompleted(workItem, decoratedWork, new WorkSchedulerException(th.getMessage(), th));
   }
 }
Exemple #16
0
  public boolean assign(Runnable work, boolean addToQueueIfFull) {
    if (this.stopThePool) {
      throw new RuntimeException("Pool is stopping... no more work please.");
    }
    Work runWork = new Work(work);

    PooledThread thread = getNextAvailableThread();
    if (thread != null) {
      this.busyList.add(thread);
      thread.assignWork(runWork);
      return true;
    }
    if (addToQueueIfFull) {
      runWork.setEnterQueueTime(System.currentTimeMillis());
      this.workOverflowQueue.add(runWork);
    }
    return false;
  }
Exemple #17
0
  @Override
  public boolean doSomething() {

    if (_worker != null) {
      System.out.println("Prepare to work");
      _worker.doSomething();
      System.out.println("Cleanup after working");
      return true;
    } else {
      System.out.println("No worker available");
      return false;
    }
  }
Exemple #18
0
 public AuthorEntity createEntry() {
   if (getClass() == AuthorEntity.class) return (AuthorEntity) this;
   AuthorEntity entity = new AuthorEntity();
   entity.setHasUpdates(hasUpdates);
   entity.setId(id);
   entity.setHasAvatar(hasAvatar);
   entity.setHasAbout(hasAbout);
   entity.setDateBirth(dateBirth);
   entity.setRate(rate);
   entity.setSize(size);
   entity.setKudoed(kudoed);
   entity.setLink(link);
   entity.setNewest(newest);
   entity.setShortName(getShortName());
   entity.setFullName(fullName);
   entity.setAnnotation(annotation);
   entity.setEmail(email);
   entity.setWorkCount(workCount);
   entity.setSectionAnnotation(sectionAnnotation);
   entity.setGender(getGender());
   entity.setAbout(about);
   entity.setViews(views);
   entity.setAddress(address);
   entity.setParsed(parsed);
   entity.setSite(site);
   entity.setLastUpdateDate(lastUpdateDate);
   for (Category category : categories) {
     category.setAuthor(entity);
     entity.addCategory(category.createEntry());
   }
   for (Work recommendation : recommendations) {
     recommendation.setAuthor(entity);
     entity.addRecommendation(recommendation.createEntity());
   }
   for (Work rootWork : rootWorks) {
     rootWork.setRootAuthor(entity);
     entity.addRootLink(rootWork.createEntity());
   }
   for (Link rootLink : rootLinks) {
     rootLink.setRootAuthor(entity);
     entity.addRootLink(rootLink.createEntity());
   }
   for (Author author : friendList) {
     entity.addFriend(author.createEntry());
   }
   for (Author author : friendOfList) {
     entity.addFriendOf(author.createEntry());
   }
   return entity;
 }
Exemple #19
0
 public void execute(Work work) {
   System.out.printf("WorkRunner[%s] execute Work[%d]\n", beanId, work.getOrder());
   work.run();
 }
 public MailWork() {
   super();
   super.setType(Work.TYPE_MAIL_MESSAGE);
 }
 public MailWork(String id, String name) {
   super(id, name);
   super.setType(Work.TYPE_MAIL_MESSAGE);
 }
Exemple #22
0
    @SuppressWarnings({"UnusedDeclaration"})
    @PUT
    @Path("{pId}/{tId}/terminator")
    public Response terminate(
        @PathParam("pId") @DefaultValue("") String pId,
        @PathParam("tId") @DefaultValue("") String tId,
        String content) {
      TxStatus status = TxSupport.toTxStatus(content);

      // String status = TxSupport.getStatus(content);
      Work work = faults.get(pId);

      if (work == null) return Response.status(HttpURLConnection.HTTP_NOT_FOUND).build();

      String fault = work.fault;

      if (status.isPrepare()) {
        if ("READONLY".equals(fault)) {
          //                    faults.remove(pId);
          work.status = TxStatus.TransactionReadOnly.name();
        } else if ("PREPARE_FAIL".equals(fault)) {
          //                    faults.remove(pId);
          return Response.status(HttpURLConnection.HTTP_CONFLICT).build();
          // throw new WebApplicationException(HttpURLConnection.HTTP_CONFLICT);
        } else {
          if ("PDELAY".equals(fault)) {
            try {
              Thread.sleep(2000);
            } catch (InterruptedException e) {
            }
          }
          work.status = TxStatus.TransactionPrepared.name();
        }
      } else if (status.isCommit() || status.isCommitOnePhase()) {
        if ("H_HAZARD".equals(fault)) work.status = TxStatus.TransactionHeuristicHazard.name();
        else if ("H_ROLLBACK".equals(fault))
          work.status = TxStatus.TransactionHeuristicRollback.name();
        else if ("H_MIXED".equals(fault)) work.status = TxStatus.TransactionHeuristicMixed.name();
        else {
          if ("CDELAY".equals(fault)) {
            try {
              Thread.sleep(3000);
            } catch (InterruptedException e) {
              // ok
            }
          }
          work.status =
              status.isCommitOnePhase()
                  ? TxStatus.TransactionCommittedOnePhase.name()
                  : TxStatus.TransactionCommitted.name();

          work.end(true);
        }
      } else if (status.isAbort()) {
        if ("H_HAZARD".equals(fault)) work.status = TxStatus.TransactionHeuristicHazard.name();
        else if ("H_COMMIT".equals(fault)) work.status = TxStatus.TransactionHeuristicCommit.name();
        else if ("H_MIXED".equals(fault)) work.status = TxStatus.TransactionHeuristicMixed.name();
        else {
          if ("ADELAY".equals(fault)) {
            try {
              Thread.sleep(2000);
            } catch (InterruptedException e) {
              // ok
            }
          }
          work.status = TxStatus.TransactionRolledBack.name();
          work.end(false);
          //                    faults.remove(pId);
        }
      } else {
        return Response.status(HttpURLConnection.HTTP_BAD_REQUEST).build();
        // throw new WebApplicationException(HttpURLConnection.HTTP_BAD_REQUEST);
      }

      // return TxSupport.toStatusContent(work.status);
      return Response.ok(TxSupport.toStatusContent(work.status)).build();
    }
 @Override
 public WorkAck doWork(Work work) {
   String cmd = work.getCommand();
   LOGGER.info(":: WorkService :: Received work command => " + cmd);
   return new WorkAck().setCommand(cmd).setReceived(true);
 }
Exemple #24
0
    @POST
    @Produces(TxMediaType.PLAIN_MEDIA_TYPE)
    public String enlist(
        @Context UriInfo info,
        @QueryParam("pId") @DefaultValue("") String pId,
        @QueryParam("fault") @DefaultValue("") String fault,
        @QueryParam("twoPhaseAware") @DefaultValue("true") String twoPhaseAware,
        @QueryParam("isVolatile") @DefaultValue("false") String isVolatile,
        String enlistUrl)
        throws IOException {
      Work work = faults.get(pId);
      TxSupport txn = new TxSupport();
      String txId = enlistUrl.substring(enlistUrl.lastIndexOf('/') + 1);
      boolean isTwoPhaseAware = "true".equals(twoPhaseAware);
      boolean isVolatileParticipant = "true".equals(isVolatile);
      String vRegistration = null; // URI for registering with the volatile phase
      String vParticipantLink = null; // URI for handling pre and post 2PC phases
      String path = TxSupport.extractUri(info);

      if (work == null) {
        int id = ++pid;

        work =
            makeWork(
                txn,
                path,
                String.valueOf(id),
                txId,
                enlistUrl,
                isTwoPhaseAware,
                isVolatileParticipant,
                null,
                fault);
      } else {
        Work newWork =
            makeWork(
                txn,
                path,
                work.id,
                txId,
                enlistUrl,
                isTwoPhaseAware,
                isVolatileParticipant,
                null,
                fault);
        newWork.oldState = work.oldState;
        newWork.newState = work.newState;
        work = newWork;
      }

      if (enlistUrl.indexOf(',') != -1) {
        String[] urls = enlistUrl.split(",");

        if (urls.length < 2) throw new WebApplicationException(HttpURLConnection.HTTP_BAD_REQUEST);

        enlistUrl = urls[0];
        vRegistration = urls[1];

        String vParticipant =
            new StringBuilder(path)
                .append('/')
                .append(work.id)
                .append('/')
                .append(txId)
                .append('/')
                .append("vp")
                .toString();
        vParticipantLink =
            txn.addLink2(new StringBuilder(), TxLinkNames.VOLATILE_PARTICIPANT, vParticipant, true)
                .toString();
      }

      try {
        // enlist TestResource in the transaction as a participant
        work.recoveryUrl = txn.enlistParticipant(enlistUrl, work.pLinks);

        if (vParticipantLink != null)
          txn.enlistVolatileParticipant(vRegistration, vParticipantLink);
      } catch (HttpResponseException e) {
        throw new WebApplicationException(e.getActualResponse());
      }

      work.status = TxStatus.TransactionActive.name();
      work.start();

      faults.put(work.id, work);

      return work.id;
    }
Exemple #25
0
    @SuppressWarnings({"UnusedDeclaration"})
    @GET
    public String getBasic(
        @Context UriInfo info,
        @QueryParam("pId") @DefaultValue("") String pId,
        @QueryParam("context") @DefaultValue("") String ctx,
        @QueryParam("name") @DefaultValue("") String name,
        @QueryParam("value") @DefaultValue("") String value,
        @QueryParam("query") @DefaultValue("pUrl") String query,
        @QueryParam("arg") @DefaultValue("") String arg,
        @QueryParam("twoPhaseAware") @DefaultValue("true") String twoPhaseAware,
        @QueryParam("isVolatile") @DefaultValue("false") String isVolatileParticipant,
        @QueryParam("register") @DefaultValue("true") String register) {
      Work work = faults.get(pId);
      String res = null;
      boolean isVolatile = "true".equals(isVolatileParticipant);
      boolean isTwoPhaseAware = "true".equals(twoPhaseAware);

      if (name.length() != 0) {
        if (value.length() != 0) {
          if (work == null) {
            work =
                makeWork(
                    new TxSupport(),
                    TxSupport.extractUri(info),
                    String.valueOf(++pid),
                    null,
                    null,
                    isTwoPhaseAware,
                    isVolatile,
                    null,
                    null);
            work.oldState.put(name, value);
            faults.put(work.id, work);
            return work.id;
          }

          work.newState.put(name, value);
        }

        if (work != null) {
          if ("syncCount".equals(name)) res = String.valueOf(work.syncCount);
          else if ("commitCnt".equals(name)) res = String.valueOf(work.commitCnt);
          else if ("prepareCnt".equals(name)) res = String.valueOf(work.prepareCnt);
          else if ("rollbackCnt".equals(name)) res = String.valueOf(work.rollbackCnt);
          else if ("commmitOnePhaseCnt".equals(name)) res = String.valueOf(work.commmitOnePhaseCnt);
          else if (work.inTxn()) res = work.newState.get(name);
          else res = work.oldState.get(name);
        }
      }

      if (work == null) throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);

      if ("move".equals(query))
        res = moveParticipant(work, arg, register, isTwoPhaseAware, isVolatile);
      else if ("recoveryUrl".equals(query)) res = work.recoveryUrl;
      else if ("status".equals(query)) res = work.status;
      else if (res == null) res = work.pLinks;

      return res; // null will generate a 204 status code (no content)
    }
Exemple #26
0
 public String getBoss() {
   return work.getBoss();
 }
Exemple #27
0
 /**
  * Execute the discrete work encapsulated by a {@link Work} instance using the supplied
  * connection.
  *
  * <p>Because {@link Work} does not return a value when executed (via {@link
  * Work#execute(java.sql.Connection)}, this method always returns null.
  *
  * @param work The @link ReturningWork} instance encapsulating the discrete work
  * @param connection The connection on which to perform the work.
  * @return null>.
  * @throws SQLException Thrown during execution of the underlying JDBC interaction.
  * @throws org.hibernate.HibernateException Generally indicates a wrapped SQLException.
  */
 public <T> T executeWork(Work work, Connection connection) throws SQLException {
   work.execute(connection);
   return null;
 }