// FIXME cosmically ineffective not to implemente the other write methods.
 @Override
 public void write(int b) throws IOException {
   this.buffer.append((char) b);
   String s = buffer.toString();
   // This next line is an optimisation. Only convert the whole buffer to string
   // if the most recent character might be the end of the line separator.
   if ((lineSeparator.indexOf(b) != -1) && s.contains(lineSeparator)) {
     s = prefix + "'" + s + "'";
     switch (loggingLevel) {
       case TRACE:
         logger.trace(s);
         break;
       case DEBUG:
         logger.debug(s);
         break;
       case INFO:
         logger.info(s);
         break;
       case WARN:
         logger.warn(s);
         break;
       case ERROR:
         logger.error(s);
         break;
     }
     buffer.setLength(0);
   }
 }
  @GET
  @Path("servers/{id}/containers")
  @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
  public Response listContainerSpec(
      @Context HttpHeaders headers, @PathParam("id") String serverTemplateId) {
    String contentType = getContentType(headers);
    try {
      logger.debug("Received get containers for server template with id {}", serverTemplateId);

      Collection<ContainerSpec> containerSpecs = super.listContainerSpec(serverTemplateId);

      String response = marshal(contentType, new ContainerSpecList(containerSpecs));
      logger.debug(
          "Returning response for get containers for server templates with id {}: {}",
          serverTemplateId,
          response);

      return createCorrectVariant(response, headers, Response.Status.OK);
    } catch (KieServerControllerNotFoundException e) {
      return createCorrectVariant(e.getMessage(), headers, Response.Status.NOT_FOUND);
    } catch (KieServerControllerException e) {
      return createCorrectVariant(
          "Request failed to be processed due to" + e.getMessage(),
          headers,
          Response.Status.BAD_REQUEST);
    } catch (Exception e) {
      logger.error("Get server templates failed due to {}", e.getMessage(), e);
      return createCorrectVariant(
          "Unknown error " + e.getMessage(), headers, Response.Status.INTERNAL_SERVER_ERROR);
    }
  }
Example #3
1
  public void turlRetrievalFailed(
      String surl, String reason, String remoteRequestId, String remoteFileId) {
    synchronized (remoteSurlToFileReqIds) {
      Collection<Long> fileRequestSet = remoteSurlToFileReqIds.get(surl);
      if (fileRequestSet == null || fileRequestSet.isEmpty()) {
        LOG.error("turlArrived for unknown SURL = " + surl);
        return;
      }
      for (long id : fileRequestSet) {
        CopyFileRequest cfr = getFileRequest(id);

        try {
          String type = isSourceSrm() && !isSourceLocal() ? "source" : "destination";
          String error = "retrieval of " + type + " TURL failed with error " + reason;
          LOG.error(error);
          cfr.setState(State.FAILED, error);
        } catch (IllegalStateTransition ist) {
          LOG.error("Illegal State Transition : " + ist.getMessage());
        }
        cfr.saveJob();

        remoteSurlToFileReqIds.remove(surl, id);
      }
    }
    remoteFileRequestDone(surl, remoteRequestId, remoteFileId);
  }
Example #4
0
 /**
  * 获取缓存数据
  *
  * @param region 缓存分区
  * @param key 缓存key
  * @param invoker 回调方法
  * @return 返回对应类型的数据
  */
 @SuppressWarnings("unchecked")
 public static <T> T get(final String region, final String key, final ICacheInvoker<T> invoker) {
   // 1. 从正常缓存中获取数据
   T data = (T) EhCacheManager.get(region, key);
   if (data == null) {
     logger.debug("在L1缓存中未找到内容!{} - {}", region, key);
     // 2. 从全局二级缓存中获取数据,执行自动更新数据策略,结果直接返回
     data = (T) RedisCacheManager.get(region, key);
     if (invoker != null) {
       if (data == null) {
         logger.debug("在L2缓存中未找到内容!{} - {}", region, key);
         data = invoker.callback();
         EhCacheManager.set(region, key, (Serializable) data);
         RedisCacheManager.set(region, key, (Serializable) data);
       } else {
         logger.debug("执行自动更新数据策略{} - {}", region, key);
         String thread_name = String.format("CacheUpdater-%s-%s", region, key);
         g_ThreadPool.execute(
             new Thread(thread_name) {
               @Override
               public void run() {
                 Object result = invoker.callback();
                 if (result != null) {
                   EhCacheManager.set(region, key, (Serializable) result);
                   RedisCacheManager.set(region, key, (Serializable) result);
                 }
               }
             });
       }
     }
   }
   return data;
 }
  /** Sends email asynchronously through Sendgrid. */
  @Override
  @Async
  public void sendEmail(final EmailMessage message) {
    if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
      return;
    }

    SendGrid sendgrid = new SendGrid(username, password);
    sendgrid.setFrom(message.getFromEmail());
    sendgrid.setFromName(message.getFromName());
    sendgrid.addTo(message.getToEmail());
    sendgrid.addToName(message.getToName());
    sendgrid.setReplyTo(message.getReplyTo());
    sendgrid.setSubject(message.getSubject());
    sendgrid.setText(message.getBody());

    try {
      LOGGER.info(
          "Try to send email to {}, message is: {}", message.getToEmail(), message.getBody());
      String response = sendgrid.send();
      LOGGER.info("Sent email successfully, response from SendGrid is: {}", response);
    } catch (Exception ex) {
      LOGGER.debug("Exception:", ex);
      LOGGER.error("Got exception when sending email through sendgrid: {}", ex.getMessage());
    }
  }
