@SuppressWarnings("incomplete-switch")
  @Override
  public void onConnectionStateChange(ConnectionState state) {
    switch (state) {
      case CLOSED:
        IOState ioState = this.connection.getIOState();
        CloseInfo close = ioState.getCloseInfo();
        // confirmed close of local endpoint
        notifyClose(close.getStatusCode(), close.getReason());

        // notify session listeners
        for (SessionListener listener : sessionListeners) {
          try {
            if (LOG.isDebugEnabled())
              LOG.debug("{}.onSessionClosed()", listener.getClass().getSimpleName());
            listener.onSessionClosed(this);
          } catch (Throwable t) {
            LOG.ignore(t);
          }
        }
        break;
      case CONNECTED:
        // notify session listeners
        for (SessionListener listener : sessionListeners) {
          try {
            if (LOG.isDebugEnabled())
              LOG.debug("{}.onSessionOpen()", listener.getClass().getSimpleName());
            listener.onSessionOpened(this);
          } catch (Throwable t) {
            LOG.ignore(t);
          }
        }
        break;
    }
  }
Esempio n. 2
0
  /**
   * Create MBean for Object. Attempts to create an MBean for the object by searching the package
   * and class name space. For example an object of the type
   *
   * <PRE>
   * class com.acme.MyClass extends com.acme.util.BaseClass implements com.acme.Iface
   * </PRE>
   *
   * Then this method would look for the following classes:
   *
   * <UL>
   *   <LI>com.acme.jmx.MyClassMBean
   *   <LI>com.acme.util.jmx.BaseClassMBean
   *   <LI>org.eclipse.jetty.jmx.ObjectMBean
   * </UL>
   *
   * @param o The object
   * @return A new instance of an MBean for the object or null.
   */
  public static Object mbeanFor(Object o) {
    try {
      Class oClass = o.getClass();
      Object mbean = null;

      while (mbean == null && oClass != null) {
        String pName = oClass.getPackage().getName();
        String cName = oClass.getName().substring(pName.length() + 1);
        String mName = pName + ".jmx." + cName + "MBean";

        try {
          Class mClass =
              (Object.class.equals(oClass))
                  ? oClass = ObjectMBean.class
                  : Loader.loadClass(oClass, mName, true);
          if (LOG.isDebugEnabled()) LOG.debug("mbeanFor " + o + " mClass=" + mClass);

          try {
            Constructor constructor = mClass.getConstructor(OBJ_ARG);
            mbean = constructor.newInstance(new Object[] {o});
          } catch (Exception e) {
            LOG.ignore(e);
            if (ModelMBean.class.isAssignableFrom(mClass)) {
              mbean = mClass.newInstance();
              ((ModelMBean) mbean).setManagedResource(o, "objectReference");
            }
          }

          if (LOG.isDebugEnabled()) LOG.debug("mbeanFor " + o + " is " + mbean);
          return mbean;
        } catch (ClassNotFoundException e) {
          // The code below was modified to fix bugs 332200 and JETTY-1416
          // The issue was caused by additional information added to the
          // message after the class name when running in Apache Felix,
          // as well as before the class name when running in JBoss.
          if (e.getMessage().contains(mName)) LOG.ignore(e);
          else LOG.warn(e);
        } catch (Error e) {
          LOG.warn(e);
          mbean = null;
        } catch (Exception e) {
          LOG.warn(e);
          mbean = null;
        }

        oClass = oClass.getSuperclass();
      }
    } catch (Exception e) {
      LOG.ignore(e);
    }
    return null;
  }
 @Override
 public void shutdown() {
   // loop over all the sessions in memory (a few times if necessary to catch sessions that have
   // been
   // added while we're running
   int loop = 100;
   while (!_sessions.isEmpty() && loop-- > 0) {
     for (Session session : _sessions.values()) {
       // if we have a backing store and the session is dirty make sure it is written out
       if (_sessionDataStore != null) {
         if (session.getSessionData().isDirty()) {
           session.willPassivate();
           try {
             _sessionDataStore.store(session.getId(), session.getSessionData());
           } catch (Exception e) {
             LOG.warn(e);
           }
         }
         doDelete(session.getId()); // remove from memory
       } else {
         // not preserving sessions on exit
         try {
           session.invalidate();
         } catch (Exception e) {
           LOG.ignore(e);
         }
       }
     }
   }
 }
    @Override
    public URL[] getURLs() {
      Set<URL> urls = new HashSet<URL>();

      // convert urls from antLoader
      String[] paths =
          antLoader.getClasspath().split(new String(new char[] {File.pathSeparatorChar}));
      if (paths != null) {
        for (String p : paths) {
          File f = new File(p);
          try {
            urls.add(f.toURI().toURL());
          } catch (Exception e) {
            LOG.ignore(e);
          }
        }
      }

      // add in any that may have been added to us as a URL directly
      URL[] ourURLS = super.getURLs();
      if (ourURLS != null) {
        for (URL u : ourURLS) urls.add(u);
      }

      return urls.toArray(new URL[urls.size()]);
    }
