Ejemplo n.º 1
0
 /*
  * Verify that the provider JAR files are signed properly, which
  * means the signer's certificate can be traced back to a
  * JCE trusted CA.
  * Return null if ok, failure Exception if verification failed.
  */
 static synchronized Exception getVerificationResult(Provider p) {
   Object o = verificationResults.get(p);
   if (o == PROVIDER_VERIFIED) {
     return null;
   } else if (o != null) {
     return (Exception) o;
   }
   if (verifyingProviders.get(p) != null) {
     // this method is static synchronized, must be recursion
     // return failure now but do not save the result
     return new NoSuchProviderException("Recursion during verification");
   }
   try {
     verifyingProviders.put(p, Boolean.FALSE);
     URL providerURL = getCodeBase(p.getClass());
     verifyProviderJar(providerURL);
     // Verified ok, cache result
     verificationResults.put(p, PROVIDER_VERIFIED);
     return null;
   } catch (Exception e) {
     verificationResults.put(p, e);
     return e;
   } finally {
     verifyingProviders.remove(p);
   }
 }
  /**
   * Gets the FontMetrics object for the supplied font. This method caches font metrics to ensure
   * native fonts are not loaded twice for the same font.
   */
  static synchronized QtFontMetrics getFontMetrics(Font font, boolean backwardCompat) {

    /* See if metrics has been stored in font already. */

    QtFontMetrics fm = (QtFontMetrics) font.metrics;

    if (fm == null) {
      boolean strikethrough = false, underline = false;

      /* See if a font metrics of the same native name and size has already been loaded.
      If it has then we use that one. */

      String nativeName = (String) fontNameMap.get(font.name.toLowerCase());

      if (nativeName == null) nativeName = (String) fontNameMap.get("default");

      String key = nativeName + "." + font.style + "." + font.size;

      if (!backwardCompat) {
        Map fa = font.getAttributes();
        Object obj;

        if ((obj = fa.get(TextAttribute.STRIKETHROUGH)) != null) {
          if (obj.equals(TextAttribute.STRIKETHROUGH_ON)) {
            key += ".s";
            strikethrough = true;
          }
        }

        if ((obj = fa.get(TextAttribute.UNDERLINE)) != null) {
          if (obj.equals(TextAttribute.UNDERLINE_ON)) {
            key += ".u";
            underline = true;
          }
        }
      }

      fm = (QtFontMetrics) fontMetricsMap.get(key);

      if (fm == null) {
        fontMetricsMap.put(
            key, fm = new QtFontMetrics(font, nativeName, font.style, strikethrough, underline));
      }

      font.metrics = fm;
    }

    return fm;
  }
Ejemplo n.º 3
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);
      }
    }
  }
Ejemplo n.º 5
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);
  }
Ejemplo n.º 6
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);
      }
    }
  }
Ejemplo n.º 7
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);
      }
    }
  }
Ejemplo n.º 8
0
  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;
  }
Ejemplo n.º 9
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;
  }
Ejemplo n.º 10
0
 /**
  * Gets the BDFontMetrics object for the supplied font. This method caches font metrics to ensure
  * native fonts are not loaded twice for the same font.
  */
 static synchronized BDFontMetrics getFontMetrics(Font font) {
   /* See if metrics has been stored in font already. */
   BDFontMetrics fm = null;
   // BDFontMetrics fm = (BDFontMetrics)font.metrics;
   // if (fm == null) {
   /* See if a font metrics of the same native name and size has already been loaded.
   If it has then we use that one. */
   String nativeName =
       (String) fontNameMap.get(font.getName().toLowerCase() + "." + font.getStyle());
   if (nativeName == null) nativeName = (String) fontNameMap.get("default." + font.getStyle());
   String key = nativeName + "." + font.getSize();
   fm = (BDFontMetrics) fontMetricsMap.get(key);
   if (fm == null) fontMetricsMap.put(key, fm = new BDFontMetrics(font, nativeName));
   // font.metrics = fm;
   // }
   return fm;
 }