Example #6
0
 public static final Optional<String> httpPost(
     Entity framework, String subUrl, String dataUrl, Map<String, Object> substitutions) {
   String targetUrl =
       Urls.mergePaths(framework.sensors().get(MesosFramework.FRAMEWORK_URL), subUrl);
   String templateContents = ResourceUtils.create().getResourceAsString(dataUrl);
   String processedJson =
       TemplateProcessor.processTemplateContents(templateContents, substitutions);
   LOG.debug("Posting JSON to {}: {}", targetUrl, processedJson);
   URI postUri = URI.create(targetUrl);
   HttpToolResponse response =
       HttpTool.httpPost(
           MesosUtils.buildClient(framework),
           postUri,
           MutableMap.of(
               HttpHeaders.CONTENT_TYPE, "application/json",
               HttpHeaders.ACCEPT, "application/json"),
           processedJson.getBytes());
   LOG.debug("Response: " + response.getContentAsString());
   if (!HttpTool.isStatusCodeHealthy(response.getResponseCode())) {
     LOG.warn(
         "Invalid response code {}: {}", response.getResponseCode(), response.getReasonPhrase());
     return Optional.absent();
   } else {
     LOG.debug("Successfull call to {}: {}", targetUrl);
     return Optional.of(response.getContentAsString());
   }
 }
  /**
   * Called when the client provides the multi-sig contract. Checks that the previously-provided
   * refund transaction spends this transaction (because we will use it as a base to create payment
   * transactions) as well as output value and form (ie it is a 2-of-2 multisig to the correct
   * keys).
   *
   * @param multisigContract The provided multisig contract. Do not mutate this object after this
   *     call.
   * @return A future which completes when the provided multisig contract successfully broadcasts,
   *     or throws if the broadcast fails for some reason Note that if the network simply rejects
   *     the transaction, this future will never complete, a timeout should be used.
   * @throws VerificationException If the provided multisig contract is not well-formed or does not
   *     meet previously-specified parameters
   */
  public synchronized ListenableFuture<PaymentChannelServerState> provideMultiSigContract(
      final Transaction multisigContract) throws VerificationException {
    checkNotNull(multisigContract);
    checkState(state == State.WAITING_FOR_MULTISIG_CONTRACT);
    try {
      multisigContract.verify();
      this.multisigContract = multisigContract;
      this.multisigScript = multisigContract.getOutput(0).getScriptPubKey();

      // Check that multisigContract's first output is a 2-of-2 multisig to the correct pubkeys in
      // the correct order
      final Script expectedScript =
          ScriptBuilder.createMultiSigOutputScript(2, Lists.newArrayList(clientKey, serverKey));
      if (!Arrays.equals(multisigScript.getProgram(), expectedScript.getProgram()))
        throw new VerificationException(
            "Multisig contract's first output was not a standard 2-of-2 multisig to client and server in that order.");

      this.totalValue = multisigContract.getOutput(0).getValue();
      if (this.totalValue.signum() <= 0)
        throw new VerificationException(
            "Not accepting an attempt to open a contract with zero value.");
    } catch (VerificationException e) {
      // We couldn't parse the multisig transaction or its output.
      log.error("Provided multisig contract did not verify: {}", multisigContract.toString());
      throw e;
    }
    log.info("Broadcasting multisig contract: {}", multisigContract);
    state = State.WAITING_FOR_MULTISIG_ACCEPTANCE;
    final SettableFuture<PaymentChannelServerState> future = SettableFuture.create();
    Futures.addCallback(
        broadcaster.broadcastTransaction(multisigContract).future(),
        new FutureCallback<Transaction>() {
          @Override
          public void onSuccess(Transaction transaction) {
            log.info(
                "Successfully broadcast multisig contract {}. Channel now open.",
                transaction.getHashAsString());
            try {
              // Manually add the multisigContract to the wallet, overriding the isRelevant checks
              // so we can track
              // it and check for double-spends later
              wallet.receivePending(multisigContract, null, true);
            } catch (VerificationException e) {
              throw new RuntimeException(
                  e); // Cannot happen, we already called multisigContract.verify()
            }
            state = State.READY;
            future.set(PaymentChannelServerState.this);
          }

          @Override
          public void onFailure(Throwable throwable) {
            // Couldn't broadcast the transaction for some reason.
            log.error("Broadcast multisig contract failed", throwable);
            state = State.ERROR;
            future.setException(throwable);
          }
        });
    return future;
  }
