コード例 #1
0
  private String getLink(
      final String event,
      final String label,
      final String css,
      String defaultValue,
      String selectedValue,
      String tooltip) {
    String status = Utilities.escapeHTML(Utilities.filterOutHTMLTags(tooltip));

    StringBuffer link = new StringBuffer();
    defaultValue = defaultValue == null ? AbstractChip.FALSE : defaultValue;
    selectedValue = selectedValue == null ? AbstractChip.TRUE : selectedValue;
    link.append("<input type=\"hidden\" name=\"" + event + "\" value=\"" + defaultValue + "\" />");
    link.append(
        "<a href=\"#\" onMouseover=\"window.status='"
            + status
            + "'; return true;\" onMouseout=\"window.status=''; return true;\" ");
    if (css != null) {
      link.append("class=\"" + css + "\" ");
    }
    link.append("hidefocus=\"true\" ");
    link.append(
        "onclick=\"document.editorForm.elements['"
            + event
            + "'].value='"
            + selectedValue
            + "';setScrollAndSubmit();return false;\">");
    link.append(label);
    link.append("</a>");
    return link.toString();
  }
コード例 #2
0
ファイル: Bot.java プロジェクト: dims12/program-ab
  /**
   * Constructor
   *
   * @param name name of bot
   * @param path root path of Program AB
   * @param action Program AB action
   */
  public Bot(String name, String path, String action) {
    int cnt = 0;
    int elementCnt = 0;
    this.name = name;
    setAllPaths(path, name);
    this.brain = new Graphmaster(this);

    this.learnfGraph = new Graphmaster(this, "learnf");
    this.learnGraph = new Graphmaster(this, "learn");
    //      this.unfinishedGraph = new Graphmaster(this);
    //  this.categories = new ArrayList<Category>();

    preProcessor = new PreProcessor(this);
    addProperties();
    cnt = addAIMLSets();
    if (MagicBooleans.trace_mode) System.out.println("Loaded " + cnt + " set elements.");
    cnt = addAIMLMaps();
    if (MagicBooleans.trace_mode) System.out.println("Loaded " + cnt + " map elements");
    this.pronounSet = getPronouns();
    AIMLSet number = new AIMLSet(MagicStrings.natural_number_set_name, this);
    setMap.put(MagicStrings.natural_number_set_name, number);
    AIMLMap successor = new AIMLMap(MagicStrings.map_successor, this);
    mapMap.put(MagicStrings.map_successor, successor);
    AIMLMap predecessor = new AIMLMap(MagicStrings.map_predecessor, this);
    mapMap.put(MagicStrings.map_predecessor, predecessor);
    AIMLMap singular = new AIMLMap(MagicStrings.map_singular, this);
    mapMap.put(MagicStrings.map_singular, singular);
    AIMLMap plural = new AIMLMap(MagicStrings.map_plural, this);
    mapMap.put(MagicStrings.map_plural, plural);
    // System.out.println("setMap = "+setMap);
    Date aimlDate = new Date(new File(aiml_path).lastModified());
    Date aimlIFDate = new Date(new File(aimlif_path).lastModified());
    if (MagicBooleans.trace_mode)
      System.out.println("AIML modified " + aimlDate + " AIMLIF modified " + aimlIFDate);
    // readUnfinishedIFCategories();
    MagicStrings.pannous_api_key = Utilities.getPannousAPIKey(this);
    MagicStrings.pannous_login = Utilities.getPannousLogin(this);
    if (action.equals("aiml2csv")) addCategoriesFromAIML();
    else if (action.equals("csv2aiml")) addCategoriesFromAIMLIF();
    else if (action.equals("chat-app")) {
      if (MagicBooleans.trace_mode) System.out.println("Loading only AIMLIF files");
      cnt = addCategoriesFromAIMLIF();
    } else if (aimlDate.after(aimlIFDate)) {
      if (MagicBooleans.trace_mode) System.out.println("AIML modified after AIMLIF");
      cnt = addCategoriesFromAIML();
      writeAIMLIFFiles();
    } else {
      addCategoriesFromAIMLIF();
      if (brain.getCategories().size() == 0) {
        System.out.println("No AIMLIF Files found.  Looking for AIML");
        cnt = addCategoriesFromAIML();
      }
    }
    Category b =
        new Category(
            0, "PROGRAM VERSION", "*", "*", MagicStrings.program_name_version, "update.aiml");
    brain.addCategory(b);
    brain.nodeStats();
    learnfGraph.nodeStats();
  }
コード例 #3
0
  public void run() {
    if (clientSocket == null) {
      return;
    }

    PrintStream out = null;

    Utilities.printMsg("creating output stream");

    try {
      out = new PrintStream(clientSocket.getOutputStream());
    } catch (IOException e) {
      System.err.println("Error binding output to socket, " + e);
      System.exit(1);
    }

    Utilities.printMsg("writing current date");

    Date d = new Date();
    out.println(d);

    try {
      out.close();
      clientSocket.close();
    } catch (IOException e) {
    }
  }
コード例 #4
0
  /**
   * This method transform a byte value to MB, GB or TB
   *
   * @param bytes Byte value to transform
   * @param storageType Type to transform
   * @param numbOfDecimals number of decimals
   * @return value transformed
   */
  public String transformSize(double bytes, char storageType, int numbOfDecimals) {
    double m = 1048576.0;
    double g = 1073741824.0;
    double t = 1099511627776.0;
    double result = 0.0;
    String resultStr = "";

    switch (storageType) {
      case ConstantsClass.STORAGE_TYPE_MB:
        result = bytes / m;
        break;
      case ConstantsClass.STORAGE_TYPE_GB:
        result = bytes / g;
        break;
      case ConstantsClass.STORAGE_TYPE_TB:
        result = bytes / t;
        break;
    }
    resultStr =
        (numbOfDecimals == 2
            ? ensureTwoDecimalNumber(Utilities.round(result, numbOfDecimals))
            : Double.toString(Utilities.round(result, numbOfDecimals)));
    // resultStr = resultStr.concat(String.valueOf(storageType));

    return resultStr;
  }
コード例 #5
0
ファイル: Rope.java プロジェクト: NormanShapiro/Naomi
  private void end(StringBuilder ans, Pretty pretty, String indent) {
    if (endEncloser == null) return;
    if (!pretty.pretty) ans.append(endEncloser);
    else {
      Utilities.assureEndsWithNewLine(ans);
      ans.append(indent + endEncloser);
      if (pretty.comments && endComment.length() > 0) ans.append("#" + endComment);

      Utilities.assureEndsWithNewLine(ans);
    }
  }
コード例 #6
0
  /**
   * Returns the TabularData
   *
   * @return TabularData containing the rows corresponding the NetworkTable
   */
  public TabularData getNetworkTable() {
    try {
      if (table != null)
        return Utilities.getTabularData(this, indexNames, table, instrClassName, null);
      else if (vec != null)
        return Utilities.getTabularData(this, indexNames, vec, instrClassName, null);
    } catch (Exception ex) {
      ex.printStackTrace();
    }

    return null;
  }
