/**
   * Common initialization for all constructors.
   *
   * @throws Exception
   */
  private void initialize() throws Exception {
    // Disable most Cobra logging.
    Logger.getLogger("org.lobobrowser").setLevel(Level.WARNING);

    // Initialize variables for use with Cobra HTML parsing
    uacontext = new SimpleUserAgentContext();
    domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true); // never forget this!
    domBuilder = domFactory.newDocumentBuilder();
    doc = domBuilder.newDocument();

    // Initialize variables for the inherited methods
    xpathFactory = XPathFactory.newInstance();
    xpath = xpathFactory.newXPath();
  }
  // This error handler uses a Logger to log error messages
  static class MyErrorHandler implements ErrorHandler {
    private Logger log = Logger.getLogger(ERROR_LOGGER_NAME);

    //  This method is called in the event of a recoverable error
    public void error(SAXParseException e) {
      log(Logger.LEVEL_WARNING, e);
    }

    //  This method is called in the event of a non-recoverable error
    public void fatalError(SAXParseException e) {
      log(Logger.LEVEL_ERROR, e);
    }

    //  This method is called in the event of a warning
    public void warning(SAXParseException e) {
      log(Logger.LEVEL_WARNING, e);
    }

    // Log the error
    private void log(int level, SAXParseException e) {
      int line = e.getLineNumber();
      int col = e.getColumnNumber();
      String publicId = e.getPublicId();
      String systemId = e.getSystemId();
      StringBuffer sb = new StringBuffer();
      sb.append(e.getMessage());
      if (line > 0 || col > 0) {
        sb.append(": line=");
        sb.append(line);
        sb.append(", col=");
        sb.append(col);
      }
      if (publicId != null || systemId != null) {
        sb.append(": publicId=");
        sb.append(publicId);
        sb.append(", systemId=");
        sb.append(systemId);
      }
      // Log the message
      log.log(level, sb.toString());
    }
  }
/**
 * Wrapper for an existing DocumentBuilderFactory, delegates all calls to it except that the
 * ErrorHandler of created DocumentBuilders is set to one that logs to the LOCKSS logger. XXX Java
 * version-dependent: if the DocumentBuilderFactory API changes, this must be updated to forward all
 * methods. Needs to know what underlying factory to use, which makes it also dependent on
 * xercesImpl - XXX Xerces
 */
public class LockssDocumentBuilderFactoryImpl extends DocumentBuilderFactory {
  static Logger log = Logger.getLogger("DocumentBuilderFactory");
  public static String ERROR_LOGGER_NAME = "SAX";

  DocumentBuilderFactory fact;

  public LockssDocumentBuilderFactoryImpl() {
    //     fact = new org.apache.crimson.jaxp.DocumentBuilderFactoryImpl();
    fact = new org.apache.xerces.jaxp.DocumentBuilderFactoryImpl();
    log.debug3("Created fact: " + fact);
  }

  /** Forward to real factory, set error handler */
  public DocumentBuilder newDocumentBuilder() throws ParserConfigurationException {
    DocumentBuilder db = fact.newDocumentBuilder();
    log.debug3("Created builder: " + db);
    db.setErrorHandler(new MyErrorHandler());
    return db;
  }

  public void setAttribute(String name, Object value) {
    fact.setAttribute(name, value);
  }

  public Object getAttribute(String name) {
    return fact.getAttribute(name);
  }

  public void setNamespaceAware(boolean awareness) {
    fact.setNamespaceAware(awareness);
  }

  public void setValidating(boolean validating) {
    fact.setValidating(validating);
  }

  public void setIgnoringElementContentWhitespace(boolean whitespace) {
    fact.setIgnoringElementContentWhitespace(whitespace);
  }

  public void setExpandEntityReferences(boolean expandEntityRef) {
    fact.setExpandEntityReferences(expandEntityRef);
  }

  public void setIgnoringComments(boolean ignoreComments) {
    fact.setIgnoringComments(ignoreComments);
  }

  public void setCoalescing(boolean coalescing) {
    fact.setCoalescing(coalescing);
  }

  public boolean isNamespaceAware() {
    return fact.isNamespaceAware();
  }

  public boolean isValidating() {
    return fact.isValidating();
  }

  public boolean isIgnoringElementContentWhitespace() {
    return fact.isIgnoringElementContentWhitespace();
  }