Example #8
0
  public void fileRequestCompleted() {
    resetRetryDeltaTime();

    if (isProcessingDone()) {
      try {
        boolean hasOnlyFinalFileRequests = true;
        for (CopyFileRequest request : getFileRequests()) {
          State state = request.getState();
          if (!(state.isFinal())) {
            hasOnlyFinalFileRequests = false;
          }
        }

        State state = getState();
        if (!state.isFinal() && hasOnlyFinalFileRequests) {
          setState(State.DONE, "All transfers have completed.");
        }
      } catch (IllegalStateTransition e) {
        LOG.error("setting to done anyway: {}", e.toString());
        try {
          State state = getState();
          if (!state.isFinal()) {
            setState(State.DONE, e.toString());
          }
        } catch (IllegalStateTransition ist) {
          LOG.error("Illegal State Transition : {}", ist.getMessage());
        }
      }
    }
  }
  @POST
  @Path("servers/{id}/containers/{containerId}/status/started")
  @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
  @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
  public Response startContainer(
      @Context HttpHeaders headers,
      @PathParam("id") String serverTemplateId,
      @PathParam("containerId") String containerId) {
    logger.debug(
        "Requesting start container with id {} server instance: {}", containerId, serverTemplateId);
    try {
      ContainerSpecKey containerSpecKey = new ContainerSpecKey();
      containerSpecKey.setId(containerId);
      containerSpecKey.setServerTemplateKey(new ServerTemplateKey(serverTemplateId, ""));
      super.startContainer(containerSpecKey);

      logger.debug(
          "Returning response for start container with id {} server instance: {}",
          containerId,
          serverTemplateId);
      return createCorrectVariant("", headers, Response.Status.OK);
    } catch (KieServerControllerNotFoundException e) {
      return createCorrectVariant(e.getMessage(), headers, Response.Status.NOT_FOUND);
    } catch (Exception e) {
      logger.error("Start container failed due to {}", e.getMessage(), e);
      return createCorrectVariant(
          "Unknown error " + e.getMessage(), headers, Response.Status.INTERNAL_SERVER_ERROR);
    }
  }
  public <RESPONSE extends ReaderResponse<?>> RESPONSE transmit(ReaderCommand<?, ?> readerCommand)
      throws Exception {

    Log.trace("Sending command: " + readerCommand.toString());

    // ACR122
    byte[] header = {(byte) 0xff, (byte) 0x00, (byte) 0x00, (byte) 0x00};
    out.put(header);
    out.put((byte) readerCommand.getLength());
    readerCommand.transfer(out);

    try {
      out.flip();
      CommandAPDU apdu = new CommandAPDU(out);
      ResponseAPDU resp = channel.transmit(apdu);
      out.clear();
      ByteBuffer in = ByteBuffer.wrap(resp.getBytes());
      // check response !!!

      RESPONSE response = (RESPONSE) readerCommand.receive(in);
      Log.trace("Receiving command: " + response.toString());
      return response;
    } catch (CardException e) {
      e.printStackTrace();
      throw new Exception(e.getMessage());
    }
  }
