Esempio n. 1
1
  public void testHeadNotPopular() throws Exception {
    VersionCounts versionCounts = VersionCounts.make();

    VoteBlock vb1 = makeVoteBlock("http://test.com/foo1");
    byte[] hash1 = addVersion(vb1, "content 1 for foo1");
    byte[] hash2 = addVersion(vb1, "content 2 for foo1");

    VoteBlock vb2 = makeVoteBlock("http://test.com/foo1");
    addVersion(vb2, "content 1 for foo1");
    addVersion(vb2, "content 2 for foo1");

    VoteBlock vb3 = makeVoteBlock("http://test.com/foo1");
    addVersion(vb3, "content 3 for foo1");
    addVersion(vb3, "content 2 for foo1");

    versionCounts.vote(vb1, participant1);
    versionCounts.vote(vb2, participant2);
    versionCounts.vote(vb3, participant3);

    Map<ParticipantUserData, HashResult> repairCandidates;
    repairCandidates = versionCounts.getRepairCandidates(0);
    assertSameElements(
        SetUtil.set(participant1, participant2, participant3), repairCandidates.keySet());

    repairCandidates = versionCounts.getRepairCandidates(1);
    assertSameElements(
        SetUtil.set(participant1, participant2, participant3), repairCandidates.keySet());

    repairCandidates = versionCounts.getRepairCandidates(2);
    assertSameElements(SetUtil.set(participant1, participant2), repairCandidates.keySet());

    repairCandidates = versionCounts.getRepairCandidates(3);
    assertEmpty(repairCandidates.keySet());
  }
Esempio n. 2
0
  public void testMultipleIdenticalVersions() throws Exception {
    VersionCounts versionCounts = VersionCounts.make();

    VoteBlock vb1 = makeVoteBlock("http://test.com/foo1");
    byte[] hash1 = addVersion(vb1, "content 1 for foo1");
    byte[] hash2 = addVersion(vb1, "content 2 for foo1");

    VoteBlock vb2 = makeVoteBlock("http://test.com/foo1");
    addVersion(vb2, "content 1 for foo1");
    addVersion(vb2, "content 1 for foo1");
    addVersion(vb2, "content 1 for foo1");
    addVersion(vb2, "content 1 for foo1");
    addVersion(vb2, "content 2 for foo1");

    VoteBlock vb3 = makeVoteBlock("http://test.com/foo1");
    addVersion(vb3, "content 1 for foo1");
    addVersion(vb3, "content 2 for foo1");
    addVersion(vb3, "content 2 for foo1");
    addVersion(vb3, "content 2 for foo1");
    addVersion(vb3, "content 2 for foo1");

    versionCounts.vote(vb1, participant1);
    versionCounts.vote(vb2, participant2);
    versionCounts.vote(vb3, participant3);

    Map<ParticipantUserData, HashResult> repairCandidates;
    repairCandidates = versionCounts.getRepairCandidates(2);
    assertSameElements(
        SetUtil.set(participant1, participant2, participant3), repairCandidates.keySet());

    // With only three candidates, no version should reach a threshold
    // of 4, unless counting multiples is wrong.
    repairCandidates = versionCounts.getRepairCandidates(4);
    assertEmpty(repairCandidates.keySet());
  }
Esempio n. 3
0
  protected Properties convertProperties(Map<String, Object> m) {
    Properties res = null;

    {
      if (m != null) {
        res = new Properties();

        Set<String> keys = m.keySet();
        for (String key : keys) {
          String value = null;

          // Set 'value':
          {
            Object o = m.get(key);
            if (o != null) {
              value = o.toString();
            }
          }

          res.setProperty(key, value);
        }
      }
    }

    return res;
  }