Ejemplo n.º 11
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;
   }
 }
Ejemplo n.º 12
0
 /**
  * Return icon type (GtkIconSize value) given a symbolic name which can occur in a theme file.
  *
  * @param size symbolic name, e.g. gtk-button
  * @return icon type. Valid types are 1 to 6
  */
 public static int getIconType(String size) {
   if (size == null) {
     return UNDEFINED;
   }
   if (ICON_TYPE_MAP == null) {
     initIconTypeMap();
   }
   Integer n = ICON_TYPE_MAP.get(size);
   return n != null ? n.intValue() : UNDEFINED;
 }
Ejemplo n.º 13
0
 /*
  * Create a unique mapping from codeSigner cache entries to CodeSource.
  * In theory, multiple URLs origins could map to a single locally cached
  * and shared JAR file although in practice there will be a single URL in use.
  */
 private synchronized CodeSource mapSignersToCodeSource(URL url, CodeSigner[] signers) {
   Map map;
   if (url == lastURL) {
     map = lastURLMap;
   } else {
     map = (Map) urlToCodeSourceMap.get(url);
     if (map == null) {
       map = new HashMap();
       urlToCodeSourceMap.put(url, map);
     }
     lastURLMap = map;
     lastURL = url;
   }
   CodeSource cs = (CodeSource) map.get(signers);
   if (cs == null) {
     cs = new VerifierCodeSource(csdomain, url, signers);
     signerToCodeSource.put(signers, cs);
   }
   return cs;
 }
Ejemplo n.º 14
0
  /**
   * Handle authentication and Proxy'ing
   *
   * @param cb
   * @throws HTTPException
   */
  protected synchronized void setAuthenticationAndProxy(HttpClientBuilder cb) throws HTTPException {
    // First, setup the ssl factory
    cb.setSSLSocketFactory(globalsslfactory);

    // Second, Construct a CredentialsProvider that is
    // the union of the Proxy credentials plus
    // either the global local credentials; local overrides global
    // Unfortunately, we cannot either clone or extract the contents
    // of the client supplied provider, so we are forced (for now)
    // to modify the client supplied provider.

    // Look in the local authcreds for best scope match
    AuthScope bestMatch = HTTPAuthUtil.bestmatch(scope, localcreds.keySet());
    CredentialsProvider cp = null;
    if (bestMatch != null) {
      cp = localcreds.get(bestMatch);
    } else {
      bestMatch = HTTPAuthUtil.bestmatch(scope, globalcreds.keySet());
      if (bestMatch != null) cp = globalcreds.get(bestMatch);
    }
    // Build the proxy credentials and AuthScope
    Credentials proxycreds = null;
    AuthScope proxyscope = null;
    if (proxyuser != null && (httpproxy != null || httpsproxy != null)) {
      if (httpproxy != null) proxyscope = HTTPAuthUtil.hostToAuthScope(httpproxy);
      else // httpsproxy != null
      proxyscope = HTTPAuthUtil.hostToAuthScope(httpsproxy);
      proxycreds = new UsernamePasswordCredentials(proxyuser, proxypwd);
    }
    if (cp == null && proxycreds != null && proxyscope != null) {
      // If client provider is null and proxycreds are not,
      // then use proxycreds alone
      cp = new BasicCredentialsProvider();
      cp.setCredentials(proxyscope, proxycreds);
    } else if (cp != null && proxycreds != null && proxyscope != null) {
      // If client provider is not null and proxycreds are not,
      // then add proxycreds to the client provider
      cp.setCredentials(proxyscope, proxycreds);
    }
    if (cp != null) this.sessioncontext.setCredentialsProvider(cp);
  }
Ejemplo n.º 15
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);
   }
 }
Ejemplo n.º 16
0
  public Session getSessionFromId(String id) throws IOException {
    Session res = null;

    {
      synchronized (lookupSessionById) {
        AbstractSession session = lookupSessionById.get(id);
        expandSession(session);
        res = session;
      }
    }

    return res;
  }