Example #11
0
 /**
  * This test reproduces a deadlock found in 1.4-beta1 around loading interactions and
  * getWithLoader. Now fixed.
  */
 @Test
 public void testCompositeLoad() {
   LOG.info("Getting from cache");
   ComponentA compA =
       (ComponentA) CacheHelper.get("ehcache-loaderinteractions.xml", "ACache", "key1");
   LOG.info(compA.toString());
 }
  @Override
  public synchronized void connect(
      String url, RunnableExchangeEventListener runnableExchangeEventListener) {

    log.info("Connecting...");

    // Validate inputs
    Assert.notNull(runnableExchangeEventListener, "runnableMarketDataListener cannot be null");

    // Validate state
    if (eventExecutorService.isShutdown()) {
      throw new IllegalStateException(
          "Service has been stopped. Create a new one rather than reuse a reference.");
    }

    try {
      log.debug(
          "Attempting to open a socketIO against {}:{}", url, exchangeSpecification.getPort());
      this.runnableExchangeEventProducer = new RunnableSocketIOEventProducer(producerEventQueue);
      this.socketIO =
          new SocketIO(url, (RunnableSocketIOEventProducer) runnableExchangeEventProducer);
    } catch (IOException e) {
      throw new ExchangeException("Failed to open socket!", e);
    }

    // Configure the exchange event listener event queue
    runnableExchangeEventListener.setExchangeEventQueue(producerEventQueue);

    // Submit the event threads to their services
    eventExecutorService.submit(runnableExchangeEventProducer);
    eventExecutorService.submit(runnableExchangeEventListener);

    log.info("Socket connected OK. Check queues for events.");
  }
  @Override
  public void run() {
    // clone a copy of the killable tasks
    Set<TaskID> killableTasks = Sets.newHashSet(schedulerState.getKillableTasks());

    if (CollectionUtils.isEmpty(killableTasks)) {
      return;
    }

    Status driverStatus = driverManager.getDriverStatus();
    if (Status.DRIVER_RUNNING != driverStatus) {
      LOGGER.warn("Cannot kill tasks, as driver is not running. Status: {}", driverStatus);
      return;
    }

    for (TaskID taskIdToKill : killableTasks) {
      if (this.schedulerState.getPendingTaskIds().contains(taskIdToKill)) {
        this.schedulerState.removeTask(taskIdToKill);
      } else {
        Status status = this.driverManager.kill(taskIdToKill);
        NodeTask task = schedulerState.getTask(taskIdToKill);
        if (task != null) {
          offerLifeCycleManager.declineOutstandingOffers(task.getHostname());
          this.schedulerState.removeTask(taskIdToKill);
        } else {
          schedulerState.removeTask(taskIdToKill);
          LOGGER.warn("NodeTask with taskId: {} does not exist", taskIdToKill);
        }
        Preconditions.checkState(status == Status.DRIVER_RUNNING);
      }
    }
  }
Example #14
0
 private void sendMaybeEmail(String to) {
   String subject = "Processing is taking a long time";
   StringBuilder content = new StringBuilder();
   content.append("Your process is taking longer than expected.");
   content.append("  It might finish in a bit, but here is the status so far");
   content.append("\n\tUpload: ").append((uploadSuccessful) ? "success" : "waiting");
   content.append("\n\tParse: ").append((netcdfSuccessful) ? "success" : "waiting");
   content.append("\n\tStatistics: ").append((rStatsSuccessful) ? "success" : "waiting");
   content.append("\n\tMetadata: ").append((cswTransSuccessful) ? "success" : "waiting");
   content.append(
       "\n\nYou will receive another email if there is a success, but may not receive a failure notification.");
   List<String> bcc = new ArrayList<String>();
   String from = props.getProperty("watersmart.email.from");
   String bccAddr = props.getProperty("watersmart.email.tracker");
   if (!"".equals(bccAddr)) {
     bcc.add(bccAddr);
   }
   EmailMessage message = new EmailMessage(from, to, null, bcc, subject, content.toString());
   try {
     EmailHandler.sendMessage(message);
   } catch (AddressException ex) {
     log.error("Unable to send maybe e-mail:\n" + message, ex);
   } catch (MessagingException ex) {
     log.error("Unable to send maybe e-mail:\n" + message, ex);
   }
 }
Example #15
0
  /**
   * Invokes each test case on the input, verifying the output.
   *
   * @return true if all tests passed, false
   */
  public List<IteratorTestReport> runTests() {
    List<IteratorTestReport> testReports = new ArrayList<>(testCases.size());
    for (IteratorTestCase testCase : testCases) {
      log.info(
          "Invoking {} on {}",
          testCase.getClass().getName(),
          testInput.getIteratorClass().getName());

      IteratorTestOutput actualOutput = null;

      try {
        actualOutput = testCase.test(testInput);
      } catch (Exception e) {
        log.error(
            "Failed to invoke {} on {}",
            testCase.getClass().getName(),
            testInput.getIteratorClass().getName(),
            e);
        actualOutput = new IteratorTestOutput(e);
      }

      // Sanity-check on the IteratorTestCase implementation.
      if (null == actualOutput) {
        throw new IllegalStateException(
            "IteratorTestCase implementations should always return a non-null IteratorTestOutput. "
                + testCase.getClass().getName()
                + " did not!");
      }

      testReports.add(new IteratorTestReport(testInput, testOutput, actualOutput, testCase));
    }

    return testReports;
  }