Esempio n. 4
0
  /** @return matching bloc B bloc -> A bloc */
  public static Map<Integer, Integer> diff(FileDesc a, FileDesc b) {
    Map<Integer, List<IndexedHash>> blocA = new HashMap<Integer, List<IndexedHash>>();
    int i = 0;
    for (Bloc bloc : a.blocs) {
      List<IndexedHash> l = blocA.get(bloc.roll);
      if (l == null) {
        l = new ArrayList<IndexedHash>();
        blocA.put(bloc.roll, l);
      }
      l.add(new IndexedHash(i++, bloc.hash));
    }

    Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    loop:
    for (i = 0; i < b.blocs.length; i++) {
      Bloc blocB = b.blocs[i];
      List<IndexedHash> list = blocA.get(blocB.roll);
      if (list != null) {
        for (IndexedHash bloc : list) {
          if (blocB.hash.equals(bloc.h)) {
            map.put(i, bloc.i);
            continue loop;
          }
        }
      }
    }
    return map;
  }
  public static Map<String, String> postDataAPI(
      EndPointInfo apiUtilities, Map<String, String> headers) throws IDPTokenManagerException {
    HTTP_METHODS httpMethod = apiUtilities.getHttpMethod();
    String url = apiUtilities.getEndPoint();
    Map<String, String> params = apiUtilities.getRequestParamsMap();

    Map<String, String> responseParams = new HashMap<String, String>();
    HttpClient httpclient = getCertifiedHttpClient();
    String payload = buildPayload(params);

    if (httpMethod.equals(HTTP_METHODS.POST)) {
      HttpPost httpPost = new HttpPost(url);
      HttpPost httpPostWithHeaders = (HttpPost) buildHeaders(httpPost, headers, httpMethod);
      byte[] postData = payload.getBytes();
      try {
        httpPostWithHeaders.setEntity(new ByteArrayEntity(postData));
        HttpResponse response = httpclient.execute(httpPostWithHeaders);
        String status = String.valueOf(response.getStatusLine().getStatusCode());

        responseParams.put(Constants.SERVER_RESPONSE_BODY, getResponseBody(response));
        responseParams.put(Constants.SERVER_RESPONSE_STATUS, status);
        return responseParams;
      } catch (ClientProtocolException e) {
        throw new IDPTokenManagerException("Invalid client protocol.", e);
      } catch (IOException e) {
        responseParams.put(Constants.SERVER_RESPONSE_BODY, "Internal Server Error");
        responseParams.put(Constants.SERVER_RESPONSE_STATUS, Constants.INTERNAL_SERVER_ERROR);
        throw new IDPTokenManagerException("Server connectivity failure.", e);
      }
    }

    return responseParams;
  }
  public static Map<String, String> sendPostRequest(
      String url, JSONObject params, Map<String, String> headers) throws IDPTokenManagerException {
    HttpPost httpPost = new HttpPost(url);
    HttpClient httpClient = getCertifiedHttpClient();
    Map<String, String> responseParams = new HashMap<String, String>();

    if (params != null) {
      try {
        httpPost.setEntity(new StringEntity(params.toString()));
      } catch (UnsupportedEncodingException e) {
        throw new IDPTokenManagerException("Invalid encoding type.", e);
      }
    }

    HttpPost httpPostWithHeaders = (HttpPost) buildHeaders(httpPost, headers, HTTP_METHODS.POST);
    try {
      HttpResponse response = httpClient.execute(httpPostWithHeaders);
      String status = String.valueOf(response.getStatusLine().getStatusCode());

      responseParams.put(Constants.SERVER_RESPONSE_BODY, getResponseBody(response));
      responseParams.put(Constants.SERVER_RESPONSE_STATUS, status);

    } catch (ClientProtocolException e) {
      throw new IDPTokenManagerException("Invalid client protocol.", e);
    } catch (IOException e) {
      responseParams.put(Constants.SERVER_RESPONSE_BODY, "Internal Server Error");
      responseParams.put(Constants.SERVER_RESPONSE_STATUS, Constants.INTERNAL_SERVER_ERROR);
      throw new IDPTokenManagerException("Server connectivity failure.", e);
    }

    return responseParams;
  }
  public String getTokenValue(HttpServletRequest request, String uri) {
    String tokenValue = null;
    HttpSession session = request.getSession(false);

    if (session != null) {
      if (isTokenPerPageEnabled()) {
        @SuppressWarnings("unchecked")
        Map<String, String> pageTokens =
            (Map<String, String>) session.getAttribute(CsrfGuard.PAGE_TOKENS_KEY);

        if (pageTokens != null) {
          if (isTokenPerPagePrecreate()) {
            createPageToken(pageTokens, uri);
          }
          tokenValue = pageTokens.get(uri);
        }
      }

      if (tokenValue == null) {
        tokenValue = (String) session.getAttribute(getSessionKey());
      }
    }

    return tokenValue;
  }