Ejemplo n.º 17
0
  protected void expandSessionPrincipal(AbstractSession session) throws IOException {
    if (session != null) {
      String id = session.getId();
      HttpSession httpSession = lookupHttpSessionById.get(id);

      // Set 'userPrincipal' upon session:
      {
        if (httpSession != null) {
          Principal userPrincipal = PrincipalSessionDecorator.getPrincipal(httpSession);
          if (userPrincipal != null) {
            session.setUserPrincipal(userPrincipal);
          }
        }
      }
    }
  }
Ejemplo n.º 18
0
  @Override
  public Image getIcon(final int iconType) {
    Image icon = img.get(iconType);
    if (icon != null) return icon;

    // try to get a special icon
    icon = BeanSupport.getBeanIcon(component.getBeanClass(), iconType);
    if (icon == null) {
      final String className = component.getBeanClass().getName();
      final String classDetails =
          (String) component.getAuxValue(RADComponent.AUX_VALUE_CLASS_DETAILS);
      if (!iconsInitialized) {
        // getIconForClass invokes getNodes(true) which cannot be called in Mutex
        EventQueue.invokeLater(
            new Runnable() {
              @Override
              public void run() {
                Image icon = PaletteUtils.getIconForClass(className, classDetails, iconType, true);
                iconsInitialized = true;
                if (icon != null) {
                  img.put(iconType, icon);
                  fireIconChange();
                }
              }
            });
      } else {
        icon = PaletteUtils.getIconForClass(className, classDetails, iconType, false);
      }

      if (icon == null) {
        // get icon from BeanInfo
        java.beans.BeanInfo bi = component.getBeanInfo();
        if (bi != null) {
          icon = bi.getIcon(iconType);
        }

        if (icon == null) {
          // use default icon
          icon = super.getIcon(iconType);
        }
      }
    }
    img.put(iconType, icon);
    return icon;
  }
Ejemplo n.º 19
0
  /**
   * Does the actual work for decrypting - if version does not match current cipher then tries the
   * previous cipher
   */
  private Message decryptMessage(Cipher cipher, Message msg) throws Exception {
    EncryptHeader hdr = (EncryptHeader) msg.getHeader(this.id);
    if (!Arrays.equals(hdr.getVersion(), getSymVersion())) {
      log.warn(
          "attempting to use stored cipher as message does not use current encryption version ");
      cipher = keyMap.get(new AsciiString(hdr.getVersion()));
      if (cipher == null) {
        log.warn("unable to find a matching cipher in previous key map");
        return null;
      }
      log.trace("decrypting using previous cipher version");
      synchronized (cipher) {
        return _decrypt(cipher, msg, hdr.encryptEntireMessage());
      }
    }

    return _decrypt(cipher, msg, hdr.encryptEntireMessage());
  }
Ejemplo n.º 20
0
  public Map<String, Revision> latest(Collection<Revision> list) {
    Map<String, Revision> programs = new HashMap<String, Library.Revision>();

    for (Revision r : list) {
      String coordinates = r.groupId + ":" + r.artifactId;
      if (r.classifier != null) coordinates += ":" + r.classifier;

      if (r.groupId.equals(Library.SHA_GROUP)) continue;

      Revision current = programs.get(coordinates);
      if (current == null) programs.put(coordinates, r);
      else {
        // who is better?
        if (compare(r, current) >= 0) programs.put(coordinates, r);
      }
    }
    return programs;
  }
