Example #1
1
  /**
   * Create a new BeeswaxServiceImpl.
   *
   * @param dtHost The Hue host (ip or hostname).
   * @param dtPort The port Desktop runs on.
   * @param dtHttps Whether Desktop is running https.
   */
  public BeeswaxServiceImpl(String dtHost, int dtPort, boolean dtHttps) {
    LogContext.initLogCapture();
    this.executor = Executors.newCachedThreadPool(new NamingThreadFactory("Beeswax-%d"));
    this.runningQueries = new ConcurrentHashMap<String, RunningQueryState>();

    String protocol;
    if (dtHttps) {
      protocol = "https";
      try {
        // Disable SSL verification. HUE cert may be signed by untrusted CA.
        SSLContext sslcontext = SSLContext.getInstance("SSL");
        sslcontext.init(
            null, new DummyX509TrustManager[] {new DummyX509TrustManager()}, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory());
      } catch (NoSuchAlgorithmException ex) {
        LOG.warn("Failed to disable SSL certificate check " + ex);
      } catch (KeyManagementException ex) {
        LOG.warn("Failed to disable SSL certificate check " + ex);
      }
      DummyHostnameVerifier dummy = new DummyHostnameVerifier();
      HttpsURLConnection.setDefaultHostnameVerifier(dummy);
    } else {
      protocol = "http";
    }
    this.notifyUrl = protocol + "://" + dtHost + ":" + dtPort + NOTIFY_URL_BASE;

    // A daemon thread that periodically evict stale RunningQueryState objects
    Thread evicter =
        new Thread(
            new Runnable() {
              @Override
              public void run() {
                while (true) {
                  long now = System.currentTimeMillis();
                  for (Map.Entry<String, RunningQueryState> entry : runningQueries.entrySet()) {
                    RunningQueryState rqState = entry.getValue();
                    if (rqState.getAtime() + RUNNING_QUERY_LIFETIME < now) {
                      String id = entry.getKey();
                      runningQueries.remove(id);
                      LOG.debug("Removed " + rqState.toString());
                      Thread.yield(); // be nice
                    }
                  }

                  LogContext.garbageCollect(RUNNING_QUERY_LIFETIME);

                  long wakeup = now + EVICTION_INTERVAL;
                  while (System.currentTimeMillis() < wakeup) {
                    try {
                      Thread.sleep(EVICTION_INTERVAL);
                    } catch (InterruptedException e) {
                    }
                  }
                }
              }
            },
            "Evicter");
    evicter.setDaemon(true);
    evicter.start();
  }
Example #2
1
  /** {@inheritDoc} */
  public LLRPBitList encodeBinarySpecific() {
    LLRPBitList resultBits = new LLRPBitList();

    if (vendorIdentifier == null) {
      LOGGER.warn(" vendorIdentifier not set");
      throw new MissingParameterException(
          " vendorIdentifier not set  for Parameter of Type Custom");
    }

    resultBits.append(vendorIdentifier.encodeBinary());

    if (parameterSubtype == null) {
      LOGGER.warn(" parameterSubtype not set");
      throw new MissingParameterException(
          " parameterSubtype not set  for Parameter of Type Custom");
    }

    resultBits.append(parameterSubtype.encodeBinary());

    if (data == null) {
      LOGGER.warn(" data not set");
      throw new MissingParameterException(" data not set  for Parameter of Type Custom");
    }

    resultBits.append(data.encodeBinary());

    return resultBits;
  }
  /**
   * Add a section to a list of components.
   *
   * @param components List of components
   * @param sectionId The {@link URI} identifying the section
   * @param menuOptions {@link MenuOptions options} for creating the menu
   */
  private void addSection(List<Component> components, URI sectionId, MenuOptions menuOptions) {
    List<Component> childComponents = makeComponents(sectionId, menuOptions);

    MenuComponent sectionDef = uriToMenuElement.get(sectionId);
    addNullSeparator(components);
    if (childComponents.isEmpty()) {
      logger.warn("No sub components found for section " + sectionId);
      return;
    }
    Action sectionAction = sectionDef.getAction();
    if (sectionAction != null) {
      String sectionLabel = (String) sectionAction.getValue(NAME);
      if (sectionLabel != null) {
        // No separators before the label
        stripTrailingNullSeparator(components);
        Color labelColor = (Color) sectionAction.getValue(SECTION_COLOR);
        if (labelColor == null) labelColor = GREEN;
        ShadedLabel label = new ShadedLabel(sectionLabel, labelColor);
        components.add(label);
      }
    }
    for (Component childComponent : childComponents)
      if (childComponent == null) {
        logger.warn("Separator found within section " + sectionId);
        addNullSeparator(components);
      } else components.add(childComponent);
    addNullSeparator(components);
  }