Esempio n. 8
0
  /**
   * Remove records telling what entity caps node a contact has.
   *
   * @param contact the contact
   */
  public void removeContactCapsNode(Contact contact) {
    Caps caps = null;
    String lastRemovedJid = null;

    Iterator<String> iter = userCaps.keySet().iterator();
    while (iter.hasNext()) {
      String jid = iter.next();

      if (StringUtils.parseBareAddress(jid).equals(contact.getAddress())) {
        caps = userCaps.get(jid);
        lastRemovedJid = jid;
        iter.remove();
      }
    }

    // fire only for the last one, at the end the event out
    // of the protocol will be one and for the contact
    if (caps != null) {
      UserCapsNodeListener[] listeners;
      synchronized (userCapsNodeListeners) {
        listeners = userCapsNodeListeners.toArray(NO_USER_CAPS_NODE_LISTENERS);
      }
      if (listeners.length != 0) {
        String nodeVer = caps.getNodeVer();

        for (UserCapsNodeListener listener : listeners)
          listener.userCapsNodeRemoved(lastRemovedJid, nodeVer, false);
      }
    }
  }
Esempio n. 9
0
  /**
   * Add a record telling what entity caps node a user has.
   *
   * @param user the user (Full JID)
   * @param node the node (of the caps packet extension)
   * @param hash the hashing algorithm used to calculate <tt>ver</tt>
   * @param ver the version (of the caps packet extension)
   * @param ext the ext (of the caps packet extension)
   * @param online indicates if the user is online
   */
  private void addUserCapsNode(
      String user, String node, String hash, String ver, String ext, boolean online) {
    if ((user != null) && (node != null) && (hash != null) && (ver != null)) {
      Caps caps = userCaps.get(user);

      if ((caps == null)
          || !caps.node.equals(node)
          || !caps.hash.equals(hash)
          || !caps.ver.equals(ver)) {
        caps = new Caps(node, hash, ver, ext);

        userCaps.put(user, caps);
      } else return;

      // Fire userCapsNodeAdded.
      UserCapsNodeListener[] listeners;

      synchronized (userCapsNodeListeners) {
        listeners = userCapsNodeListeners.toArray(NO_USER_CAPS_NODE_LISTENERS);
      }
      if (listeners.length != 0) {
        String nodeVer = caps.getNodeVer();

        for (UserCapsNodeListener listener : listeners)
          listener.userCapsNodeAdded(user, nodeVer, online);
      }
    }
  }
Esempio n. 10
0
  private void rotateTokens(HttpServletRequest request) {
    HttpSession session = request.getSession(true);

    /** rotate master token * */
    String tokenFromSession = null;

    try {
      tokenFromSession = RandomGenerator.generateRandomId(getPrng(), getTokenLength());
    } catch (Exception e) {
      throw new RuntimeException(
          String.format("unable to generate the random token - %s", e.getLocalizedMessage()), e);
    }

    session.setAttribute(getSessionKey(), tokenFromSession);

    /** rotate page token * */
    if (isTokenPerPageEnabled()) {
      @SuppressWarnings("unchecked")
      Map<String, String> pageTokens =
          (Map<String, String>) session.getAttribute(CsrfGuard.PAGE_TOKENS_KEY);

      try {
        pageTokens.put(
            request.getRequestURI(), RandomGenerator.generateRandomId(getPrng(), getTokenLength()));
      } catch (Exception e) {
        throw new RuntimeException(
            String.format("unable to generate the random token - %s", e.getLocalizedMessage()), e);
      }
    }
  }