コード例 #7
0
    public void actionPerformed(java.awt.event.ActionEvent arg0) {

      if (JTable1.getSelectedRowCount() != 1) {

        Utilities.errorMessage(resourceBundle.getString("Please select a view to edit"));
        return;
      }

      views = new ViewsWizard(ViewConfig.this, applet);
      views.setSecurityModel(model);
      Point p = JLabel1.getLocationOnScreen();
      views.setLocation(p);
      views.init();

      views.setState(false);
      Vector viewvec = model.getAllViews();
      for (int i = 0; i < viewvec.size(); i++) {
        String viewname = ((AuthViewWithOperations) viewvec.elementAt(i)).getAuthorizedViewName();
        if (JTable1.getValueAt(JTable1.getSelectedRow(), 0).toString().equals(viewname)) {
          views.setValues((AuthViewWithOperations) viewvec.elementAt(i));
        }
      }

      disableButtons();
      views.setVisible(true);
    }
コード例 #8
0
    public void actionPerformed(java.awt.event.ActionEvent arg0) {
      if (JTable1.getSelectedRowCount() != 1) {
        Utilities.errorMessage(resourceBundle.getString("Please select a view to delete"));
        return;
      }

      if (JOptionPane.showConfirmDialog(
              null,
              resourceBundle.getString("Are you sure you want to delete the selected view "),
              resourceBundle.getString("Warning!"),
              JOptionPane.YES_NO_OPTION,
              JOptionPane.WARNING_MESSAGE,
              null)
          == JOptionPane.NO_OPTION) return;

      Vector viewvec = model.getAllViews();
      for (int i = 0; i < viewvec.size(); i++) {
        String viewname = ((AuthViewWithOperations) viewvec.elementAt(i)).getAuthorizedViewName();
        if (JTable1.getValueAt(JTable1.getSelectedRow(), 0).toString().equals(viewname)) {
          AuthViewWithOperations avop = (AuthViewWithOperations) viewvec.elementAt(i);

          model.delViewOp(
              avop.getAuthorizedViewName(), avop.getViewProperties(), avop.getOperations());
        }
      }

      disableButtons();
    }
コード例 #9
0
ファイル: YamlConfig.java プロジェクト: yafengli/jyaml
 public ObjectWrapper getWrapperSetContent(String classname, String content) {
   SimpleObjectWrapper wrapper;
   Class type = ReflectionUtil.classForName(transfer2classname(classname));
   if (handlers != null && handlers.containsKey(classname)) {
     wrapper = (SimpleObjectWrapper) initWrapper(classname, type);
     wrapper.setObject(Utilities.convertType(content, wrapper.expectedArgType()));
   } else if (type != null && type.isEnum()) {
     wrapper = new EnumWrapper(type);
     wrapper.setObject(Utilities.convertType(content, wrapper.expectedArgType()));
   } else {
     wrapper = new DefaultSimpleTypeWrapper(type);
     wrapper.setObject(Utilities.convertType(content, wrapper.expectedArgType()));
   }
   wrapper.setYamlConfig(this);
   return wrapper;
 }
コード例 #10
0
 /**
  * If the appropriate config property is true (hmc.escape.html), all html content in the given
  * string will be escaped.
  */
 private String escapeHTML(String text) {
   if (ConfigConstants.getInstance().HTML_ESCAPE) {
     return Utilities.escapeHTML(text);
   } else {
     return text;
   }
 }
コード例 #11
0
  /**
   * Returns the TabularData
   *
   * @return TabularData containing the rows corresponding the AlarmTable
   */
  public TabularData getAlarmTable() {

    // User code starts here
    if (true) {
      return getTable();
    }
    // User code ends here

    try {
      if (table != null)
        return Utilities.getTabularData(this, indexNames, table, instrClassName, null);
      else if (vec != null)
        return Utilities.getTabularData(this, indexNames, vec, instrClassName, null);
    } catch (Exception ex) {
      ex.printStackTrace();
    }

    return null;
  }
コード例 #12
0
ファイル: Rope.java プロジェクト: NormanShapiro/Naomi
 void doKids(StringBuilder ans, Pretty pretty, String indent) {
   if (kids == null) return;
   for (Rope kid : kids) {
     if (!pretty.pretty) {
       kid.toString(ans, pretty, "");
     } else {
       kid.toString(ans, pretty, indent + getKidIndentIncrement(kid, pretty));
       Utilities.assureEndsWithNewLine(ans);
     }
   }
 }
コード例 #13
0
ファイル: Bot.java プロジェクト: dims12/program-ab
 HashSet<String> getPronouns() {
   HashSet<String> pronounSet = new HashSet<String>();
   String pronouns = Utilities.getFile(config_path + "/pronouns.txt");
   String[] splitPronouns = pronouns.split("\n");
   for (int i = 0; i < splitPronouns.length; i++) {
     String p = splitPronouns[i].trim();
     if (p.length() > 0) pronounSet.add(p);
   }
   if (MagicBooleans.trace_mode) System.out.println("Read pronouns: " + pronounSet);
   return pronounSet;
 }
コード例 #14
0
ファイル: Rope.java プロジェクト: NormanShapiro/Naomi
 private void start(StringBuilder ans, Pretty pretty, String indent) {
   if (startEncloser == null) return;
   if (!pretty.pretty) {
     ans.append(startEncloser);
   } else {
     String comment;
     if (pretty.comments && startComment.length() > 0) comment = " #" + startComment;
     else comment = "";
     ans.append(indent + startEncloser + comment);
     Utilities.assureEndsWithNewLine(ans);
   }
 }
コード例 #15
0
  /**
   * This method check if the data graph and footer value has different format (it happens when one
   * of them has a m and the other does not have anything) if not, just validate if both have the
   * same value
   *
   * @param graphStr Graph value
   * @param footerStr Footer value
   * @param numbOfDecimals number of decimals displayed in data points
   * @param numbOfDecimals number of decimals displayed in data points
   * @return <code>true</code> if the value is the same <code>false</code> otherwise
   */
  private boolean evaluateIfEquals(String graphStr, String footerStr, int numbOfDecimals) {
    boolean graphToDivide = graphStr.contains("m");
    boolean footerToDivide = footerStr.contains("m");

    if (graphToDivide
        != footerToDivide) { // it means they are displayed in different format and one of them with
                             // m
      if (graphToDivide) {
        double doubleTmp = Double.parseDouble(graphStr.replaceAll("m", "")) / 1000;
        graphStr = ensureTwoDecimalNumber(Utilities.round(doubleTmp, numbOfDecimals));
        footerStr =
            ensureTwoDecimalNumber(Utilities.round(Double.parseDouble(footerStr), numbOfDecimals));
      } else if (footerToDivide) {
        double doubleTmp = Double.parseDouble(footerStr.replaceAll("m", "")) / 1000;
        footerStr = ensureTwoDecimalNumber(Utilities.round(doubleTmp, 2));
        graphStr = ensureTwoDecimalNumber(Utilities.round((Double.parseDouble(graphStr)), 2));
      }
    }
    return graphStr
        .replaceAll("[a-z-A-Z]", "")
        .equals(footerStr.replaceAll("[a-z-A-Z]", "")); // Remove any letter in the value
  }
コード例 #16
0
  @RequestMapping(
      value = "/home",
      method = {RequestMethod.GET, RequestMethod.POST})
  public String getCity(HttpServletRequest request, ModelMap model) {

    try {
      List<City> cityList = cityService.getCity();
      utilities.setSuccessResponse(response, cityList);
    } catch (Exception ex) {
      logger.error("getCity :" + ex.getMessage());
    }
    model.addAttribute("model", response);
    return "home";
  }
