예제 #1
5
  /** Process incoming heartbeat messages from the task trackers. */
  public synchronized int emitHeartbeat(TaskTrackerStatus trackerStatus, boolean initialContact) {
    String trackerName = trackerStatus.getTrackerName();
    trackerStatus.setLastSeen(System.currentTimeMillis());

    synchronized (taskTrackers) {
      synchronized (trackerExpiryQueue) {
        boolean seenBefore = updateTaskTrackerStatus(trackerName, trackerStatus);
        if (initialContact) {
          // If it's first contact, then clear out any state hanging around
          if (seenBefore) {
            lostTaskTracker(trackerName);
          }
        } else {
          // If not first contact, there should be some record of the tracker
          if (!seenBefore) {
            return InterTrackerProtocol.UNKNOWN_TASKTRACKER;
          }
        }

        if (initialContact) {
          trackerExpiryQueue.add(trackerStatus);
        }
      }
    }

    updateTaskStatuses(trackerStatus);
    // LOG.info("Got heartbeat from "+trackerName);
    return InterTrackerProtocol.TRACKERS_OK;
  }
예제 #2
1
 private static String getPlatformDescription() {
   return System.getProperty(BaseConstants.SystemProperties.OS_NAME)
       + BaseConstants.WS
       + System.getProperty(BaseConstants.SystemProperties.OS_VERSION)
       + ", "
       + System.getProperty(BaseConstants.SystemProperties.OS_ARCH);
 }
예제 #3
1
  public ConsoleManager(GlowServer server) {
    this.server = server;

    // install Ansi code handler, which makes colors work on Windows
    AnsiConsole.systemInstall();

    for (Handler h : logger.getHandlers()) {
      logger.removeHandler(h);
    }

    // used until/unless gui is created
    consoleHandler = new FancyConsoleHandler();
    // consoleHandler.setFormatter(new DateOutputFormatter(CONSOLE_DATE));
    logger.addHandler(consoleHandler);

    // todo: why is this here?
    Runtime.getRuntime().addShutdownHook(new ServerShutdownThread());

    // reader must be initialized before standard streams are changed
    try {
      reader = new ConsoleReader();
    } catch (IOException ex) {
      logger.log(Level.SEVERE, "Exception initializing console reader", ex);
    }
    reader.addCompleter(new CommandCompleter());

    // set system output streams
    System.setOut(new PrintStream(new LoggerOutputStream(Level.INFO), true));
    System.setErr(new PrintStream(new LoggerOutputStream(Level.WARNING), true));
  }
  public static void main(String args[]) throws Exception {
    // cache the initial set of loggers before this test begins
    // to add any loggers
    Enumeration<String> e = logMgr.getLoggerNames();
    List<String> defaultLoggers = getDefaultLoggerNames();
    while (e.hasMoreElements()) {
      String logger = e.nextElement();
      if (!defaultLoggers.contains(logger)) {
        initialLoggerNames.add(logger);
      }
    }
    ;

    String tstSrc = System.getProperty(TST_SRC_PROP);
    File fname = new File(tstSrc, LM_PROP_FNAME);
    String prop = fname.getCanonicalPath();
    System.setProperty(CFG_FILE_PROP, prop);
    logMgr.readConfiguration();

    System.out.println();
    if (checkLoggers() == PASSED) {
      System.out.println(MSG_PASSED);
    } else {
      System.out.println(MSG_FAILED);
      throw new Exception(MSG_FAILED);
    }
  }