Esempio n. 5
0
 public void receive() {
   EndPoint endPoint = connection.getEndPoint();
   HttpClient client = connection.getHttpClient();
   ByteBufferPool bufferPool = client.getByteBufferPool();
   ByteBuffer buffer = bufferPool.acquire(client.getResponseBufferSize(), true);
   try {
     while (true) {
       // Connection may be closed in a parser callback
       if (connection.isClosed()) {
         LOG.debug("{} closed", connection);
         break;
       } else {
         int read = endPoint.fill(buffer);
         LOG.debug("Read {} bytes from {}", read, connection);
         if (read > 0) {
           parse(buffer);
         } else if (read == 0) {
           fillInterested();
           break;
         } else {
           shutdown();
           break;
         }
       }
     }
   } catch (EofException x) {
     LOG.ignore(x);
     failAndClose(x);
   } catch (Exception x) {
     LOG.debug(x);
     failAndClose(x);
   } finally {
     bufferPool.release(buffer);
   }
 }
Esempio n. 6
0
 private void close(Closeable resource) {
   try {
     resource.close();
   } catch (Throwable x) {
     LOG.ignore(x);
   }
 }
Esempio n. 7
0
 protected void stopScheduler() {
   try {
     _scheduler.stop();
   } catch (Exception x) {
     LOG.ignore(x);
   }
 }
 /* ------------------------------------------------------------ */
 public void close() {
   try {
     _generator.flush();
     _endp.close();
   } catch (IOException e) {
     LOG.ignore(e);
   }
 }
 @Override
 public void close() {
   try {
     if (iterator instanceof Closeable) ((Closeable) iterator).close();
   } catch (Exception x) {
     LOG.ignore(x);
   }
 }
 @Override
 public void close() {
   try {
     if (LOG.isDebugEnabled()) LOG.debug("Closing {}", this);
     channel.close();
   } catch (IOException x) {
     LOG.ignore(x);
   }
 }
Esempio n. 11
0
 private void stopRegistry() {
   if (_registry != null) {
     try {
       UnicastRemoteObject.unexportObject(_registry, true);
     } catch (Exception ex) {
       LOG.ignore(ex);
     }
   }
 }
Esempio n. 12
0
  public static Object call(Class<?> oClass, String methodName, Object obj, Object[] arg)
      throws InvocationTargetException, NoSuchMethodException {
    Objects.requireNonNull(oClass, "Class cannot be null");
    Objects.requireNonNull(methodName, "Method name cannot be null");
    if (StringUtil.isBlank(methodName)) {
      throw new IllegalArgumentException("Method name cannot be blank");
    }

    // Lets just try all methods for now
    for (Method method : oClass.getMethods()) {
      if (!method.getName().equals(methodName)) continue;
      if (method.getParameterTypes().length != arg.length) continue;
      if (Modifier.isStatic(method.getModifiers()) != (obj == null)) continue;
      if ((obj == null) && method.getDeclaringClass() != oClass) continue;

      try {
        return method.invoke(obj, arg);
      } catch (IllegalAccessException | IllegalArgumentException e) {
        LOG.ignore(e);
      }
    }

    // Lets look for a method with optional arguments
    Object[] args_with_opts = null;

    for (Method method : oClass.getMethods()) {
      if (!method.getName().equals(methodName)) continue;
      if (method.getParameterTypes().length != arg.length + 1) continue;
      if (!method.getParameterTypes()[arg.length].isArray()) continue;
      if (Modifier.isStatic(method.getModifiers()) != (obj == null)) continue;
      if ((obj == null) && method.getDeclaringClass() != oClass) continue;

      if (args_with_opts == null)
        args_with_opts = ArrayUtil.addToArray(arg, new Object[] {}, Object.class);
      try {
        return method.invoke(obj, args_with_opts);
      } catch (IllegalAccessException | IllegalArgumentException e) {
        LOG.ignore(e);
      }
    }

    throw new NoSuchMethodException(methodName);
  }