  public boolean isExpandEntityReferences() {
    return fact.isExpandEntityReferences();
  }

  public boolean isIgnoringComments() {
    return fact.isIgnoringComments();
  }

  public boolean isCoalescing() {
    return fact.isCoalescing();
  }

  // Abstract methods added to DocumentBuilderFactory interface in 1.5.
  // They must be implemented and proxied, but direct calls won't compile
  // in 1.4, so invoke them using reflection.  Java 1.5 remove this?

  static Class[] argsGetFeature = {String.class};

  public boolean getFeature(String name) throws ParserConfigurationException {
    //     return fact.getFeature(name);
    try {
      Object res = invoke("getFeatureccc", argsGetFeature, new Object[] {name});
      return ((Boolean) res).booleanValue();
    } catch (InvocationTargetException e) {
      if (e.getCause() instanceof ParserConfigurationException) {
        throw (ParserConfigurationException) e.getCause();
      }
      if (e.getCause() instanceof RuntimeException) {
        throw (RuntimeException) e.getCause();
      }
      throw new RuntimeException(e);
    }
  }

  static Class[] argsSetFeature = {String.class, Boolean.TYPE};

  public void setFeature(String name, boolean value) throws ParserConfigurationException {
    //     fact.setFeature(name, value);
    try {
      invoke("setFeature", argsSetFeature, new Object[] {name, Boolean.valueOf(value)});
    } catch (InvocationTargetException e) {
      if (e.getCause() instanceof ParserConfigurationException) {
        throw (ParserConfigurationException) e.getCause();
      }
      if (e.getCause() instanceof RuntimeException) {
        throw (RuntimeException) e.getCause();
      }
      throw new RuntimeException(e);
    }
  }

  Object invoke(String method, Class[] argtypes, Object[] args) throws InvocationTargetException {
    try {
      Method m = fact.getClass().getMethod(method, argtypes);
      return m.invoke(fact, args);
    } catch (NoSuchMethodException e) {
      throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
      throw new RuntimeException(e);
    }
  }

  // This error handler uses a Logger to log error messages
  static class MyErrorHandler implements ErrorHandler {
    private Logger log = Logger.getLogger(ERROR_LOGGER_NAME);

    //  This method is called in the event of a recoverable error
    public void error(SAXParseException e) {
      log(Logger.LEVEL_WARNING, e);
    }

    //  This method is called in the event of a non-recoverable error
    public void fatalError(SAXParseException e) {
      log(Logger.LEVEL_ERROR, e);
    }

    //  This method is called in the event of a warning
    public void warning(SAXParseException e) {
      log(Logger.LEVEL_WARNING, e);
    }

    // Log the error
    private void log(int level, SAXParseException e) {
      int line = e.getLineNumber();
      int col = e.getColumnNumber();
      String publicId = e.getPublicId();
      String systemId = e.getSystemId();
      StringBuffer sb = new StringBuffer();
      sb.append(e.getMessage());
      if (line > 0 || col > 0) {
        sb.append(": line=");
        sb.append(line);
        sb.append(", col=");
        sb.append(col);
      }
      if (publicId != null || systemId != null) {
        sb.append(": publicId=");
        sb.append(publicId);
        sb.append(", systemId=");
        sb.append(systemId);
      }
      // Log the message
      log.log(level, sb.toString());
    }
  }
}
Exemple #4
0
/** Перевод всех проектов, сохраненных в XML формат в сводный Excel файл. */
public class Project2Excel {

  private static final Logger LOG = Logger.getLogger(Project2Excel.class.getName());

  private final List<Region> regions = new ArrayList<>(90);

  public void run() {
    File dir = new File("../../../../github_data/megafon/cs-core/");

    try {
      Nokia(new File(dir, "nokia/Master project CS SWAP_15.xml"));
      Huawei("УФ", new File(dir, "huawei/ПГ EKA + Ural v0 13 (2000).xml"));
      Huawei("ДвФ", new File(dir, "huawei/ПГ Khab+all cities V 1.6 (2000-2003).xml"));
      Huawei("СбФ", new File(dir, "huawei/ПГ Siberia all cities V 1.1 (2000-2003)_20161209.xml"));

      saveExcelPoject(new File(dir, "projects.xlsx"));
      saveStartProjects(new File(dir, "starts.csv"));
    } catch (IOException | ParserConfigurationException | SAXException e) {
      LOG.log(Level.SEVERE, "Исключение", e);
    }
  }