Ejemplo n.º 21
0
  public static synchronized void sessionCreated(HttpSessionEvent ev) {
    HttpSession httpSession = ev.getSession();
    String id = httpSession.getId();

    // Remember HTTP-session:
    {
      lookupHttpSessionById.put(id, httpSession);
    }

    AbstractSession session = null;

    synchronized (lookupSessionById) {
      session = lookupSessionById.get(id);
    }

    if (session == null) {
      Principal userPrincipal = null;
      Date timeCreation = new Date(httpSession.getCreationTime());
      Date timeLastAccess = new Date(httpSession.getLastAccessedTime());
      List<String> urisForLastRequests = null;
      Properties properties = null;

      session =
          new DefaultSession(
              id, userPrincipal, timeCreation, timeLastAccess, urisForLastRequests, properties);

      synchronized (lookupSessionById) {
        lookupSessionById.put(id, session);

        // Update 'sessionCountMax':
        {
          int sessionCount = lookupSessionById.size();
          if (sessionCount > sessionCountMax) {
            sessionCountMax = sessionCount;
            sessionCountMaxTime = System.currentTimeMillis();
          }
        }
      }
    }
  }
Ejemplo n.º 22
0
  /**
   * Write the output file with a graph format.
   *
   * @param outputFileName the output file to write to
   * @param urlToImageFileMap the map of url's to image files
   * @param edgeList the list of sources and sinks to write
   */
  public void writeDotFile(
      String outputFileName,
      Map<String, String> urlToImageFileMap,
      Map<String, Set<String>> edgeList) {

    try {

      File outputFile = new File(outputFileName);
      FileWriter fileWriter = new FileWriter(outputFile);
      fileWriter.write("digraph G {\n");
      fileWriter.write("  node [shape=box];\n");
      Set<String> urls = urlToImageFileMap.keySet();

      for (String url : urls) {
        String hashedUrl = getHashCode(url);
        String imageFileName = urlToImageFileMap.get(url);
        fileWriter.write("  " + hashedUrl + "[label=\"\" image=\"" + imageFileName + "\"];\n");
      }

      for (String url : urls) {
        Set<String> links = edgeList.get(url);
        if (links != null) {
          for (String link : links) {
            if (urls.contains(link)) {
              String hashUrlSource = getHashCode(url);
              String hashUrlSink = getHashCode(link);
              fileWriter.write("  " + hashUrlSource + " -> " + hashUrlSink + "\n");
            }
          }
        }
      }

      fileWriter.write("}\n");
      fileWriter.flush();
      fileWriter.close();
      System.out.println("Wrote results to [" + outputFileName + "]");
    } catch (Exception e) {
      System.out.println("Exception writing the results to the output file: " + e);
    }
  }
Ejemplo n.º 23
0
  protected void expandSession(AbstractSession session) throws IOException {
    if (session != null) {
      String id = session.getId();
      HttpSession httpSession = lookupHttpSessionById.get(id);

      // Set 'timeLastAccess' upon session:
      {
        if (httpSession != null) {
          Date timeLastAccess = new Date(httpSession.getLastAccessedTime());
          session.setTimeLastAccess(timeLastAccess);
        }
      }

      expandSessionPrincipal(session);

      // Set 'requestURI' upon session:
      {
        if (httpSession != null) {
          List<String> requestURIs = RequestURISessionDecorator.getRequestURIs(httpSession);
          if (requestURIs != null) {
            Collections.reverse(requestURIs); // reverse the order!
            session.setRequestURIs(requestURIs);
          }
        }
      }

      // Set 'properties' upon session:
      {
        if (httpSession != null) {
          Map<String, Object> m = PropertiesSessionDecorator.getProperties(httpSession);
          if (m != null) {
            Properties properties = convertProperties(m);
            session.setProperties(properties);
          }
        }
      }
    }
  }
Ejemplo n.º 24
0
  private void verifyPageToken(HttpServletRequest request) throws CsrfGuardException {
    HttpSession session = request.getSession(true);
    @SuppressWarnings("unchecked")
    Map<String, String> pageTokens =
        (Map<String, String>) session.getAttribute(CsrfGuard.PAGE_TOKENS_KEY);

    String tokenFromPages = (pageTokens != null ? pageTokens.get(request.getRequestURI()) : null);
    String tokenFromSession = (String) session.getAttribute(getSessionKey());
    String tokenFromRequest = request.getParameter(getTokenName());

    if (tokenFromRequest == null) {
      /** FAIL: token is missing from the request * */
      throw new CsrfGuardException("required token is missing from the request");
    } else if (tokenFromPages != null) {
      if (!tokenFromPages.equals(tokenFromRequest)) {
        /** FAIL: request does not match page token * */
        throw new CsrfGuardException("request token does not match page token");
      }
    } else if (!tokenFromSession.equals(tokenFromRequest)) {
      /** FAIL: the request token does not match the session token * */
      throw new CsrfGuardException("request token does not match session token");
    }
  }