Example #4
0
 /**
  * Get value out of a specified element's name in XML file
  *
  * @param xmlFile XML File to look at
  * @param elementName Element name, in which the value is wanted
  * @return (String) Element's value
  * @throws IOException
  */
 public static String parseXmlFile(String xmlFile, String elementName) throws IOException {
   DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
   String output = null;
   try {
     File file = new File(xmlFile);
     DocumentBuilder db = dbf.newDocumentBuilder();
     Document doc = db.parse(file);
     doc.getDocumentElement().normalize();
     NodeList nodeLst = doc.getDocumentElement().getElementsByTagName("key");
     for (int i = 0; i < nodeLst.getLength(); i++) {
       Node currentNode = nodeLst.item(i);
       Element currentElement = (Element) currentNode;
       String keyName = currentElement.getAttribute("name");
       if (!keyName.equals(elementName)) {
         continue;
       } else {
         Element value = (Element) currentElement.getElementsByTagName("value").item(0);
         output = value.getChildNodes().item(0).getNodeValue();
         break;
       }
     }
   } catch (ParserConfigurationException pce) {
     logger.warn(pce);
   } catch (SAXException se) {
     logger.warn(se);
   }
   return output;
 }
Example #5
0
  /**
   * Create a new file based on hash code, including the directory structure if necessary. In case
   * of collision, we will reset hashcode and try again.
   *
   * @param dir the directory where the new file will be created
   * @param hash the initial hash value
   * @return the file created successfully
   * @throws Exception
   */
  public static File createNewFile(File dir, int hash) throws Exception {
    File f = null;
    boolean success = false;
    Exception lastException = null;
    for (int i = 0; i < MAX_TIMES_CREATE_FILE && !success; i++) {
      // In UNIX, mkdirs and createNewFile can throw IOException
      // instead of nicely returning false
      try {
        if (!dir.exists()) {
          success = dir.mkdirs();
          if (!success)
            throw new IOException("Directory creation failed: " + dir.getCanonicalPath());
        }

        // Try to construct a new file name everytime
        f = new File(dir, toHex(hash++));

        success = f.createNewFile();

        if (i > 0)
          log.info("file: " + dir.getCanonicalPath() + " created successfully after retries: " + i);

        if (success) return f;
        else i--; // if not success, we should not increment i which is
        // for exceptional retry
      } catch (Exception e) {
        if (lastException == null)
          log.warn(
              "failed to create file: "
                  + dir.getCanonicalPath()
                  + " - retry: "
                  + (i + 1)
                  + " of "
                  + MAX_TIMES_CREATE_FILE
                  + ". Will retry again.",
              e);
        else
          log.warn(
              "failed to create file: "
                  + dir.getCanonicalPath()
                  + " - got the same exception as above - retry: "
                  + (i + 1)
                  + " of "
                  + MAX_TIMES_CREATE_FILE
                  + ". Will retry again");
        lastException = e;

        success = false;

        // Maybe other thread is trying to do the same thing
        // Let's wait for INTERVAL_CREATE_FILE ms - this rarely happens
        try {
          Thread.sleep(INTERVAL_CREATE_FILE);
        } catch (InterruptedException e1) {
        }
      }
    }
    // Run out of retries, throw original exception
    throw lastException;
  }