  private void Nokia(File file) throws IOException, ParserConfigurationException, SAXException {
    XMLProject project = new XMLProject();

    project.parse(file, new NokiaProjectHandler(this.regions));
  }

  private void Huawei(String filial, File file)
      throws IOException, ParserConfigurationException, SAXException {
    XMLProject project = new XMLProject();

    project.parse(file, new HuaweiProjectHandler(this.regions, filial));
  }

  private void saveExcelPoject(File file) throws IOException {
    Workbook wb = new XSSFWorkbook();
    Sheet sheet = wb.createSheet("timeplan");
    // Заголовок в 0 строке
    Row row = sheet.createRow(0);
    Cell cell = row.createCell(0);
    cell.setCellValue("Филиал");
    cell = row.createCell(1);
    cell.setCellValue("Город");
    Calendar cal = Calendar.getInstance();
    cal.set(2017, 0, 5); // Начальная дата проекта
    SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yy");
    for (int i = 0; i < 3 * 52; i++) { // Счетчик по неделям
      cell = row.createCell(i + 2);
      cell.setCellValue(sdf.format(cal.getTime()));
      cal.add(Calendar.WEEK_OF_YEAR, 1); // Следующая неделя
    }

    // sheet.setColumnWidth(0, 256);

    // Цвета ячеек
    CellStyle[] styles = new CellStyle[6];
    styles[0] = wb.createCellStyle();
    styles[0].setFillForegroundColor(HSSFColor.RED.index);
    styles[0].setFillPattern(FillPatternType.SOLID_FOREGROUND);
    styles[1] = wb.createCellStyle();
    styles[1].setFillForegroundColor(HSSFColor.GREEN.index);
    styles[1].setFillPattern(FillPatternType.SOLID_FOREGROUND);
    styles[2] = wb.createCellStyle();
    styles[2].setFillForegroundColor(HSSFColor.BLUE.index);
    styles[2].setFillPattern(FillPatternType.SOLID_FOREGROUND);
    styles[3] = wb.createCellStyle();
    styles[3].setFillForegroundColor(HSSFColor.ROSE.index);
    styles[3].setFillPattern(FillPatternType.SOLID_FOREGROUND);
    styles[4] = wb.createCellStyle();
    styles[4].setFillForegroundColor(HSSFColor.LIGHT_BLUE.index);
    styles[4].setFillPattern(FillPatternType.SOLID_FOREGROUND);
    styles[5] = wb.createCellStyle();
    styles[5].setFillForegroundColor(HSSFColor.LIGHT_GREEN.index);
    styles[5].setFillPattern(FillPatternType.SOLID_FOREGROUND);

    short rowIdx = 0;
    for (Region region : this.regions) {
      row = sheet.createRow(++rowIdx);
      cell = row.createCell(0);
      cell.setCellValue(region.filial);
      cell = row.createCell(1);
      cell.setCellValue(region.name);

      cal = Calendar.getInstance();
      cal.set(2017, 0, 5); // Начальная дата проекта
      for (int i = 0; i < 3 * 52; i++) { // Счетчик по неделям
        short color = region.getDateColorIndex(cal.getTime());
        if (color >= 0) {
          cell = row.createCell(i + 2);
          cell.setCellStyle(styles[color]);
        }

        cal.add(Calendar.WEEK_OF_YEAR, 1); // Следующая неделя
      }
    }

    try (FileOutputStream fileOut = new FileOutputStream(file)) {
      wb.write(fileOut);
    }
  }

  private void saveStartProjects(File file) throws IOException {
    Calendar cal = Calendar.getInstance();

    try (PrintWriter out = new PrintWriter(file, "windows-1251")) {
      for (Region region : this.regions) {
        cal.setTime(region.start);

        out.write("\"");
        out.write(region.filial + " " + region.name);
        out.write("\";;;");

        int skeepCells = (cal.get(Calendar.YEAR) - 2017) * 5 + (cal.get(Calendar.MONDAY) % 4);
        for (int i = 0; i < skeepCells; i++) {
          out.write(";");
        }
        out.println("X");
      }
    }
  }
}
public class ClientThread extends Thread implements Observer, ServerInterface {
  private Socket s = null;
  private DataInputStream in = null;
  private DataOutputStream out = null;
  private Users users;
  private static final Logger logger = Logger.getLogger("im.server");
  private History history;
  private String userName = "******";
  private Messages messages = null;
  private boolean disabled = false;

