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);
      }
    }
  }
  /**
   * @param sourceFile File to read from
   * @return List of String objects with the shas
   */
  public static FileRequestFileContent readRequestFile(final File sourceFile) {
    if (!sourceFile.isFile() || !(sourceFile.length() > 0)) {
      return null;
    }
    Document d = null;
    try {
      d = XMLTools.parseXmlFile(sourceFile.getPath());
    } catch (final Throwable t) {
      logger.log(Level.SEVERE, "Exception in readRequestFile, during XML parsing", t);
      return null;
    }

    if (d == null) {
      logger.log(Level.SEVERE, "Could'nt parse the request file");
      return null;
    }

    final Element rootNode = d.getDocumentElement();

    if (rootNode.getTagName().equals(TAG_FrostFileRequestFile) == false) {
      logger.severe(
          "Error: xml request file does not contain the root tag '"
              + TAG_FrostFileRequestFile
              + "'");
      return null;
    }

    final String timeStampStr = XMLTools.getChildElementsTextValue(rootNode, TAG_timestamp);
    if (timeStampStr == null) {
      logger.severe("Error: xml file does not contain the tag '" + TAG_timestamp + "'");
      return null;
    }
    final long timestamp = Long.parseLong(timeStampStr);

    final List<Element> nodelist = XMLTools.getChildElementsByTagName(rootNode, TAG_shaList);
    if (nodelist.size() != 1) {
      logger.severe("Error: xml request files must contain only one element '" + TAG_shaList + "'");
      return null;
    }

    final Element rootShaNode = nodelist.get(0);

    final List<String> shaList = new LinkedList<String>();
    final List<Element> xmlKeys = XMLTools.getChildElementsByTagName(rootShaNode, TAG_sha);
    for (final Element el : xmlKeys) {

      final Text txtname = (Text) el.getFirstChild();
      if (txtname == null) {
        continue;
      }

      final String sha = txtname.getData();
      shaList.add(sha);
    }

    final FileRequestFileContent content = new FileRequestFileContent(timestamp, shaList);
    return content;
  }
Beispiel #3
0
  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);
    }
  }
Beispiel #4
0
  @Override
  public org.mmbase.bridge.Node getNode(final Cloud userCloud, final Document doc) {
    String docId = doc.get("number");
    if (docId == null) {
      throw new IllegalArgumentException("No number found in " + doc);
    }
    LazyMap m = nodeCache.get(docId); //
    if (m == null) {
      Map<String, String> keys = new HashMap<String, String>();
      for (String keyWord : keyWords) {
        keys.put(keyWord, doc.get(keyWord));
      }
      m = new LazyMap(docId, keys);
      nodeCache.put(docId, m);
    }
    org.mmbase.bridge.Node node =
        new MapNode<String>(
            m,
            new MapNodeManager(userCloud, m) {
              @Override
              public boolean hasField(String name) {
                if (JdbcIndexDefinition.this.key.equals(name)) return true;
                return super.hasField(name);
              }

              @Override
              public org.mmbase.bridge.Field getField(String name) {
                if (map == null && JdbcIndexDefinition.this.key.equals(name)) {
                  org.mmbase.core.CoreField fd =
                      org.mmbase.core.util.Fields.createField(
                          name,
                          org.mmbase.core.util.Fields.classToType(Object.class),
                          org.mmbase.bridge.Field.TYPE_UNKNOWN,
                          org.mmbase.bridge.Field.STATE_VIRTUAL,
                          null);
                  return new org.mmbase.bridge.implementation.BasicField(fd, this);
                } else {
                  return super.getField(name);
                }
              }
            });
    if (log.isDebugEnabled()) {
      log.debug("Returning node for " + node);
    }
    return node;
  }
Beispiel #5
0
 @Override
 public CloseableIterator<JdbcEntry> getSubCursor(String identifier) {
   if (isSub) {
     log.debug("Using getSubCursor for " + identifier);
     return getSqlCursor(getSql(identifier));
   } else {
     return getSqlCursor(getFindSql(identifier));
   }
 }
  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.");
  }