Esempio n. 13
0
  public static Object construct(
      Class<?> klass, Object[] arguments, Map<String, Object> namedArgMap)
      throws InvocationTargetException, NoSuchMethodException {
    Objects.requireNonNull(klass, "Class cannot be null");
    Objects.requireNonNull(namedArgMap, "Named Argument Map cannot be null");

    for (Constructor<?> constructor : klass.getConstructors()) {
      if (arguments == null) {
        // null arguments in .newInstance() is allowed
        if (constructor.getParameterTypes().length != 0) continue;
      } else if (constructor.getParameterTypes().length != arguments.length) continue;

      try {
        Annotation[][] parameterAnnotations = constructor.getParameterAnnotations();

        if (arguments == null || arguments.length == 0) {
          if (LOG.isDebugEnabled()) LOG.debug("Constructor has no arguments");
          return constructor.newInstance(arguments);
        } else if (parameterAnnotations == null || parameterAnnotations.length == 0) {
          if (LOG.isDebugEnabled()) LOG.debug("Constructor has no parameter annotations");
          return constructor.newInstance(arguments);
        } else {
          Object[] swizzled = new Object[arguments.length];

          int count = 0;
          for (Annotation[] annotations : parameterAnnotations) {
            for (Annotation annotation : annotations) {
              if (annotation instanceof Name) {
                Name param = (Name) annotation;

                if (namedArgMap.containsKey(param.value())) {
                  if (LOG.isDebugEnabled())
                    LOG.debug("placing named {} in position {}", param.value(), count);
                  swizzled[count] = namedArgMap.get(param.value());
                } else {
                  if (LOG.isDebugEnabled())
                    LOG.debug("placing {} in position {}", arguments[count], count);
                  swizzled[count] = arguments[count];
                }
                ++count;
              } else {
                if (LOG.isDebugEnabled()) LOG.debug("passing on annotation {}", annotation);
              }
            }
          }

          return constructor.newInstance(swizzled);
        }

      } catch (InstantiationException | IllegalAccessException | IllegalArgumentException e) {
        LOG.ignore(e);
      }
    }
    throw new NoSuchMethodException("<init>");
  }
  @Override
  public Resource getResource(String uriInContext) throws MalformedURLException {
    Resource resource = null;
    // Try to get regular resource
    resource = super.getResource(uriInContext);

    // If no regular resource exists check for access to /WEB-INF/lib or /WEB-INF/classes
    if ((resource == null || !resource.exists()) && uriInContext != null && _classes != null) {
      String uri = URIUtil.canonicalPath(uriInContext);
      if (uri == null) return null;

      try {
        // Replace /WEB-INF/classes with candidates for the classpath
        if (uri.startsWith(WEB_INF_CLASSES_PREFIX)) {
          if (uri.equalsIgnoreCase(WEB_INF_CLASSES_PREFIX)
              || uri.equalsIgnoreCase(WEB_INF_CLASSES_PREFIX + "/")) {
            // exact match for a WEB-INF/classes, so preferentially return the resource matching the
            // web-inf classes
            // rather than the test classes
            if (_classes != null) return Resource.newResource(_classes);
            else if (_testClasses != null) return Resource.newResource(_testClasses);
          } else {
            // try matching
            Resource res = null;
            int i = 0;
            while (res == null && (i < _webInfClasses.size())) {
              String newPath = uri.replace(WEB_INF_CLASSES_PREFIX, _webInfClasses.get(i).getPath());
              res = Resource.newResource(newPath);
              if (!res.exists()) {
                res = null;
                i++;
              }
            }
            return res;
          }
        } else if (uri.startsWith(WEB_INF_LIB_PREFIX)) {
          // Return the real jar file for all accesses to
          // /WEB-INF/lib/*.jar
          String jarName = uri.replace(WEB_INF_LIB_PREFIX, "");
          if (jarName.startsWith("/") || jarName.startsWith("\\")) jarName = jarName.substring(1);
          if (jarName.length() == 0) return null;
          File jarFile = _webInfJarMap.get(jarName);
          if (jarFile != null) return Resource.newResource(jarFile.getPath());

          return null;
        }
      } catch (MalformedURLException e) {
        throw e;
      } catch (IOException e) {
        LOG.ignore(e);
      }
    }
    return resource;
  }
Esempio n. 15
0
  /**
   * Convert String value to instance.
   *
   * @param type The class of the instance, which may be a primitive TYPE field.
   * @param value The value as a string.
   * @return The value as an Object.
   */
  public static Object valueOf(Class<?> type, String value) {
    try {
      if (type.equals(java.lang.String.class)) return value;

      Method m = class2Value.get(type);
      if (m != null) return m.invoke(null, value);

      if (type.equals(java.lang.Character.TYPE) || type.equals(java.lang.Character.class))
        return value.charAt(0);

      Constructor<?> c = type.getConstructor(java.lang.String.class);
      return c.newInstance(value);
    } catch (NoSuchMethodException | IllegalAccessException | InstantiationException x) {
      LOG.ignore(x);
    } catch (InvocationTargetException x) {
      if (x.getTargetException() instanceof Error) throw (Error) x.getTargetException();
      LOG.ignore(x);
    }
    return null;
  }