  public ClientThread(Socket socket, History history, Users users) throws IOException {

    logger.warn("New client is trying to connect to the chat...");
    logger.info("Assigning a socket to a new client...");
    this.s = socket;

    logger.info("Getting the input stream...");
    in = new DataInputStream(s.getInputStream());

    logger.info("Getting the output stream...");
    out = new DataOutputStream(s.getOutputStream());

    this.users = users;
    users.addObserver(this);

    this.history = history;

    start();
    logger.warn("Connection with new user is established.");
  }

  public void run() {
    try {
      prepareClient();
      logger.info("Starting normal session with " + getClientName());
      while (true) {
        this.receive();
      }
    } catch (IOException ioe) {
      logger.warn("Client " + this + " has been disconnected.");
      this.setDisabled(true);
      users.remove(this);
    } finally {
      try {
        if (s != null && !s.isClosed()) {
          s.close();
          logger.warn("Socket with " + this + " has been closed.");
        }
      } catch (IOException ioe) {
        logger.error("Socket has not been closed.", ioe);
      }
    }
  }

  public void receive() throws IOException {
    Message message = Operations.receive(in);
    logger.info("New message received.");

    processMessage(message);
  }

  private void processMessage(Message message) throws IOException {
    if (message.getType().equals("SimpleMessage")) {
      MessageType messageType = (MessageType) message.getValue();
      String receiver = messageType.getToUser();
      history.get(receiver).add(messageType);
    }

    if (message.getType().equals("ConnectUserMessage")) {
      String user = (String) message.getValue();
      Messages messages = history.get(user);
      Operations.sendHistory(messages.getLastFiveWith(user), out);
    }
  }

  // public void send(MessageType message) throws IOException {
  // Operations.sendMessage(message, out);
  // }

  public String toString() {
    return getClientName() + " [" + s.getInetAddress() + "]";
  }

  public String getClientName() {
    return userName;
  }

  public void update(Observable source, Object object) {
    if (source instanceof Users) {
      if (!this.isDisabled()) {
        try {
          Operations.sendUserNamesList(users.getUserNames(), out);
        } catch (IOException io) {
          logger.error("IO Exception", io);
        }
      }
    }

    if (source instanceof Messages) {
      try {
        Operations.sendMessage((MessageType) object, out);
      } catch (IOException io) {
        if (out != null) {
          try {
            out.close();
          } catch (Exception ioe) {
            logger.error("Failed to close the output stream", ioe);
          }
        }

        logger.error("Impossible to send messages", io);
      }
    }
  }

  private void setDisabled(boolean state) {
    this.disabled = state;
  }

  private boolean isDisabled() {
    return this.disabled;
  }

  private void setClientName(String userName) {
    this.userName = userName;
  }

  private void prepareClient() throws IOException {
    logger.info("Waiting for client's name");
    Message mes = Operations.receive(in);
    setClientName((String) mes.getValue());
    logger.info("Username for " + s.getInetAddress() + " received: " + userName);

    users.add(this);
    logger.info("User " + getClientName() + " has been added to the userlist.");

    messages = new Messages();
    logger.info("Message list created");

    if (!history.containsKey(userName)) {
      history.put(userName, messages);
    } else {
      messages = history.get(userName);
    }
    messages.addObserver(this);
    logger.info("Message list assigned to history");

    logger.info("Sending the list of users.");
    Operations.sendUserNamesList(users.getUserNames(), out);
    logger.info("Userlist has been sent");
  }
}
/** Implements the "get status table" command */
public class AddAuConfigure extends AuActivityBase {

  private static String NAME = "AddAuConfigure";
  private static Logger log = Logger.getLogger(NAME);

  public AddAuConfigure() {
    super();
  }

  /**
   * Populate the response body
   *
   * @return true on success
   */
  public boolean doRemoteSetupAndVerification() throws IOException {

    /*
     * Stop if any required parameters are missing (error)
     */
    if (!verifyMinimumParameters()) {
      throw new ResponseException("Missing required parameters");
    }
    /*
     * Initial page setup
     */
    return commandSetup();
  }