Example #16
0
 /**
  * Unregisters all JSP page servlets for a plugin.
  *
  * @param webXML the web.xml file containing JSP page names to servlet class file mappings.
  */
 public static void unregisterServlets(File webXML) {
   if (!webXML.exists()) {
     Log.error(
         "Could not unregister plugin servlets, file "
             + webXML.getAbsolutePath()
             + " does not exist.");
     return;
   }
   // Find the name of the plugin directory given that the webXML file
   // lives in plugins/[pluginName]/web/web.xml
   String pluginName = webXML.getParentFile().getParentFile().getParentFile().getName();
   try {
     SAXReader saxReader = new SAXReader(false);
     saxReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
     Document doc = saxReader.read(webXML);
     // Find all <servelt-mapping> entries to discover name to URL mapping.
     List names = doc.selectNodes("//servlet-mapping");
     for (int i = 0; i < names.size(); i++) {
       Element nameElement = (Element) names.get(i);
       String url = nameElement.element("url-pattern").getTextTrim();
       // Destroy the servlet than remove from servlets map.
       GenericServlet servlet = servlets.get(pluginName + url);
       if (servlet != null) {
         servlet.destroy();
       }
       servlets.remove(pluginName + url);
       servlet = null;
     }
   } catch (Throwable e) {
     Log.error(e.getMessage(), e);
   }
 }
Example #17
0
 public int update(String sql, Object... params) throws SystemError, LogicError {
   try {
     Connection conn = getConnection();
     try {
       PreparedStatement stm = conn.prepareStatement(sql);
       try {
         setParams(stm, params);
         return stm.executeUpdate();
       } finally {
         stm.close();
       }
     } finally {
       conn.close();
     }
   } catch (LogicError e) {
     logger.error("Error", e);
     throw e;
   } catch (SystemError e) {
     logger.error("Error", e);
     throw e;
   } catch (SQLException e) {
     logger.error("Error", e);
     throw new SystemError("Error in update:" + e, MODULO, DaoUtils.getMethod(e), e);
   } catch (Exception e) {
     logger.error("Error", e);
     throw new SystemError("Error in update:" + e, MODULO, DaoUtils.getMethod(e), e);
   }
 }