Esempio n. 16
0
 /** Close an existing connection */
 private void closeConnection() {
   if (_con != null) {
     if (LOG.isDebugEnabled()) LOG.debug("Closing db connection for JDBCUserRealm");
     try {
       _con.close();
     } catch (Exception e) {
       LOG.ignore(e);
     }
   }
   _con = null;
 }
Esempio n. 17
0
    protected void invokeObject(Object obj, Object value)
        throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {

      if (_type.isEnum()) {
        if (value instanceof Enum) _setter.invoke(obj, new Object[] {value});
        else
          _setter.invoke(
              obj, new Object[] {Enum.valueOf((Class<? extends Enum>) _type, value.toString())});
      } else if (_numberType != null && value instanceof Number) {
        _setter.invoke(obj, new Object[] {_numberType.getActualValue((Number) value)});
      } else if (Character.TYPE.equals(_type) || Character.class.equals(_type)) {
        _setter.invoke(obj, new Object[] {String.valueOf(value).charAt(0)});
      } else if (_componentType != null && value.getClass().isArray()) {
        if (_numberType == null) {
          int len = Array.getLength(value);
          Object array = Array.newInstance(_componentType, len);
          try {
            System.arraycopy(value, 0, array, 0, len);
          } catch (Exception e) {
            // unusual array with multiple types
            LOG.ignore(e);
            _setter.invoke(obj, new Object[] {value});
            return;
          }
          _setter.invoke(obj, new Object[] {array});
        } else {
          Object[] old = (Object[]) value;
          Object array = Array.newInstance(_componentType, old.length);
          try {
            for (int i = 0; i < old.length; i++)
              Array.set(array, i, _numberType.getActualValue((Number) old[i]));
          } catch (Exception e) {
            // unusual array with multiple types
            LOG.ignore(e);
            _setter.invoke(obj, new Object[] {value});
            return;
          }
          _setter.invoke(obj, new Object[] {array});
        }
      } else _setter.invoke(obj, new Object[] {value});
    }
Esempio n. 18
0
  private void ack(SipResponse response) {
    SipRequest ack = _request.createRequest(SipMethod.ACK);

    if (ack.to().getTag() == null) {
      String tag = response.to().getTag();
      if (tag != null) ack.to().setParameter(AddressImpl.TAG, tag);
    }
    try {
      getServer().sendRequest(ack, getConnection());
    } catch (IOException e) {
      LOG.ignore(e);
    }
  }
  public String normalizePath(Path path) {
    for (PathAttribute attr : attributes) {
      if (attr.path == null) continue;

      try {
        if (path.startsWith(attr.path)
            || path.equals(attr.path)
            || Files.isSameFile(path, attr.path)) {
          return URIUtil.addPaths("${" + attr.key + "}", attr.path.relativize(path).toString());
        }
      } catch (IOException ignore) {
        LOG.ignore(ignore);
      }
    }

    return path.toString();
  }
Esempio n. 20
0
  /* ------------------------------------------------------------ */
  private List<String> listEntries() {
    checkConnection();

    ArrayList<String> list = new ArrayList<String>(32);
    JarFile jarFile = _jarFile;
    if (jarFile == null) {
      try {
        JarURLConnection jc = (JarURLConnection) ((new URL(_jarUrl)).openConnection());
        jc.setUseCaches(getUseCaches());
        jarFile = jc.getJarFile();
      } catch (Exception e) {

        e.printStackTrace();
        LOG.ignore(e);
      }
      if (jarFile == null) throw new IllegalStateException();
    }

    Enumeration e = jarFile.entries();
    String dir = _urlString.substring(_urlString.indexOf("!/") + 2);
    while (e.hasMoreElements()) {

      JarEntry entry = (JarEntry) e.nextElement();
      String name = entry.getName().replace('\\', '/');
      if (!name.startsWith(dir) || name.length() == dir.length()) {
        continue;
      }
      String listName = name.substring(dir.length());
      int dash = listName.indexOf('/');
      if (dash >= 0) {
        // when listing jar:file urls, you get back one
        // entry for the dir itself, which we ignore
        if (dash == 0 && listName.length() == 1) continue;
        // when listing jar:file urls, all files and
        // subdirs have a leading /, which we remove
        if (dash == 0) listName = listName.substring(dash + 1, listName.length());
        else listName = listName.substring(0, dash + 1);

        if (list.contains(listName)) continue;
      }

      list.add(listName);
    }

    return list;
  }