  /**
   * Populate the response body
   *
   * @return true on success
   */
  public boolean doCommand() throws IOException {
    Element infoElement;

    /*
     * Return disk space
     */
    infoElement = getXmlUtils().createElement(getResponseRoot(), AP_E_INFO);
    renderDiskXml(infoElement);

    /*
     * No further action if this isn't a create command (success)
     */
    if (!isCreateCommand()) {
      return true;
    }
    /*
     * Stop if any required parameters are missing (error)
     */
    if (!verifyTarget() || !verifyMinimumParameters() || !verifyDefiningParameters()) {
      throw new ResponseException("Missing required parameters");
    }
    /*
     * Create the AU
     */
    if (!commandSetup()) {
      return false;
    }
    return createAu();
  }

  /*
   * "Helpers"
   */

  /**
   * Did the client provide the minimal parameters required?
   *
   * @return true If so
   */
  private boolean verifyMinimumParameters() {
    int count = 0;

    if (!StringUtil.isNullString(getParameter(AP_E_PUBLICATION))) count++;
    if (!StringUtil.isNullString(getParameter(AP_E_CLASSNAME))) count++;
    if (!StringUtil.isNullString(getParameter(AP_E_PLUGIN))) count++;

    return (count > 0);
  }

  /**
   * A target system is required to create an AU - was it provided?
   *
   * @return true If at least one target was specified
   */
  private boolean verifyTarget() {
    if (!isCreateCommand()) {
      return true;
    }

    return !StringUtil.isNullString(getParameter(AP_E_TARGET));
  }

  /**
   * Are all of the "defining parameters" required to create an AU available?
   *
   * @return true If so
   */
  private boolean verifyDefiningParameters() {
    KeyedList parameters;
    int size;

    if (!isCreateCommand()) {
      return true;
    }

    parameters = ParseUtils.getDynamicFields(getXmlUtils(), getRequestDocument(), AP_MD_AUDEFINING);
    size = parameters.size();

    for (int i = 0; i < size; i++) {
      if (StringUtil.isNullString((String) parameters.getValue(i))) {
        return false;
      }
    }
    return true;
  }

  /**
   * "Create" command?
   *
   * @return true If so...
   */
  private boolean isCreateCommand() {
    return "create".equalsIgnoreCase(getParameter(AP_E_ACTION));
  }

  /** Query the daemon for information required to set up this command */
  private boolean commandSetup() {

    Configuration configuration = null;
    Collection noEditKeys = null;
    String key;
    String value;

    /*
     * Configure a well known publication?
     */
    if ((value = getParameter(AP_E_PUBLICATION)) != null) {
      PluginProxy plugin = getTitlePlugin(value);

      /*
       * Set plugin and Title configuration information
       */
      if (plugin == null) {
        String message = "Unknown Publication:" + value;

        log.warning(message);
        return error(message);
      }

      setPlugin(plugin);
      setTitleConfig(plugin.getTitleConfig(value));

      configuration = getTitleConfig().getConfig();
      noEditKeys = getNoEditKeys();

    } else {
      /*
       * Lookup by Plugin or Class name - set the plugin
       *
       * NB: As of 23-Feb-04, this is not supported from AddAuPage.java.  See
       *     AddAuWithCompleteFunctionalityPage.java for full support.
       */
      if ((value = getParameter(AP_E_PLUGIN)) != null) {
        key = RemoteApi.pluginKeyFromId(value);

      } else if ((value = getParameter(AP_E_CLASSNAME)) != null) {
        key = RemoteApi.pluginKeyFromId(value);

      } else {
        return error("Supply a Publication, Plugin, or Class name");
      }

      if (StringUtil.isNullString(key)) {
        return error("Supply a valid Publication, Plugin, or Class name");
      }

      if (!pluginLoaded(key)) {
        return error("Plugin is not loaded: " + key);
      }

      setPlugin(getPluginProxy(key));
    }

    /*
     * Finally, return an XML rendition of the Plugin and AU key set up
     */
    generateSetupXml(configuration, noEditKeys);
    return true;
  }

