Ejemplo n.º 1
0
  // create a calc document with content, which needs some time for saving
  private XInterface createBigCalcDoc() {
    m_aLog.log(Protocol.TYPE_SCOPE_OPEN, "createBigCalcDoc() started ...");
    try {
      m_aLog.log("Create empty calc document for testing.");
      XSpreadsheetDocument xSheetDoc = m_aSOF.createCalcDoc("_default");
      m_aLog.log("Retrieve first sheet from calc document.");
      XSpreadsheets xSheets = xSheetDoc.getSheets();
      XSpreadsheet xSheet =
          (XSpreadsheet)
              AnyConverter.toObject(
                  new Type(XSpreadsheet.class), xSheets.getByName(xSheets.getElementNames()[0]));
      m_aLog.log("Fill two cells with value and formula.");
      xSheet.getCellByPosition(0, 0).setValue(1);
      xSheet.getCellByPosition(0, 1).setFormula("=a1+1");
      m_aLog.log("Retrieve big range.");
      XCellRange xRange = xSheet.getCellRangeByName("A1:Z9999");
      XCellSeries xSeries = UnoRuntime.queryInterface(XCellSeries.class, xRange);
      m_aLog.log("Duplicate cells from top to bottom inside range.");
      xSeries.fillAuto(FillDirection.TO_BOTTOM, 2);
      m_aLog.log("Duplicate cells from left to right inside range.");
      xSeries.fillAuto(FillDirection.TO_RIGHT, 1);

      m_aLog.log(Protocol.TYPE_SCOPE_CLOSE | Protocol.TYPE_OK, "createBigCalcDoc() finished.");
      return xSheetDoc;
    } catch (Throwable ex) {
      m_aLog.log(ex);
    }

    m_aLog.log(Protocol.TYPE_SCOPE_CLOSE, "createBigCalcDoc() finished.");
    return null;
  }
Ejemplo n.º 2
0
  private void saveDoc(XInterface xDoc, String sURL) {
    m_aLog.log(Protocol.TYPE_SCOPE_OPEN, "saveDoc('" + sURL + "') started ...");
    try {
      URL[] aURL = new URL[1];
      aURL[0] = new URL();
      aURL[0].Complete = ".uno:SaveAs";
      m_xURLParser.parseStrict(aURL);

      XModel xModel = UnoRuntime.queryInterface(XModel.class, xDoc);
      XDispatchProvider xProvider =
          UnoRuntime.queryInterface(XDispatchProvider.class, xModel.getCurrentController());
      XDispatch xDispatch = xProvider.queryDispatch(aURL[0], "_self", 0);

      PropertyValue[] lArgs = new PropertyValue[3];
      lArgs[0] = new PropertyValue();
      lArgs[0].Name = "URL";
      lArgs[0].Value = sURL;
      lArgs[1] = new PropertyValue();
      lArgs[1].Name = "Overwrite";
      lArgs[1].Value = Boolean.TRUE;
      lArgs[2] = new PropertyValue();
      lArgs[2].Name = "StoreTo";
      lArgs[2].Value = Boolean.TRUE;

      xDispatch.dispatch(aURL[0], lArgs);

      m_aLog.log(Protocol.TYPE_OK, "saveDoc('" + sURL + "') = OK.");
    } catch (Throwable ex) {
      m_aLog.log(ex);
    }
    m_aLog.log(Protocol.TYPE_SCOPE_CLOSE, "saveDoc('" + sURL + "') finished.");
  }
 @Test
 public void encodeSend() throws Exception {
   Message origin = messages.get(CommandType.MSG);
   Protocol protocol = new SerializationProtocol();
   byte[] data = protocol.encode(origin);
   Message copy = protocol.decode(data);
   System.out.println(copy);
   System.out.println(origin);
   assertTrue(copy.toString().equals(origin.toString()));
 }