Ejemplo n.º 25
0
  @Override
  public Object get(SynthContext context, Object key) {
    // See if this is a class specific value.
    String classKey = CLASS_SPECIFIC_MAP.get(key);
    if (classKey != null) {
      Object value = getClassSpecificValue(classKey);
      if (value != null) {
        return value;
      }
    }

    // Is it a specific value ?
    if (key == "ScrollPane.viewportBorderInsets") {
      return getThicknessInsets(context, new Insets(0, 0, 0, 0));
    } else if (key == "Slider.tickColor") {
      return getColorForState(context, ColorType.FOREGROUND);
    } else if (key == "ScrollBar.minimumThumbSize") {
      int len = getClassSpecificIntValue(context, "min-slider-length", 21);
      JScrollBar sb = (JScrollBar) context.getComponent();
      if (sb.getOrientation() == JScrollBar.HORIZONTAL) {
        return new DimensionUIResource(len, 0);
      } else {
        return new DimensionUIResource(0, len);
      }
    } else if (key == "Separator.thickness") {
      JSeparator sep = (JSeparator) context.getComponent();
      if (sep.getOrientation() == JSeparator.HORIZONTAL) {
        return getYThickness();
      } else {
        return getXThickness();
      }
    } else if (key == "ToolBar.separatorSize") {
      int size = getClassSpecificIntValue(WidgetType.TOOL_BAR, "space-size", 12);
      return new DimensionUIResource(size, size);
    } else if (key == "ScrollBar.buttonSize") {
      JScrollBar sb = (JScrollBar) context.getComponent().getParent();
      boolean horiz = (sb.getOrientation() == JScrollBar.HORIZONTAL);
      WidgetType wt = horiz ? WidgetType.HSCROLL_BAR : WidgetType.VSCROLL_BAR;
      int sliderWidth = getClassSpecificIntValue(wt, "slider-width", 14);
      int stepperSize = getClassSpecificIntValue(wt, "stepper-size", 14);
      return horiz
          ? new DimensionUIResource(stepperSize, sliderWidth)
          : new DimensionUIResource(sliderWidth, stepperSize);
    } else if (key == "ArrowButton.size") {
      String name = context.getComponent().getName();
      if (name != null && name.startsWith("Spinner")) {
        // Believe it or not, the size of a spinner arrow button is
        // dependent upon the size of the spinner's font.  These
        // calculations come from gtkspinbutton.c (version 2.8.20),
        // spin_button_get_arrow_size() method.
        String pangoFontName;
        synchronized (sun.awt.UNIXToolkit.GTK_LOCK) {
          pangoFontName = nativeGetPangoFontName(WidgetType.SPINNER.ordinal());
        }
        int arrowSize = (pangoFontName != null) ? PangoFonts.getFontSize(pangoFontName) : 10;
        return (arrowSize + (getXThickness() * 2));
      }
      // For all other kinds of arrow buttons (e.g. combobox arrow
      // buttons), we will simply fall back on the value of
      // ArrowButton.size as defined in the UIDefaults for
      // GTKLookAndFeel when we call UIManager.get() below...
    } else if ("CheckBox.iconTextGap".equals(key) || "RadioButton.iconTextGap".equals(key)) {
      // The iconTextGap value needs to include "indicator-spacing"
      // and it also needs to leave enough space for the focus line,
      // which falls between the indicator icon and the text.
      // See getRadioInsets() and 6489585 for more details.
      int indicatorSpacing = getClassSpecificIntValue(context, "indicator-spacing", 2);
      int focusSize = getClassSpecificIntValue(context, "focus-line-width", 1);
      int focusPad = getClassSpecificIntValue(context, "focus-padding", 1);
      return indicatorSpacing + focusSize + focusPad;
    }

    // Is it a stock icon ?
    GTKStockIcon stockIcon = null;
    synchronized (ICONS_MAP) {
      stockIcon = ICONS_MAP.get(key);
    }

    if (stockIcon != null) {
      return stockIcon;
    }

    // Is it another kind of value ?
    if (key != "engine") {
      // For backward compatibility we'll fallback to the UIManager.
      // We don't go to the UIManager for engine as the engine is GTK
      // specific.
      Object value = UIManager.get(key);
      if (key == "Table.rowHeight") {
        int focusLineWidth = getClassSpecificIntValue(context, "focus-line-width", 0);
        if (value == null && focusLineWidth > 0) {
          value = Integer.valueOf(16 + 2 * focusLineWidth);
        }
      }
      return value;
    }

    // Don't call super, we don't want to pick up defaults from
    // SynthStyle.
    return null;
  }
