/*
   * Read multiple resource files from the classpaths given the file name.
   * This method is designed as package visibility to improve performance when
   * called by anonymous inner classes.
   *
   * @param name - the name of the resource file @param existingProps -
   * existing properties, cannot be null @param filter - to filter properties
   */
  static Hashtable<Object, Object> readMultipleResourceFiles(
      final String name, final Hashtable<Object, Object> existingProps, ClassLoader cl)
      throws NamingException {

    if (null == cl) {
      cl = ClassLoader.getSystemClassLoader();
    }

    Enumeration<URL> e = null;
    try {
      // Load all resource files
      e = cl.getResources(name);
    } catch (final IOException ex) {
      // Unexpected ClassLoader exception
      // jndi.23=Failed to load JNDI resource files.
      final ConfigurationException newEx =
          new ConfigurationException(Messages.getString("jndi.23")); // $NON-NLS-1$
      newEx.setRootCause(ex);
      throw newEx;
    }

    // Read all the loaded properties and merge
    URL url = null;
    InputStream is = null;
    final Properties p = new Properties();
    while (e.hasMoreElements()) {
      url = e.nextElement();
      try {
        if (null != (is = url.openStream())) {
          p.load(is);
          mergeEnvironment(p, existingProps, true);
          p.clear();
        }
      } catch (final IOException ex) {
        // Can't read this resource file
        // jndi.24=Failed to read JNDI resource files.
        final ConfigurationException newEx =
            new ConfigurationException(Messages.getString("jndi.24")); // $NON-NLS-1$
        newEx.setRootCause(ex);
        throw newEx;
      } finally {
        try {
          if (null != is) {
            is.close();
          }
        } catch (final IOException ex) {
          // Ignore closing exception
        } finally {
          is = null;
        }
      }
    }
    return existingProps;
  }
 @Override
 public Name add(String element) throws InvalidNameException {
   if (element == null) {
     // jndi.8C=component must not be null
     throw new IllegalArgumentException(Messages.getString("jndi.8C")); // $NON-NLS-1$
   }
   if (FLAT.equals(direction) && (size() > 0)) {
     // jndi.0A=A flat name can only have a single component
     throw new InvalidNameException(Messages.getString("jndi.0A")); // $NON-NLS-1$
   }
   elems.add(element);
   return this;
 }
  public boolean hasMore() throws NamingException {
    // has been closed
    if (values == null) {
      return false;
    }

    if (!values.isEmpty()) {
      return true;
    }

    synchronized (values) {
      if (values.isEmpty() && !isFinished) {
        waitMoreElement();
        if (!values.isEmpty()) {
          return true;
        }
      }
    }

    close();

    if (exception != null) {
      throw exception;
    }

    if (!isFinished) {
      // ldap.31=Read LDAP response message time out
      throw new CommunicationException(Messages.getString("ldap.31")); // $NON-NLS-1$
    }

    return false;
  }
 @Override
 public Name addAll(int index, Name name) throws InvalidNameException {
   if (name == null) {
     // jndi.00=name must not be null
     throw new NullPointerException(Messages.getString("jndi.00")); // $NON-NLS-1$
   }
   if (!(name instanceof CompoundName)) {
     // jndi.09={0} is not a compound name.
     throw new InvalidNameException(Messages.getString("jndi.09", name.toString())); // $NON-NLS-1$
   }
   if (FLAT.equals(direction) && (size() + name.size() > 1)) {
     // jndi.0A=A flat name can only have a single component
     throw new InvalidNameException(Messages.getString("jndi.0A")); // $NON-NLS-1$
   }
   validateIndex(index, true);
   final Enumeration<String> enumeration = name.getAll();
   while (enumeration.hasMoreElements()) {
     elems.add(index++, enumeration.nextElement());
   }
   return this;
 }