Ejemplo n.º 4
0
  public static void toJSON(ConfigurationAdmin admin, Writer osw, String filter) throws Exception {

    Configuration[] list = admin.listConfigurations(filter);
    Encoder encoder = codec.enc().to(osw);

    Protocol p = new Protocol();
    p.version = 1;
    p.date = new Date();
    p.size = list.length;
    encoder.put(p).append('\n');

    if (list != null)
      for (Configuration c : list) {
        Dictionary<String, Object> d = c.getProperties();
        Export export = new Export();
        export.values = new HashMap<String, Object>();
        export.factoryPid = c.getFactoryPid();
        export.pid = c.getPid();

        for (Enumeration<String> e = d.keys(); e.hasMoreElements(); ) {
          String k = e.nextElement();
          Object v = d.get(k);

          if (!(v instanceof String)) {

            if (export.types == null) export.types = new HashMap<String, Type>();

            Type type = new Type();

            Class<?> clazz = v.getClass();
            if (v instanceof Collection) {
              Collection<?> coll = (Collection<?>) v;
              clazz = String.class;
              if (coll.size() > 0) type.vectorOf = shortName(coll.iterator().next().getClass());
              else type.vectorOf = shortName(String.class);
            } else if (v.getClass().isArray()) {
              type.arrayOf = shortName(clazz.getComponentType());
            } else type.scalar = shortName(v.getClass());

            export.types.put(k, type);
          }
          export.values.put(k, v);
        }

        encoder.mark().put(export);
        // encoder.put(encoder.digest());
        encoder.append('\n');
      }
    osw.flush();
  }
Ejemplo n.º 5
0
  /**
   * Creates a channel from an array of protocols. Note that after a {@link
   * org.jgroups.JChannel#close()}, the protocol list <em>should not</em> be reused, ie. new
   * JChannel(protocols) would reuse the same protocol list, and this might lead to problems !
   *
   * @param protocols The list of protocols, from bottom to top, ie. the first protocol in the list
   *     is the transport, the last the top protocol
   * @throws Exception
   */
  public JChannel(Collection<Protocol> protocols) throws Exception {
    prot_stack = new ProtocolStack();
    setProtocolStack(prot_stack);
    for (Protocol prot : protocols) {
      prot_stack.addProtocol(prot);
      prot.setProtocolStack(prot_stack);
    }
    prot_stack.init();

    // Substitute vars with defined system props (if any)
    List<Protocol> prots = prot_stack.getProtocols();
    Map<String, String> map = new HashMap<>();
    for (Protocol prot : prots) Configurator.resolveAndAssignFields(prot, map);
  }
Ejemplo n.º 6
0
 public void disposing(com.sun.star.lang.EventObject aEvent) {
   m_aLog.log(Protocol.TYPE_INFO, "disposing() called from AutoSave.");
   synchronized (this) {
     m_xAutoSave = null;
     m_aRegistration = null;
   }
 }
Ejemplo n.º 7
0
  public static void Test_data(int myPeerID) {
    Protocol d = new Protocol(myPeerID);
    int i, j;
    System.out.println("PeerInfo.cfg");
    System.out.println("Number of peers" + d.NumPeers);
    for (i = 0; i < d.NumPeers; i++) {
      System.out.println(
          d.PeerID[i] + " " + d.Hostname[i] + " " + d.Ports[i] + " " + d.HaveFile[i]);
    }
    System.out.println("Common.cfg");
    System.out.println(d.NumPN);
    System.out.println(d.Interval);
    System.out.println(d.OptInterval);
    System.out.println(d.FileName);
    System.out.println(d.FileSize);
    System.out.println(d.PieceSize);
    System.out.println(d.NumPieces);

    d.initIO();
    byte b[] = null;
    byte buffer[] = new byte[d.PieceSize];

    for (i = 0; i < 20; i += 1) {
      b = d.readPiece(i);
      System.out.print(i + ":");
      for (j = 0; j < d.PieceSize; j++) {
        System.out.print(b[j]);
      }
      System.out.println("");
    }
    for (i = 0; i < 20; i += 2) {
      b = d.readPiece(i);
      System.out.print(i + ":");
      for (j = 0; j < d.PieceSize; j++) {
        System.out.print(b[j]);
      }
      System.out.println("");
    }

    for (j = 0; j < d.PieceSize; j++) buffer[j] = 'X';
    d.writePiece(4, buffer);

    for (j = 0; j < d.PieceSize; j++) buffer[j] = 'Y';
    d.writePiece(7, buffer);

    for (j = 0; j < d.PieceSize; j++) buffer[j] = 'Z';
    d.writePiece(15, buffer);

    for (i = 0; i < 20; i += 1) {
      b = d.readPiece(i);
      System.out.print(i + ":");
      for (j = 0; j < d.PieceSize; j++) {
        System.out.print(b[j]);
      }
      System.out.println("");
    }
  }