Ejemplo n.º 26
0
  /**
   * Transforms invoke instructions that match the specified list for this class to call the
   * specified static call instead.
   */
  private InstructionList xform_inst(MethodGen mg, Instruction inst) {

    switch (inst.getOpcode()) {
      case Constants.INVOKESTATIC:
        {
          InstructionList il = new InstructionList();
          INVOKESTATIC is = (INVOKESTATIC) inst;
          String cname = is.getClassName(pgen);
          String mname = is.getMethodName(pgen);
          Type[] args = is.getArgumentTypes(pgen);
          MethodDef orig = new MethodDef(cname + "." + mname, args);
          MethodInfo call = method_map.get(orig);
          if (call != null) {
            call.cnt++;
            String classname = call.method_class;
            String methodname = mname;
            debug_map.log(
                "%s.%s: Replacing method %s.%s (%s) with %s.%s%n",
                mg.getClassName(),
                mg.getName(),
                cname,
                mname,
                UtilMDE.join(args, ", "),
                classname,
                methodname);
            il.append(
                ifact.createInvoke(
                    classname, methodname, is.getReturnType(pgen), args, Constants.INVOKESTATIC));
          }
          return (il);
        }

      case Constants.INVOKEVIRTUAL:
        {
          InstructionList il = new InstructionList();
          INVOKEVIRTUAL iv = (INVOKEVIRTUAL) inst;
          String cname = iv.getClassName(pgen);
          String mname = iv.getMethodName(pgen);
          Type[] args = iv.getArgumentTypes(pgen);
          Type instance_type = iv.getReferenceType(pgen);
          Type[] new_args = BCELUtil.insert_type(instance_type, args);
          MethodDef orig = new MethodDef(cname + "." + mname, args);
          if (debug_class) System.out.printf("looking for %s in map %s%n", orig, method_map);
          MethodInfo call = method_map.get(orig);
          if (call != null) {
            call.cnt++;
            String classname = call.method_class;
            String methodname = mname;
            debug_map.log(
                "Replacing method %s.%s (%s) with %s.%s%n",
                cname, mname, ArraysMDE.toString(args), classname, methodname);
            il.append(
                ifact.createInvoke(
                    classname,
                    methodname,
                    iv.getReturnType(pgen),
                    new_args,
                    Constants.INVOKESTATIC));
          }
          return (il);
        }

      default:
        return (null);
    }
  }