예제 #5
1
  private void doInit() throws MqttException {
    String server = System.getProperty("knx2mqtt.mqtt.server", "tcp://localhost:1883");
    String clientID = System.getProperty("knx2mqtt.mqtt.clientid", "knx2mqtt");
    mqttc = new MqttClient(server, clientID, new MemoryPersistence());
    mqttc.setCallback(
        new MqttCallback() {
          @Override
          public void messageArrived(String topic, MqttMessage msg) throws Exception {
            try {
              processMessage(topic, msg);
            } catch (Exception e) {
              L.log(Level.WARNING, "Error when processing message " + msg + " for " + topic, e);
            }
          }

          @Override
          public void deliveryComplete(IMqttDeliveryToken token) {
            /* Intentionally ignored */
          }

          @Override
          public void connectionLost(Throwable t) {
            L.log(Level.WARNING, "Connection to MQTT broker lost", t);
            queueConnect();
          }
        });
    doConnect();
    Main.t.schedule(new StateChecker(), 30 * 1000, 30 * 1000);
  }
  /**
   * Aware-P Epanet application entry point
   *
   * @param args
   * @throws UnsupportedLookAndFeelException
   */
  public static void main(String[] args) throws UnsupportedLookAndFeelException {
    if (Utilities.isMac()) {
      System.setProperty("apple.laf.useScreenMenuBar", "true");
      System.setProperty("com.apple.mrj.application.apple.menu.about.name", "Aware-P Epanet");

      Application app = Application.getApplication();
      app.setDockIconImage(
          Toolkit.getDefaultToolkit().getImage(EpanetUI.class.getResource("/uiresources/ae.png")));

      JMenuBar menuBar = new JMenuBar();
      JMenu fileMenu = new JMenu("File");
      menuBar.add(fileMenu);

      openAction = new JMenuItem("Open");
      saveAction = new JMenuItem("Save");
      runAction = new JMenuItem("Run");

      fileMenu.add(openAction);
      fileMenu.add(saveAction);
      fileMenu.add(runAction);
      app.setDefaultMenuBar(menuBar);
    }
    UIManager.setLookAndFeel(new Plastic3DLookAndFeel());
    new EpanetUI();
  }
예제 #7
1
  /**
   * Return the value for a given name from the System Properties or the Environmental Variables.
   * The former overrides the latter.
   *
   * @param name - the name of the System Property or Environmental Variable
   * @return the value of the variable or null if it was not found
   */
  public static String getEnvOrProp(String name) {
    // System properties override env. variables
    String envVal = System.getenv(name);
    String sysPropVal = System.getProperty(name);

    if (sysPropVal != null) return sysPropVal;

    return envVal;
  }
예제 #8
1
  private String createUniqueFilename(String path) {
    String random = "" + System.nanoTime();

    // just use the last 16 numbers
    if (random.length() > 16) random = random.substring(random.length() - 16);

    random += "" + new Random(System.currentTimeMillis()).nextInt(10000);

    return path + "\\DELETE_ME_" + random;
  }
예제 #9
1
 static {
   updaterIntervalMS =
       Integer.parseInt(System.getProperty("com.mongodb.updaterIntervalMS", "5000"));
   slaveAcceptableLatencyMS =
       Integer.parseInt(System.getProperty("com.mongodb.slaveAcceptableLatencyMS", "15"));
   inetAddrCacheMS = Integer.parseInt(System.getProperty("com.mongodb.inetAddrCacheMS", "300000"));
   _mongoOptions.connectTimeout =
       Integer.parseInt(System.getProperty("com.mongodb.updaterConnectTimeoutMS", "20000"));
   _mongoOptions.socketTimeout =
       Integer.parseInt(System.getProperty("com.mongodb.updaterSocketTimeoutMS", "20000"));
 }
 private static Process startSlaveProcess(int commPort) throws IOException {
   String separator = System.getProperty("file.separator");
   String javaProc = System.getProperty("java.home") + separator + "bin" + separator + "java";
   ProcessBuilder pb =
       new ProcessBuilder(
           javaProc,
           "-cp",
           "target/test-classes;.",
           CrashingSlave.class.getName(),
           String.valueOf(commPort));
   return pb.start();
 }