Example #18
0
 public <T extends PersistentObject> int updateObject(
     String sql, BeanSqlSetter<T> sqlSetter, T bean) throws SystemError, LogicError {
   try {
     Connection conn = getConnection();
     try {
       PreparedStatement stm = conn.prepareStatement(sql);
       try {
         sqlSetter.setParams(stm, bean);
         int res = stm.executeUpdate();
         if (res == 1) bean.saved();
         return res;
       } finally {
         stm.close();
       }
     } finally {
       conn.close();
     }
   } catch (LogicError e) {
     logger.error("Error", e);
     throw e;
   } catch (SystemError e) {
     logger.error("Error", e);
     throw e;
   } catch (SQLException e) {
     logger.error("Error", e);
     throw new SystemError("Error in update:" + e, MODULO, DaoUtils.getMethod(e), e);
   } catch (Exception e) {
     logger.error("Error", e);
     throw new SystemError("Error in update:" + e, MODULO, DaoUtils.getMethod(e), e);
   }
 }
  @Override
  @Transactional
  public void handleRequest() throws HopsException {
    Delivery delivery = (Delivery) ActionContextUtil.getActionContextParam(ActionMapKey.DELIVERY);
    try {
      Integer deliveryStatus = delivery.getDeliveryStatus();
      logger.debug(
          "修改发货记录状态(DELIVERY_STATUS_WAIT->DELIVERY_STATUS_SENDING) [开始]"
              + delivery.getDeliveryId());
      delivery =
          (Delivery)
              deliveryStatusManagementServiceImpl.updateStatus(
                  delivery.getDeliveryId(),
                  delivery.getDeliveryStatus(),
                  Constant.Delivery.DELIVERY_STATUS_SENDING);
      // deliveryManagement.updateDeliveryStatus(delivery.getDeliveryStatus(), deliveryStatus,
      // delivery.getDeliveryId());
      delivery = deliveryManagement.save(delivery);
      logger.debug(
          "修改发货记录状态(DELIVERY_STATUS_WAIT->DELIVERY_STATUS_SENDING) [结束]"
              + delivery.getDeliveryId());

      ActionContextUtil.setActionContext(ActionMapKey.DELIVERY, delivery);
    } catch (Exception e) {
      logger.error(
          "deliveryStatusSendingAction happen Exception caused by "
              + ExceptionUtil.getStackTraceAsString(e));
      throw new ApplicationException(
          "transaction002006", new String[] {ExceptionUtil.getStackTraceAsString(e)}, e);
    }
  }
 private BxBounds parseElementContainingVertexes(Element el) {
   ArrayList<Element> vs = getChildren("Vertex", el);
   if (vs.isEmpty()) {
     return null;
   }
   ArrayList<ComparablePair<Integer, Integer>> list =
       new ArrayList<ComparablePair<Integer, Integer>>();
   int minx = Integer.MAX_VALUE;
   int maxx = Integer.MIN_VALUE;
   int miny = Integer.MAX_VALUE;
   int maxy = Integer.MIN_VALUE;
   for (Element v : vs) {
     int x = Integer.parseInt(v.getAttribute("x"));
     if (x < minx) minx = x;
     if (x > maxx) maxx = x;
     int y = Integer.parseInt(v.getAttribute("y"));
     if (y < miny) miny = y;
     if (y > maxy) maxy = y;
     list.add(new ComparablePair<Integer, Integer>(x, y));
   }
   Collections.sort(list);
   ComparablePair<Integer, Integer> mine = list.get(0);
   ComparablePair<Integer, Integer> maxe = list.get(list.size() - 1);
   BxBounds ret = new BxBounds(minx, miny, maxx - minx, maxy - miny);
   if (ret.getHeight() == 0 || ret.getWidth() == 0) {
     log.warn("problems with height or width points are:");
     for (ComparablePair<Integer, Integer> pa : list) {
       log.warn("\t" + pa.o1 + " , " + pa.o2);
     }
   }
   return ret;
 }
Example #21
0
  private void expire() {
    if (expire == null) {
      clear();
    } else {
      if (expireTime > 0 && GungnirUtils.currentTimeMillis() >= expireTime) {
        if (LOG.isDebugEnabled()) {
          LOG.debug("expire {} >= {}", GungnirUtils.currentTimeMillis(), expireTime);
        }
        clear();

        if (expire.getType() == IntervalType.CRON) {
          try {
            CronExpression cronExpr = new CronExpression(expire.getSchedulingPattern());
            expireTime =
                cronExpr
                    .getNextValidTimeAfter(new Date(GungnirUtils.currentTimeMillis()))
                    .getTime();
          } catch (ParseException e) {
            expireTime = 0;
            LOG.error("Failed to parse pattern", e);
          }
        } else {
          long expireMs = expire.getPeriod().getTimeUnit().toMillis(expire.getPeriod().getTime());
          expireTime += ((GungnirUtils.currentTimeMillis() - expireTime) / expireMs + 1) * expireMs;
        }
      }
    }
  }
Example #22
0
  @Override
  public void execute(GungnirTuple tuple) {
    if (LOG.isDebugEnabled()) {
      LOG.debug("execute({} {}) {}", getContext().getTopologyId(), getName(), tuple);
    }

    if (interval.getType() == IntervalType.COUNT) {
      TupleValues tupleValues = getTupleValues(tuple);

      counter++;
      if (counter >= interval.getCount()) {
        dispatch(tupleValues);
        for (Field field : fields) {
          if (field instanceof AggregateFunction<?>) {
            ((AggregateFunction<?>) field).clear();
          }
        }
        counter = 0;
      }
    } else {
      synchronized (this) {
        if (lastTupleValues == null) {
          expire();
        }
        lastTupleValues = getTupleValues(tuple);
      }
    }
  }
Example #23
0
 private void makeQosReservation(int fileIndex) throws MalformedURLException, SRMException {
   try {
     CopyFileRequest cfr = getFileRequests().get(fileIndex);
     RequestCredential credential = RequestCredential.getRequestCredential(credentialId);
     QOSTicket qosTicket =
         getQosPlugin()
             .createTicket(
                 credential.getCredentialName(),
                 getStorage().getFileMetaData(getUser(), cfr.getSourceSurl(), false).size,
                 cfr.getSourceSurl().toASCIIString(),
                 cfr.getSourceSurl().getPort(),
                 cfr.getSourceSurl().getPort(),
                 cfr.getSourceSurl().getScheme(),
                 cfr.getDestinationSurl().toASCIIString(),
                 cfr.getDestinationSurl().getPort(),
                 cfr.getDestinationSurl().getPort(),
                 cfr.getDestinationSurl().getScheme());
     getQosPlugin().addTicket(qosTicket);
     if (getQosPlugin().submit()) {
       cfr.setQOSTicket(qosTicket);
       LOG.debug("QOS Ticket Received {}", getQosPlugin());
     }
   } catch (Exception e) {
     LOG.error("Could not create QOS reservation: {}", e.getMessage());
   }
 }