Ejemplo n.º 27
0
  public static void load(Properties properties)
      throws NoSuchAlgorithmException, InstantiationException, IllegalAccessException,
          ClassNotFoundException, IOException, NoSuchProviderException {
    CsrfGuard csrfGuard = SingletonHolder.instance;

    /** load simple properties * */
    csrfGuard.setLogger(
        (ILogger)
            Class.forName(
                    properties.getProperty(
                        "org.owasp.csrfguard.Logger", "org.owasp.csrfguard.log.ConsoleLogger"))
                .newInstance());
    csrfGuard.setTokenName(
        properties.getProperty("org.owasp.csrfguard.TokenName", "OWASP_CSRFGUARD"));
    csrfGuard.setTokenLength(
        Integer.parseInt(properties.getProperty("org.owasp.csrfguard.TokenLength", "32")));
    csrfGuard.setRotate(
        Boolean.valueOf(properties.getProperty("org.owasp.csrfguard.Rotate", "false")));
    csrfGuard.setTokenPerPage(
        Boolean.valueOf(properties.getProperty("org.owasp.csrfguard.TokenPerPage", "false")));
    csrfGuard.setTokenPerPagePrecreate(
        Boolean.valueOf(
            properties.getProperty("org.owasp.csrfguard.TokenPerPagePrecreate", "false")));
    csrfGuard.setPrng(
        SecureRandom.getInstance(
            properties.getProperty("org.owasp.csrfguard.PRNG", "SHA1PRNG"),
            properties.getProperty("org.owasp.csrfguard.PRNG.Provider", "SUN")));
    csrfGuard.setNewTokenLandingPage(
        properties.getProperty("org.owasp.csrfguard.NewTokenLandingPage"));

    // default to false if newTokenLandingPage is not set; default to true if set.
    if (csrfGuard.getNewTokenLandingPage() == null) {
      csrfGuard.setUseNewTokenLandingPage(
          Boolean.valueOf(
              properties.getProperty("org.owasp.csrfguard.UseNewTokenLandingPage", "false")));
    } else {
      csrfGuard.setUseNewTokenLandingPage(
          Boolean.valueOf(
              properties.getProperty("org.owasp.csrfguard.UseNewTokenLandingPage", "true")));
    }
    csrfGuard.setSessionKey(
        properties.getProperty("org.owasp.csrfguard.SessionKey", "OWASP_CSRFGUARD_KEY"));
    csrfGuard.setAjax(Boolean.valueOf(properties.getProperty("org.owasp.csrfguard.Ajax", "false")));
    csrfGuard.setProtect(
        Boolean.valueOf(properties.getProperty("org.owasp.csrfguard.Protect", "false")));

    /** first pass: instantiate actions * */
    Map<String, IAction> actionsMap = new HashMap<String, IAction>();

    for (Object obj : properties.keySet()) {
      String key = (String) obj;

      if (key.startsWith(ACTION_PREFIX)) {
        String directive = key.substring(ACTION_PREFIX.length());
        int index = directive.indexOf('.');

        /** action name/class * */
        if (index < 0) {
          String actionClass = properties.getProperty(key);
          IAction action = (IAction) Class.forName(actionClass).newInstance();

          action.setName(directive);
          actionsMap.put(action.getName(), action);
          csrfGuard.getActions().add(action);
        }
      }
    }

    /** second pass: initialize action parameters * */
    for (Object obj : properties.keySet()) {
      String key = (String) obj;

      if (key.startsWith(ACTION_PREFIX)) {
        String directive = key.substring(ACTION_PREFIX.length());
        int index = directive.indexOf('.');

        /** action name/class * */
        if (index >= 0) {
          String actionName = directive.substring(0, index);
          IAction action = actionsMap.get(actionName);

          if (action == null) {
            throw new IOException(
                String.format("action class %s has not yet been specified", actionName));
          }

          String parameterName = directive.substring(index + 1);
          String parameterValue = properties.getProperty(key);

          action.setParameter(parameterName, parameterValue);
        }
      }
    }

    /** ensure at least one action was defined * */
    if (csrfGuard.getActions().size() <= 0) {
      throw new IOException("failure to define at least one action");
    }

    /** initialize protected, unprotected pages * */
    for (Object obj : properties.keySet()) {
      String key = (String) obj;

      if (key.startsWith(PROTECTED_PAGE_PREFIX)) {
        String directive = key.substring(PROTECTED_PAGE_PREFIX.length());
        int index = directive.indexOf('.');

        /** page name/class * */
        if (index < 0) {
          String pageUri = properties.getProperty(key);

          csrfGuard.getProtectedPages().add(Pattern.compile(pageUri));
        }
      }

      if (key.startsWith(UNPROTECTED_PAGE_PREFIX)) {
        String directive = key.substring(UNPROTECTED_PAGE_PREFIX.length());
        int index = directive.indexOf('.');

        /** page name/class * */
        if (index < 0) {
          String pageUri = properties.getProperty(key);

          csrfGuard.getUnprotectedPages().add(Pattern.compile(pageUri));
        }
      }
    }

    /** initialize protected methods * */
    String methodList = properties.getProperty("org.owasp.csrfguard.ProtectedMethods");
    if (methodList != null && methodList.trim().length() != 0) {
      for (String method : methodList.split(",")) {
        csrfGuard.getProtectedMethods().add(method.trim());
      }
    }
  }