Example #6
0
  @Override
  public void configure(Configuration conf, FileSystem fs) {
    // read stopwords from file (stopwords will be empty set if file does not exist or is empty)
    String stopwordsFile = conf.get(Constants.StopwordList);
    stopwords = readInput(fs, stopwordsFile);
    String stemmedStopwordsFile = conf.get(Constants.StemmedStopwordList);
    stemmedStopwords = readInput(fs, stemmedStopwordsFile);
    isStopwordRemoval = !stopwords.isEmpty();
    isStemming = conf.getBoolean(Constants.Stemming, true);

    VocabularyWritable vocab;
    try {
      vocab =
          (VocabularyWritable)
              HadoopAlign.loadVocab(new Path(conf.get(Constants.CollectionVocab)), fs);
      setVocab(vocab);
    } catch (Exception e) {
      LOG.warn("No vocabulary provided to tokenizer.");
      vocab = null;
    }

    LOG.warn(
        "Stemming is "
            + isStemming
            + "; Stopword removal is "
            + isStopwordRemoval
            + "; number of stopwords: "
            + stopwords.size()
            + "; stemmed: "
            + stemmedStopwords.size());
  }
  public static boolean waitForInstellationToFinish(
      String installationStatus, int timeout, String commandParam, ExecuteWindowsCommands command) {
    boolean success = false;
    try {
      while (totalTimeout > timeout) {
        if (installationStatus.contains("RUNNING")) {
          success = true;
          System.out.println(SUCCESS_MESSAGE);
          logger.info(SUCCESS_MESSAGE);
          break;
        } else {

          TimeUnit.SECONDS.sleep(timeout);
          timeout = timeout + 60;
          logger.warn(WARNING_MESSAGE);
          System.out.println(WARNING_MESSAGE);
          installationStatus = command.anyCMDCommandLocally(commandParam);
        }
      }
    } catch (InterruptedException e) {
      logger.warn(WARNING_MESSAGE + e.getMessage());
    }
    if (timeout > totalTimeout && (!installationStatus.contains("RUNNING"))) {
      ERROR_MESSAGE_TC = "It was Not Possible to Install Agent";
      logger.fatal(ERROR_MESSAGE_TC);
      System.out.println(ERROR_MESSAGE_TC);
    }
    return success;
  }
  private void startAdditionalServices() {

    Script command = new Script("rm", s_logger);
    command.add("-rf");
    command.add(extractMountPoint);
    String result = command.execute();
    if (result != null) {
      s_logger.warn("Error in creating file " + extractMountPoint + " ,error: " + result);
      return;
    }

    command = new Script("touch", s_logger);
    command.add(extractMountPoint);
    result = command.execute();
    if (result != null) {
      s_logger.warn("Error in creating file " + extractMountPoint + " ,error: " + result);
      return;
    }

    command = new Script("/bin/bash", s_logger);
    command.add("-c");
    command.add("ln -sf " + parentDir + " " + extractMountPoint);
    result = command.execute();
    if (result != null) {
      s_logger.warn("Error in linking  err=" + result);
      return;
    }
  }
Example #9
0
  public static JSONObject getVersionInfo() {
    synchronized (LOGGER) {
      final JSONObject o = new JSONObject();
      try {
        final InputStream stream = Stats.class.getResourceAsStream("/version.prop");
        if (props == null) {
          props = new Properties();
          try {
            props.load(stream);
            stream.close();
          } catch (Exception e) {
            LOGGER.warn(e, e);
            props = null;
          }
        }
        props.put("uptime", Long.toString(MonitorApplication.getUptime()));

        final List<CacheDataModel> cwProps = CacheWatcher.getProps();
        for (CacheDataModel m : cwProps) {
          props.put(m.getKey(), m.getValue());
        }
        o.put("stats", props);

      } catch (JSONException e) {
        LOGGER.warn(e, e);
      }
      return o;
    }
  }
Example #10
0
  /** Create a tree of issues with relationship between parent and child issues */
  public void loadIssues() {
    if (this.getIssues() != null) {
      this.getIssues().clear();
    }
    issueListTree = new DefaultTreeNode("root", null);
    List<Issue> issuestemp = issueService.findIssuesParent(projectId, sprintId);
    try {
      issuestemp.addAll(issueService.findIssuesSingle(sprintId));
    } catch (Exception e) {
      LOGGER.warn(e);
    }
    try {
      for (Issue i : issuestemp) {
        TreeNode parent = new DefaultTreeNode(String.valueOf(i.getIssueId()), i, issueListTree);
        parent.setExpanded(true);

        List<Issue> subissues = issueService.findIssueByParent(i);
        if (subissues == null || subissues.size() <= 0) {
          this.getIssues().add(i);
        }
        try {
          for (Issue j : subissues) {
            new DefaultTreeNode(String.valueOf(j.getIssueId()), j, parent);
            this.getIssues().add(j);
          }

        } catch (Exception e) {
          LOGGER.warn(e);
        }
      }

    } catch (Exception e) {
      LOGGER.warn(e);
    }
  }