Esempio n. 21
0
  public static Object construct(Class<?> klass, Object[] arguments)
      throws InvocationTargetException, NoSuchMethodException {
    Objects.requireNonNull(klass, "Class cannot be null");

    for (Constructor<?> constructor : klass.getConstructors()) {
      if (arguments == null) {
        // null arguments in .newInstance() is allowed
        if (constructor.getParameterTypes().length != 0) continue;
      } else if (constructor.getParameterTypes().length != arguments.length) continue;

      try {
        return constructor.newInstance(arguments);
      } catch (InstantiationException | IllegalAccessException | IllegalArgumentException e) {
        LOG.ignore(e);
      }
    }
    throw new NoSuchMethodException("<init>");
  }
Esempio n. 22
0
  @Override
  public boolean startRequest(
      HttpMethod httpMethod, String method, ByteBuffer uri, HttpVersion version) {
    _expect = false;
    _expect100Continue = false;
    _expect102Processing = false;

    if (_request.getTimeStamp() == 0) _request.setTimeStamp(System.currentTimeMillis());
    _request.setMethod(httpMethod, method);

    if (httpMethod == HttpMethod.CONNECT)
      _uri.parseConnect(uri.array(), uri.arrayOffset() + uri.position(), uri.remaining());
    else _uri.parse(uri.array(), uri.arrayOffset() + uri.position(), uri.remaining());
    _request.setUri(_uri);

    String path;
    try {
      path = _uri.getDecodedPath();
    } catch (Exception e) {
      LOG.warn("Failed UTF-8 decode for request path, trying ISO-8859-1");
      LOG.ignore(e);
      path = _uri.getDecodedPath(StandardCharsets.ISO_8859_1);
    }

    String info = URIUtil.canonicalPath(path);

    if (info == null) {
      if (path == null && _uri.getScheme() != null && _uri.getHost() != null) {
        info = "/";
        _request.setRequestURI("");
      } else {
        badMessage(400, null);
        return true;
      }
    }
    _request.setPathInfo(info);
    _version = version == null ? HttpVersion.HTTP_0_9 : version;
    _request.setHttpVersion(_version);

    return false;
  }
Esempio n. 23
0
  /* ------------------------------------------------------------ */
  public int checkNonce(String nonce, long timestamp) {
    try {
      byte[] n = B64Code.decode(nonce.toCharArray());
      if (n.length != 24) return -1;

      long ts = 0;
      long sk = nonceSecret;
      byte[] n2 = new byte[16];
      System.arraycopy(n, 0, n2, 0, 8);
      for (int i = 0; i < 8; i++) {
        n2[8 + i] = (byte) (sk & 0xff);
        sk = sk >> 8;
        ts = (ts << 8) + (0xff & (long) n[7 - i]);
      }

      long age = timestamp - ts;
      if (LOG.isDebugEnabled()) LOG.debug("age=" + age);

      byte[] hash = null;
      try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.reset();
        md.update(n2, 0, 16);
        hash = md.digest();
      } catch (Exception e) {
        LOG.warn(e);
      }

      for (int i = 0; i < 16; i++) if (n[i + 8] != hash[i]) return -1;

      if (maxNonceAge > 0 && (age < 0 || age > maxNonceAge)) return 0; // stale

      return 1;
    } catch (Exception e) {
      LOG.ignore(e);
    }
    return -1;
  }
Esempio n. 24
0
  /**
   * Check that local RMI registry is used, and ensure it is started. If local RMI registry is being
   * used and not started, start it.
   *
   * @param hostPath hostname and port number of RMI registry
   * @throws Exception
   */
  private String startRegistry(String hostPath) throws Exception {
    int rmiPort = 1099; // default RMI registry port
    String rmiHost = hostPath;

    int idx = hostPath.indexOf(':');
    if (idx > 0) {
      rmiPort = Integer.parseInt(hostPath.substring(idx + 1));
      rmiHost = hostPath.substring(0, idx);
    }

    // Verify that local registry is being used
    InetAddress hostAddress = InetAddress.getByName(rmiHost);
    if (hostAddress.isLoopbackAddress()) {
      if (rmiPort == 0) {
        ServerSocket socket = new ServerSocket(0);
        rmiPort = socket.getLocalPort();
        socket.close();
      } else {
        try {
          // Check if a local registry is already running
          LocateRegistry.getRegistry(rmiPort).list();
          return null;
        } catch (Exception ex) {
          LOG.ignore(ex);
        }
      }

      _registry = LocateRegistry.createRegistry(rmiPort);
      Thread.sleep(1000);

      rmiHost = InetAddress.getLocalHost().getCanonicalHostName();
      return rmiHost + ':' + Integer.toString(rmiPort);
    }

    return null;
  }
  /* ------------------------------------------------------------ */
  public Connection handle() throws IOException {
    try {
      // handle stupid hixie random bytes
      if (_hixieBytes != null) {

        // take any available bytes from the parser buffer, which may have already been read
        Buffer buffer = _parser.getBuffer();
        if (buffer != null && buffer.length() > 0) {
          int l = buffer.length();
          if (l > (8 - _hixieBytes.length())) l = 8 - _hixieBytes.length();
          _hixieBytes.put(buffer.peek(buffer.getIndex(), l));
          buffer.skip(l);
        }

        // while we are not blocked
        while (_endp.isOpen()) {
          // do we now have enough
          if (_hixieBytes.length() == 8) {
            // we have the silly random bytes
            // so let's work out the stupid 16 byte reply.
            doTheHixieHixieShake();
            _endp.flush(_hixieBytes);
            _hixieBytes = null;
            _endp.flush();
            break;
          }

          // no, then let's fill
          int filled = _endp.fill(_hixieBytes);
          if (filled < 0) {
            _endp.flush();
            _endp.close();
            break;
          }
        }

        if (_websocket instanceof OnFrame) ((OnFrame) _websocket).onHandshake(this);
        _websocket.onOpen(this);
        return this;
      }

      // handle the framing protocol
      boolean progress = true;

      while (progress) {
        int flushed = _generator.flush();
        int filled = _parser.parseNext();

        progress = flushed > 0 || filled > 0;

        _endp.flush();

        if (_endp instanceof AsyncEndPoint && ((AsyncEndPoint) _endp).hasProgressed())
          progress = true;
      }
    } catch (IOException e) {
      LOG.debug(e);
      try {
        if (_endp.isOpen()) _endp.close();
      } catch (IOException e2) {
        LOG.ignore(e2);
      }
      throw e;
    } finally {
      if (_endp.isOpen()) {
        if (_endp.isInputShutdown() && _generator.isBufferEmpty()) _endp.close();
        else checkWriteable();

        checkWriteable();
      }
    }
    return this;
  }