Ejemplo n.º 28
0
  /**
   * The entry point into the Parser class.
   *
   * @param root A RootDoc intstance obtained via the doclet API
   * @return A XML (XStream) serializable element, containing everything parsed from javadoc doclet
   */
  public static Root ParseRoot(RootDoc root) {
    processingStorage = new HashMap<PackageDoc, ParserMediary>();

    try {
      md5 = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
      log.error("unable to acquire MD5 algorithm", e);
      return null;
    }

    rootXml = new Root();

    ClassDoc[] allClasses = root.classes();

    for (ClassDoc classDoc : allClasses) {
      PackageDoc doc = classDoc.containingPackage();

      ParserMediary mediary = null;

      // the age old 'if I have it pull out existing, if I don't make a new one'
      if (processingStorage.containsKey(doc)) {
        mediary = processingStorage.get(doc);
      } else {
        mediary =
            new ParserMediary(
                doc.name(),
                doc.commentText(),
                ParseAnnotationInstances(doc.annotations(), doc.name()));

        processingStorage.put(doc, mediary);
      }

      if (classDoc.isIncluded()) {
        // dev comment--why do enums show up as ordinary class?
        if (classDoc.isOrdinaryClass() || classDoc.isException() || classDoc.isError()) {
          mediary.addClass(ParseClass(classDoc));
        } else if (classDoc.isEnum()) {
          mediary.addEnum(ParseEnum(classDoc));
        } else if (isAnnotation(classDoc)) {
          mediary.addAnnotation(ParseAnnotation(classDoc));
        } else if (classDoc.isInterface()) {
          mediary.addInterface(ParseInterface(classDoc));
        }
      } else {
        log.debug("Skipping not-included class " + classDoc.qualifiedName());
      }
    }

    if (processingStorage.size() > 0) {
      List list = new ArrayList<Package>();

      for (ParserMediary mediary : processingStorage.values()) {
        list.add(mediary.wrapup());
      }

      rootXml.packages = (Package[]) list.toArray(new Package[] {});
    } else {
      log.warn("No packages found!");
    }

    return rootXml;
  }
Ejemplo n.º 29
0
 /**
  * gets a class from the class cache. This cache contains only classes loaded through this class
  * loader or an InnerLoader instance. If no class is stored for a specific name, then the method
  * should return null.
  *
  * @param name of the class
  * @return the class stored for the given name
  * @see #removeClassCacheEntry(String)
  * @see #setClassCacheEntry(Class)
  * @see #clearCache()
  */
 protected Class getClassCacheEntry(String name) {
   if (name == null) return null;
   synchronized (classCache) {
     return classCache.get(name);
   }
 }
 /**
  * Return the named LockssKeyStore
  *
  * @param name the keystore name
  * @param criticalServiceName if non-null, this is a criticial keystore whose unavailability
  *     should cause the daemon to exit (if org.lockss.keyMgr.exitIfMissingKeystore is true)
  */
 public LockssKeyStore getLockssKeyStore(String name, String criticalServiceName) {
   LockssKeyStore res = keystoreMap.get(name);
   checkFact(res, name, criticalServiceName, null);
   return res;
 }