예제 #11
1
 // ----This function gets as a parameter a list of terms----
 // ---------the function returns a list of tweet ids from collection search_results-----------
 // ----------------------------------------------------------------------------------------
 public LinkedList<String> get_tweets(LinkedList<String> search_terms) {
   log4j.info("starting function get_tweets");
   LinkedList<String> result = new LinkedList<String>();
   Iterator<String> terms = search_terms.iterator();
   long curr_time = System.currentTimeMillis();
   long min_time = curr_time - this.frame_time; // time below min_time will be ignored
   int count_all = 0; // tweets counter
   while (terms.hasNext()) {
     int count = 0;
     String term = terms.next();
     DBObject st = new BasicDBObject();
     try {
       st.put("searchword", term);
       DBObject obj = this.collsr.findOne(st); // look for the relevant document
       String[] tweets_plus_time =
           obj.get("tweets")
               .toString()
               .split(","); // make an array, even indexes are tweet_id's and odd indexes are their
       // time
       String new_string =
           ""; // the string to replace eventually the current field 'tweets' in the document
       for (int i = 0;
           i < tweets_plus_time.length - 1;
           i += 2) // go over the tweet ids from the document
       {
         if (Long.parseLong(tweets_plus_time[i + 1])
             >= min_time) // tweet time is within the time frame
         {
           result.add(tweets_plus_time[i]); // add tweet id to result
           count++;
           if (new_string == "") // add tweet information without leading comma
           {
             new_string += tweets_plus_time[i] + "," + tweets_plus_time[i + 1];
             // count++;
           } else // add tweet information with leading comma
           {
             new_string += "," + tweets_plus_time[i] + "," + tweets_plus_time[i + 1];
           }
         }
       }
       count_all += count;
       log4j.info(count + " tweets for term: " + term);
       obj.put("tweets", new_string); // replace 'tweets' field
       obj.put("last_update", System.currentTimeMillis()); // update time of update
       collsr.save(obj);
     } catch (NullPointerException e) {
       log4j.info("search_term: " + term + ", is not in collection search_results");
     }
   }
   log4j.info("over_all there are " + count_all + " tweets to compare!!!");
   log4j.info("ending function get_tweets");
   return result;
 }
예제 #12
1
  /**
   * This method should setup the flags/switches for the java command which will determine the
   * actual command to be executed.
   *
   * <p>Sets up flags like :
   *
   * <ul>
   *   <li>-Dem.home
   *   <li>-Dprocess.name
   * </ul>
   *
   * <br>
   * add computes the classpath.
   */
  protected void updateFlags(ServerCommand serverCmd) {

    String bootDir = System.getProperty("em.home");
    String appType = System.getProperty("appType");
    String appInst = System.getProperty("appInst");

    String javaClasspath = serverCmd.getClasspath();
    String processName = getProcessNameForLog();

    List jvmFlags = serverCmd.getJVMFlags();

    int cpToken = -1;

    for (int i = 0; i < jvmFlags.size(); i++) {
      String token = (String) jvmFlags.get(i);
      if (token.startsWith("-classpath")) {
        cpToken = i;
        javaClasspath = null;
      } else if (token.startsWith("-Dem.home")) {
        bootDir = null;
      } else if (token.startsWith("-Dprocess.name")) {
        processName = null;
      }
    }

    List addonJVMFlags = new LinkedList();

    if (bootDir != null) {
      addonJVMFlags.add("-Dem.home=" + bootDir);
    }

    if (processName != null) {
      addonJVMFlags.add("-Dprocess.name=" + processName);
    }

    if (!(appType == null || appType.trim().equals(""))) {
      addonJVMFlags.add("-DappType=" + appType);
    }

    if (!(appInst == null || appInst.trim().equals(""))) {
      addonJVMFlags.add("-DappInst=" + appInst);
    }

    if (cpToken != -1) {
      jvmFlags.remove(cpToken);
      String str = (String) jvmFlags.remove(cpToken);
      serverCmd.setClasspath(str);
    }

    jvmFlags.addAll(addonJVMFlags);
  }
 /** push bytes back, to be read again later. */
 private void pushback(byte[] bytes, int len) {
   if (pushbackBufferLen == 0) {
     pushbackBuffer = bytes; // TODO: copy?
     pushbackBufferLen = len;
     pushbackBufferOffset = 0;
   } else {
     final byte[] newPushbackBuffer = new byte[pushbackBufferLen + len];
     System.arraycopy(pushbackBuffer, 0, newPushbackBuffer, 0, pushbackBufferLen);
     System.arraycopy(bytes, 0, newPushbackBuffer, pushbackBufferLen, len);
     pushbackBuffer = newPushbackBuffer;
     pushbackBufferLen = pushbackBufferLen + len;
     pushbackBufferOffset = 0;
   }
 }