  /**
   * Create an Archival Unit
   *
   * @return true If successful
   */
  private boolean createAu() {

    Configuration config = getAuConfigFromForm();

    AuProxy au;
    Element element;

    try {
      au = getRemoteApi().createAndSaveAuConfiguration(getPlugin(), config);

    } catch (ArchivalUnit.ConfigurationException exception) {
      return error("Configuration failed: " + exception.getMessage());

    } catch (IOException exception) {
      return error("Unable to save configuration: " + exception.getMessage());
    }
    /*
     * Successful creation - add the AU name and ID to the response document
     */
    element = getXmlUtils().createElement(getResponseRoot(), AP_E_AU);
    XmlUtils.addText(element, au.getName());

    element = getXmlUtils().createElement(getResponseRoot(), AP_E_AUID);
    XmlUtils.addText(element, au.getAuId());

    return true;
  }
}
/**
 * WhiteboardObjectTextJabberImpl
 *
 * <p>WhiteboardObjectTextJabberImpl are created through the <tt>WhiteboardSession</tt> session.
 *
 * <p>All WhiteboardObjectTextJabberImpl have whiteboard object id.
 *
 * @author Julien Waechter
 */
public class WhiteboardObjectTextJabberImpl extends WhiteboardObjectJabberImpl
    implements WhiteboardObjectText {
  private static final Logger logger = Logger.getLogger(WhiteboardObjectTextJabberImpl.class);

  /** The WhiteboardObjectTextJabberImpl's text size */
  private int fontSize = 0;
  /** The WhiteboardObjectTextJabberImpl's font name */
  private String fontName = "Dialog";
  /** The WhiteboardObjectTextJabberImpl's text */
  private String text = "";
  /** The coordinates of this object. */
  private WhiteboardPoint whiteboardPoint;

  /** Default WhiteboardObjectTextJabberImpl constructor. */
  public WhiteboardObjectTextJabberImpl() {
    super();

    this.setWhiteboardPoint(new WhiteboardPoint(0, 0));
    this.setFontName(fontName);
    this.setFontSize(fontSize);
    this.setText(text);
  }

  /**
   * WhiteboardObjectTextJabberImpl constructor.
   *
   * @param xml the XML string object to parse.
   */
  public WhiteboardObjectTextJabberImpl(String xml) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;
    try {
      builder = factory.newDocumentBuilder();
      InputStream in = new ByteArrayInputStream(xml.getBytes());
      Document doc = builder.parse(in);

      Element e = doc.getDocumentElement();
      String elementName = e.getNodeName();
      if (elementName.equals("text")) {
        // we have a text
        String id = e.getAttribute("id");
        double x = Double.parseDouble(e.getAttribute("x"));
        double y = Double.parseDouble(e.getAttribute("y"));
        String fill = e.getAttribute("fill");
        String fontFamily = e.getAttribute("font-family");
        int fontSize = Integer.parseInt(e.getAttribute("font-size"));
        String text = e.getTextContent();

        this.setID(id);
        this.setWhiteboardPoint(new WhiteboardPoint(x, y));
        this.setFontName(fontFamily);
        this.setFontSize(fontSize);
        this.setText(text);
        this.setColor(Color.decode(fill).getRGB());
      }
    } catch (ParserConfigurationException ex) {
      if (logger.isDebugEnabled()) logger.debug("Problem WhiteboardObject : " + xml);
    } catch (IOException ex) {
      if (logger.isDebugEnabled()) logger.debug("Problem WhiteboardObject : " + xml);
    } catch (Exception ex) {
      if (logger.isDebugEnabled()) logger.debug("Problem WhiteboardObject : " + xml);
    }
  }

  /**
   * Returns the coordinates of this whiteboard object.
   *
   * @return the coordinates of this object.
   */
  public WhiteboardPoint getWhiteboardPoint() {
    return this.whiteboardPoint;
  }

  /**
   * Sets the coordinates of this whiteboard object.
   *
   * @param whiteboardPoint the coordinates of this object.
   */
  public void setWhiteboardPoint(WhiteboardPoint whiteboardPoint) {
    this.whiteboardPoint = whiteboardPoint;
  }

  /**
   * Returns the WhiteboardObjectTextJabberImpl's text.
   *
   * @return the WhiteboardObjectTextJabberImpl's text.
   */
  public String getText() {
    return this.text;
  }

  /**
   * Sets the WhiteboardObjectTextJabberImpl's text.
   *
   * @param text the new WhiteboardObjectTextJabberImpl's text.
   */
  public void setText(String text) {
    this.text = text;
  }

  /**
   * Returns the WhiteboardObjectTextJabberImpl's font size.
   *
   * @return the WhiteboardObjectTextJabberImpl's font size.
   */
  public int getFontSize() {
    return this.fontSize;
  }

  /**
   * Sets the WhiteboardObjectTextJabberImpl's font size.
   *
   * @param fontSize the new WhiteboardObjectTextJabberImpl's font size.
   */
  public void setFontSize(int fontSize) {
    this.fontSize = fontSize;
  }

  /**
   * Returns the WhiteboardObjectTextJabberImpl's font name. (By default Dialog)
   *
   * @return the new WhiteboardObjectTextJabberImpl's font name.
   */
  public String getFontName() {
    return this.fontName;
  }

  /**
   * Sets the WhiteboardObjectTextJabberImpl's font name.
   *
   * @param fontName the new WhiteboardObjectTextJabberImpl's font name.
   */
  public void setFontName(String fontName) {
    this.fontName = fontName;
  }

  /**
   * Returns the XML reppresentation of the PacketExtension.
   *
   * @return the packet extension as XML.
   * @todo Implement this org.jivesoftware.smack.packet.PacketExtension method
   */
  public String toXML() {
    String s =
        "<text id=\"#i\" x=\"#x\" y=\"#y\" "
            + "fill=\"#fi\" font-family=\"#ff\" font-size=\"#fs\">#t</text>";
    s = s.replaceAll("#i", getID());
    s = s.replaceAll("#fi", colorToHex(getColor()));
    WhiteboardPoint p = getWhiteboardPoint();
    s = s.replaceAll("#x", "" + p.getX());
    s = s.replaceAll("#y", "" + p.getY());
    s = s.replaceAll("#ff", getFontName());
    s = s.replaceAll("#fs", "" + getFontSize());
    s = s.replaceAll("#t", getText());
    return s;
  }
}
Exemple #8
0
/**
 * Information provided via the spellchecer's xml parameters.
 *
 * @author Damian Johnson
 */