Example #24
0
  @Test
  public void testZkClientWhenZKIsDownAndRestarts() throws Exception {

    // Iterate updating the timestamp and check the final value
    long previousMaxTimestamp = INITIAL_MAX_TS_VALUE;
    for (int i = 0; i < ITERATION_COUNT; i++) {
      long newMaxTimestamp = previousMaxTimestamp + 1_000_000;
      storage.updateMaxTimestamp(previousMaxTimestamp, newMaxTimestamp);
      previousMaxTimestamp = newMaxTimestamp;
    }
    assertEquals(storage.getMaxTimestamp(), 1_000_000 * ITERATION_COUNT);

    // Stop ZK Server, expect the IO exception, reconnect and get the right value
    LOG.info("Stopping ZK Server");
    zkServer.stop();
    LOG.info("ZK Server Stopped");

    try {
      storage.getMaxTimestamp();
      fail();
    } catch (IOException ioe) {
      LOG.info("Expected exception", ioe);
    }

    LOG.info("Restarting ZK again");
    zkServer.restart();
    assertEquals(storage.getMaxTimestamp(), 1_000_000 * ITERATION_COUNT);
  }
Example #25
0
 @Override
 public void propertyChange(PropertyChangeEvent evt) {
   LOG.debug("propertyChange");
   try {
     if (evt instanceof TURLsArrivedEvent) {
       TURLsArrivedEvent tae = (TURLsArrivedEvent) evt;
       String SURL = tae.getSURL();
       String TURL = tae.getTURL();
       String remoteRequestId = tae.getRequestId();
       String remoteFileId = tae.getFileRequestId();
       Long size = tae.getSize();
       turlArrived(SURL, TURL, remoteRequestId, remoteFileId, size);
     } else if (evt instanceof TURLsGetFailedEvent) {
       TURLsGetFailedEvent tgfe = (TURLsGetFailedEvent) evt;
       String SURL = tgfe.getSURL();
       String reason = tgfe.getReason();
       String remoteRequestId = tgfe.getRequestId();
       String remoteFileId = tgfe.getFileRequestId();
       turlRetrievalFailed(SURL, reason, remoteRequestId, remoteFileId);
     } else if (evt instanceof RequestFailedEvent) {
       RequestFailedEvent rfe = (RequestFailedEvent) evt;
       Object reason = rfe.getReason();
       turlsRetrievalFailed(reason);
     }
   } catch (Exception e) {
     LOG.error(e.toString());
   }
 }
Example #26
0
  public void authenticate(
      OAuthAccessToken oAuthAccessToken, HttpServletRequest request, HttpServletResponse response)
      throws FacebookException, IOException, ServletException {
    Facebook facebook =
        Face4jFactory.getInstance().getFacebookFactory().getInstance(oAuthAccessToken);
    User fbUser = facebook.getCurrentUser();
    PreAuthenticatedAuthenticationToken token =
        new PreAuthenticatedAuthenticationToken(fbUser, null);
    token.setDetails(ads.buildDetails((HttpServletRequest) request));

    try {
      Authentication authentication = authenticationManager.authenticate(token);
      SecurityContextHolder.getContext().setAuthentication(authentication);

      HttpSession session = request.getSession(true);
      session.setAttribute("username", fbUser.getEmail());

      LOG.info("Facebook user " + fbUser.getName());
      if (authentication.getAuthorities().contains(AppRole.NEW_USER)) {
        LOG.debug("New user authenticated. Redirecting to registration page");
        ((HttpServletResponse) response).sendRedirect(REGISTRATION_URL);

        return;
      }

    } catch (AuthenticationException e) {
      failureHandler.onAuthenticationFailure(
          (HttpServletRequest) request, (HttpServletResponse) response, e);

      return;
    }
  }