예제 #14
1
  // ----This function getting search term and tweet id ----
  // ----the function adding the tweet id and the time of search to the collection search_results--
  public void SearchResultId(String searchword, String tweet_id) {
    log4j.info(
        "starting function SearchResultId with parameters: searchword = "
            + searchword
            + ", tweet_id"
            + tweet_id);
    try {
      DBObject searchobj = new BasicDBObject();
      searchobj.put("searchword", searchword);
      DBObject obj = this.collsr.findOne(searchobj); // get document if exists
      long min_time =
          System.currentTimeMillis() - this.frame_time; // minimum time to keep in document

      if (Long.parseLong(obj.get("last_update").toString()) < min_time) {
        // last updated before minimum time - checking each tweet
        String[] tweets = obj.get("tweets").toString().split(",");
        String new_string = "";
        for (int i = 1; i < tweets.length; i += 2) // going over all existing tweets in document
        {
          if (Long.parseLong(tweets[i]) >= min_time) {
            // tweet stays in document
            if (new_string == "") {
              // no leading comma
              new_string += tweets[i - 1] + "," + tweets[i];
            } else {
              // leading comma
              new_string += "," + tweets[i - 1] + "," + tweets[i];
            }
          }
        }
        obj.put("tweets", new_string + "," + tweet_id);
        obj.put("last_update", System.currentTimeMillis());
        // obj.put("in_process", 0);
        this.collsr.save(obj);
      } else {
        // last updated after minimum time - just adding tweet
        obj.put("tweets", obj.get("tweets").toString() + "," + tweet_id);
        this.collsr.save(obj);
      }

    } catch (NullPointerException e) {
      // there is no document yet, creating one
      DBObject searchobj = new BasicDBObject();
      searchobj.put("searchword", searchword);
      searchobj.put("tweets", tweet_id);
      searchobj.put("last_update", System.currentTimeMillis());
      this.collsr.save(searchobj);
    }
    log4j.info("ending function SearchResultId");
  }
  /**
   * Obtain an ObjectInputStream that allows de-serialization of a graph of objects.
   *
   * @throws IOException when the de-serialziation fails
   * @return an ObjectInputStream that can be used to deserialize objects
   */
  public ObjectInputStream createObjectInputStream(
      final InputStream is, final boolean resolveObject, final ClassLoader loader)
      throws Exception {
    ObjectInputStream ois = null;
    if (loader != null) {
      // Need privileged block here because EJBObjectInputStream
      // does enableResolveObject
      if (System.getSecurityManager() == null) {
        ois = new EJBObjectInputStream(is, loader, resolveObject);
      } else {
        try {
          ois =
              (ObjectInputStream)
                  AccessController.doPrivileged(
                      new PrivilegedExceptionAction() {
                        public java.lang.Object run() throws Exception {
                          return new EJBObjectInputStream(is, loader, resolveObject);
                        }
                      });
        } catch (PrivilegedActionException ex) {
          throw (IOException) ex.getException();
        }
      }
    } else {
      ois = new ObjectInputStream(is);
    }

    return ois;
  }
예제 #16
1
  /*
   * Obtain device names configured in the WebUI (ReGa)
   */
  private static void fetchDeviceNamesFromReGa() {
    lastFetch = System.currentTimeMillis();

    L.info("Obtaining ReGa device and channel names");
    String r =
        TCLRegaHandler.sendHMScript(
            "string id;"
                + "foreach(id, root.Channels ().EnumUsedIDs())"
                + "  {"
                + "   var ch=dom.GetObject(id);"
                + "   WriteLine(ch.Address()+\"\t\"+ch.Name());"
                + "  }"
                + "foreach(id, root.Devices().EnumUsedIDs())"
                + "  {"
                + "   var d=dom.GetObject(id);"
                + "   WriteLine(d.Address()+\":0\t\"+d.Name());"
                + "  }");
    if (r == null) return;
    String lines[] = r.split("\n");
    for (String l : lines) {
      String p[] = l.split("\t");
      synchronized (nameCache) {
        if (p.length == 2) nameCache.put(p[0], p[1]);
      }
    }
    couldFetchOnce = true;
    DeviceInfo.resolveNames();
  }
예제 #17
1
  private void winning() {
    String[] options = {"Try again", "Go back to Start", "Quit"};
    InformationFrame.stopClock();
    int n =
        JOptionPane.showOptionDialog(
            rootPane,
            "You won!"
                + "\n╔══╗░░░░╔╦╗░░╔═════╗"
                + "\n║╚═╬════╬╣╠═╗║░▀░▀░║"
                + "\n╠═╗║╔╗╔╗║║║╩╣║╚═══╝║"
                + "\n╚══╩╝╚╝╚╩╩╩═╝╚═════╝",
            "Smileys  c:  ☺  ☻  ت ヅ  ツ  ッ  シ Ü  ϡ  ﭢ" + "\nWhat would you like to do now?",
            JOptionPane.YES_NO_CANCEL_OPTION,
            JOptionPane.QUESTION_MESSAGE,
            null,
            options,
            options[2]);

    if (n == 2) {
      // System.out.println("n = " + n);
      System.exit(0);
    } else if (n == 1) {
      InformationFrame.dispose();
      main(null);
      this.dispose();
    } else if (n == 0) {
      String difficulty = MainManager.getMainGrid().getDifficulty();
      MainPanel.removeAll();
      constructMinesweeper(difficulty.toLowerCase());
    }
  }