Esempio n. 26
0
  private boolean handleKnownHeaders(ByteBuffer buffer) {
    boolean add_to_connection_trie = false;
    switch (_header) {
      case CONTENT_LENGTH:
        if (_endOfContent != EndOfContent.CHUNKED_CONTENT) {
          try {
            _contentLength = Long.parseLong(_valueString);
          } catch (NumberFormatException e) {
            LOG.ignore(e);
            throw new BadMessage(HttpStatus.BAD_REQUEST_400, "Bad Content-Length");
          }
          if (_contentLength <= 0) _endOfContent = EndOfContent.NO_CONTENT;
          else _endOfContent = EndOfContent.CONTENT_LENGTH;
        }
        break;

      case TRANSFER_ENCODING:
        if (_value == HttpHeaderValue.CHUNKED) _endOfContent = EndOfContent.CHUNKED_CONTENT;
        else {
          if (_valueString.endsWith(HttpHeaderValue.CHUNKED.toString()))
            _endOfContent = EndOfContent.CHUNKED_CONTENT;
          else if (_valueString.indexOf(HttpHeaderValue.CHUNKED.toString()) >= 0) {
            throw new BadMessage(HttpStatus.BAD_REQUEST_400, "Bad chunking");
          }
        }
        break;

      case HOST:
        add_to_connection_trie = _connectionFields != null && _field == null;
        _host = true;
        String host = _valueString;
        int port = 0;
        if (host == null || host.length() == 0) {
          throw new BadMessage(HttpStatus.BAD_REQUEST_400, "Bad Host header");
        }

        int len = host.length();
        loop:
        for (int i = len; i-- > 0; ) {
          char c2 = (char) (0xff & host.charAt(i));
          switch (c2) {
            case ']':
              break loop;

            case ':':
              try {
                len = i;
                port = StringUtil.toInt(host.substring(i + 1));
              } catch (NumberFormatException e) {
                if (DEBUG) LOG.debug(e);
                throw new BadMessage(HttpStatus.BAD_REQUEST_400, "Bad Host header");
              }
              break loop;
          }
        }
        if (host.charAt(0) == '[') {
          if (host.charAt(len - 1) != ']') {
            throw new BadMessage(HttpStatus.BAD_REQUEST_400, "Bad IPv6 Host header");
          }
          host = host.substring(1, len - 1);
        } else if (len != host.length()) host = host.substring(0, len);

        if (_requestHandler != null) _requestHandler.parsedHostHeader(host, port);

        break;

      case CONNECTION:
        // Don't cache if not persistent
        if (_valueString != null && _valueString.indexOf("close") >= 0) {
          _closed = true;
          _connectionFields = null;
        }
        break;

      case AUTHORIZATION:
      case ACCEPT:
      case ACCEPT_CHARSET:
      case ACCEPT_ENCODING:
      case ACCEPT_LANGUAGE:
      case COOKIE:
      case CACHE_CONTROL:
      case USER_AGENT:
        add_to_connection_trie = _connectionFields != null && _field == null;
        break;

      default:
        break;
    }

    if (add_to_connection_trie
        && !_connectionFields.isFull()
        && _header != null
        && _valueString != null) {
      _field = new HttpField(_header, _valueString);
      _connectionFields.put(_field);
    }

    return false;
  }