Beispiel #7
0
 @Override
 public boolean inIndex(String identifier) {
   CloseableIterator<JdbcEntry> i = getSqlCursor(getFindSql(identifier));
   boolean result = i.hasNext();
   try {
     i.close();
   } catch (IOException ex) {
     log.warn(ex);
   }
   return result;
 }
  /**
   * 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);
    }
  }
	 public List search(String searchClassName, Object criterion) throws Exception
	 {
		try
		{
		 	ApplicationService applicationService = ApplicationServiceProvider.getApplicationService();		 	
		 	List criterionList = applicationService.search(searchClassName, criterion);
			return criterionList;
		}catch(Exception e)
		{
			log.error("Error thrown from Generic Service " + e.getMessage());
			throw new org.apache.axis.AxisFault("Error thrown from Generic Service "+e.getMessage() );
		}
	}
Beispiel #10
0
 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);
     }
   }
 }
  /**
   * @param chkKeys List of String objects with the shas
   * @param targetFile target file
   * @return true if write was successful
   */
  public static boolean writeRequestFile(
      final FileRequestFileContent content, final File targetFile) {

    final Document doc = XMLTools.createDomDocument();
    if (doc == null) {
      logger.severe("Error - writeRequestFile: factory could'nt create XML Document.");
      return false;
    }

    final Element rootElement = doc.createElement(TAG_FrostFileRequestFile);
    doc.appendChild(rootElement);

    final Element timeStampElement = doc.createElement(TAG_timestamp);
    final Text timeStampText = doc.createTextNode(Long.toString(content.getTimestamp()));
    timeStampElement.appendChild(timeStampText);
    rootElement.appendChild(timeStampElement);

    final Element rootChkElement = doc.createElement(TAG_shaList);
    rootElement.appendChild(rootChkElement);

    for (final String chkKey : content.getShaStrings()) {

      final Element nameElement = doc.createElement(TAG_sha);
      final Text text = doc.createTextNode(chkKey);
      nameElement.appendChild(text);

      rootChkElement.appendChild(nameElement);
    }

    boolean writeOK = false;
    try {
      writeOK = XMLTools.writeXmlFile(doc, targetFile);
    } catch (final Throwable t) {
      logger.log(Level.SEVERE, "Exception in writeRequestFile/writeXmlFile", t);
    }

    return writeOK;
  }
Beispiel #12
0
  /**
   * 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);
      }
    }
  }
Beispiel #13
0
 /**
  * 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);
     }
   }
 }
Beispiel #14
0
 /**
  * Jdbc connection pooling of MMBase would kill the statement if too duratious. This produces a
  * 'direct connection' in that case, to circumvent that problem (Indexing queries _may_ take a
  * while).
  */
 protected Connection getDirectConnection() throws SQLException {
   directConnections++;
   try {
     if (dataSource instanceof GenericDataSource) {
       return ((GenericDataSource) dataSource).getDirectConnection();
     } else {
       return dataSource.getConnection();
     }
   } catch (SQLException sqe) {
     log.error("With direct connection #" + directConnections + ": " + sqe.getMessage());
     throw sqe;
   } catch (Throwable t) {
     throw new RuntimeException("direct connection #" + directConnections, t);
   }
 }
Beispiel #15
0
  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");
  }
/**
 * Reads and write request files containing SHA keys.
 *
 * <p>XML format:
 *
 * <p><FrostFileRequestFile> <timestamp>...</timestamp> <shaList> <sha>...</sha> <sha>...</sha>
 * </shaList> </FrostRequestFile>
 */
public class FileRequestFile {

  private static final Logger logger = Logger.getLogger(FileRequestFile.class.getName());

  private static final String TAG_FrostFileRequestFile = "FrostFileRequestFile";
  private static final String TAG_timestamp = "timestamp";
  private static final String TAG_shaList = "shaList";
  private static final String TAG_sha = "sha";

  /**
   * @param chkKeys List of String objects with the shas
   * @param targetFile target file
   * @return true if write was successful
   */
  public static boolean writeRequestFile(
      final FileRequestFileContent content, final File targetFile) {

    final Document doc = XMLTools.createDomDocument();
    if (doc == null) {
      logger.severe("Error - writeRequestFile: factory could'nt create XML Document.");
      return false;
    }

    final Element rootElement = doc.createElement(TAG_FrostFileRequestFile);
    doc.appendChild(rootElement);

    final Element timeStampElement = doc.createElement(TAG_timestamp);
    final Text timeStampText = doc.createTextNode(Long.toString(content.getTimestamp()));
    timeStampElement.appendChild(timeStampText);
    rootElement.appendChild(timeStampElement);

    final Element rootChkElement = doc.createElement(TAG_shaList);
    rootElement.appendChild(rootChkElement);

    for (final String chkKey : content.getShaStrings()) {

      final Element nameElement = doc.createElement(TAG_sha);
      final Text text = doc.createTextNode(chkKey);
      nameElement.appendChild(text);

      rootChkElement.appendChild(nameElement);
    }

    boolean writeOK = false;
    try {
      writeOK = XMLTools.writeXmlFile(doc, targetFile);
    } catch (final Throwable t) {
      logger.log(Level.SEVERE, "Exception in writeRequestFile/writeXmlFile", t);
    }

    return writeOK;
  }