예제 #18
1
 /** constructor */
 public DanceQueuePanel() {
   //	flow layout
   setLayout(new FlowLayout());
   //	uses buffer	to	draw arrows	based	on	queues in an array
   myImage = new BufferedImage(600, 600, BufferedImage.TYPE_INT_RGB);
   myBuffer = myImage.getGraphics();
   // uses timer to queue buffer changes
   time = 0;
   timer = new Timer(5, new Listener());
   timer.start();
   setFocusable(true);
   // picks instructions	based	on	song & level
   if (Danceoff.getSong() == -1 && Danceoff.getDifficulty() == 0) {
     arrows = new Arrow[] {new UpArrow(1000), new DownArrow(2000), new LeftArrow(3000)};
   }
   // setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.BLACK, 3),
   //	"DanceQueuePanel"));
   // load images for arrows
   rightArrowImg = null;
   leftArrowImg = null;
   upArrowImg = null;
   downArrowImg = null;
   try {
     rightArrowImg = ImageIO.read(new File("arrowB right.png"));
     leftArrowImg = ImageIO.read(new File("arrowB left.png"));
     upArrowImg = ImageIO.read(new File("arrowB up copy.png"));
     downArrowImg = ImageIO.read(new File("arrowB down.png"));
   } catch (IOException e) {
     warn("YOU FAIL", e);
     System.exit(2);
   }
 }
예제 #19
1
 @Override
 public void paintChildren(Graphics g) {
   super.paintChildren(g);
   if (exitAfterFirstPaint) {
     System.exit(0);
   }
 }
 /**
  * Obtain an ObjectOutputStream that allows serialization of a graph of objects. The objects can
  * be plain Serializable objects or can be converted into Serializable objects using the handler
  *
  * @throws IOException when the serialziation fails
  * @return an ObjectOutputStream that can be used to serialize objects
  */
 public ObjectOutputStream createObjectOutputStream(
     final OutputStream os,
     final boolean replaceObject,
     final NonSerializableObjectHandler handler)
     throws IOException {
   // Need privileged block here because EJBObjectOutputStream
   // does enableReplaceObject
   ObjectOutputStream oos = null;
   if (System.getSecurityManager() == null) {
     oos = new EJBObjectOutputStream(os, replaceObject, handler);
   } else {
     try {
       oos =
           (ObjectOutputStream)
               AccessController.doPrivileged(
                   new PrivilegedExceptionAction() {
                     public java.lang.Object run() throws Exception {
                       return new EJBObjectOutputStream(os, replaceObject, handler);
                     }
                   });
     } catch (PrivilegedActionException ex) {
       throw (IOException) ex.getException();
     }
   }
   return oos;
 }
예제 #21
0
 /** Prints an error message. */
 private static void printError(String msg, boolean quit) {
   System.err.println(msg);
   if (quit) {
     System.err.println("See mucommander --help for more information.");
     System.exit(1);
   }
 }
예제 #22
0
파일: LibRt.java 프로젝트: yamila87/rt_src
 public static void logInit(boolean force) throws IOException {
   if (!IsLogInitialized || force) {
     LogManager.getLogManager()
         .readConfiguration(
             LibRt.class.getClassLoader().getResourceAsStream("cfg.logging.properties"));
     String logFile = System.getProperty("CfgLog");
     if (logFile != null) {
       LogManager.getLogManager().readConfiguration(new FileInputStream(logFile));
     }
     try {
       LogLvlMax = Integer.parseInt(System.getProperty("LogLvlMax", LogLvlMax + ""));
     } catch (Exception ex) {
     }
     ; // XXX: mostrar mensaje?
   }
 }