Esempio n. 27
0
  /** Returns true if the represented resource exists. */
  @Override
  public boolean exists() {
    if (_exists) return true;

    if (_urlString.endsWith("!/")) {

      String file_url = _urlString.substring(4, _urlString.length() - 2);
      try {
        return newResource(file_url).exists();
      } catch (Exception e) {
        LOG.ignore(e);
        return false;
      }
    }

    boolean check = checkConnection();

    // Is this a root URL?
    if (_jarUrl != null && _path == null) {
      // Then if it exists it is a directory
      _directory = check;
      return true;
    } else {
      // Can we find a file for it?
      JarFile jarFile = null;
      if (check)
        // Yes
        jarFile = _jarFile;
      else {
        // No - so lets look if the root entry exists.
        try {
          JarURLConnection c = (JarURLConnection) ((new URL(_jarUrl)).openConnection());
          c.setUseCaches(getUseCaches());
          jarFile = c.getJarFile();
        } catch (Exception e) {
          LOG.ignore(e);
        }
      }

      // Do we need to look more closely?
      if (jarFile != null && _entry == null && !_directory) {
        // OK - we have a JarFile, lets look at the entries for our path
        Enumeration<JarEntry> e = jarFile.entries();
        while (e.hasMoreElements()) {
          JarEntry entry = e.nextElement();
          String name = entry.getName().replace('\\', '/');

          // Do we have a match
          if (name.equals(_path)) {
            _entry = entry;
            // Is the match a directory
            _directory = _path.endsWith("/");
            break;
          } else if (_path.endsWith("/")) {
            if (name.startsWith(_path)) {
              _directory = true;
              break;
            }
          } else if (name.startsWith(_path)
              && name.length() > _path.length()
              && name.charAt(_path.length()) == '/') {
            _directory = true;
            break;
          }
        }

        if (_directory && !_urlString.endsWith("/")) {
          _urlString += "/";
          try {
            _url = new URL(_urlString);
          } catch (MalformedURLException ex) {
            LOG.warn(ex);
          }
        }
      }
    }

    _exists = (_directory || _entry != null);
    return _exists;
  }
Esempio n. 28
0
  /* ------------------------------------------------------------ */
  protected void handleRequest() throws IOException {
    boolean error = false;

    String threadName = null;
    try {
      if (LOG.isDebugEnabled()) {
        threadName = Thread.currentThread().getName();
        Thread.currentThread().setName(threadName + " - " + _uri);
      }

      // Loop here to handle async request redispatches.
      // The loop is controlled by the call to async.unhandle in the
      // finally block below.  If call is from a non-blocking connector,
      // then the unhandle will return false only if an async dispatch has
      // already happened when unhandle is called.   For a blocking connector,
      // the wait for the asynchronous dispatch or timeout actually happens
      // within the call to unhandle().

      final Server server = _server;
      boolean handling = _request._async.handling() && server != null && server.isRunning();
      while (handling) {
        _request.setHandled(false);

        String info = null;
        try {
          _uri.getPort();
          info = URIUtil.canonicalPath(_uri.getDecodedPath());
          if (info == null && !_request.getMethod().equals(HttpMethods.CONNECT))
            throw new HttpException(400);
          _request.setPathInfo(info);

          if (_out != null) _out.reopen();

          if (_request._async.isInitial()) {
            _request.setDispatcherType(DispatcherType.REQUEST);
            _connector.customize(_endp, _request);
            server.handle(this);
          } else {
            _request.setDispatcherType(DispatcherType.ASYNC);
            server.handleAsync(this);
          }
        } catch (ContinuationThrowable e) {
          LOG.ignore(e);
        } catch (EofException e) {
          LOG.debug(e);
          error = true;
          _request.setHandled(true);
        } catch (RuntimeIOException e) {
          LOG.debug(e);
          error = true;
          _request.setHandled(true);
        } catch (HttpException e) {
          LOG.debug(e);
          error = true;
          _request.setHandled(true);
          _response.sendError(e.getStatus(), e.getReason());
        } catch (Throwable e) {
          if (e instanceof ThreadDeath) throw (ThreadDeath) e;

          LOG.warn(String.valueOf(_uri), e);
          error = true;
          _request.setHandled(true);
          _generator.sendError(info == null ? 400 : 500, null, null, true);
        } finally {
          handling = !_request._async.unhandle() && server.isRunning() && _server != null;
        }
      }
    } finally {
      if (threadName != null) Thread.currentThread().setName(threadName);

      if (_request._async.isUncompleted()) {
        _request._async.doComplete();

        if (_expect100Continue) {
          LOG.debug("100 continues not sent");
          // We didn't send 100 continues, but the latest interpretation
          // of the spec (see httpbis) is that the client will either
          // send the body anyway, or close.  So we no longer need to
          // do anything special here other than make the connection not persistent
          _expect100Continue = false;
          if (!_response.isCommitted()) _generator.setPersistent(false);
        }

        if (_endp.isOpen()) {
          if (error) {
            _endp.shutdownOutput();
            _generator.setPersistent(false);
            if (!_generator.isComplete()) _response.complete();
          } else {
            if (!_response.isCommitted() && !_request.isHandled())
              _response.sendError(HttpServletResponse.SC_NOT_FOUND);
            _response.complete();
            if (_generator.isPersistent()) _connector.persist(_endp);
          }
        } else {
          _response.complete();
        }

        _request.setHandled(true);
      }
    }
  }