Esempio n. 11
0
  /**
   * Reads the file that specifies method calls that should be replaced by other method calls. The
   * file is of the form:
   *
   * <p>[regex] [orig-method-def] [new-method-name]
   *
   * <p>where the orig_method-def is of the form:
   *
   * <p>fully-qualified-method-name (args)
   *
   * <p>Blank lines and // comments are ignored. The orig-method-def is replaced by a call to
   * new-method-name with the same arguments in any classfile that matches the regular expressions.
   * All method names and argument types should be fully qualified.
   */
  public void read_map_file(File map_file) throws IOException {

    LineNumberReader lr = new LineNumberReader(new FileReader(map_file));
    MapFileError mfe = new MapFileError(lr, map_file);
    Pattern current_regex = null;
    Map<MethodDef, MethodInfo> map = new LinkedHashMap<MethodDef, MethodInfo>();
    for (String line = lr.readLine(); line != null; line = lr.readLine()) {
      line = line.replaceFirst("//.*$", "");
      if (line.trim().length() == 0) continue;
      if (line.startsWith(" ")) {
        if (current_regex == null)
          throw new IOException("No current class regex on line " + lr.getLineNumber());
        StrTok st = new StrTok(line, mfe);
        st.stok.wordChars('.', '.');
        MethodDef md = parse_method(st);
        String new_method = st.need_word();
        map.put(md, new MethodInfo(new_method));
      } else {
        if (current_regex != null) {
          MethodMapInfo mmi = new MethodMapInfo(current_regex, map);
          map_list.add(mmi);
          map = new LinkedHashMap<MethodDef, MethodInfo>();
        }
        current_regex = Pattern.compile(line);
      }
    }
    if (current_regex != null) {
      MethodMapInfo mmi = new MethodMapInfo(current_regex, map);
      map_list.add(mmi);
    }

    dump_map_list();
  }
Esempio n. 12
0
  public void writeStream(DataInputStream input) throws IOException, NoSuchAlgorithmException {
    try {
      int bytesRead = 0;
      int bytesToSkip = 0;

      while (true) {
        final int value = input.readUnsignedByte();
        bytesRead++;
        check.nextByte(value);
        writeRaw(value);
        final int weakChecksum = check.weakChecksum();
        String strongChecksum = null;

        if (bytesToSkip > 0) {
          bytesToSkip--;
        } else {
          Map<String, Integer> weakMatches = inputBlocks.get(weakChecksum);
          if (weakMatches != null) {
            strongChecksum = check.strongChecksum();
            Integer previousOffset = weakMatches.get(strongChecksum);
            if (previousOffset != null) {
              snipRawBuffer();
              System.err.println(
                  "Using previously remembered : "
                      + previousOffset
                      + " : "
                      + (bytesRead - BLOCK_SIZE));
              writeBlock(previousOffset);
              bytesToSkip = BLOCK_SIZE - 1;
            }
          }
        }

        if ((bytesRead % BLOCK_SIZE) == 0) {
          Map<String, Integer> weakMatches = inputBlocks.get(weakChecksum);
          if (weakMatches == null) {
            weakMatches = new HashMap<String, Integer>();
            inputBlocks.put(weakChecksum, weakMatches);
          }
          if (strongChecksum == null) {
            strongChecksum = check.strongChecksum();
          }
          if (!weakMatches.containsKey(strongChecksum)) {
            weakMatches.put(strongChecksum, bytesRead - BLOCK_SIZE);
            System.err.println(
                "Remembering : "
                    + weakChecksum
                    + " : "
                    + strongChecksum
                    + " : "
                    + (bytesRead - BLOCK_SIZE));
          }
        }
      }
    } catch (EOFException e) {
      flushRaw();
    }
    System.err.println("Original data: " + rawChunks);
    System.err.println("Reused data: " + blockChunks);
  }
  /** Create LockssKeystores from config subtree below {@link #PARAM_KEYSTORE} */
  void configureKeyStores(Configuration config) {
    Configuration allKs = config.getConfigTree(PARAM_KEYSTORE);
    for (Iterator iter = allKs.nodeIterator(); iter.hasNext(); ) {
      String id = (String) iter.next();
      Configuration oneKs = allKs.getConfigTree(id);
      try {
        LockssKeyStore lk = createLockssKeyStore(oneKs);
        String name = lk.getName();
        if (name == null) {
          log.error("KeyStore definition missing name: " + oneKs);
          continue;
        }
        LockssKeyStore old = keystoreMap.get(name);
        if (old != null && !lk.equals(old)) {
          log.warning(
              "Keystore "
                  + name
                  + " redefined.  "
                  + "New definition may not take effect until daemon restart");
        }

        log.debug("Adding keystore " + name);
        keystoreMap.put(name, lk);

      } catch (Exception e) {
        log.error("Couldn't create keystore: " + oneKs, e);
      }
    }
  }