class Parameters {
  private static final Logger logger = Logger.getLogger(Parameters.class);

  private static final String RESOURCE_LOC = "resources/config/spellcheck/parameters.xml";

  private static final String NODE_DEFAULTS = "defaults";

  private static final String NODE_LOCALES = "locales";

  private static final HashMap<Default, String> DEFAULTS = new HashMap<Default, String>();

  private static final ArrayList<Locale> LOCALES = new ArrayList<Locale>();

  static {
    try {
      URL url = SpellCheckActivator.bundleContext.getBundle().getResource(RESOURCE_LOC);

      InputStream stream = url.openStream();

      if (stream == null) throw new IOException();

      // strict parsing options
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

      factory.setValidating(false);
      factory.setIgnoringComments(true);
      factory.setIgnoringElementContentWhitespace(true);

      // parses configuration xml
      /*-
       * Warning: Felix is unable to import the com.sun.rowset.internal
       * package, meaning this can't use the XmlErrorHandler. This causes
       * a warning and a default handler to be attached. Otherwise this
       * should have: builder.setErrorHandler(new XmlErrorHandler());
       */
      DocumentBuilder builder = factory.newDocumentBuilder();
      Document doc = builder.parse(stream);

      // iterates over nodes, parsing contents
      Node root = doc.getChildNodes().item(1);

      NodeList categories = root.getChildNodes();

      for (int i = 0; i < categories.getLength(); ++i) {
        Node node = categories.item(i);
        if (node.getNodeName().equals(NODE_DEFAULTS)) {
          parseDefaults(node.getChildNodes());
        } else if (node.getNodeName().equals(NODE_LOCALES)) {
          parseLocales(node.getChildNodes());
        } else {
          logger.warn("Unrecognized category: " + node.getNodeName());
        }
      }
    } catch (IOException exc) {
      logger.error("Unable to load spell checker parameters", exc);
    } catch (SAXException exc) {
      logger.error("Unable to parse spell checker parameters", exc);
    } catch (ParserConfigurationException exc) {
      logger.error("Unable to parse spell checker parameters", exc);
    }
  }

  /**
   * Retrieves default values from xml.
   *
   * @param list the configuration list
   */
  private static void parseDefaults(NodeList list) {
    for (int i = 0; i < list.getLength(); ++i) {
      NamedNodeMap mapping = list.item(i).getAttributes();
      String attribute = mapping.getNamedItem("attribute").getNodeValue();
      String value = mapping.getNamedItem("value").getNodeValue();

      try {
        Default field = Default.fromString(attribute);
        DEFAULTS.put(field, value);
      } catch (IllegalArgumentException exc) {
        logger.warn("Unrecognized default attribute: " + attribute);
      }
    }
  }