Esempio n. 29
0
  /**
   * Get a temporary directory in which to unpack the war etc etc. The algorithm for determining
   * this is to check these alternatives in the order shown:
   *
   * <p>A. Try to use an explicit directory specifically for this webapp:
   *
   * <ol>
   *   <li>Iff an explicit directory is set for this webapp, use it. Do NOT set delete on exit.
   *   <li>Iff javax.servlet.context.tempdir context attribute is set for this webapp && exists &&
   *       writeable, then use it. Do NOT set delete on exit.
   * </ol>
   *
   * <p>B. Create a directory based on global settings. The new directory will be called
   * "Jetty_"+host+"_"+port+"__"+context+"_"+virtualhost Work out where to create this directory:
   *
   * <ol>
   *   <li>Iff $(jetty.home)/work exists create the directory there. Do NOT set delete on exit. Do
   *       NOT delete contents if dir already exists.
   *   <li>Iff WEB-INF/work exists create the directory there. Do NOT set delete on exit. Do NOT
   *       delete contents if dir already exists.
   *   <li>Else create dir in $(java.io.tmpdir). Set delete on exit. Delete contents if dir already
   *       exists.
   * </ol>
   */
  public void resolveTempDirectory(WebAppContext context) {
    // If a tmp directory is already set, we're done
    File tmpDir = context.getTempDirectory();
    if (tmpDir != null && tmpDir.isDirectory() && tmpDir.canWrite()) {
      context.setAttribute(TEMPDIR_CONFIGURED, Boolean.TRUE);
      return; // Already have a suitable tmp dir configured
    }

    // No temp directory configured, try to establish one.
    // First we check the context specific, javax.servlet specified, temp directory attribute
    File servletTmpDir = asFile(context.getAttribute(WebAppContext.TEMPDIR));
    if (servletTmpDir != null && servletTmpDir.isDirectory() && servletTmpDir.canWrite()) {
      // Use as tmpDir
      tmpDir = servletTmpDir;
      // Ensure Attribute has File object
      context.setAttribute(WebAppContext.TEMPDIR, tmpDir);
      // Set as TempDir in context.
      context.setTempDirectory(tmpDir);
      return;
    }

    try {
      // Put the tmp dir in the work directory if we had one
      File work = new File(System.getProperty("jetty.home"), "work");
      if (work.exists() && work.canWrite() && work.isDirectory()) {
        makeTempDirectory(
            work, context, false); // make a tmp dir inside work, don't delete if it exists
      } else {
        File baseTemp = asFile(context.getAttribute(WebAppContext.BASETEMPDIR));
        if (baseTemp != null && baseTemp.isDirectory() && baseTemp.canWrite()) {
          // Use baseTemp directory (allow the funky Jetty_0_0_0_0.. subdirectory logic to kick in
          makeTempDirectory(baseTemp, context, false);
        } else {
          makeTempDirectory(
              new File(System.getProperty("java.io.tmpdir")),
              context,
              true); // make a tmpdir, delete if it already exists
        }
      }
    } catch (Exception e) {
      tmpDir = null;
      LOG.ignore(e);
    }

    // Third ... Something went wrong trying to make the tmp directory, just make
    // a jvm managed tmp directory
    if (context.getTempDirectory() == null) {
      try {
        // Last resort
        tmpDir = File.createTempFile("JettyContext", "");
        if (tmpDir.exists()) IO.delete(tmpDir);
        tmpDir.mkdir();
        tmpDir.deleteOnExit();
        context.setTempDirectory(tmpDir);
      } catch (IOException e) {
        tmpDir = null;
        throw new IllegalStateException(
            "Cannot create tmp dir in "
                + System.getProperty("java.io.tmpdir")
                + " for context "
                + context,
            e);
      }
    }
  }
Esempio n. 30
0
 /* ------------------------------------------------------------ */
 protected void log(Throwable t) {
   LOG.ignore(t);
 }