Example #27
0
  public String getTransformedURL(Core core) {
    String result = getUrl();
    log.debug("URL before transformation: " + url);
    // index.jsp?param=${type}&param2=${id}&param3=${fieldname}
    Pattern p = Pattern.compile("(?!\\$\\{)([A-Za-z0-9]+?)(?:\\})", Pattern.CASE_INSENSITIVE);

    List<String> list = new ArrayList<String>();
    Matcher m = p.matcher(url);
    while (m.find()) {
      String tokenpart = m.group(1);
      log.debug("tokenpart = " + tokenpart);
      list.add(tokenpart);
    }
    log.debug("We found parameters: " + list);

    for (String param : list) {
      if ("user".equalsIgnoreCase(param)) {
        result = result.replaceAll("\\$\\{user\\}", core.getLoggedInUser().getUserName());
      }
    }

    log.debug("Returning URL: " + result);

    return result;
  }
Example #28
0
  @RequestMapping(
      value = "",
      method = {RequestMethod.PUT})
  @ResponseBody
  public StreamingRequest updateStreamingConfig(@RequestBody StreamingRequest streamingRequest)
      throws JsonProcessingException {
    StreamingConfig streamingConfig = deserializeSchemalDesc(streamingRequest);
    KafkaConfig kafkaConfig = deserializeKafkaSchemalDesc(streamingRequest);

    if (streamingConfig == null) {
      return streamingRequest;
    }
    try {
      streamingConfig = streamingService.updateStreamingConfig(streamingConfig);
    } catch (AccessDeniedException accessDeniedException) {
      throw new ForbiddenException("You don't have right to update this StreamingConfig.");
    } catch (Exception e) {
      logger.error("Failed to deal with the request:" + e.getLocalizedMessage(), e);
      throw new InternalErrorException(
          "Failed to deal with the request: " + e.getLocalizedMessage());
    }
    try {
      kafkaConfig = kafkaConfigService.updateKafkaConfig(kafkaConfig);
    } catch (AccessDeniedException accessDeniedException) {
      throw new ForbiddenException("You don't have right to update this KafkaConfig.");
    } catch (Exception e) {
      logger.error("Failed to deal with the request:" + e.getLocalizedMessage(), e);
      throw new InternalErrorException(
          "Failed to deal with the request: " + e.getLocalizedMessage());
    }

    streamingRequest.setSuccessful(true);

    return streamingRequest;
  }
 /**
  * Returns either a list of all the files connected to this program or the single file that
  * represents this program exactly, if such a file exists.
  *
  * @param request
  * @param context
  * @return
  * @throws InvalidCredentialsException
  * @throws InvalidResourceException
  * @throws MethodFailedException
  */
 private List<String> findFileObjects(TranscodeRequest request, InfrastructureContext context)
     throws InvalidCredentialsException, InvalidResourceException, MethodFailedException {
   CentralWebservice doms = CentralWebserviceFactory.getServiceInstance(context);
   List<String> fileObjectPids = new ArrayList<String>();
   List<Relation> relations = doms.getRelations(request.getObjectPid());
   for (Relation relation : relations) {
     logger.debug(
         "Relation: "
             + request.getObjectPid()
             + " "
             + relation.getPredicate()
             + " "
             + relation.getObject());
     if (relation.getPredicate().equals(HAS_EXACT_FILE_RELATION)) {
       fileObjectPids = new ArrayList<String>();
       fileObjectPids.add(relation.getObject());
       request.setHasExactFile(true);
       logger.debug(
           "Program " + request.getObjectPid() + " has an exact file " + relation.getObject());
       return fileObjectPids;
     } else if (relation.getPredicate().equals(HAS_FILE_RELATION)) {
       fileObjectPids.add(relation.getObject());
     }
   }
   return fileObjectPids;
 }
Example #30
0
  private String startConnector(String remoteDomain, HostAndPort address)
      throws ExecutionException, InterruptedException {
    String cellName = "c-" + remoteDomain + "*";
    String clientKey = args.getOpt("clientKey");
    clientKey = (clientKey != null) && (clientKey.length() > 0) ? ("-clientKey=" + clientKey) : "";
    String clientName = args.getOpt("clientUserName");
    clientName =
        (clientName != null) && (clientName.length() > 0) ? ("-clientUserName=" + clientName) : "";

    String cellArgs =
        "-domain="
            + remoteDomain
            + " "
            + "-lm="
            + getCellName()
            + " "
            + "-role="
            + role
            + " "
            + "-where="
            + address
            + " "
            + clientKey
            + " "
            + clientName;
    LOGGER.info("Starting connector with {}", cellArgs);
    LocationManagerConnector c = new LocationManagerConnector(cellName, cellArgs);
    c.start().get();
    LOGGER.info("Created : {}", c);
    return c.getCellName();
  }