Esempio n. 14
0
  public synchronized Enumeration<String> entryNames(JarFile jar, final CodeSource[] cs) {
    final Map map = signerMap();
    final Iterator itor = map.entrySet().iterator();
    boolean matchUnsigned = false;

    /*
     * Grab a single copy of the CodeSigner arrays. Check
     * to see if we can optimize CodeSigner equality test.
     */
    List req = new ArrayList(cs.length);
    for (int i = 0; i < cs.length; i++) {
      CodeSigner[] match = findMatchingSigners(cs[i]);
      if (match != null) {
        if (match.length > 0) {
          req.add(match);
        } else {
          matchUnsigned = true;
        }
      } else {
        matchUnsigned = true;
      }
    }

    final List signersReq = req;
    final Enumeration enum2 = (matchUnsigned) ? unsignedEntryNames(jar) : emptyEnumeration;

    return new Enumeration<String>() {

      String name;

      public boolean hasMoreElements() {
        if (name != null) {
          return true;
        }

        while (itor.hasNext()) {
          Map.Entry e = (Map.Entry) itor.next();
          if (signersReq.contains((CodeSigner[]) e.getValue())) {
            name = (String) e.getKey();
            return true;
          }
        }
        while (enum2.hasMoreElements()) {
          name = (String) enum2.nextElement();
          return true;
        }
        return false;
      }

      public String nextElement() {
        if (hasMoreElements()) {
          String value = name;
          name = null;
          return value;
        }
        throw new NoSuchElementException();
      }
    };
  }
Esempio n. 15
0
 /**
  * Removes all classes from the class cache.
  *
  * @see #getClassCacheEntry(String)
  * @see #setClassCacheEntry(Class)
  * @see #removeClassCacheEntry(String)
  */
 public void clearCache() {
   synchronized (classCache) {
     classCache.clear();
   }
   synchronized (sourceCache) {
     sourceCache.clear();
   }
 }
Esempio n. 16
0
  /**
   * This is called when JPM runs in the background to start jobs
   *
   * @throws Exception
   */
  public void daemon() throws Exception {
    Runtime.getRuntime()
        .addShutdownHook(
            new Thread("Daemon shutdown") {
              public void run() {

                for (Service service : startedByDaemon) {
                  try {
                    reporter.error("Stopping " + service);
                    service.stop();
                    reporter.error("Stopped " + service);
                  } catch (Exception e) {
                    // Ignore
                  }
                }
              }
            });
    List<ServiceData> services = getServices();
    Map<String, ServiceData> map = new HashMap<String, ServiceData>();
    for (ServiceData d : services) {
      map.put(d.name, d);
    }
    List<ServiceData> start = new ArrayList<ServiceData>();
    Set<ServiceData> set = new HashSet<ServiceData>();
    for (ServiceData sd : services) {
      checkStartup(map, start, sd, set);
    }

    if (start.isEmpty()) reporter.warning("No services to start");

    for (ServiceData sd : start) {
      try {
        Service service = getService(sd.name);
        reporter.trace("Starting " + service);
        String result = service.start();
        if (result != null) reporter.error("Started error " + result);
        else startedByDaemon.add(service);
        reporter.trace("Started " + service);
      } catch (Exception e) {
        reporter.error("Cannot start daemon %s, due to %s", sd.name, e);
      }
    }

    while (true) {
      for (Service sd : startedByDaemon) {
        try {
          if (!sd.isRunning()) {
            reporter.error("Starting due to failure " + sd);
            String result = sd.start();
            if (result != null) reporter.error("Started error " + result);
          }
        } catch (Exception e) {
          reporter.error("Cannot start daemon %s, due to %s", sd, e);
        }
      }
      Thread.sleep(10000);
    }
  }
Esempio n. 17
0
 private static void initIconTypeMap() {
   ICON_TYPE_MAP = new HashMap<String, Integer>();
   ICON_TYPE_MAP.put("gtk-menu", Integer.valueOf(1));
   ICON_TYPE_MAP.put("gtk-small-toolbar", Integer.valueOf(2));
   ICON_TYPE_MAP.put("gtk-large-toolbar", Integer.valueOf(3));
   ICON_TYPE_MAP.put("gtk-button", Integer.valueOf(4));
   ICON_TYPE_MAP.put("gtk-dnd", Integer.valueOf(5));
   ICON_TYPE_MAP.put("gtk-dialog", Integer.valueOf(6));
 }