Example #11
0
  @Override
  public void reconnect() {
    int numTries = 0;
    int pauseInMs = 100;
    boolean connected = false;

    if (connectionFactory == null) {
      logger.warn("Asked to reconnect to AMQ but no connectionFactory was configured!");
      return;
    }

    synchronized (connectionMonitor) {
      close();
      while (!connected) {
        numTries++;
        try {
          connection = connectionFactory.createTopicConnection();
          connection.start();
          connected = true;
        } catch (JMSException ex) {
          logger.warn("Got error while trying to connect to activemq");
          try {
            Thread.sleep((long) pauseInMs);
          } catch (InterruptedException innerEx) {
            Thread.currentThread().interrupt();
            return;
          }
          if (numTries < 10) {
            pauseInMs += pauseInMs;
          }
        }
      }
    }
  }
  /**
   * TODO: getPKType definition.
   *
   * @param table
   */
  private Integer getPKType(Table table) {
    if (table.getPrimaryKey() == null) {
      logger.warn(table.getName() + " has no PK");
      return null;
    } else if (table.getPrimaryKey().getColumns().size() != 1) {
      logger.warn(
          table.getName()
              + " - PK is not a single-column one "
              + table.getPrimaryKey().getColumns());
      return null;
    } else {
      // Check whether primary key is NUMBER based
      int type = table.getPrimaryKey().getColumns().get(0).getType();

      if (type == Types.VARCHAR
          || (type == Types.OTHER
              && table
                  .getPrimaryKey()
                  .getColumns()
                  .get(0)
                  .getTypeDescription()
                  .contains("VARCHAR"))) {
        return Types.VARCHAR;
      } else if ((type == Types.BIGINT
          || type == Types.INTEGER
          || type == Types.SMALLINT
          || type == Types.DECIMAL)) {
        return Types.NUMERIC;
      } else {
        logger.warn(table.getName() + " - PK is not a supported chunking datatype ");
        return null;
      }
    }
  }
Example #13
0
  @Override
  public void run(Client client, Message msg) {
    // Lookup client
    Client other = Server.getServer().getClient(msg.getParam(0));

    if (other == null) {
      // No such nickname
      client.send(
          client
              .newNickMessage("401")
              .appendParam(msg.getParam(0))
              .appendParam("No such nick / channel"));
    } else {
      // Must have kill rights
      if (client.hasPermission(Permissions.kill)) {
        // Kill them
        logger.warn(
            client.id.toString() + " killed " + other.id.toString() + " (" + msg.getParam(1) + ")");
        other.close("Killed by " + client.id.nick + " (" + msg.getParam(1) + ")");
      } else {
        // Permission denied
        logger.warn(
            client.id.toString() + " attempted to kill " + other.id.toString() + " but was denied");
        client.send(client.newNickMessage("481").appendParam("KILL: Permission Denied"));
      }
    }
  }
Example #14
0
  /**
   * Send a message to the peer which is represented by the current PeerViewElement.
   *
   * @param msg the message to send
   * @param serviceName the service name on the destination peer to which the message will be
   *     demultiplexed
   * @param serviceParam the service param on the destination peer to which the message will be
   *     demultiplexed
   * @return true if the message was successfully handed off to the endpoint for delivery, false
   *     otherwise
   */
  public boolean sendMessage(Message msg, String serviceName, String serviceParam) {

    if (throttling) {
      if (LOG.isEnabledFor(Level.WARN)) {
        LOG.warn("Declining to send -- throttling on " + this);
      }
      return false;
    }

    Messenger sendVia = getCachedMessenger();

    if (null == sendVia) {
      // There is nothing really we can do.
      if (LOG.isEnabledFor(Level.WARN)) {
        LOG.warn("Could not get messenger for " + getDestAddress());
      }

      OutgoingMessageEvent event =
          new OutgoingMessageEvent(
              msg, new IOException("Couldn't get messenger for " + getDestAddress()));

      messageSendFailed(event);
      return false;
    }

    sendVia.sendMessage(msg, serviceName, serviceParam, this);

    return true;
  }