コード例 #17
0
  @RequestMapping(
      value = "/getCityApi",
      method = {RequestMethod.GET, RequestMethod.POST})
  public String getCityApi(
      HttpServletRequest request,
      @RequestParam(value = "locationname") String locationname,
      ModelMap model) {

    Map<Object, Object> map = new HashMap<Object, Object>();
    JSONArray jSONArray = new JSONArray();
    try {
      String status = "active";
      List<City> cityList = cityService.getCityApi(locationname, status);
      if (cityList != null && cityList.size() > 0) {
        for (int i = 0; i < cityList.size(); i++) {
          City city = (City) cityList.get(i);
          String cityName = (String) city.getCity();
          String stateName = (String) city.getState();

          int ID = (Integer) (city.getId());
          JSONObject jSONObject = new JSONObject();

          jSONObject.put("id", ID);
          jSONObject.put("text", cityName);
          jSONArray.put(jSONObject);
        }
        utilities.setSuccessResponse(response, jSONArray.toString());
      } else {
        throw new ConstException(ConstException.ERR_CODE_NO_DATA, ConstException.ERR_MSG_NO_DATA);
      }
    } catch (Exception ex) {
      logger.error("getCity :" + ex.getMessage());
      utilities.setErrResponse(ex, response);
    }
    model.addAttribute("model", jSONArray.toString());
    return "home";
  }
コード例 #18
0
ファイル: Bot.java プロジェクト: dims12/program-ab
  /** Write all AIML files. Adds categories for BUILD and DEVELOPMENT ENVIRONMENT */
  public void writeAIMLFiles() {
    if (MagicBooleans.trace_mode) System.out.println("writeAIMLFiles");
    HashMap<String, BufferedWriter> fileMap = new HashMap<String, BufferedWriter>();
    Category b = new Category(0, "BRAIN BUILD", "*", "*", new Date().toString(), "update.aiml");
    brain.addCategory(b);
    // b = new Category(0, "PROGRAM VERSION", "*", "*", MagicStrings.program_name_version,
    // "update.aiml");
    // brain.addCategory(b);
    ArrayList<Category> brainCategories = brain.getCategories();
    Collections.sort(brainCategories, Category.CATEGORY_NUMBER_COMPARATOR);
    for (Category c : brainCategories) {

      if (!c.getFilename().equals(MagicStrings.null_aiml_file))
        try {
          // System.out.println("Writing "+c.getCategoryNumber()+" "+c.inputThatTopic());
          BufferedWriter bw;
          String fileName = c.getFilename();
          if (fileMap.containsKey(fileName)) bw = fileMap.get(fileName);
          else {
            String copyright = Utilities.getCopyright(this, fileName);
            bw = new BufferedWriter(new FileWriter(aiml_path + "/" + fileName));
            fileMap.put(fileName, bw);
            bw.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "\n" + "<aiml>\n");
            bw.write(copyright);
            // bw.newLine();
          }
          bw.write(Category.categoryToAIML(c) + "\n");
          // bw.newLine();
        } catch (Exception ex) {
          ex.printStackTrace();
        }
    }
    Set set = fileMap.keySet();
    for (Object aSet : set) {
      BufferedWriter bw = fileMap.get(aSet);
      // Close the bw
      try {
        if (bw != null) {
          bw.write("</aiml>\n");
          bw.flush();
          bw.close();
        }
      } catch (IOException ex) {
        ex.printStackTrace();
      }
    }
    File dir = new File(aiml_path);
    dir.setLastModified(new Date().getTime());
  }
コード例 #19
0
ファイル: Utilities.java プロジェクト: kim0z/gpslogger
  public static String GetFormattedCustomFileName(String baseName) {

    Time t = new Time();
    t.setToNow();

    String finalFileName = baseName;
    finalFileName =
        finalFileName.replaceAll("(?i)%ser", String.valueOf(Utilities.GetBuildSerial()));
    finalFileName = finalFileName.replaceAll("(?i)%hour", String.valueOf(t.hour));
    finalFileName = finalFileName.replaceAll("(?i)%min", String.valueOf(t.minute));
    finalFileName = finalFileName.replaceAll("(?i)%year", String.valueOf(t.year));
    finalFileName = finalFileName.replaceAll("(?i)%month", String.valueOf(t.month + 1));
    finalFileName = finalFileName.replaceAll("(?i)%day", String.valueOf(t.monthDay));
    return finalFileName;
  }
コード例 #20
0
 @Override
 public Component getListCellRendererComponent(
     JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
   JLabel label =
       (JLabel)
           (super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus));
   if (value instanceof TypeColorEntry) {
     TypeColorEntry entry = (TypeColorEntry) value;
     Token.Type type = entry.getType();
     Color color = entry.getColor();
     label.setText(Utilities.normalize(type.toString()));
     if ((type == Token.Type.MATCHED_BRACKET) || (type == Token.Type.UNMATCHED_BRACKET)) {
       label.setBackground(color);
       label.setForeground(Color.BLACK);
     } else {
       label.setForeground(color);
     }
   }
   return label;
 }
コード例 #21
0
  /**
   * Sets up the <em>startup</em> {@linkplain Mock mocks} defined in one or more mock classes, just
   * like {@link #setUpMocks(Object...)} does for regular mock classes. The difference is in the
   * lifetime of the mocks, which will last to the end of the test run. Consequently, this method
   * should only be called once, before the first test begins execution. One way to achieve this is
   * to put the call in the static initializer of a common base class extended by all test classes
   * in the suite. Another way is by configuring what happens at startup through external means.
   *
   * <p>There are three ways to set up mock classes at startup time:
   *
   * <ol>
   *   <li>Define a value for the "<code>jmockit-mocks</code>" system property, as a comma-separated
   *       list of fully qualified class names.
   *   <li>Add a custom "<code>jmockit.properties</code>" file to the classpath, with an entry for
   *       the "<code>jmockit-mocks</code>" (or just "<code>mocks</code>") property.
   *   <li>Specify the "<code>-javaagent:jmockit.jar=&lt;agentArgs></code>" JVM argument, with "
   *       <code>agentArgs</code>" containing one or more mock class names, separated by semicolons
   *       if more than one.
   * </ol>
   *
   * Note that option two above makes it possible to package a whole set of reusable mock classes in
   * a jar file, provided it contains a suitable <code>jmockit.properties</code> file. By simply
   * adding the jar to the classpath <em>before</em> <code>jmockit.jar</code>, the specified mock
   * classes will be loaded and applied automatically on every test run, as soon as JMockit itself
   * gets initialized.
   *
   * @param mockClassesOrInstances one or more mock classes (either <code>Class</code> literals or
   *     fully qualified class names) or instances of mock classes
   * @throws IllegalArgumentException if a given mock class fails to specify the corresponding real
   *     class using the {@code @MockClass(realClass = ...)} annotation; or if a mock class defines
   *     a mock method for which no corresponding real method or constructor exists in the real
   *     class; or if the real method matching a mock method is {@code abstract}
   * @see <a
   *     href="http://code.google.com/p/jmockit/source/browse/trunk/main/test/mockit/MockAnnotationsTest.java#465">
   *     Example</a>
   *     <p>In the Tutorial: <a
   *     href="http://jmockit.googlecode.com/svn/trunk/www/tutorial/UsingMocksAndStubs.html">Using
   *     mocks and stubs over entire test classes and suites</a>
   */
  public static void setUpStartupMocks(Object... mockClassesOrInstances) {
    for (Object mockClassOrInstance : mockClassesOrInstances) {
      Class<?> mockClass;
      Object mock;

      if (mockClassOrInstance instanceof Class<?>) {
        mockClass = (Class<?>) mockClassOrInstance;
        mock = null;
      } else if (mockClassOrInstance instanceof String) {
        String className = ((String) mockClassOrInstance).trim();
        if (className.length() == 0) continue;
        mockClass = Utilities.loadClass(className);
        mock = null;
      } else {
        mockClass = mockClassOrInstance.getClass();
        mock = mockClassOrInstance;
      }

      new MockClassSetup(mock, mockClass).setUpStartupMock();
    }
  }