  public static void main(final String[] args) {
    final File targetFile = new File("D:\\abc.def");
    final File tmp = new File(targetFile.getPath() + ".frftmp");
    if (!FileAccess.compressFileGZip(targetFile, tmp)) {
      return; // error
    }
    targetFile.delete();
    tmp.renameTo(targetFile);
  }

  /**
   * @param sourceFile File to read from
   * @return List of String objects with the shas
   */
  public static FileRequestFileContent readRequestFile(final File sourceFile) {
    if (!sourceFile.isFile() || !(sourceFile.length() > 0)) {
      return null;
    }
    Document d = null;
    try {
      d = XMLTools.parseXmlFile(sourceFile.getPath());
    } catch (final Throwable t) {
      logger.log(Level.SEVERE, "Exception in readRequestFile, during XML parsing", t);
      return null;
    }

    if (d == null) {
      logger.log(Level.SEVERE, "Could'nt parse the request file");
      return null;
    }

    final Element rootNode = d.getDocumentElement();

    if (rootNode.getTagName().equals(TAG_FrostFileRequestFile) == false) {
      logger.severe(
          "Error: xml request file does not contain the root tag '"
              + TAG_FrostFileRequestFile
              + "'");
      return null;
    }

    final String timeStampStr = XMLTools.getChildElementsTextValue(rootNode, TAG_timestamp);
    if (timeStampStr == null) {
      logger.severe("Error: xml file does not contain the tag '" + TAG_timestamp + "'");
      return null;
    }
    final long timestamp = Long.parseLong(timeStampStr);

    final List<Element> nodelist = XMLTools.getChildElementsByTagName(rootNode, TAG_shaList);
    if (nodelist.size() != 1) {
      logger.severe("Error: xml request files must contain only one element '" + TAG_shaList + "'");
      return null;
    }

    final Element rootShaNode = nodelist.get(0);

    final List<String> shaList = new LinkedList<String>();
    final List<Element> xmlKeys = XMLTools.getChildElementsByTagName(rootShaNode, TAG_sha);
    for (final Element el : xmlKeys) {

      final Text txtname = (Text) el.getFirstChild();
      if (txtname == null) {
        continue;
      }

      final String sha = txtname.getData();
      shaList.add(sha);
    }

    final FileRequestFileContent content = new FileRequestFileContent(timestamp, shaList);
    return content;
  }
}
Beispiel #17
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;
    }
  }
}
Beispiel #18
0
  public void receive() throws IOException {
    Message message = Operations.receive(in);
    logger.info("New message received.");

    processMessage(message);
  }
Beispiel #19
0
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");
  }
}
/**
 * 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;
  }
}
/** 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;
  }
}
  /** 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;
  }
Beispiel #23
0
  CloseableIterator<JdbcEntry> getSqlCursor(final String sql) {
    try {
      long start = System.currentTimeMillis();
      final Connection con = getDirectConnection();
      log.debug("About to execute " + sql + " (" + directConnections + ")");
      final Statement statement = con.createStatement();
      final ResultSet results = statement.executeQuery(sql);
      if (log.isDebugEnabled()) {
        log.debug("Executed " + sql + " in " + (System.currentTimeMillis() - start) + " ms");
      }
      final ResultSetMetaData meta = results.getMetaData();

      return new CloseableIterator<JdbcEntry>() {
        boolean hasNext = results.isBeforeFirst();
        int i = 0;

        @Override
        public boolean hasNext() {
          return hasNext;
        }

        @Override
        public JdbcEntry next() {
          if (!hasNext) {
            throw new NoSuchElementException();
          }
          try {
            results.next();
            hasNext = !results.isLast();
          } catch (java.sql.SQLException sqe) {
            log.error(sqe);
            hasNext = false;
          }
          JdbcEntry entry = new JdbcEntry(meta, results, sql);
          i++;
          if (log.isServiceEnabled()) {
            if (i % 100 == 0) {
              log.service("jdbc cursor " + i + " (now at id=" + entry.getIdentifier() + ")");
            } else if (log.isDebugEnabled()) {
              log.trace("jdbc cursor " + i + " (now at id=" + entry.getIdentifier() + ")");
            }
          }
          return entry;
        }

        @Override
        public void remove() {
          throw new UnsupportedOperationException();
        }

        @Override
        public void close() {
          log.debug("Closing " + con);
          try {
            if (results != null) results.close();
            if (statement != null) statement.close();
            if (con != null) con.close();
          } catch (Exception e) {
            log.error(e);
          }
        }
      };
    } catch (Exception e) {
      throw new RuntimeException(e.getMessage(), e);
    }
  }