Ejemplo n.º 8
0
    /**
     * Invokes an operation and puts the return value into map
     *
     * @param map
     * @param operation Protocol.OperationName[args], e.g. STABLE.foo[arg1 arg2 arg3]
     */
    protected void handleOperation(Map<String, String> map, String operation) throws Exception {
      int index = operation.indexOf(".");
      if (index == -1)
        throw new IllegalArgumentException(
            "operation " + operation + " is missing the protocol name");
      String prot_name = operation.substring(0, index);
      Protocol prot = prot_stack.findProtocol(prot_name);
      if (prot == null) return; // less drastic than throwing an exception...

      int args_index = operation.indexOf("[");
      String method_name;
      if (args_index != -1) method_name = operation.substring(index + 1, args_index).trim();
      else method_name = operation.substring(index + 1).trim();

      String[] args = null;
      if (args_index != -1) {
        int end_index = operation.indexOf("]");
        if (end_index == -1) throw new IllegalArgumentException("] not found");
        List<String> str_args =
            Util.parseCommaDelimitedStrings(operation.substring(args_index + 1, end_index));
        Object[] strings = str_args.toArray();
        args = new String[strings.length];
        for (int i = 0; i < strings.length; i++) args[i] = (String) strings[i];
      }

      Method method = MethodCall.findMethod(prot.getClass(), method_name, args);
      if (method == null) {
        log.warn(
            Util.getMessage("MethodNotFound"),
            local_addr,
            prot.getClass().getSimpleName(),
            method_name);
        return;
      }
      MethodCall call = new MethodCall(method);
      Object[] converted_args = null;
      if (args != null) {
        converted_args = new Object[args.length];
        Class<?>[] types = method.getParameterTypes();
        for (int i = 0; i < args.length; i++)
          converted_args[i] = MethodCall.convert(args[i], types[i]);
      }
      Object retval = call.invoke(prot, converted_args);
      if (retval != null) map.put(prot_name + "." + method_name, retval.toString());
    }
Ejemplo n.º 9
0
    private void disableListener() {
      m_aLog.log(Protocol.TYPE_SCOPE_OPEN, "stop listening for AutoSave notifications ...");

      XDispatch xAutoSave = null;
      URL aRegURL = null;
      synchronized (this) {
        xAutoSave = m_xAutoSave;
        aRegURL = m_aRegistration;
      }

      try {
        if ((xAutoSave != null) && (aRegURL != null)) xAutoSave.removeStatusListener(this, aRegURL);
      } catch (Throwable ex) {
        m_aLog.log(ex);
      }

      m_aLog.log(Protocol.TYPE_SCOPE_CLOSE, "");
    }
Ejemplo n.º 10
0
  /**
   * @short check concurrent save requests to the same document at the same time.
   * @descr First we simulate an UI save by dispatching the right URL to the document and at the
   *     same time we try to trigger an AutoSave from another thread. So these operations should be
   *     started at the same time. It should not crash. The AutoSave request must be postphoned.
   */
  @Test
  public void checkConcurrentAutoSaveToNormalUISave() {
    m_aLog.log(Protocol.TYPE_TESTMARK, "AutoSave");
    m_aLog.log(Protocol.TYPE_SCOPE_OPEN, "checkConcurrentAutoSaveToNormalUISave()");

    AutoSaveListener xListener = new AutoSaveListener(m_xSMGR, m_xAutoSave, m_aLog);

    try {
      DocThread aThread = new DocThread();
      aThread.start();
      aThread.join();
    } catch (Throwable ex) {
    }

    xListener.disableListener();

    m_aLog.log(Protocol.TYPE_SCOPE_CLOSE, "checkConcurrentAutoSaveToNormalUISave()");
    m_aLog.logStatistics();
  }