Example #15
0
 public void visitAndExpr(OpAnd and) {
   if (predicates > 0) {
     Expression parent = and.getParent();
     if (!(parent instanceof PathExpr)) {
       LOG.warn("Parent expression of boolean operator is not a PathExpr: " + parent);
       return;
     }
     PathExpr path;
     Predicate predicate;
     if (parent instanceof Predicate) {
       predicate = (Predicate) parent;
       path = predicate;
     } else {
       path = (PathExpr) parent;
       parent = path.getParent();
       if (!(parent instanceof Predicate) || path.getLength() > 1) {
         LOG.warn(
             "Boolean operator is not a top-level expression in the predicate: "
                 + parent.getClass().getName());
         return;
       }
       predicate = (Predicate) parent;
     }
     if (LOG.isTraceEnabled())
       LOG.trace("Rewriting boolean expression: " + ExpressionDumper.dump(and));
     hasOptimized = true;
     LocationStep step = (LocationStep) predicate.getParent();
     Predicate newPred = new Predicate(context);
     newPred.add(and.getRight());
     step.insertPredicate(predicate, newPred);
     path.replaceExpression(and, and.getLeft());
   }
 }
  /**
   * Update the information about completed thread that ran for runtime in milliseconds
   *
   * <p>This method updates all of the key timing and tracking information in the factory so that
   * thread can be retired. After this call the factory shouldn't have a pointer to the thread any
   * longer
   *
   * @param thread the thread whose information we are updating
   */
  @Ensures({"getTotalTime() >= old(getTotalTime())"})
  public synchronized void threadIsDone(final Thread thread) {
    nThreadsAnalyzed++;

    if (DEBUG) logger.warn("UpdateThreadInfo called");

    final long threadID = thread.getId();
    final ThreadInfo info = bean.getThreadInfo(thread.getId());
    final long totalTimeNano = bean.getThreadCpuTime(threadID);
    final long userTimeNano = bean.getThreadUserTime(threadID);
    final long systemTimeNano = totalTimeNano - userTimeNano;
    final long userTimeInMilliseconds = nanoToMilli(userTimeNano);
    final long systemTimeInMilliseconds = nanoToMilli(systemTimeNano);

    if (info != null) {
      if (DEBUG)
        logger.warn(
            "Updating thread with user runtime "
                + userTimeInMilliseconds
                + " and system runtime "
                + systemTimeInMilliseconds
                + " of which blocked "
                + info.getBlockedTime()
                + " and waiting "
                + info.getWaitedTime());
      incTimes(State.BLOCKING, info.getBlockedTime());
      incTimes(State.WAITING, info.getWaitedTime());
      incTimes(State.USER_CPU, userTimeInMilliseconds);
      incTimes(State.WAITING_FOR_IO, systemTimeInMilliseconds);
    }
  }