Esempio n. 18
0
 /**
  * Parses the given code source into a Java class. If there is a class file for the given code
  * source, then no parsing is done, instead the cached class is returned.
  *
  * @param shouldCacheSource if true then the generated class will be stored in the source cache
  * @return the main class defined in the given script
  */
 public Class parseClass(GroovyCodeSource codeSource, boolean shouldCacheSource)
     throws CompilationFailedException {
   synchronized (sourceCache) {
     Class answer = sourceCache.get(codeSource.getName());
     if (answer != null) return answer;
     answer = doParseClass(codeSource);
     if (shouldCacheSource) sourceCache.put(codeSource.getName(), answer);
     return answer;
   }
 }
 void loadKeyStores() {
   List<LockssKeyStore> lst = new ArrayList<LockssKeyStore>(keystoreMap.values());
   for (LockssKeyStore lk : lst) {
     try {
       lk.load();
     } catch (Exception e) {
       log.error("Can't load keystore " + lk.getName(), e);
       keystoreMap.remove(lk.getName());
     }
   }
 }
 @Override
 public Map<String, String[]> getRenderParameterMap() {
   String meth = "getRenderParameterMap";
   Object[] args = {};
   Map<String, String[]> parms = new HashMap<String, String[]>();
   parms.put("parm1", new String[] {"val1", "val2"});
   parms.put("parm2", new String[] {"val1", "val2"});
   Map<String, String[]> ret = parms;
   retVal = ret;
   checkArgs(meth, args);
   return ret;
 }
Esempio n. 21
0
 private synchronized Map signerMap() {
   if (signerMap == null) {
     /*
      * Snapshot signer state so it doesn't change on us. We care
      * only about the asserted signatures. Verification of
      * signature validity happens via the JarEntry apis.
      */
     signerMap = new HashMap(verifiedSigners.size() + sigFileSigners.size());
     signerMap.putAll(verifiedSigners);
     signerMap.putAll(sigFileSigners);
   }
   return signerMap;
 }
Esempio n. 22
0
 static Config getConfig(final String name, final InputStream stream) {
   Config config = configMap.get(name);
   if (config != null) {
     return config;
   }
   try {
     config = new Config(name, stream);
     configMap.put(name, config);
     return config;
   } catch (Exception e) {
     throw new ProviderException("Error parsing configuration", e);
   }
 }
Esempio n. 23
0
  /**
   * Create page token if it doesn't exist.
   *
   * @param pageTokens A map of tokens. If token doesn't exist it will be added.
   * @param uri The key for the tokens.
   */
  private void createPageToken(Map<String, String> pageTokens, String uri) {

    if (pageTokens == null) return;

    /** create token if it does not exist * */
    if (pageTokens.containsKey(uri)) return;
    try {
      pageTokens.put(uri, RandomGenerator.generateRandomId(getPrng(), getTokenLength()));
    } catch (Exception e) {
      throw new RuntimeException(
          String.format("unable to generate the random token - %s", e.getLocalizedMessage()), e);
    }
  }
Esempio n. 24
0
  public static synchronized void sessionDestroyed(HttpSessionEvent ev) {
    HttpSession httpSession = ev.getSession();
    String id = httpSession.getId();

    synchronized (lookupSessionById) {
      lookupSessionById.remove(id);
    }

    // Forget HTTP-session:
    {
      lookupHttpSessionById.remove(id);
    }
  }
Esempio n. 25
0
 static { // watch out: order is important for these initializers
   CEKILL = new HTTPUtil.ContentEncodingInterceptor();
   contentDecoderMap = new HashMap<String, InputStreamFactory>();
   contentDecoderMap.put("zip", new ZipStreamFactory());
   contentDecoderMap.put("gzip", new GZIPStreamFactory());
   globalsettings = new Settings();
   setDefaults(globalsettings);
   processDFlags(); // Process all -D flags
   connmgr = new PoolingHttpClientConnectionManager(sslregistry);
   setGlobalUserAgent(DFALTUSERAGENT);
   // does not work setGlobalThreadCount(DFALTTHREADCOUNT);
   setGlobalConnectionTimeout(DFALTCONNTIMEOUT);
   setGlobalSoTimeout(DFALTSOTIMEOUT);
 }