Ejemplo n.º 11
0
    public void statusChanged(FeatureStateEvent aEvent) {
      m_aLog.log(Protocol.TYPE_SCOPE_OPEN, "statusChanged() called from AutoSave ...");

      m_aLog.log("FeatureURL        = \"" + aEvent.FeatureURL.Complete + "\"");
      m_aLog.log("FeatureDescriptor = \"" + aEvent.FeatureDescriptor + "\"");
      m_aLog.log("IsEnabled         = \"" + aEvent.IsEnabled + "\"");
      m_aLog.log("Requery           = \"" + aEvent.Requery + "\"");
      m_aLog.log("State:");
      m_aLog.log(aEvent.State);

      m_aLog.log(Protocol.TYPE_SCOPE_CLOSE, "");
    }
Ejemplo n.º 12
0
  public void impl_checkConcurrentAutoSaveToNormalUISave() {
    Random aRandom = new Random();

    int i = 0;
    int c = 5;
    for (i = 0; i < c; ++i) {
      XInterface xDoc = createBigCalcDoc();
      try {
        long nWait = aRandom.nextInt(120000);
        m_aLog.log(Protocol.TYPE_INFO, "sleep for " + nWait + " ms");
        synchronized (this) {
          wait(nWait);
        }
      } catch (Throwable ex) {
        m_aLog.log(Protocol.TYPE_WARNING, "got exception for wait() !?");
        m_aLog.log(Protocol.TYPE_WARNING_INFO, ex.getMessage());
      }
      saveDoc(xDoc, utils.getOfficeTemp(m_xSMGR) + "/test_calc.ods");
      closeDoc(xDoc);
    }
  }
Ejemplo n.º 13
0
 void rdataFromString(Tokenizer st, Name origin) throws IOException {
   String flagString = st.getIdentifier();
   flags = Flags.value(flagString);
   if (flags < 0) throw st.exception("Invalid flags: " + flagString);
   String protoString = st.getIdentifier();
   proto = Protocol.value(protoString);
   if (proto < 0) throw st.exception("Invalid protocol: " + protoString);
   String algString = st.getIdentifier();
   alg = DNSSEC.Algorithm.value(algString);
   if (alg < 0) throw st.exception("Invalid algorithm: " + algString);
   /* If this is a null KEY, there's no key data */
   if ((flags & Flags.USE_MASK) == Flags.NOKEY) key = null;
   else key = st.getBase64();
 }
Ejemplo n.º 14
0
    private AutoSaveListener(XMultiServiceFactory xSMGR, XDispatch xAutoSave, Protocol aLog) {
      m_aLog = aLog;
      m_aLog.log(Protocol.TYPE_SCOPE_OPEN, "create listener for AutoSave notifications ...");

      try {
        m_xAutoSave = xAutoSave;

        XURLTransformer xParser =
            UnoRuntime.queryInterface(
                XURLTransformer.class, xSMGR.createInstance("com.sun.star.util.URLTransformer"));
        URL[] aURL = new URL[1];
        aURL[0] = new URL();
        aURL[0].Complete = "vnd.sun.star.autorecovery:/doAutoSave";
        xParser.parseStrict(aURL);
        m_aRegistration = aURL[0];

        m_xAutoSave.addStatusListener(this, m_aRegistration);
        m_aLog.log(Protocol.TYPE_INFO, "successfully registered as AutoSave listener.");
      } catch (Throwable ex) {
        m_aLog.log(ex);
      }

      m_aLog.log(Protocol.TYPE_SCOPE_CLOSE, "");
    }
Ejemplo n.º 15
0
  /**
   * @short Create the environment for following tests.
   * @descr create an empty test frame, where we can load different components inside.
   */
  @Before
  public void before() {
    m_aLog =
        new Protocol(
            Protocol.MODE_HTML | Protocol.MODE_STDOUT,
            Protocol.FILTER_NONE,
            utils.getUsersTempDir() + "/complex_log_ascii_01.html");

    try {
      // get uno service manager from global test environment
      m_xSMGR = getMSF();

      // get another helper to e.g. create test documents
      m_aSOF = SOfficeFactory.getFactory(m_xSMGR);

      // create AutoSave instance
      m_xAutoSave = theAutoRecovery.get(connection.getComponentContext());

      // prepare AutoSave
      // make sure it will be started every 1 min
      ConfigHelper aConfig =
          new ConfigHelper(
              connection.getComponentContext(), "org.openoffice.Office.Recovery", false);
      aConfig.writeRelativeKey("AutoSave", "Enabled", Boolean.TRUE);
      aConfig.writeRelativeKey("AutoSave", "TimeIntervall", Integer.valueOf(1)); // 1 min
      aConfig.flush();
      aConfig = null;

      // is needed to parse dispatch commands
      m_xURLParser =
          UnoRuntime.queryInterface(
              XURLTransformer.class, m_xSMGR.createInstance("com.sun.star.util.URLTransformer"));

    } catch (java.lang.Throwable ex) {
      m_aLog.log(ex);
      fail("Couldn't create test environment");
    }
  }