Example #17
0
  public static void main(String[] args) {
    GnuParser parser = new GnuParser();
    CommandLine commandLine;
    try {
      commandLine = parser.parse(CommandLineOption.ALL_COMMAND_LINE_OPTIONS, args);
    } catch (ParseException e) {
      printUsage(e);
      return;
    }

    URL url = ClassLoader.getSystemClassLoader().getResource("config.properties");
    Configuration.load(url);
    PropertyConfigurator.configure(url);

    AbstractCommand command = getCommand(commandLine);
    if (command != null) {
      CommandResult result = command.perform();
      switch (result.getCode()) {
        case SUCCESS:
          logger.info(result.getMessage());
          break;
        default:
          logger.warn(result.getMessage());
          break;
      }
    } else {
      logger.warn("Could not find command");
    }
  }
  @After
  public void tearDown() throws Exception {
    if (memberService.delete(haveManyEmailMember)) {
      LOGGER.info("member " + haveManyEmailMember.getMemberId() + " is deleted");
    } else {
      LOGGER.warn("member " + haveManyEmailMember.getMemberId() + " is not deleted");
    }

    if (memberService.delete(noManyEmailMember)) {
      LOGGER.info("member " + noManyEmailMember.getMemberId() + " is deleted");
    } else {
      LOGGER.warn("member " + noManyEmailMember.getMemberId() + " is not deleted");
    }

    if (memberEmailService.delete(email1)) {
      LOGGER.info("email " + email1.getEmailId() + " is deleted");
    } else {
      LOGGER.warn("email " + email1.getEmailId() + " is not deleted");
    }

    if (memberEmailService.delete(email2)) {
      LOGGER.info("email " + email2.getEmailId() + " is deleted");
    } else {
      LOGGER.warn("email " + email2.getEmailId() + " is not deleted");
    }

    if (memberEmailService.delete(email3)) {
      LOGGER.info("email " + email3.getEmailId() + " is deleted");
    } else {
      LOGGER.warn("email " + email3.getEmailId() + " is not deleted");
    }
    memberEmailList.clear();
    LOGGER.info("clear member email list done");
  }
  public void receivedAck(final FileRequest fr, final AESObject aes) {
    // so the other user has the file and will send it to us through the
    // socket (or is already transmitting).
    if (!this.currentRequest.equals(fr)) {
      log.warn("received a ack, but not for the right file request");
      return;
    }
    try {
      log.info("received server ACK, starting file transfer");
      AvailableLater<IcePeer> peerAvl = iceconnect.getNomination(fr.getPeer());
      final INegotiationSuccessListener listener = getCurrentListener();
      new AvailableLaterWrapperObject<Void, IcePeer>(peerAvl) {

        @Override
        public Void calculate() throws Exception {
          log.debug("we finally have a peer -- connecting");
          socket = udtconnect.connect(iceconnect.getSocket(), getSourceResult(), false);
          log.debug("connected -- running file transfer now");
          IceUdtFileTransfer ft = new IceUdtFileTransfer(fr, socket, aes);
          listener.succeeded(ft);
          ft.run();
          return null;
        }
      }.start();
    } catch (Exception e) {
      log.warn("received a Ack, but we couldn't find a socket", e);
      getCurrentListener()
          .failed(new IOException("No socket connection available. Try again later."));
    }
  }
  /**
   * NOT IMPLEMENTED YET, DO NOT USE see <code> makeNegativeExamplesFromParallelClasses</code>
   *
   * @param positiveSet
   */
  @SuppressWarnings("unused")
  private void makeNegativeExamplesFromClassesOfInstances(SortedSet<OWLIndividual> positiveSet) {
    logger.debug("making neg Examples from parallel classes");
    SortedSet<OWLClassExpression> classes = new TreeSet<OWLClassExpression>();
    this.fromParallelClasses.clear();

    for (OWLIndividual instance : positiveSet) {
      try {
        // realization is not implemented in reasoningservice
        // classes.addAll(reasoningService.realize()
      } catch (Exception e) {
        logger.warn("not implemented in " + this.getClass());
      }
    }
    logger.debug("getting negExamples from " + classes.size() + " parallel classes");
    for (OWLClassExpression oneClass : classes) {
      logger.debug(oneClass);
      // rsc = new
      // JenaResultSetConvenience(queryConcept("\""+oneClass+"\"",limit));
      try {
        this.fromParallelClasses.addAll(reasoningService.getIndividuals(oneClass));
      } catch (Exception e) {
        logger.warn("not implemented in " + this.getClass());
      }
    }

    fromParallelClasses.removeAll(fullPositiveSet);
    logger.debug("|-neg Example size from parallelclass: " + fromParallelClasses.size());
    throw new RuntimeException(
        "not implemented in " + this.getClass() + "method makeNegativeExamplesFromParallelClasses");
  }
 @Override
 public void startElement(
     final String uri, final String localName, final String qName, final Attributes attributes)
     throws SAXException {
   if ("testResults".equals(localName)) {
     // Check the version and output a warning if it differs
     final String version = attributes.getValue("version");
     if (version == null) {
       log.warn("No version specified in JTL file");
     } else {
       if (!version.equals(JTL_VERSION)) {
         log.warn("Parsing unknown JTL version: " + version);
       }
     }
   } else if ("sample".equals(localName) || "httpSample".equals(localName)) {
     // Get the label
     String label = attributes.getValue("lb");
     if ((label == null) || (label.length() == 0)) {
       label = "null";
     }
     SamplerImpl sampler = (SamplerImpl) samplerMap.get(label);
     if (sampler == null) {
       sampler = new SamplerImpl(label);
       samplerMap.put(label, sampler);
     }
     final long sampleTime = getLongAttribute(attributes, "t");
     final long startTime = getLongAttribute(attributes, "ts");
     final boolean pass = getBooleanAttribute(attributes, "s");
     sampler.addSample(startTime, sampleTime, pass);
     totalSampler.addSample(startTime, sampleTime, pass);
   }
 }
  public void init() {
    logger.debug(APPLICATION + " init()");

    try {
      EntityManager.registerEntityProducer(this, REFERENCE_ROOT);
    } catch (Exception e) {
      logger.warn("Error registering " + APPLICATION + " Entity Producer", e);
    }

    try {
      ComponentManager.loadComponent(
          "org.sakaiproject.bbb.tool.entity.BBBMeetingEntityProducer", this);
    } catch (Exception e) {
      logger.warn(
          "Error registering "
              + APPLICATION
              + " Entity Producer with Spring. "
              + APPLICATION
              + " will work, but "
              + APPLICATION
              + " tools won't be imported from site archives. This normally happens only if you redeploy "
              + APPLICATION
              + ". Suggest restarting Sakai",
          e);
    }
  }