Esempio n. 26
0
 public static void addPumpMessage(Display dpy, Runnable pumpMessage) {
   if (useMainThread) {
     return; // error ?
   }
   if (null == pumpMessagesTimer) {
     synchronized (MainThread.class) {
       if (null == pumpMessagesTimer) {
         pumpMessagesTimer = new Timer();
         pumpMessagesTimerTask =
             new TimerTask() {
               public void run() {
                 synchronized (pumpMessageDisplayMap) {
                   for (Iterator i = pumpMessageDisplayMap.values().iterator(); i.hasNext(); ) {
                     ((Runnable) i.next()).run();
                   }
                 }
               }
             };
         pumpMessagesTimer.scheduleAtFixedRate(
             pumpMessagesTimerTask, 0, defaultEDTPollGranularity);
       }
     }
   }
   synchronized (pumpMessageDisplayMap) {
     pumpMessageDisplayMap.put(dpy, pumpMessage);
   }
 }
Esempio n. 27
0
  /**
   * Add {@link DiscoverInfo} to our caps database.
   *
   * <p><b>Warning</b>: The specified <tt>DiscoverInfo</tt> is trusted to be valid with respect to
   * the specified <tt>Caps</tt> for performance reasons because the <tt>DiscoverInfo</tt> should
   * have already been validated in order to be used elsewhere anyway.
   *
   * @param caps the <tt>Caps<tt/> i.e. the node, the hash and the ver for which a
   *     <tt>DiscoverInfo</tt> is to be added to our caps database.
   * @param info {@link DiscoverInfo} for the specified <tt>Caps</tt>.
   */
  public static void addDiscoverInfoByCaps(Caps caps, DiscoverInfo info) {
    cleanupDiscoverInfo(info);
    /*
     * DiscoverInfo carries the node we're now associating it with a
     * specific node so we'd better keep them in sync.
     */
    info.setNode(caps.getNodeVer());

    synchronized (caps2discoverInfo) {
      DiscoverInfo oldInfo = caps2discoverInfo.put(caps, info);

      /*
       * If the specified info is a new association for the specified
       * node, remember it across application instances in order to not
       * query for it over the network.
       */
      if ((oldInfo == null) || !oldInfo.equals(info)) {
        String xml = info.getChildElementXML();

        if ((xml != null) && (xml.length() != 0)) {
          getConfigService().setProperty(getCapsPropertyName(caps), xml);
        }
      }
    }
  }
Esempio n. 28
0
 public static HttpRequestBase buildHeaders(
     HttpRequestBase httpRequestBase, Map<String, String> headers) {
   for (Entry<String, String> header : headers.entrySet()) {
     httpRequestBase.setHeader(header.getKey(), header.getValue());
   }
   return httpRequestBase;
 }
Esempio n. 29
0
  private void checkStartup(
      Map<String, ServiceData> map,
      List<ServiceData> start,
      ServiceData sd,
      Set<ServiceData> cyclic) {
    if (sd.after.isEmpty() || start.contains(sd)) return;

    if (cyclic.contains(sd)) {
      reporter.error("Cyclic dependency for " + sd.name);
      return;
    }

    cyclic.add(sd);

    for (String dependsOn : sd.after) {
      if (dependsOn.equals("boot")) continue;

      ServiceData deps = map.get(dependsOn);
      if (deps == null) {
        reporter.error("No such service " + dependsOn + " but " + sd.name + " depends on it");
      } else {
        checkStartup(map, start, deps, cyclic);
      }
    }
    start.add(sd);
  }
Esempio n. 30
0
  /**
   * @param data
   * @param target
   * @throws Exception
   * @throws IOException
   */
  public String createCommand(CommandData data, boolean force) throws Exception, IOException {

    // TODO
    // if (Data.validate(data) != null)
    // return "Invalid command data: " + Data.validate(data);

    Map<String, String> map = null;
    if (data.trace) {
      map = new HashMap<String, String>();
      map.put("java.security.manager", "aQute.jpm.service.TraceSecurityManager");
      reporter.trace("tracing");
    }
    String s = platform.createCommand(data, map, force, service.getAbsolutePath());
    if (s == null) storeData(new File(commandDir, data.name), data);
    return s;
  }