Ejemplo n.º 16
0
  private void closeDoc(XInterface xDoc) {
    m_aLog.log(Protocol.TYPE_SCOPE_OPEN, "closeDoc() started ...");

    try {
      Random aRandom = new Random();
      int nRetry = 5;
      while (nRetry > 0) {
        try {
          XCloseable xClose = UnoRuntime.queryInterface(XCloseable.class, xDoc);
          if (xClose != null) {
            xClose.close(false);
            m_aLog.log(Protocol.TYPE_OK, "closeDoc() = OK.");
            nRetry = 0;
          } else {
            m_aLog.log(
                Protocol.TYPE_ERROR, "closeDoc() = ERROR. Doc doesn't provide needed interface!");
          }
        } catch (com.sun.star.util.CloseVetoException exVeto) {
          m_aLog.log(Protocol.TYPE_WARNING, "got CloseVetoException on calling doc.close().");
          m_aLog.log(
              Protocol.TYPE_WARNING_INFO, "Please check the reason for that more in detail.");
          m_aLog.log(
              Protocol.TYPE_WARNING_INFO,
              "A message like \"Can not close while saving.\" was intended and doesn't show an error!");
          m_aLog.log(Protocol.TYPE_WARNING_INFO, exVeto.getMessage());
        }

        if (nRetry > 0) {
          --nRetry;
          long nWait = aRandom.nextInt(30000); // 30 sec.
          try {
            m_aLog.log(Protocol.TYPE_INFO, "sleep for " + nWait + " ms");
            synchronized (this) {
              wait(nWait);
            }
          } catch (Throwable ex) {
            m_aLog.log(Protocol.TYPE_WARNING, "got exception for wait() !?");
            m_aLog.log(Protocol.TYPE_WARNING_INFO, ex.getMessage());
          }
        }
      }
    } catch (Throwable ex) {
      m_aLog.log(ex);
    }

    m_aLog.log(Protocol.TYPE_SCOPE_CLOSE, "closeDoc() finished.");
  }
Ejemplo n.º 17
0
 /**
  * Supposed to be overwritten by subclasses. Usually the transport returns a valid non-null thread
  * factory, but thread factories can also be created by individual protocols
  *
  * @return
  */
 public ThreadFactory getThreadFactory() {
   return down_prot != null ? down_prot.getThreadFactory() : null;
 }
Ejemplo n.º 18
0
 /**
  * Returns the SocketFactory associated with this protocol, if overridden in a subclass, or passes
  * the call down
  *
  * @return SocketFactory
  */
 public SocketFactory getSocketFactory() {
   return down_prot != null ? down_prot.getSocketFactory() : null;
 }
Ejemplo n.º 19
0
 /**
  * Sets a SocketFactory. Socket factories are typically provided by the transport ({@link
  * org.jgroups.protocols.TP}) or {@link org.jgroups.protocols.TP.ProtocolAdapter}
  *
  * @param factory
  */
 public void setSocketFactory(SocketFactory factory) {
   if (down_prot != null) down_prot.setSocketFactory(factory);
 }