  /**
   * Populates LOCALES list with contents of xml.
   *
   * @param list the configuration list
   */
  private static void parseLocales(NodeList list) {
    for (int i = 0; i < list.getLength(); ++i) {
      Node node = list.item(i);
      NamedNodeMap attributes = node.getAttributes();
      String label = ((Attr) attributes.getNamedItem("label")).getValue();
      String code = ((Attr) attributes.getNamedItem("isoCode")).getValue();
      String dictLocation = ((Attr) attributes.getNamedItem("dictionaryUrl")).getValue();
      try {
        LOCALES.add(new Locale(label, code, new URL(dictLocation)));
      } catch (MalformedURLException exc) {
        logger.warn(
            "Unable to parse dictionary location of " + label + " (" + dictLocation + ")", exc);
      }
    }
  }

  /**
   * Provides the value of a particular default field, null if undefined.
   *
   * @param field default field to retrieve
   * @return value corresponding to default field
   */
  public static String getDefault(Default field) {
    return DEFAULTS.get(field);
  }

  /**
   * Provides locale with a given iso code. Null if undefined.
   *
   * @param isoCode iso code of locale to be retrieved
   * @return locale with corresponding iso code
   */
  public static Locale getLocale(String isoCode) {
    for (Locale locale : LOCALES) {
      if (locale.getIsoCode().equals(isoCode)) return locale;
    }

    return null;
  }

  /**
   * Provides locales in which dictionary resources are available.
   *
   * @return locations with dictionary resources
   */
  public static ArrayList<Locale> getLocales() {
    return new ArrayList<Locale>(LOCALES);
  }

  /** Locale with an available dictionary resource. */
  public static class Locale {
    private final String label;

    private final String isoCode;

    private final URL dictLocation;

    private boolean isLoading = false;

    private Locale(String label, String isoCode, URL dictLocation) {
      this.label = label;
      this.isoCode = isoCode;
      this.dictLocation = dictLocation;
    }

    /**
     * Provides user readable name of language.
     *
     * @return name of language presented to user
     */
    public String getLabel() {
      return this.label;
    }

    /**
     * Provides ISO code as defined by:<br>
     * http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
     *
     * @return iso code
     */
    public String getIsoCode() {
      return this.isoCode;
    }

    /**
     * Gets the ICU locale, which is a combination of the ISO code and the country variant. English
     * for the United States is therefore en_US, German for Switzerland de_CH.
     *
     * @return ICU locale
     */
    public String getIcuLocale() {
      String[] parts = this.isoCode.split(",");
      return parts[0].toLowerCase() + "_" + parts[1].toUpperCase();
    }

    /**
     * Provides the url where the dictionary resource can be found for this language.
     *
     * @return url of dictionary resource
     */
    public URL getDictUrl() {
      return this.dictLocation;
    }

    /**
     * Sets the loading property. Indicates if this locale is currently loaded in the list.
     *
     * @param loading indicates if this locale is currently loading in the locales list
     */
    public void setLoading(boolean loading) {
      this.isLoading = loading;
    }

    /**
     * Indicates if this locale is currenly loading in the list of locales.
     *
     * @return <tt>true</tt> if the locale is loading, <tt>false</tt> - otherwise
     */
    public boolean isLoading() {
      return isLoading;
    }

    @Override
    public String toString() {
      return this.label + " (" + this.isoCode + ")";
    }
  }

  /** Default attribute that may be defined in the parameters xml. */
  public enum Default {
    LOCALE("locale");

    private String tag;

    Default(String tag) {
      this.tag = tag;
    }

    /**
     * Returns the enum representation of a string. This is case sensitive.
     *
     * @param str toString representation of a default field
     * @return default field associated with a string
     * @throws IllegalArgumentException if argument is not represented by a default field.
     */
    public static Default fromString(String str) {
      for (Default field : Default.values()) {
        if (str.equals(field.toString())) {
          return field;
        }
      }
      throw new IllegalArgumentException();
    }

    @Override
    public String toString() {
      return this.tag;
    }
  }
}