コード例 #22
0
  /**
   * Method that parse the JSON String got from the graph, this method returns a HashMap with the
   * respective Min, Max, Avg, and End values for each Row of the respective graph Legend, each
   * HashMap key to access the row is the name of the row in the Legend of the graph,
   *
   * @param JSON - A JSON String to parse
   * @param numbOfDecimals Numbers of decimals displayed in the graph
   * @param storage Storage unit displayed next to each value e.g: M
   * @return Map<String, ArrayList<String>> A HashMap that contains the values of the graph
   * @throws JSONException
   *     <p>NOTE: The array that contain each row data is ordered as following: - [0] End - [1] min
   *     - [2] max - [3] avg In case the JSON is empty or null, the method is going to return Null.
   */
  public Map<String, ArrayList<String>> JSONParser(String JSON, int numbOfDecimals, char storage)
      throws JSONException {
    Map<String, ArrayList<String>> graphData = null;
    String endStr = "";
    String minStr = "";
    String maxStr = "";
    String avgStr = "";

    if (!(JSON == ConstantsClass.EMPTY_JSON) || !(JSON == null)) {
      Object parsedJson = JSONValue.parse(JSON);
      graphData = new HashMap<String, ArrayList<String>>();
      double max = 0.0;
      double min = -1.0;
      double end = 0.0;
      double avg = 0.0;
      JSONArray array = (JSONArray) parsedJson;
      for (int i = 0; i < array.size(); i++) {
        final JSONObject obj = new JSONObject(array.get(i).toString());
        final org.json.JSONArray legendRows = obj.getJSONArray("values");
        final int n = legendRows.length();
        if (!(obj.getString("key").contains("high load"))) {
          for (int j = 0; j < n; ++j) {
            final JSONObject row = legendRows.getJSONObject(j);
            String rowY = row.get("y").toString();
            if (rowY.compareTo("null") != 0) {
              if (min == -1.0) min = row.getDouble("y");
              // collecting data for average
              avg += row.getDouble("y");
              // get min value
              if (row.getDouble("y") < min) min = row.getDouble("y");
              // get max value
              if (row.getDouble("y") > max) max = row.getDouble("y");
              // get ending
              if (j == n - 1) {
                end = row.getDouble("y");
                // avg = Utilities.round(avg / n, numbOfDecimals);
                avg = (avg / n);
              }
            }
          }

          if (storage == ConstantsClass.STORAGE_TYPE_B) {
            if (numbOfDecimals == 2) { // If the graph has 2 decimals in the table values
              endStr = ensureTwoDecimalNumber(Utilities.round(end, numbOfDecimals));
              minStr = ensureTwoDecimalNumber(Utilities.round(min, numbOfDecimals));
              maxStr = ensureTwoDecimalNumber(Utilities.round(max, numbOfDecimals));
              avgStr = ensureTwoDecimalNumber(Utilities.round(avg, numbOfDecimals));
            } else {
              endStr = Double.toString(Utilities.round(end, numbOfDecimals));
              minStr = Double.toString(Utilities.round(min, numbOfDecimals));
              maxStr = Double.toString(Utilities.round(max, numbOfDecimals));
              avgStr = Double.toString(Utilities.round(avg, numbOfDecimals));
            }
          } else {
            endStr = transformSize(end, storage, numbOfDecimals);
            minStr = transformSize(min, storage, numbOfDecimals);
            maxStr = transformSize(max, storage, numbOfDecimals);
            avgStr = transformSize(avg, storage, numbOfDecimals);
          }

          graphData.put(
              obj.getString("key"),
              new ArrayList<String>(Arrays.asList(endStr, minStr, maxStr, avgStr)));
        }
        max = 0.0;
        min = -1.0;
        end = 0.0;
        avg = 0.0;
      }
    }
    return graphData;
  }