예제 #23
0
    /**
     * The run method lives for the life of the JobTracker, and removes Jobs that are not still
     * running, but which finished a long time ago.
     */
    public void run() {
      while (shouldRun) {
        try {
          Thread.sleep(RETIRE_JOB_CHECK_INTERVAL);
        } catch (InterruptedException ie) {
        }

        synchronized (jobs) {
          synchronized (jobInitQueue) {
            synchronized (jobsByArrival) {
              for (Iterator it = jobs.keySet().iterator(); it.hasNext(); ) {
                String jobid = (String) it.next();
                JobInProgress job = (JobInProgress) jobs.get(jobid);

                if (job.getStatus().getRunState() != JobStatus.RUNNING
                    && job.getStatus().getRunState() != JobStatus.PREP
                    && (job.getFinishTime() + RETIRE_JOB_INTERVAL < System.currentTimeMillis())) {
                  it.remove();

                  jobInitQueue.remove(job);
                  jobsByArrival.remove(job);
                }
              }
            }
          }
        }
      }
    }
예제 #24
0
  private String ReadWholeFileToString(String filename) {

    File file = new File(filename);
    StringBuffer contents = new StringBuffer();
    BufferedReader reader = null;

    try {
      reader = new BufferedReader(new FileReader(file));
      String text = null;

      // repeat until all lines is read
      while ((text = reader.readLine()) != null) {
        contents.append(text).append(System.getProperty("line.separator"));
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        if (reader != null) {
          reader.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    // show file contents here
    return contents.toString();
  }
예제 #25
0
  /**
   * Is Period Open for Doc Base Type
   *
   * @param DocBaseType document base type
   * @param dateAcct accounting date
   * @return error message or null
   */
  public String isOpen(String DocBaseType, Timestamp dateAcct) {
    if (!isActive()) {
      s_log.warning("Period not active: " + getName());
      return "@C_Period_ID@ <> @IsActive@";
    }

    MAcctSchema as = MClient.get(getCtx(), getAD_Client_ID()).getAcctSchema();
    if (as != null && as.isAutoPeriodControl()) {
      if (!as.isAutoPeriodControlOpen(dateAcct)) return "@PeriodClosed@ - @AutoPeriodControl@";
      //	We are OK
      Timestamp today = new Timestamp(System.currentTimeMillis());
      if (isInPeriod(today) && as.getC_Period_ID() != getC_Period_ID()) {
        as.setC_Period_ID(getC_Period_ID());
        as.save();
      }
      return null;
    }

    //	Standard Period Control
    if (DocBaseType == null) {
      log.warning(getName() + " - No DocBaseType");
      return "@NotFound@ @DocBaseType@";
    }
    MPeriodControl pc = getPeriodControl(DocBaseType);
    if (pc == null) {
      log.warning(getName() + " - Period Control not found for " + DocBaseType);
      return "@NotFound@ @C_PeriodControl_ID@: " + DocBaseType;
    }
    log.fine(getName() + ": " + DocBaseType);
    if (pc.isOpen()) return null;
    return "@PeriodClosed@ - @C_PeriodControl_ID@ (" + DocBaseType + ", " + dateAcct + ")";
  } //	isOpen
예제 #26
0
  private void initContext() {

    // Initialize context identifier. Mandatory.
    contextId = System.getProperty(CONFIG_KEY_CERES_CONTEXT, DEFAULT_CERES_CONTEXT);

    // Initialize application specific configuration keys
    homeDirKey = String.format("%s.%s", contextId, CONFIG_KEY_HOME);
    debugKey = String.format("%s.%s", contextId, CONFIG_KEY_DEBUG);
    configFileKey = String.format("%s.%s", contextId, CONFIG_KEY_CONFIG_FILE_NAME);
    modulesDirKey = String.format("%s.%s", contextId, CONFIG_KEY_MODULES);
    libDirsKey = String.format("%s.%s", contextId, CONFIG_KEY_LIB_DIRS);
    mainClassKey = String.format("%s.%s", contextId, CONFIG_KEY_MAIN_CLASS);
    classpathKey = String.format("%s.%s", contextId, CONFIG_KEY_CLASSPATH);
    applicationIdKey = String.format("%s.%s", contextId, CONFIG_KEY_APP);
    logLevelKey = String.format("%s.%s", contextId, CONFIG_KEY_LOG_LEVEL);
    consoleLogKey = String.format("%s.%s", contextId, CONFIG_KEY_CONSOLE_LOG);

    // Initialize default file and directory paths
    char sep = File.separatorChar;
    defaultRelConfigFilePath =
        String.format("%s/%s", DEFAULT_CONFIG_DIR_NAME, configFileKey).replace('/', sep);
    defaultHomeConfigFilePath =
        String.format("${%s}/%s", homeDirKey, defaultRelConfigFilePath).replace('/', sep);
    defaultHomeModulesDirPath =
        String.format("${%s}/%s", homeDirKey, DEFAULT_MODULES_DIR_NAME).replace('/', sep);
    defaultHomeLibDirPath =
        String.format("${%s}/%s", homeDirKey, DEFAULT_LIB_DIR_NAME).replace('/', sep);
  }
예제 #27
0
  /**
   * Restart of the application server :
   *
   * <p>All running services are stopped. LookupManager is flushed.
   *
   * <p>Client code that started us should notice the special return value and restart us.
   */
  protected final void doExecute(AdminCommandContext context) {
    try {
      // unfortunately we can't rely on constructors with HK2...
      if (registry == null)
        throw new NullPointerException(
            new LocalStringsImpl(getClass())
                .get("restart.server.internalError", "registry was not set"));

      init(context);

      if (!verbose) {
        // do it now while we still have the Logging service running...
        reincarnate();
      }
      // else we just return a special int from System.exit()

      Collection<Module> modules = registry.getModules("com.sun.enterprise.osgi-adapter");
      if (modules.size() == 1) {
        final Module mgmtAgentModule = modules.iterator().next();
        mgmtAgentModule.stop();
      } else
        context.getLogger().warning(strings.get("restart.server.badNumModules", modules.size()));

    } catch (Exception e) {
      context.getLogger().severe(strings.get("restart.server.failure", e));
    }

    int ret = RESTART_NORMAL;

    if (debug != null) ret = debug ? RESTART_DEBUG_ON : RESTART_DEBUG_OFF;

    System.exit(ret);
  }
예제 #28
0
 public long GetRateTimeFrame(Long UserId, Long numofhours) {
   this.log4j.info("=================================================================");
   this.log4j.info(
       "getting rate for user id: " + UserId + " within the last " + numofhours + " hours");
   long diff = numofhours * 60 * 60 * 1000; // hours to millis
   BasicDBObject docline = new BasicDBObject();
   docline.put("user_id", UserId); // querying to find the right userId
   DBObject doc = this.collrate.findOne(docline);
   if (doc == null) // there is no document for the user
   {
     this.log4j.error("user id : " + UserId + " does not exist");
     return -1L;
   } else // document exists
   {
     long result = 0;
     long currstart = Long.parseLong(doc.get("current_slot_start_time_millis").toString());
     if (System.currentTimeMillis() - diff > currstart) {
       this.log4j.info("result is 0");
       return 0;
     } else {
       double backslots = diff / this.slot_time_millis;
       if (backslots > this.num_of_slots) {
         this.log4j.info(
             "you requested longer time than the time frame, the result will be only for the previous timeframe");
       }
       for (int i = 0; i < backslots || i < this.num_of_slots; i++) {
         int slot = (int) ((this.current_slot_index - i + this.num_of_slots) % this.num_of_slots);
         result += Long.parseLong(doc.get("slot" + slot).toString());
       }
       this.log4j.info("result is " + result);
       return result;
     }
   }
 }
예제 #29
0
 /**
  * Set Measure Actual
  *
  * @param MeasureActual actual
  */
 @Override
 public void setMeasureActual(BigDecimal MeasureActual) {
   if (MeasureActual == null) return;
   super.setMeasureActual(MeasureActual);
   setDateLastRun(new Timestamp(System.currentTimeMillis()));
   setGoalPerformance();
 } //	setMeasureActual
예제 #30
0
    public void run() {
      while (!_closed) {
        try {
          updateAll();

          long now = System.currentTimeMillis();
          if (inetAddrCacheMS > 0 && _nextResolveTime < now) {
            _nextResolveTime = now + inetAddrCacheMS;
            for (Node node : _all) {
              node.updateAddr();
            }
          }

          // force check on master
          // otherwise master change may go unnoticed for a while if no write concern
          _mongo.getConnector().checkMaster(true, false);
        } catch (Exception e) {
          _logger.log(Level.WARNING, "couldn't do update pass", e);
        }

        try {
          Thread.sleep(updaterIntervalMS);
        } catch (InterruptedException ie) {
        }
      }
    }