Example #23
0
 public void perform() {
   while (isRunning) {
     while (dataStack.size() > 0) {
       DataPackage dataPackage = dataStack.elementAt(0);
       dataStack.removeElementAt(0);
       try {
         byte[] data = dataPackage.getAllData();
         // log.info("Send data len: " + data.length);
         os.writeInt(data.length);
         os.write(data);
         os.flush();
         lastTimeSend = System.currentTimeMillis();
       } catch (IOException e) {
         log.warn(
             "ERROR: WriterThread: IOException when try to write data which has header: "
                 + dataPackage.getHeader());
         client.detroy();
         return;
       } catch (Throwable ex) {
         log.warn("ERROR: WriterThread : faltal exception:", ex);
       }
     }
     try {
       sleep(20);
     } catch (InterruptedException e) {
     }
   }
 }
Example #24
0
  public void addListener(DistributionRequest listener) {
    synchronized (listeners) {
      if (!listeners.contains(listener)) {
        logger.warn("Adding a listener to Distributer:" + listener.toString());
        boolean needsAnd =
            SQLValidator.removeSingleQuotes(SQLValidator.removeQuotes(listener.getQuery()))
                    .indexOf(" where ")
                > 0;
        String query = SQLValidator.addPkField(listener.getQuery());
        if (needsAnd) query += " AND ";
        else query += " WHERE ";
        query += " timed > " + listener.getStartTime() + " and pk > ? order by timed asc ";
        PreparedStatement prepareStatement = null;
        try {
          prepareStatement =
              getPersistantConnection(listener.getVSensorConfig())
                  .prepareStatement(
                      query); // prepareStatement =
                              // StorageManager.getInstance().getConnection().prepareStatement(query);
          prepareStatement.setMaxRows(1000); // Limit the number of rows loaded in memory.
        } catch (Exception e) {
          throw new RuntimeException(e);
        }
        preparedStatements.put(listener, prepareStatement);
        listeners.add(listener);
        addListenerToCandidates(listener);

      } else {
        logger.warn(
            "Adding a listener to Distributer failed, duplicated listener! " + listener.toString());
      }
    }
  }