コード例 #23
0
ファイル: Utilities.java プロジェクト: Jacqqq/gpslogger
  /** Gets user preferences, populates the AppSettings class. */
  public static void PopulateAppSettings(Context context) {

    tracer.info("Getting preferences");
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

    AppSettings.setUseImperial(prefs.getBoolean("useImperial", false));

    AppSettings.setLogToKml(prefs.getBoolean("log_kml", false));

    AppSettings.setLogToGpx(prefs.getBoolean("log_gpx", true));

    AppSettings.setLogToPlainText(prefs.getBoolean("log_plain_text", false));

    AppSettings.setLogToNmea(prefs.getBoolean("log_nmea", false));

    AppSettings.setLogToCustomUrl(prefs.getBoolean("log_customurl_enabled", false));
    AppSettings.setCustomLoggingUrl(prefs.getString("log_customurl_url", ""));

    AppSettings.setLogToOpenGTS(prefs.getBoolean("log_opengts", false));

    Set<String> listeners = new HashSet<String>();
    listeners.add("gps");
    listeners.add("network");
    listeners.add("passive");
    AppSettings.setChosenListeners(prefs.getStringSet("listeners", listeners));

    String minimumDistanceString = prefs.getString("distance_before_logging", "0");

    if (minimumDistanceString != null && minimumDistanceString.length() > 0) {
      AppSettings.setMinimumDistanceInMeters(Integer.valueOf(minimumDistanceString));
    } else {
      AppSettings.setMinimumDistanceInMeters(0);
    }

    String minimumAccuracyString = prefs.getString("accuracy_before_logging", "0");

    if (minimumAccuracyString != null && minimumAccuracyString.length() > 0) {
      AppSettings.setMinimumAccuracyInMeters(Integer.valueOf(minimumAccuracyString));
    } else {
      AppSettings.setMinimumAccuracyInMeters(0);
    }

    if (AppSettings.shouldUseImperial()) {
      AppSettings.setMinimumDistanceInMeters(
          Utilities.FeetToMeters(AppSettings.getMinimumDistanceInMeters()));

      AppSettings.setMinimumAccuracyInMeters(
          Utilities.FeetToMeters(AppSettings.getMinimumAccuracyInMeters()));
    }

    String minimumSecondsString = prefs.getString("time_before_logging", "60");

    if (minimumSecondsString != null && minimumSecondsString.length() > 0) {
      AppSettings.setMinimumSeconds(Integer.valueOf(minimumSecondsString));
    } else {
      AppSettings.setMinimumSeconds(60);
    }

    AppSettings.setKeepFix(prefs.getBoolean("keep_fix", false));

    String retryIntervalString = prefs.getString("retry_time", "60");

    if (retryIntervalString != null && retryIntervalString.length() > 0) {
      AppSettings.setRetryInterval(Integer.valueOf(retryIntervalString));
    } else {
      AppSettings.setRetryInterval(60);
    }

    /**
     * New file creation preference: onceaday, custom file (static), every time the service starts
     */
    AppSettings.setNewFileCreation(prefs.getString("new_file_creation", "onceaday"));

    if (AppSettings.getNewFileCreation().equals("onceaday")) {
      AppSettings.setNewFileOnceADay(true);
      AppSettings.setCustomFile(false);
    } else if (AppSettings.getNewFileCreation().equals("custom")
        || AppSettings.getNewFileCreation().equals("static")) {
      AppSettings.setCustomFile(true);
      AppSettings.setCustomFileName(prefs.getString("new_file_custom_name", "gpslogger"));
    } else /* new log with each start */ {
      AppSettings.setNewFileOnceADay(false);
      AppSettings.setCustomFile(false);
    }

    AppSettings.setAutoSendEnabled(prefs.getBoolean("autosend_enabled", false));

    AppSettings.setAutoEmailEnabled(prefs.getBoolean("autoemail_enabled", false));

    if (Float.valueOf(prefs.getString("autosend_frequency", "0")) >= 8f) {
      SharedPreferences.Editor editor = prefs.edit();
      editor.putString("autosend_frequency", "8");
      editor.commit();
    }

    AppSettings.setAutoSendDelay(Float.valueOf(prefs.getString("autosend_frequency", "0")));

    AppSettings.setSmtpServer(prefs.getString("smtp_server", ""));
    AppSettings.setSmtpPort(prefs.getString("smtp_port", "25"));
    AppSettings.setSmtpSsl(prefs.getBoolean("smtp_ssl", true));
    AppSettings.setSmtpUsername(prefs.getString("smtp_username", ""));
    AppSettings.setSmtpPassword(prefs.getString("smtp_password", ""));
    AppSettings.setAutoEmailTargets(prefs.getString("autoemail_target", ""));
    AppSettings.setDebugToFile(prefs.getBoolean("debugtofile", false));
    AppSettings.setShouldSendZipFile(prefs.getBoolean("autosend_sendzip", true));
    AppSettings.setSmtpFrom(prefs.getString("smtp_from", ""));
    AppSettings.setOpenGTSEnabled(prefs.getBoolean("opengts_enabled", false));
    AppSettings.setAutoOpenGTSEnabled(prefs.getBoolean("autoopengts_enabled", false));
    AppSettings.setOpenGTSServer(prefs.getString("opengts_server", ""));
    AppSettings.setOpenGTSServerPort(prefs.getString("opengts_server_port", ""));
    AppSettings.setOpenGTSServerCommunicationMethod(
        prefs.getString("opengts_server_communication_method", ""));
    AppSettings.setOpenGTSServerPath(prefs.getString("autoopengts_server_path", ""));
    AppSettings.setOpenGTSDeviceId(prefs.getString("opengts_device_id", ""));
    AppSettings.setOpenGTSAccountName(prefs.getString("opengts_accountname", ""));

    AppSettings.setAutoFtpEnabled(prefs.getBoolean("autoftp_enabled", false));
    AppSettings.setFtpServerName(prefs.getString("autoftp_server", ""));
    AppSettings.setFtpUsername(prefs.getString("autoftp_username", ""));
    AppSettings.setFtpPassword(prefs.getString("autoftp_password", ""));
    AppSettings.setFtpDirectory(prefs.getString("autoftp_directory", "GPSLogger"));
    AppSettings.setFtpPort(Integer.valueOf(prefs.getString("autoftp_port", "21")));
    AppSettings.setFtpUseFtps(prefs.getBoolean("autoftp_useftps", false));
    AppSettings.setFtpProtocol(prefs.getString("autoftp_ssltls", ""));
    AppSettings.setFtpImplicit(prefs.getBoolean("autoftp_implicit", false));
    AppSettings.setGpsLoggerFolder(
        prefs.getString(
            "gpslogger_folder", Environment.getExternalStorageDirectory() + "/GPSLogger"));
    AppSettings.setFileNamePrefixSerial(prefs.getBoolean("new_file_prefix_serial", false));

    String absoluteTimeoutString = prefs.getString("absolute_timeout", "0");

    if (absoluteTimeoutString != null && absoluteTimeoutString.length() > 0) {
      AppSettings.setAbsoluteTimeout(Integer.valueOf(absoluteTimeoutString));
    } else {
      AppSettings.setAbsoluteTimeout(0);
    }
  }
コード例 #24
0
ファイル: RADComponentNode.java プロジェクト: PrimoS/Netbeans
 void updateName() {
   String compClassName = Utilities.getShortClassName(component.getBeanClass());
   if (component == component.getFormModel().getTopRADComponent())
     setDisplayName(nodeNoNameFormat.format(new Object[] {compClassName}));
   else setDisplayName(nodeNameFormat.format(new Object[] {getName(), compClassName}));
 }
コード例 #25
0
  private String getSimpleImageConfirmLink(
      final String event,
      final String label,
      final String image,
      String imageOver,
      String javascript) {
    String status = Utilities.escapeHTML(Utilities.filterOutHTMLTags(label));

    if ((imageOver == null) || imageOver.equals("")) {
      imageOver = image;
    }

    if ((javascript == null) || javascript.equals("")) {
      javascript = "true";
    }

    final String imageID = event + "_img";

    StringBuffer link = new StringBuffer();

    link.append("<input type=\"hidden\" name=\"")
        .append(event)
        .append("\" value=\"")
        .append(AbstractChip.FALSE)
        .append("\" />");
    link.append("<a href=\"#\" hidefocus=\"true\" style=\"text-decoration:none; \" alt=\"")
        .append(status)
        .append("\" title=\"")
        .append(status)
        .append("\"");
    link.append("onMouseover=\"window.status='")
        .append(status)
        .append("'; swapImage('")
        .append(imageID)
        .append("', '")
        .append(imageOver)
        .append("'); return true;\" ");
    link.append("onMouseout=\"window.status=''; swapImage('")
        .append(imageID)
        .append("', '")
        .append(image)
        .append("'); return true;\" ");
    link.append("onFocus=\"swapImage('")
        .append(imageID)
        .append("', '")
        .append(imageOver)
        .append("'); return true;\" ");
    link.append("onBlur=\"swapImage('")
        .append(imageID)
        .append("', '")
        .append(image)
        .append("'); return true;\" ");
    link.append("onclick=\"document.editorForm.elements['")
        .append(event)
        .append("'].value = ")
        .append(javascript)
        .append("; setScrollAndSubmit(); return false;\">");
    link.append("<img id=\"")
        .append(imageID)
        .append("\" src=\"")
        .append(image)
        .append("\" alt=\"")
        .append(status)
        .append("\">");
    link.append("</a>");

    return link.toString();
  }