Exemple #5
0
 /**
  * Returns a deep clone of this <code>Reference</code> instance.
  *
  * @return a deep clone of this object
  */
 @SuppressWarnings("unchecked")
 @Override
 public Object clone() {
   try {
     Reference r = (Reference) super.clone();
     r.addrs = (Vector<RefAddr>) this.addrs.clone();
     return r;
   } catch (CloneNotSupportedException e) {
     // jndi.03=Failed to clone object of Reference class.
     throw new AssertionError(Messages.getString("jndi.03")); // $NON-NLS-1$
   }
 }
  /**
   * Retrieves the next element. <code>NoSuchElementException</code> will be thrown, if there is no
   * other elements or <code>close()</code> has been invoked.
   */
  public T next() throws NamingException {
    if (values == null || (values.isEmpty() && isFinished)) {
      throw new NoSuchElementException();
    }

    synchronized (values) {
      if (values.isEmpty() && !isFinished) {
        waitMoreElement();
        // wait timeout
        if (values.isEmpty() && !isFinished) {
          if (exception != null) {
            throw exception;
          }
          // ldap.31=Read LDAP response message time out
          throw new CommunicationException(Messages.getString("ldap.31")); // $NON-NLS-1$
        } else if (values.isEmpty()) {
          throw new NoSuchElementException();
        }
      }
      return values.poll();
    }
  }
  /**
   * Parses given sequence of bytes and constructs a message object from it.
   *
   * @param mesBytes the byte array that should be parsed
   * @param startIdx an index of <code>mesBytes</code> array to start the parsing at
   * @param mes an object to write a result to, should already be created
   * @return updated index of <code>mesBytes</code> array
   * @throws DomainProtocolException if some error has occurred
   */
  public static int parseMessage(byte[] mesBytes, int startIdx, Message mesObj)
      throws DomainProtocolException {
    int idx = startIdx;
    int tmp, tmp2;
    int qdCnt;
    int anCnt;
    int nsCnt;
    int arCnt;

    if (mesObj == null) {
      // jndi.58=The value of parameter mesObj is null
      throw new DomainProtocolException(Messages.getString("jndi.58")); // $NON-NLS-1$
    }
    // header section
    // ID
    mesObj.setId(ProviderMgr.parse16Int(mesBytes, idx));
    idx += 2;
    // QR & opCode & AA & TC & RD & RA & Z & rCode
    tmp = ProviderMgr.parse16Int(mesBytes, idx);
    idx += 2;
    // QR
    mesObj.setQR(ProviderMgr.checkBit(tmp, ProviderConstants.QR_MASK));
    // OPCODE
    tmp2 = (tmp & ProviderConstants.OPCODE_MASK) >> ProviderConstants.OPCODE_SHIFT;
    mesObj.setOpCode(tmp2);
    // AA
    mesObj.setAA(ProviderMgr.checkBit(tmp, ProviderConstants.AA_MASK));
    // TC
    mesObj.setTc(ProviderMgr.checkBit(tmp, ProviderConstants.TC_MASK));
    // RD
    mesObj.setRD(ProviderMgr.checkBit(tmp, ProviderConstants.RD_MASK));
    // RA
    mesObj.setRA(ProviderMgr.checkBit(tmp, ProviderConstants.RA_MASK));
    // RCODE
    tmp2 = (tmp & ProviderConstants.RCODE_MASK) >> ProviderConstants.RCODE_SHIFT;
    mesObj.setRCode(tmp2);
    // QDCOUNT
    qdCnt = ProviderMgr.parse16Int(mesBytes, idx);
    mesObj.setQDCount(qdCnt);
    idx += 2;
    // ANCOUNT
    anCnt = ProviderMgr.parse16Int(mesBytes, idx);
    mesObj.setANCount(anCnt);
    idx += 2;
    // NSCOUNT
    nsCnt = ProviderMgr.parse16Int(mesBytes, idx);
    mesObj.setNSCount(nsCnt);
    idx += 2;
    // ARCOUNT
    arCnt = ProviderMgr.parse16Int(mesBytes, idx);
    mesObj.setARCount(arCnt);
    idx += 2;
    // question section
    for (int i = 0; i < qdCnt; i++) {
      QuestionRecord qr = new QuestionRecord();
      idx = QuestionRecord.parseRecord(mesBytes, idx, qr);
      mesObj.addQuestionRecord(qr);
    }
    // answer section
    for (int i = 0; i < anCnt; i++) {
      ResourceRecord rr = new ResourceRecord();
      idx = ResourceRecord.parseRecord(mesBytes, idx, rr);
      mesObj.addAnswerRR(rr);
    }
    // authority section
    for (int i = 0; i < nsCnt; i++) {
      ResourceRecord rr = new ResourceRecord();
      idx = ResourceRecord.parseRecord(mesBytes, idx, rr);
      mesObj.addAuthorityRR(rr);
    }
    // additional section
    for (int i = 0; i < arCnt; i++) {
      ResourceRecord rr = new ResourceRecord();
      idx = ResourceRecord.parseRecord(mesBytes, idx, rr);
      mesObj.addAdditionalRR(rr);
    }
    return idx;
  }
  /**
   * Generates sequence of bytes that represents the message.
   *
   * @param buffer the buffer to write bytes into
   * @param startIdx the index of <code>buffer</code> to start writing at
   * @return updated index of the <code>buffer</code>
   * @throws DomainProtocolException if something went wrong
   */
  public int writeBytes(byte[] buffer, int startIdx) throws DomainProtocolException {
    int idx = startIdx;
    int tmp = 0;

    // basic check
    if (buffer == null) {
      // jndi.32=buffer is null
      throw new DomainProtocolException(Messages.getString("jndi.32")); // $NON-NLS-1$
    }
    // ID
    idx = ProviderMgr.write16Int(id, buffer, idx);
    // QR
    tmp = ProviderMgr.setBit(tmp, ProviderConstants.QR_MASK, qr);
    // OPCODE
    tmp &= ~ProviderConstants.OPCODE_MASK;
    tmp |= (opCode & 0xf) << ProviderConstants.OPCODE_SHIFT;
    // AA
    tmp = ProviderMgr.setBit(tmp, ProviderConstants.AA_MASK, aa);
    // TC
    tmp = ProviderMgr.setBit(tmp, ProviderConstants.TC_MASK, tc);
    // RD
    tmp = ProviderMgr.setBit(tmp, ProviderConstants.RD_MASK, rd);
    // RA
    tmp = ProviderMgr.setBit(tmp, ProviderConstants.RA_MASK, ra);
    // Z, drop all those bits
    tmp &= ~ProviderConstants.Z_MASK;
    // RCODE
    tmp &= ~ProviderConstants.RCODE_MASK;
    tmp |= (rCode & 0xf) << ProviderConstants.RCODE_SHIFT;
    // write to buffer
    idx = ProviderMgr.write16Int(tmp, buffer, idx);
    // QDCOUNT
    idx = ProviderMgr.write16Int(qdCount, buffer, idx);
    // ANCOUNT
    idx = ProviderMgr.write16Int(anCount, buffer, idx);
    // NSCOUNT
    idx = ProviderMgr.write16Int(nsCount, buffer, idx);
    // ARCOUNT
    idx = ProviderMgr.write16Int(arCount, buffer, idx);
    // question section
    for (int i = 0; i < questionRecords.size(); i++) {
      QuestionRecord qr = questionRecords.elementAt(i);

      idx = qr.writeBytes(buffer, idx);
    }
    // answer section
    for (int i = 0; i < answerRRs.size(); i++) {
      ResourceRecord rr = answerRRs.elementAt(i);

      idx = rr.writeBytes(buffer, idx);
    }
    // authority section
    for (int i = 0; i < authorityRRs.size(); i++) {
      ResourceRecord rr = answerRRs.elementAt(i);

      idx = rr.writeBytes(buffer, idx);
    }
    // additional section
    for (int i = 0; i < additionalRRs.size(); i++) {
      ResourceRecord rr = answerRRs.elementAt(i);

      idx = rr.writeBytes(buffer, idx);
    }
    return idx;
  }
  /*
   * parse name from string to elements
   */
  private void parseName(String s) throws InvalidNameException {
    elems = new Vector<String>();
    if ("".equals(s)) { // $NON-NLS-1$
      // if empty string, return empty vector
      return;
    }

    // init variables
    int status = INIT_STATUS;
    final StringBuilder element = new StringBuilder();
    int pos = 0;
    final int length = s.length();
    boolean hasNotNullElement = false;
    boolean includeQuote = false;

    // scan name
    while (pos < length) {
      if (startsWithFromPos(s, pos, endQuoteString) && status == QUOTE1_STATUS) {
        status = QUOTEEND_STATUS;
        pos += addBuffer(element, endQuoteString, includeQuote);
      } else if (startsWithFromPos(s, pos, endQuoteString2) && status == QUOTE2_STATUS) {
        status = QUOTEEND_STATUS;
        pos += addBuffer(element, endQuoteString2, includeQuote);
      } else if (startsWithFromPos(s, pos, beginQuoteString) && status == INIT_STATUS) {
        hasNotNullElement = true;
        status = QUOTE1_STATUS;
        pos += addBuffer(element, beginQuoteString, includeQuote);
      } else if (startsWithFromPos(s, pos, beginQuoteString2) && status == INIT_STATUS) {
        hasNotNullElement = true;
        status = QUOTE2_STATUS;
        pos += addBuffer(element, beginQuoteString2, includeQuote);
      } else if (startsWithFromPos(s, pos, separatorString)
          && (!flat)
          && (status == INIT_STATUS || status == QUOTEEND_STATUS || status == NORMAL_STATUS)) {
        hasNotNullElement = hasNotNullElement || element.length() > 0;
        addElement(element);
        status = INIT_STATUS;
        pos += separatorString.length();
        includeQuote = false;
      } else if (startsWithFromPos(s, pos, separatorString2)
          && (!flat)
          && (status == INIT_STATUS || status == QUOTEEND_STATUS || status == NORMAL_STATUS)) {
        hasNotNullElement = hasNotNullElement || element.length() > 0;
        addElement(element);
        status = INIT_STATUS;
        pos += separatorString2.length();
        includeQuote = false;
      } else if (startsWithFromPos(s, pos, escapeString)) {
        pos += escapeString.length();
        if (pos == s.length()) {
          // if this escape char is last character, throw exception
          // jndi.06=The {0} cannot be at end of the component
          throw new InvalidNameException(
              Messages.getString("jndi.06", escapeString)); // $NON-NLS-1$
        }
        // if one escape char followed by a special char, append the
        // special char to current element
        final String str = extractEscapedString(s, pos, status);
        if (null == str) {
          pos -= escapeString.length();
          element.append(s.charAt(pos++));
        } else {
          pos += str.length();
          element.append(str);
        }

      } else if (startsWithFromPos(s, pos, sepTypeValString)
          && (status == INIT_STATUS || status == NORMAL_STATUS)) {
        includeQuote = true;
        pos += addBuffer(element, sepTypeValString, true);
        status = INIT_STATUS;
      } else if (startsWithFromPos(s, pos, sepAvaString)
          && (status == INIT_STATUS || status == NORMAL_STATUS)) {
        includeQuote = true;
        pos += addBuffer(element, sepAvaString, true);
        status = INIT_STATUS;
      } else if (status == QUOTEEND_STATUS) {
        // jndi.07={0}: close quote must appears at end of component in
        // quoted string
        throw new InvalidNameException(Messages.getString("jndi.07", s)); // $NON-NLS-1$
      } else {
        status = status == INIT_STATUS ? NORMAL_STATUS : status;
        element.append(s.charAt(pos++));
      }
    }
    if (QUOTE1_STATUS != status && QUOTE2_STATUS != status) {
      hasNotNullElement = hasNotNullElement || element.length() > 0;
      addElement(element);
    } else {
      // jndi.08={0}: close quote is required for quoted string
      throw new InvalidNameException(Messages.getString("jndi.08", s)); // $NON-NLS-1$
    }
    if (!hasNotNullElement) {
      elems.remove(elems.size() - 1);
    }
  }
  /** init instance variables */
  private void init(Properties props) {
    trimBlanks = false;
    ignoreCase = false;
    mySyntax = props;
    String property;

    // read property settings
    // direction's default value is FLAT
    direction = null == (property = props.getProperty(DIRECTION)) ? FLAT : property;
    // if direction value must equals to one of FLAT, LEFT_TO_RIGHT and
    // RIGHT_TO_LEFT, exception threw
    if (!LEFT_TO_RIGHT.equals(direction)
        && !RIGHT_TO_LEFT.equals(direction)
        && !FLAT.equals(direction)) {
      // jndi.04=Illegal direction property value, which must be one of
      // right_to_left, left_to_right or flat
      throw new IllegalArgumentException(Messages.getString("jndi.04")); // $NON-NLS-1$
    }
    flat = FLAT.equals(direction);

    separatorString = flat ? NULL_STRING : props.getProperty(SEPARATOR);
    // if direction is not FLAT, separator must be set
    if (null == separatorString && !flat) {
      // jndi.05=jndi.syntax.separator property must be set when
      // jndi.syntax.direction is not flat
      throw new IllegalArgumentException(Messages.getString("jndi.05")); // $NON-NLS-1$
    }
    separatorString2 =
        (flat || null == (property = props.getProperty(SEPARATOR2))) ? NULL_STRING : property;

    // ignorecase default value is false
    ignoreCase =
        null == (property = props.getProperty(IGNORE_CASE))
            ? false
            : Boolean.valueOf(property).booleanValue();
    // trimblanks default value is false
    trimBlanks =
        null == (property = props.getProperty(TRIM_BLANKS))
            ? false
            : Boolean.valueOf(property).booleanValue();
    escapeString = null == (property = props.getProperty(ESCAPE)) ? NULL_STRING : property;
    beginQuoteString = null == (property = props.getProperty(BEGIN_QUOTE)) ? NULL_STRING : property;
    beginQuoteString2 =
        null == (property = props.getProperty(BEGIN_QUOTE2)) ? NULL_STRING : property;
    // end quote string default value is begin quote string
    endQuoteString =
        null == (property = props.getProperty(END_QUOTE)) ? beginQuoteString : property;
    // begin quote string default value is end quote string
    if (NULL_STRING.equals(beginQuoteString)) {
      beginQuoteString = endQuoteString;
    }
    // end quote string2 default value is begin quote string2
    endQuoteString2 =
        null == (property = props.getProperty(END_QUOTE2)) ? beginQuoteString2 : property;
    // begin quote string2 default value is end quote string2
    if (NULL_STRING.equals(beginQuoteString2)) {
      beginQuoteString2 = endQuoteString2;
    }

    sepTypeValString =
        null == (property = props.getProperty(SEPARATOR_TYPEVAL)) ? NULL_STRING : property;
    sepAvaString = null == (property = props.getProperty(SEPARATOR_AVA)) ? NULL_STRING : property;
  }
  /*
   * Read the properties file "java.home"/lib/jndi.properties. Pay attention
   * to the privileged code for accessing this external resource file. This is
   * required if JNDI is run in Applet or other applications which only have
   * limited permissions to access certain resources.
   *
   * @param existingProps - existing properties, cannot be null.
   */
  public static Hashtable<Object, Object> readLibraryResourceFile(
      final Hashtable<Object, Object> existingProps) throws NamingException {
    final String sep = System.getProperty("file.separator"); // $NON-NLS-1$

    String resPath = null;
    // Construct the full filename of "java.home"/lib/jndi.properties
    resPath =
        AccessController.doPrivileged(
            new PrivilegedAction<String>() {
              @Override
              public String run() {
                return System.getProperty("java.home"); // $NON-NLS-1$
              }
            });

    if (!resPath.endsWith(sep)) {
      resPath += sep;
    }
    resPath += "lib" + sep + APPLICATION_RESOURCE_FILE; // $NON-NLS-1$

    // Try to read this properties if it exists
    InputStream is = null;
    final File resFile = new File(resPath);
    final Properties p = new Properties();
    // Use privileged code to determine whether the file exists
    final boolean resFileExists =
        AccessController.doPrivileged(
                new PrivilegedAction<Boolean>() {
                  @Override
                  public Boolean run() {
                    return Boolean.valueOf(resFile.exists());
                  }
                })
            .booleanValue();
    if (resFileExists) {
      try {
        // Use privileged code to read the file
        is =
            AccessController.doPrivileged(
                new PrivilegedExceptionAction<FileInputStream>() {
                  @Override
                  public FileInputStream run() throws IOException {
                    final FileInputStream localInputStream = new FileInputStream(resFile);
                    p.load(localInputStream);
                    return localInputStream;
                  }
                });
        mergeEnvironment(p, existingProps, true);
      } catch (final PrivilegedActionException e) {
        // Can't read "java.home"/lib/jndi.properties
        // jndi.25=Failed to read JNDI resource files in java home
        // library.
        final ConfigurationException newEx =
            new ConfigurationException(Messages.getString("jndi.25")); // $NON-NLS-1$
        newEx.setRootCause(e.getException());
        throw newEx;
      } finally {
        try {
          if (null != is) {
            is.close();
          }
        } catch (final IOException ex) {
          // Ignore closing exception
        }
      }
    }
    return existingProps;
  }