Example #25
0
  /**
   * @param file - the file to delete
   * @param deleteEmptyParents - removing empty parent folders flag
   * @param rootPath - if deleteEmptyParents is true, this parameters shows the parent folder where
   *     removing parents must stop
   * @return True, if the file has been successfully removed, otherwise returns false
   */
  public static boolean delete(File file, boolean deleteEmptyParents, String rootPath) {
    log.info("M-DELETE file: " + file);
    if (!file.exists()) {
      File rootFile = rootPath == null ? null : toFile(rootPath);
      boolean isParentReliable = isReliable(file.getParentFile(), rootFile);

      log.warn(
          format(
              isParentReliable
                  ? "File [%s] has already been deleted."
                  : "Cannot list file [%s]; is its parent-directory tree mounted and executable?",
              file));

      return isParentReliable;
    }
    if (!file.delete()) {
      log.warn("Failed to delete file: " + file);
      return false;
    }
    if (deleteEmptyParents) {
      File parentToKeep = null;
      if (rootPath != null) parentToKeep = toFile(rootPath);

      File parent = file.getParentFile();
      while (!parent.equals(parentToKeep) && parent.delete()) {
        log.info("M-DELETE directory: " + parent);
        parent = parent.getParentFile();
      }
    }
    return true;
  }
  public int sceKernelUnlockLwMutex(int workAreaAddr, int count) {
    Memory mem = Processor.memory;

    int uid = mem.read32(workAreaAddr);

    if (log.isDebugEnabled()) {
      log.debug(
          "sceKernelUnlockLwMutex (workAreaAddr=0x"
              + Integer.toHexString(workAreaAddr)
              + ", count="
              + count
              + ")");
    }

    SceKernelLwMutexInfo info = lwMutexMap.get(uid);
    if (info == null) {
      log.warn("sceKernelUnlockLwMutex unknown uid");
      return ERROR_KERNEL_LWMUTEX_NOT_FOUND;
    }
    if (info.lockedCount == 0) {
      log.debug("sceKernelUnlockLwMutex not locked");
      return ERROR_KERNEL_LWMUTEX_UNLOCKED;
    }
    if (info.lockedCount < 0) {
      log.warn("sceKernelUnlockLwMutex underflow");
      return ERROR_KERNEL_LWMUTEX_UNLOCK_UNDERFLOW;
    }

    info.lockedCount -= count;
    if (info.lockedCount == 0) {
      onLwMutexModified(info);
    }

    return 0;
  }
 /**
  * The name for this host.
  *
  * @see #HOSTNAME
  * @see <a href="http://trac.bigdata.com/ticket/886" >Provide workaround for bad reverse DNS
  *     setups</a>
  */
 public static final String getCanonicalHostName() {
   String s = System.getProperty(HOSTNAME);
   if (s != null) {
     // Trim whitespace.
     s = s.trim();
   }
   if (s != null && s.length() != 0) {
     log.warn("Hostname override: hostname=" + s);
   } else {
     try {
       /*
        * Note: This should be the host *name* NOT an IP address of a
        * preferred Ethernet adaptor.
        */
       s = InetAddress.getLocalHost().getCanonicalHostName();
     } catch (Throwable t) {
       log.warn("Could not resolve canonical name for host: " + t);
     }
     try {
       s = InetAddress.getLocalHost().getHostName();
     } catch (Throwable t) {
       log.warn("Could not resolve name for host: " + t);
       s = "localhost";
     }
   }
   return s;
 }
  public int sceKernelReferLwMutexStatusByID(int uid, int addr) {
    Memory mem = Processor.memory;

    if (log.isDebugEnabled()) {
      log.debug(
          "sceKernelReferLwMutexStatus (uid=0x"
              + Integer.toHexString(uid)
              + ", addr=0x"
              + addr
              + ")");
    }

    SceKernelLwMutexInfo info = lwMutexMap.get(uid);
    if (info == null) {
      log.warn("sceKernelReferLwMutexStatus unknown UID " + Integer.toHexString(uid));
      return ERROR_KERNEL_LWMUTEX_NOT_FOUND;
    }
    if (!Memory.isAddressGood(addr)) {
      log.warn("sceKernelReferLwMutexStatus bad address 0x" + Integer.toHexString(addr));
      return -1;
    }

    info.write(mem, addr);

    return 0;
  }
Example #29
0
  /** {@inheritDoc} */
  public Content encodeXML(String name, Namespace ns) {
    // element in namespace defined by parent element
    Element element = new Element(name, ns);
    // child element are always in default LLRP namespace
    ns = Namespace.getNamespace("llrp", LLRPConstants.LLRPNAMESPACE);

    if (vendorIdentifier == null) {
      LOGGER.warn(" vendorIdentifier not set");
      throw new MissingParameterException(" vendorIdentifier not set");
    } else {
      element.addContent(vendorIdentifier.encodeXML("VendorIdentifier", ns));
    }

    if (parameterSubtype == null) {
      LOGGER.warn(" parameterSubtype not set");
      throw new MissingParameterException(" parameterSubtype not set");
    } else {
      element.addContent(parameterSubtype.encodeXML("ParameterSubtype", ns));
    }

    if (data == null) {
      LOGGER.warn(" data not set");
      throw new MissingParameterException(" data not set");
    } else {
      element.addContent(data.encodeXML("Data", ns));
    }

    // parameters
    return element;
  }
  /**
   * Add an {@link AbstractMenuOptionGroup option group} to the list of components
   *
   * @param components List of components where to add the created {@link JMenu}
   * @param optionGroupId The {@link URI} identifying the option group
   * @param isToolbar True if the option group is to be added to a toolbar
   */
  private void addOptionGroup(
      List<Component> components, URI optionGroupId, MenuOptions menuOptions) {
    MenuOptions childOptions = new MenuOptions(menuOptions);
    childOptions.setOptionGroup(true);

    List<Component> buttons = makeComponents(optionGroupId, childOptions);
    addNullSeparator(components);
    if (buttons.isEmpty()) {
      logger.warn("No sub components found for option group " + optionGroupId);
      return;
    }
    ButtonGroup buttonGroup = new ButtonGroup();

    for (Component button : buttons) {
      if (button instanceof AbstractButton) buttonGroup.add((AbstractButton) button);
      else
        logger.warn(
            "Component of button group " + optionGroupId + " is not an AbstractButton: " + button);
      if (button == null) {
        logger.warn("Separator found within button group");
        addNullSeparator(components);
      } else components.add(button);
    }
    addNullSeparator(components);
  }