コード例 #26
0
  private String getIconButton(
      final String event,
      final String label,
      final String image,
      String javascript,
      boolean showLabel,
      boolean isEnabled) {
    String status = Utilities.escapeHTML(Utilities.filterOutHTMLTags(label));

    if ((javascript == null) || javascript.equals("")) {
      javascript = "true";
    }

    final String imageID = event + "_img";

    StringBuffer link = new StringBuffer();
    final String color = isEnabled ? "#ffffff" : "#D8DCE3";

    if (isEnabled) {
      link.append(
          "<input type=\"hidden\" name=\"" + event + "\" value=\"" + AbstractChip.FALSE + "\" />");
      link.append(
          "<a href=\"#\" hidefocus=\"true\" style=\"text-decoration:none; \" alt=\""
              + status
              + "\" ");
      link.append(
          "onMouseover=\"window.status='"
              + status
              + "'; "
              + " document.getElementById('"
              + imageID
              + "_bg_left').style.backgroundImage = 'url(images/icons/icon_button_background_hover_l.gif)'; "
              + " document.getElementById('"
              + imageID
              + "_bg_middle').style.backgroundImage = 'url(images/icons/icon_button_background_hover_m.gif)'; "
              + " document.getElementById('"
              + imageID
              + "_bg_right').style.backgroundImage = 'url(images/icons/icon_button_background_hover_r.gif)'; "
              + " return true;\" ");
      link.append(
          "onMouseout=\"window.status='';"
              + " document.getElementById('"
              + imageID
              + "_bg_left').style.backgroundImage = 'url(images/icons/icon_button_background_l.gif)'; "
              + " document.getElementById('"
              + imageID
              + "_bg_middle').style.backgroundImage = 'url(images/icons/icon_button_background_m.gif)'; "
              + " document.getElementById('"
              + imageID
              + "_bg_right').style.backgroundImage = 'url(images/icons/icon_button_background_r.gif)'; "
              + " return true;\" ");
      link.append(
          "onFocus=\"window.status='"
              + status
              + "'; "
              + " document.getElementById('"
              + imageID
              + "_bg_left').style.backgroundImage = 'url(images/icons/icon_button_background_hover_l.gif)'; "
              + " document.getElementById('"
              + imageID
              + "_bg_middle').style.backgroundImage = 'url(images/icons/icon_button_background_hover__m.gif)'; "
              + " document.getElementById('"
              + imageID
              + "_bg_right').style.backgroundImage = 'url(images/icons/icon_button_background_hover__r.gif)'; "
              + " return true;\" ");
      link.append(
          "onBlur=\"window.status='';"
              + " document.getElementById('"
              + imageID
              + "_bg_left').style.backgroundImage = 'url(images/icons/icon_button_background_l.gif)'; "
              + " document.getElementById('"
              + imageID
              + "_bg_middle').style.backgroundImage = 'url(images/icons/icon_button_background_m.gif)'; "
              + " document.getElementById('"
              + imageID
              + "_bg_right').style.backgroundImage = 'url(images/icons/icon_button_background_r.gif)'; "
              + " return true;\" ");
      link.append(
          "onclick=\"document.editorForm.elements['"
              + event
              + "'].value = "
              + javascript
              + "; setScrollAndSubmit(); return false;\">");
    }

    link.append(
        "<table title=\""
            + status
            + "\" style=\"vertical-align:middle; width:100%; height:23px; padding:0px;\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\">");
    link.append("<tr>");
    link.append(
        "<td id=\""
            + imageID
            + "_bg_left\" style=\"width:3px;font-size:1pt;padding:0px;\" background=\"images/icons/icon_button_background_l.gif\"><div style=\"width:3px;\"></div></td>");
    link.append(
        "<td id=\""
            + imageID
            + "_bg_middle\" style=\"white-space:nowrap;vertical-align:middle;text-align:center;padding:0px;\" background=\"images/icons/icon_button_background_m.gif\">");

    link.append(
        "<img id=\"" + imageID + "\" style=\"vertical-align:middle\" src=\"" + image + "\">");
    if (showLabel) {
      link.append("<span style=\"padding-left:5px; color:" + color + "\">" + label + "</span>");
    }

    link.append("</td>");
    link.append(
        "<td id=\""
            + imageID
            + "_bg_right\" style=\"width:3px;font-size:1pt;padding:0px;\" background=\"images/icons/icon_button_background_r.gif\"><div style=\"width:3px;\"></div></td>");
    link.append("</tr>");
    link.append("</table>");

    if (isEnabled) {
      link.append("</a>");
    }

    return link.toString();
  }