Ejemplo n.º 20
0
    protected void handleJmx(Map<String, String> map, String input) {
      Map<String, Object> tmp_stats;
      int index = input.indexOf("=");
      if (index > -1) {
        List<String> list = null;
        String protocol_name = input.substring(index + 1);
        index = protocol_name.indexOf(".");
        if (index > -1) {
          String rest = protocol_name;
          protocol_name = protocol_name.substring(0, index);
          String attrs = rest.substring(index + 1); // e.g. "num_sent,msgs,num_received_msgs"
          list = Util.parseStringList(attrs, ",");

          // check if there are any attribute-sets in the list
          for (Iterator<String> it = list.iterator(); it.hasNext(); ) {
            String tmp = it.next();
            index = tmp.indexOf("=");
            if (index != -1) {
              String attrname = tmp.substring(0, index);
              String attrvalue = tmp.substring(index + 1);
              Protocol prot = prot_stack.findProtocol(protocol_name);
              Field field = prot != null ? Util.getField(prot.getClass(), attrname) : null;
              if (field != null) {
                Object value = MethodCall.convert(attrvalue, field.getType());
                if (value != null) prot.setValue(attrname, value);
              } else {
                // try to find a setter for X, e.g. x(type-of-x) or setX(type-of-x)
                ResourceDMBean.Accessor setter =
                    ResourceDMBean.findSetter(
                        prot, attrname); // Util.getSetter(prot.getClass(), attrname);
                if (setter != null) {
                  try {
                    Class<?> type =
                        setter instanceof ResourceDMBean.FieldAccessor
                            ? ((ResourceDMBean.FieldAccessor) setter).getField().getType()
                            : setter instanceof ResourceDMBean.MethodAccessor
                                ? ((ResourceDMBean.MethodAccessor) setter)
                                    .getMethod()
                                    .getParameterTypes()[0]
                                    .getClass()
                                : null;
                    Object converted_value = MethodCall.convert(attrvalue, type);
                    setter.invoke(converted_value);
                  } catch (Exception e) {
                    log.error("unable to invoke %s() on %s: %s", setter, protocol_name, e);
                  }
                } else log.warn(Util.getMessage("FieldNotFound"), attrname, protocol_name);
              }

              it.remove();
            }
          }
        }
        tmp_stats = dumpStats(protocol_name, list);
        if (tmp_stats != null) {
          for (Map.Entry<String, Object> entry : tmp_stats.entrySet()) {
            Map<String, Object> tmp_map = (Map<String, Object>) entry.getValue();
            String key = entry.getKey();
            map.put(key, tmp_map != null ? tmp_map.toString() : null);
          }
        }
      } else {
        tmp_stats = dumpStats();
        if (tmp_stats != null) {
          for (Map.Entry<String, Object> entry : tmp_stats.entrySet()) {
            Map<String, Object> tmp_map = (Map<String, Object>) entry.getValue();
            String key = entry.getKey();
            map.put(key, tmp_map != null ? tmp_map.toString() : null);
          }
        }
      }
    }
Ejemplo n.º 21
0
 /**
  * An event was received from the layer below. Usually the current layer will want to examine the
  * event type and - depending on its type - perform some computation (e.g. removing headers from a
  * MSG event type, or updating the internal membership list when receiving a VIEW_CHANGE event).
  * Finally the event is either a) discarded, or b) an event is sent down the stack using <code>
  * down_prot.down()</code> or c) the event (or another event) is sent up the stack using <code>
  * up_prot.up()</code>.
  */
 public Object up(Event evt) {
   return up_prot.up(evt);
 }
Ejemplo n.º 22
0
 /**
  * An event is to be sent down the stack. The layer may want to examine its type and perform some
  * action on it, depending on the event's type. If the event is a message MSG, then the layer may
  * need to add a header to it (or do nothing at all) before sending it down the stack using <code>
  * down_prot.down()</code>. In case of a GET_ADDRESS event (which tries to retrieve the stack's
  * address from one of the bottom layers), the layer may need to send a new response event back up
  * the stack using <code>up_prot.up()</code>.
  */
 public Object down(Event evt) {
   return down_prot.down(evt);
 }
Ejemplo n.º 23
0
 public void init() throws Exception {
   super.init();
   if (max_stable_msgs < 1)
     throw new IllegalArgumentException("max_stable_msgs ( " + max_stable_msgs + ") must be > 0");
   if (max_bytes <= 0) throw new IllegalArgumentException("max_bytes has to be > 0");
 }
Ejemplo n.º 24
0
 protected void resetAllStats() {
   List<Protocol> prots = getProtocolStack().getProtocols();
   for (Protocol prot : prots) prot.resetStatistics();
   resetStats();
 }