コード例 #27
0
ファイル: Utilities.java プロジェクト: kim0z/gpslogger
  /** Gets user preferences, populates the AppSettings class. */
  public static void PopulateAppSettings(Context context) {

    tracer.debug("Getting preferences");
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

    AppSettings.setHideNotificationButtons(prefs.getBoolean("hide_notification_buttons", false));

    AppSettings.setUseImperial(prefs.getBoolean("useImperial", false));

    AppSettings.setLogToKml(prefs.getBoolean("log_kml", false));

    AppSettings.setLogToGpx(prefs.getBoolean("log_gpx", true));

    AppSettings.setLogToPlainText(prefs.getBoolean("log_plain_text", false));

    AppSettings.setLogToNmea(prefs.getBoolean("log_nmea", false));

    AppSettings.setLogToCustomUrl(prefs.getBoolean("log_customurl_enabled", false));
    AppSettings.setCustomLoggingUrl(prefs.getString("log_customurl_url", ""));

    AppSettings.setLogToOpenGts(prefs.getBoolean("log_opengts", false));

    Set<String> listeners = new HashSet<String>(GetListeners());
    AppSettings.setChosenListeners(prefs.getStringSet("listeners", listeners));

    String minimumDistanceString = prefs.getString("distance_before_logging", "0");

    if (minimumDistanceString != null && minimumDistanceString.length() > 0) {
      AppSettings.setMinimumDistanceInMeters(Integer.valueOf(minimumDistanceString));
    } else {
      AppSettings.setMinimumDistanceInMeters(0);
    }

    String minimumAccuracyString = prefs.getString("accuracy_before_logging", "0");

    if (minimumAccuracyString != null && minimumAccuracyString.length() > 0) {
      AppSettings.setMinimumAccuracyInMeters(Integer.valueOf(minimumAccuracyString));
    } else {
      AppSettings.setMinimumAccuracyInMeters(0);
    }

    String minimumSecondsString = prefs.getString("time_before_logging", "60");

    if (minimumSecondsString != null && minimumSecondsString.length() > 0) {
      AppSettings.setMinimumSeconds(Integer.valueOf(minimumSecondsString));
    } else {
      AppSettings.setMinimumSeconds(60);
    }

    AppSettings.setKeepFix(prefs.getBoolean("keep_fix", false));

    String retryIntervalString = prefs.getString("retry_time", "60");

    if (retryIntervalString != null && retryIntervalString.length() > 0) {
      AppSettings.setRetryInterval(Integer.valueOf(retryIntervalString));
    } else {
      AppSettings.setRetryInterval(60);
    }

    /**
     * New file creation preference: onceaday, custom file (static), every time the service starts
     */
    AppSettings.setNewFileCreation(prefs.getString("new_file_creation", "onceaday"));

    if (AppSettings.getNewFileCreation().equals("onceaday")) {
      AppSettings.setNewFileOnceADay(true);
      AppSettings.setCustomFile(false);
    } else if (AppSettings.getNewFileCreation().equals("custom")
        || AppSettings.getNewFileCreation().equals("static")) {
      AppSettings.setCustomFile(true);
      AppSettings.setCustomFileName(prefs.getString("new_file_custom_name", "gpslogger"));
      AppSettings.setAskCustomFileNameEachTime(prefs.getBoolean("new_file_custom_each_time", true));
    } else /* new log with each start */ {
      AppSettings.setNewFileOnceADay(false);
      AppSettings.setCustomFile(false);
    }

    AppSettings.setAutoSendEnabled(prefs.getBoolean("autosend_enabled", false));

    AppSettings.setEmailAutoSendEnabled(prefs.getBoolean("autoemail_enabled", false));

    try {
      AppSettings.setAutoSendDelay(
          Float.valueOf(prefs.getString("autosend_frequency_minutes", "60")));
    } catch (Exception e) {
      AppSettings.setAutoSendDelay(60f);
    }

    AppSettings.setAutoSendWhenIPressStop(
        prefs.getBoolean("autosend_frequency_whenstoppressed", false));

    AppSettings.setSmtpServer(prefs.getString("smtp_server", ""));
    AppSettings.setSmtpPort(prefs.getString("smtp_port", "25"));
    AppSettings.setSmtpSsl(prefs.getBoolean("smtp_ssl", true));
    AppSettings.setSmtpUsername(prefs.getString("smtp_username", ""));
    AppSettings.setSmtpPassword(prefs.getString("smtp_password", ""));
    AppSettings.setAutoEmailTargets(prefs.getString("autoemail_target", ""));
    AppSettings.setDebugToFile(prefs.getBoolean("debugtofile", false));
    AppSettings.setShouldSendZipFile(prefs.getBoolean("autosend_sendzip", true));
    AppSettings.setSmtpFrom(prefs.getString("smtp_from", ""));
    AppSettings.setOpenGtsAutoSendEnabled(prefs.getBoolean("autoopengts_enabled", false));
    AppSettings.setOpenGTSServer(prefs.getString("opengts_server", ""));
    AppSettings.setOpenGTSServerPort(prefs.getString("opengts_server_port", ""));
    AppSettings.setOpenGTSServerCommunicationMethod(
        prefs.getString("opengts_server_communication_method", ""));
    AppSettings.setOpenGTSServerPath(prefs.getString("autoopengts_server_path", ""));
    AppSettings.setOpenGTSDeviceId(prefs.getString("opengts_device_id", ""));
    AppSettings.setOpenGTSAccountName(prefs.getString("opengts_accountname", ""));

    AppSettings.setGDocsAutoSendEnabled(prefs.getBoolean("gdocs_enabled", false));
    AppSettings.setDropboxAutoSendEnabled(prefs.getBoolean("dropbox_enabled", false));
    AppSettings.setOsmAutoSendEnabled(prefs.getBoolean("osm_enabled", false));

    AppSettings.setFtpAutoSendEnabled(prefs.getBoolean("autoftp_enabled", false));
    AppSettings.setFtpServerName(prefs.getString("autoftp_server", ""));
    AppSettings.setFtpUsername(prefs.getString("autoftp_username", ""));
    AppSettings.setFtpPassword(prefs.getString("autoftp_password", ""));
    AppSettings.setFtpDirectory(prefs.getString("autoftp_directory", "GPSLogger"));
    AppSettings.setFtpPort(Integer.valueOf(prefs.getString("autoftp_port", "21")));
    AppSettings.setFtpUseFtps(prefs.getBoolean("autoftp_useftps", false));
    AppSettings.setFtpProtocol(prefs.getString("autoftp_ssltls", ""));
    AppSettings.setFtpImplicit(prefs.getBoolean("autoftp_implicit", false));

    AppSettings.setOwnCloudAutoSendEnabled(prefs.getBoolean("owncloud_enabled", false));
    AppSettings.setOwnCloudServerName(prefs.getString("owncloud_server", ""));
    AppSettings.setOwnCloudUsername(prefs.getString("owncloud_username", ""));
    AppSettings.setOwnCloudPassword(prefs.getString("owncloud_password", ""));
    AppSettings.setOwnCloudDirectory(prefs.getString("owncloud_directory", "/gpslogger"));

    AppSettings.setGpsLoggerFolder(
        prefs.getString(
            "gpslogger_folder", Utilities.GetDefaultStorageFolder(context).getAbsolutePath()));
    AppSettings.setFileNamePrefixSerial(prefs.getBoolean("new_file_prefix_serial", false));

    String absoluteTimeoutString = prefs.getString("absolute_timeout", "120");

    if (absoluteTimeoutString != null && absoluteTimeoutString.length() > 0) {
      AppSettings.setAbsoluteTimeout(Integer.valueOf(absoluteTimeoutString));
    } else {
      AppSettings.setAbsoluteTimeout(120);
    }

    AppSettings.setGoogleDriveFolderName(
        prefs.getString("gdocs_foldername", "GPSLogger for Android"));

    AppSettings.setShouldNotLogIfUserIsStill(
        prefs.getBoolean("activityrecognition_dontlogifstill", false));

    AppSettings.setAdjustAltitudeFromGeoIdHeight(
        prefs.getBoolean("altitude_subtractgeoidheight", false));
    AppSettings.setSubtractAltitudeOffset(
        Integer.valueOf(prefs.getString("altitude_subtractoffset", "0")));
  }
コード例 #28
0
ファイル: Utilities.java プロジェクト: kim0z/gpslogger
  public static void ConfigureLogbackDirectly(Context context) {
    try {
      // reset the default context (which may already have been initialized)
      // since we want to reconfigure it
      LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
      lc.reset();

      // final String LOG_DIR = "/sdcard/GPSLogger";
      SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
      final String LOG_DIR =
          prefs.getString(
              "gpslogger_folder", Utilities.GetDefaultStorageFolder(context).getAbsolutePath());

      GpsRollingFileAppender<ILoggingEvent> rollingFileAppender =
          new GpsRollingFileAppender<ILoggingEvent>();
      rollingFileAppender.setAppend(true);
      rollingFileAppender.setContext(lc);

      // OPTIONAL: Set an active log file (separate from the rollover files).
      // If rollingPolicy.fileNamePattern already set, you don't need this.
      rollingFileAppender.setFile(LOG_DIR + "/debuglog.txt");
      rollingFileAppender.setLazy(true);

      TimeBasedRollingPolicy<ILoggingEvent> rollingPolicy =
          new TimeBasedRollingPolicy<ILoggingEvent>();
      rollingPolicy.setFileNamePattern(LOG_DIR + "/debuglog.%d.txt");
      rollingPolicy.setMaxHistory(3);
      rollingPolicy.setParent(rollingFileAppender); // parent and context required!
      rollingPolicy.setContext(lc);
      rollingPolicy.start();

      rollingFileAppender.setRollingPolicy(rollingPolicy);

      PatternLayoutEncoder encoder = new PatternLayoutEncoder();
      encoder.setPattern("%d{HH:mm:ss} %-5p %class{0}.%method:%L - %m%n");
      encoder.setContext(lc);
      encoder.start();

      rollingFileAppender.setEncoder(encoder);
      rollingFileAppender.start();

      // setup LogcatAppender
      PatternLayoutEncoder encoder2 = new PatternLayoutEncoder();
      encoder2.setContext(lc);
      encoder2.setPattern("%method:%L - %m%n");
      encoder2.start();

      LogcatAppender logcatAppender = new LogcatAppender();
      logcatAppender.setContext(lc);
      logcatAppender.setEncoder(encoder2);
      logcatAppender.start();

      SessionLogcatAppender sessionAppender = new SessionLogcatAppender();
      sessionAppender.setContext(lc);
      sessionAppender.start();

      // add the newly created appenders to the root logger;
      // qualify Logger to disambiguate from org.slf4j.Logger
      ch.qos.logback.classic.Logger root =
          (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
      root.addAppender(rollingFileAppender);
      root.addAppender(logcatAppender);
      root.addAppender(sessionAppender);

    } catch (Exception ex) {
      System.out.println("Could not configure logging!");
    }
  }
コード例 #29
0
 public void showError(String err) {
   enableButtons();
   Utilities.errorMessage(resourceBundle.getString(err));
 }
コード例 #30
0
/** @author todd */
class OnlineStatusIndicator {
  private static Image OPEN_IMAGE = Utilities.loadImage(SessionNode.OPEN_ICON);
  private static Image CLOSED_IMAGE = Utilities.loadImage(SessionNode.CLOSED_ICON);
  private static Image AWAY_IMAGE = Utilities.loadImage(SessionNode.AWAY_ICON);
  private static Image BUSY_IMAGE = Utilities.loadImage(SessionNode.BUSY_ICON);
  private static Image IDLE_IMAGE = Utilities.loadImage(SessionNode.IDLE_ICON);
  private static OnlineStatusIndicator instance;

  ////////////////////////////////////////////////////////////////////////////
  // Instance fields
  ////////////////////////////////////////////////////////////////////////////
  private JLabel label;
  private Helper helper;
  private int currentStatus = CollabPrincipal.STATUS_UNKNOWN;

  Component getComponent() {
    return label;
  }

  /** */
  protected OnlineStatusIndicator() {
    helper = new Helper();
    label = new JLabel();
    label.addMouseListener(helper);
    initListening(1);
  }

  private void initListening(final int level) {
    CollabManager man = CollabManager.getDefault();
    if (man == null) {
      // manager not yet registered. This is a transient condition during
      // module enablement because of manager registration mechanism.
      // Retry 5s later
      assert level < 10;

      RequestProcessor.getDefault()
          .post(
              new Runnable() {
                public void run() {
                  initListening(level + 1);
                }
              },
              level * 5000);
    } else {
      man.addPropertyChangeListener(helper);
      attachListeners();
      updateStatus();
    }
  }

  private void setStatus(int value) {
    currentStatus = value;
    SwingUtilities.invokeLater(helper);
  }

  /** */
  protected void updateStatus() {
    final CollabManager manager = CollabManager.getDefault();

    if (manager != null) {
      int sharedStatus = CollabPrincipal.STATUS_OFFLINE;
      boolean unilateral = true;

      CollabSession[] sessions = manager.getSessions();

      for (int i = 0; i < sessions.length; i++) {
        int status = sessions[i].getUserPrincipal().getStatus();

        if (sharedStatus == CollabPrincipal.STATUS_OFFLINE) {
          sharedStatus = status;
        }

        if (status != sharedStatus) {
          unilateral = false;
        }
      }

      if (unilateral) {
        // This will occur if either:
        // 1) No sessions were found
        // 2) All available sessions had the same status
        setStatus(sharedStatus);
      } else {
        // Assume at least one session is online
        setStatus(CollabPrincipal.STATUS_ONLINE);
      }
    }
  }

  ////////////////////////////////////////////////////////////////////////////
  // Helper methods
  ////////////////////////////////////////////////////////////////////////////

  /** */
  public static String getStatusDescription(int status) {
    final String description;

    switch (status) {
      case CollabPrincipal.STATUS_AWAY:
        description =
            NbBundle.getMessage(ContactNode.class, "LBL_ContactNode_StatusAway"); // NOI18N

        break;

      case CollabPrincipal.STATUS_BUSY:
        description =
            NbBundle.getMessage(ContactNode.class, "LBL_ContactNode_StatusBusy"); // NOI18N

        break;

      case CollabPrincipal.STATUS_IDLE:
        description =
            NbBundle.getMessage(ContactNode.class, "LBL_ContactNode_StatusIdle"); // NOI18N

        break;

      case CollabPrincipal.STATUS_OFFLINE:
        description =
            NbBundle.getMessage(ContactNode.class, "LBL_ContactNode_StatusOffline"); // NOI18N

        break;

      case CollabPrincipal.STATUS_ONLINE:
        description =
            NbBundle.getMessage(ContactNode.class, "LBL_ContactNode_StatusOnline"); // NOI18N

        break;

      default:
        description =
            NbBundle.getMessage(ContactNode.class, "LBL_ContactNode_StatusUnknown"); // NOI18N
    }

    return description;
  }

  /** */
  public static Image getStatusIcon(int status) {
    final Image statusIcon;

    switch (status) {
      case CollabPrincipal.STATUS_AWAY:
        statusIcon = AWAY_IMAGE;

        break;

      case CollabPrincipal.STATUS_BUSY:
        statusIcon = BUSY_IMAGE;

        break;

      case CollabPrincipal.STATUS_IDLE:
        statusIcon = IDLE_IMAGE;

        break;

      case CollabPrincipal.STATUS_OFFLINE:
        statusIcon = CLOSED_IMAGE;

        break;

      case CollabPrincipal.STATUS_ONLINE:
        statusIcon = OPEN_IMAGE;

        break;

      default:
        statusIcon = CLOSED_IMAGE;
    }

    return statusIcon;
  }

  /** */
  protected static String getStatusToolTip() {
    StringBuffer result = new StringBuffer("<html>"); // NOI18N
    result.append("<table cellspacing=\"0\" border=\"0\">"); // NOI18N

    final CollabManager manager = CollabManager.getDefault();

    if (manager != null) {
      Set sessions =
          new TreeSet(
              new Comparator() {
                public int compare(Object o1, Object o2) {
                  String s1 = ((CollabSession) o1).getUserPrincipal().getDisplayName();
                  String s2 = ((CollabSession) o2).getUserPrincipal().getDisplayName();

                  return s1.compareTo(s2);
                }
              });

      sessions.addAll(Arrays.asList(manager.getSessions()));

      if (sessions.size() == 0) {
        result.append("<tr><td>"); // NOI18N
        result.append(getStatusDescription(CollabPrincipal.STATUS_OFFLINE));
        result.append("</td></tr>"); // NOI18N
      } else {
        for (Iterator i = sessions.iterator(); i.hasNext(); ) {
          CollabPrincipal principal = ((CollabSession) i.next()).getUserPrincipal();

          result.append("<tr>"); // NOI18N
          result.append("<td>"); // NOI18N
          result.append("<b>"); // NOI18N
          result.append(principal.getDisplayName());
          result.append(": "); // NOI18N
          result.append("</b>"); // NOI18N
          result.append("</td>"); // NOI18N
          result.append("<td>"); // NOI18N
          result.append(getStatusDescription(principal.getStatus()));
          result.append("</td>"); // NOI18N
          result.append("</tr>"); // NOI18N
        }
      }
    }

    result.append("</table>"); // NOI18N

    return result.toString();
  }

  ////////////////////////////////////////////////////////////////////////////
  // Management methods
  ////////////////////////////////////////////////////////////////////////////

  /** */
  static synchronized OnlineStatusIndicator getDefault() {
    if (instance == null) {
      instance = new OnlineStatusIndicator();
    }

    return instance;
  }

  /** */
  private void attachListeners() {
    // Add the listener from each collab session principal
    CollabSession[] sessions = CollabManager.getDefault().getSessions();

    for (int i = 0; i < sessions.length; i++) {
      sessions[i].getUserPrincipal().removePropertyChangeListener(helper);
      sessions[i].getUserPrincipal().addPropertyChangeListener(helper);
    }
  }

  private class Helper extends MouseAdapter implements PropertyChangeListener, Runnable {
    public void mouseClicked(MouseEvent event) {
      CollabExplorerPanel.getInstance().open();
      CollabExplorerPanel.getInstance().requestActive();
    }

    public void propertyChange(PropertyChangeEvent event) {
      // session list changed
      if (event.getSource() instanceof CollabManager) {
        attachListeners();
      }

      // either session list or session status changed
      updateStatus();
    }

    public void run() {
      Image statusIcon = getStatusIcon(currentStatus);
      label.setIcon(new ImageIcon(statusIcon));
      label.setToolTipText(getStatusToolTip());
    }
  }
}