/* ------------------------------------------------------------ */
  protected void doStart() throws Exception {
    if (_server == null) throw new IllegalStateException("No server");

    // open listener port
    open();

    super.doStart();

    if (_threadPool == null) _threadPool = _server.getThreadPool();
    if (_threadPool != _server.getThreadPool() && (_threadPool instanceof LifeCycle))
      ((LifeCycle) _threadPool).start();

    // Start selector thread
    synchronized (this) {
      _acceptorThread = new Thread[getAcceptors()];

      for (int i = 0; i < _acceptorThread.length; i++) {
        if (!_threadPool.dispatch(new Acceptor(i))) {
          Log.warn("insufficient maxThreads configured for {}", this);
          break;
        }
      }
    }

    Log.info("Started {}", this);
  }
 public void removeState(State state) {
   try {
     synchronized (_sessions) {
       _sessions.remove(state.getId());
     }
   } catch (Exception e) {
     Log.warn("could not remove session", e);
   }
 }
  // clarify with Tomcat, whether this is on a per Session or SessionManager basis...
  public void setMaxInactiveInterval(int interval) {
    checkState();

    try {
      _state.setMaxInactiveInterval(interval);
    } catch (RemoteException e) {
      Log.warn("could not set MaxInactiveInterval", e);
    }
  }
 protected void setMessage(String message) {
   try {
     if (_formEncoded)
       setRequestContent(new ByteArrayBuffer("message=" + URLEncoder.encode(message, "utf-8")));
     else setRequestContent(new ByteArrayBuffer(message, "utf-8"));
   } catch (Exception e) {
     Log.warn(e);
   }
 }
 public void storeState(State state) {
   try {
     synchronized (_sessions) {
       _sessions.put(state.getId(), state);
     }
   } catch (Exception e) {
     Log.warn("could not store session");
   }
 }
 public boolean dispatch(Runnable job) {
   try {
     executor.execute(job);
     return true;
   } catch (RejectedExecutionException e) {
     Log.warn(e);
     return false;
   }
 }
  public long getCreationTime() throws IllegalStateException {
    checkState();

    try {
      return _state.getCreationTime();
    } catch (RemoteException e) {
      Log.warn("could not get CreationTime", e);
      throw new IllegalStateException("problem with distribution layer");
    }
  }
  public String[] getValueNames() throws IllegalStateException {
    checkState();

    try {
      return _state.getAttributeNameStringArray();
    } catch (RemoteException e) {
      Log.warn("could not get ValueNames", e);
      throw new IllegalStateException("problem with distribution layer");
    }
  }
  public Enumeration getAttributeNames() throws IllegalStateException {
    checkState();

    try {
      return _state.getAttributeNameEnumeration();
    } catch (RemoteException e) {
      Log.warn("could not get AttributeNames", e);
      throw new IllegalStateException("problem with distribution layer");
    }
  }
  public Object getValue(String name) throws IllegalStateException {
    checkState();

    try {
      return _state.getAttribute(name);
    } catch (RemoteException e) {
      Log.warn("could not get Value", e);
      throw new IllegalStateException("problem with distribution layer");
    }
  }
 @GET
 @Produces(MediaType.WILDCARD)
 public Response redirectToWebadmin() {
   try {
     return Response.seeOther(new URI(Configurator.DEFAULT_WEB_ADMIN_PATH)).build();
   } catch (URISyntaxException e) {
     Log.warn(e.getMessage());
     return Response.serverError().build();
   }
 }
 /* ------------------------------------------------------------ */
 protected void onConnectionFailed(Throwable ex) {
   super.onConnectionFailed(ex);
   if (++_connectFailures < 5) {
     try {
       _client.send(this);
     } catch (IOException e) {
       Log.warn(e);
     }
   }
 }
  public void removeValue(String name) throws IllegalStateException {
    checkState();

    try {
      _state.removeAttribute(name, false);
    } catch (RemoteException e) {
      Log.warn("could not remove Value", e);
      throw new IllegalStateException("problem with distribution layer");
    }
  }
  public void setLastAccessedTime(long time) throws IllegalStateException {
    checkState();

    try {
      _state.setLastAccessedTime(time);
    } catch (RemoteException e) {
      Log.warn("could not set LastAccessedTime", e);
      throw new IllegalStateException("problem with distribution layer");
    }
  }
  @Override
  public ApiResponse generateRequestResponse(ApiRequest request) throws Exception {
    ApiResponse response = new ApiResponse();

    // prevent spam
    UserEntry user = request.getUser();
    long businessesCreated = user.getStats().getBusinessesCreated();
    if (businessesCreated >= MAXIMUM_BUSINESS_CREATIONS) {
      Log.warn("Prevented business creation from user: "******"Spam prevention: You may not create any more businesses. Please contact us if you want to increase your quota."));
      return response;
    }

    String name = request.getParameter("name");
    String mail = request.getParameter("mail");
    boolean addQueue = request.getParameterAsBoolean("addQueue", false);

    // create the business
    BusinessEntry businessEntry = new BusinessEntry();
    businessEntry.setName(name);
    businessEntry.setMail(mail);
    Key businessKey = BusinessHelper.saveEntry(businessEntry);
    businessEntry.setKey(businessKey);

    // update user stats
    user.getStats().setBusinessesCreated(businessesCreated + 1);
    UserHelper.saveEntry(user);

    // add permission for business
    PermissionHelper.grantPermission(user, businessEntry, PermissionEntry.PERMISSION_OWN);

    if (addQueue) {
      // create a default queue
      QueueEntry queueEntry = new QueueEntry(businessKey.getId());
      queueEntry.parseFromRequest(request);

      Key queueKey = QueueHelper.saveEntry(queueEntry);
      queueEntry.setKey(queueKey);

      // add permission for queue
      PermissionHelper.grantPermission(
          request.getUser(), queueEntry, PermissionEntry.PERMISSION_OWN);

      // add the new queue to the business in order to return both as one response
      ArrayList<QueueEntry> queues = new ArrayList<QueueEntry>();
      queues.add(queueEntry);
      businessEntry.setQueues(queues);
    }

    response.setContent(businessEntry);
    return response;
  }
    Handshake() {
      super("handshake");
      setMessage(__HANDSHAKE);

      try {
        customize(this);
        _client.send(this);
      } catch (IOException e) {
        Log.warn(e);
      }
    }
    /* ------------------------------------------------------------ */
    public void run() {
      Thread current = Thread.currentThread();
      String name;
      synchronized (AbstractConnector.this) {
        if (_acceptorThread == null) return;

        _acceptorThread[_acceptor] = current;
        name = _acceptorThread[_acceptor].getName();
        current.setName(name + " - Acceptor" + _acceptor + " " + AbstractConnector.this);
      }
      int old_priority = current.getPriority();

      try {
        current.setPriority(old_priority - _acceptorPriorityOffset);
        while (isRunning() && getConnection() != null) {
          try {
            accept(_acceptor);
          } catch (EofException e) {
            Log.ignore(e);
          } catch (IOException e) {
            Log.ignore(e);
          } catch (ThreadDeath e) {
            throw e;
          } catch (Throwable e) {
            Log.warn(e);
          }
        }
      } finally {
        current.setPriority(old_priority);
        current.setName(name);
        try {
          if (_acceptor == 0) close();
        } catch (IOException e) {
          Log.warn(e);
        }

        synchronized (AbstractConnector.this) {
          if (_acceptorThread != null) _acceptorThread[_acceptor] = null;
        }
      }
    }
  public int getMaxInactiveInterval() {
    checkState();

    try {
      return _state.getMaxInactiveInterval();
    } catch (RemoteException e) {
      // Can I throw an exception of some type here - instead of
      // returning rubbish ? - TODO
      Log.warn("could not get MaxInactiveInterval", e);
      return 0;
    }
  }
 Publish() {
   super("publish");
   synchronized (_outQ) {
     if (_outQ.size() == 0) return;
     setMessages(_outQ);
     _outQ.clear();
   }
   try {
     customize(this);
     _client.send(this);
   } catch (IOException e) {
     Log.warn(e);
   }
 }
  public void putValue(String name, Object value) throws IllegalStateException {
    checkState();

    if (name == null) throw new IllegalArgumentException("invalid attribute name: " + name);

    if (value == null) throw new IllegalArgumentException("invalid attribute value: " + value);

    try {
      _state.setAttribute(name, value, false);
    } catch (RemoteException e) {
      Log.warn("could not put Value", e);
      throw new IllegalStateException("problem with distribution layer");
    }
  }
    protected void setMessages(List<Message> messages) {
      try {
        for (Message msg : messages) {
          msg.put(Bayeux.CLIENT_FIELD, _clientId);
        }
        String json = JSON.toString(messages);

        if (_formEncoded)
          setRequestContent(new ByteArrayBuffer("message=" + URLEncoder.encode(json, "utf-8")));
        else setRequestContent(new ByteArrayBuffer(json, "utf-8"));

      } catch (Exception e) {
        Log.warn(e);
      }
    }
  private AvailabilityView getView(Endpoint ep) {
    AvailabilityView view = null;
    List<AvailabilityView> views =
        _db.getResults(ep, AvailabilityView.class, AvailabilityView.SCHEMA$);
    if (views.size() != 1) {
      Log.warn("We have {} AvailabilityView, expected was 1", views.size());
    }
    if (views.size() == 0) {
      view = new AvailabilityView();
      view.setEndpoint(ep);
      _db.insert(view);

    } else {
      view = views.get(0);
    }
    return view;
  }
  // hmmmm...
  // why does Greg call this?
  // could it be compressed into a subsequent call ?
  public boolean isValid() {
    if (_state == null) return false;

    StateInterceptor si = (StateInterceptor) _state;
    si.setManager(_manager);
    si.setSession(this);

    try {
      _state.getLastAccessedTime(); // this should cause an interceptor/the session to check
      return true;
    } catch (IllegalStateException ignore) {
      return false;
    } catch (Exception e) {
      Log.warn("problem contacting HttpSession", e);
      return false;
    }
  }
 /**
  * Get a password. A password is obtained by trying
  *
  * <UL>
  *   <LI>Calling <Code>System.getProperty(realm,dft)</Code>
  *   <LI>Prompting for a password
  *   <LI>Using promptDft if nothing was entered.
  * </UL>
  *
  * @param realm The realm name for the password, used as a SystemProperty name.
  * @param dft The default password.
  * @param promptDft The default to use if prompting for the password.
  * @return Password
  */
 public static Password getPassword(String realm, String dft, String promptDft) {
   String passwd = System.getProperty(realm, dft);
   if (passwd == null || passwd.length() == 0) {
     try {
       System.out.print(
           realm + ((promptDft != null && promptDft.length() > 0) ? " [dft]" : "") + " : ");
       System.out.flush();
       byte[] buf = new byte[512];
       int len = System.in.read(buf);
       if (len > 0) passwd = new String(buf, 0, len).trim();
     } catch (IOException e) {
       Log.warn(Log.EXCEPTION, e);
     }
     if (passwd == null || passwd.length() == 0) passwd = promptDft;
   }
   return new Password(passwd);
 }
Exemple #25
0
  /**
   * Construct a resource from a string.
   *
   * @param resource A URL or filename.
   * @param useCaches controls URLConnection caching
   * @return A Resource object.
   */
  public static Resource newResource(String resource, boolean useCaches)
      throws MalformedURLException, IOException {
    URL url = null;
    try {
      // Try to format as a URL?
      url = new URL(resource);
    } catch (MalformedURLException e) {
      if (!resource.startsWith("ftp:")
          && !resource.startsWith("file:")
          && !resource.startsWith("jar:")) {
        try {
          // It's a file.
          if (resource.startsWith("./")) resource = resource.substring(2);

          File file = new File(resource).getCanonicalFile();
          url = file.toURI().toURL();

          URLConnection connection = url.openConnection();
          connection.setUseCaches(useCaches);
          FileResource fileResource = new FileResource(url, connection, file);
          return fileResource;
        } catch (Exception e2) {
          Log.debug(Log.EXCEPTION, e2);
          throw e;
        }
      } else {
        Log.warn("Bad Resource: " + resource);
        throw e;
      }
    }

    // Make sure that any special characters stripped really are ignorable.
    String nurl = url.toString();
    if (nurl.length() > 0
        && nurl.charAt(nurl.length() - 1) != resource.charAt(resource.length() - 1)) {
      if ((nurl.charAt(nurl.length() - 1) != '/'
              || nurl.charAt(nurl.length() - 2) != resource.charAt(resource.length() - 1))
          && (resource.charAt(resource.length() - 1) != '/'
              || resource.charAt(resource.length() - 2) != nurl.charAt(nurl.length() - 1))) {
        return new BadResource(url, "Trailing special characters stripped by URL in " + resource);
      }
    }
    return newResource(url);
  }
    Connect() {
      super("connect");
      String connect =
          "{"
              + "\"channel\":\"/meta/connect\","
              + "\"clientId\":\""
              + _clientId
              + "\","
              + "\"connectionType\":\"long-polling\""
              + "}";
      setMessage(connect);

      try {
        customize(this);
        _client.send(this);
      } catch (IOException e) {
        Log.warn(e);
      }
    }
  public SegmentPlaylist(
      HttpServletRequest req, Object mediaFile, String conversionId, String quality) {
    this.req = req;
    this.mediaFile = mediaFile;
    this.mediaFileId = MediaFileAPI.GetMediaFileID(mediaFile);
    this.segmentList = new ArrayList<Segment>();
    this.conversionId = conversionId;
    this.quality = quality;
    this.isFileCurrentlyRecording = MediaFileAPI.IsFileCurrentlyRecording(mediaFile);

    if (!this.isFileCurrentlyRecording) {
      createPlaylist();
    } else {
      // retry until there's at least one full segment recorded
      while (this.isFileCurrentlyRecording && segmentList.size() <= 1) {
        this.segmentList.clear();

        createPlaylist();

        long mediaFileSegmentDurationInMillis = MediaFileAPI.GetDurationForSegment(mediaFile, 0);
        long mediaFileSegmentDurationInSeconds =
            mediaFileSegmentDurationInMillis / 1000; // milliseconds to seconds

        if (this.isFileCurrentlyRecording
            && (mediaFileSegmentDurationInSeconds < SegmentPlaylist.TARGET_DURATION)) {
          try {
            // wait until we'll have a full first segment to return
            Thread.sleep(
                (SegmentPlaylist.TARGET_DURATION - mediaFileSegmentDurationInSeconds + 1) * 1000);
          } catch (InterruptedException e) {
            Log.warn(e.getMessage());
          }
        }

        this.isFileCurrentlyRecording = MediaFileAPI.IsFileCurrentlyRecording(mediaFile);
      }
    }
  }
Exemple #28
0
    Connect() {
      super("connect");
      String connect =
          "{"
              + "\"channel\":\"/meta/connect\","
              + "\"clientId\":\""
              + _clientId
              + "\","
              + "\"connectionType\":\"long-polling\"}";
      setMessage(connect);

      // original:\s
      // {"+"\"channel\":\"/meta/connect\","+"\"clientId\":\""+_clientId+"\","+"\"connectionType\":\"long-polling\""+"}
      // Grizzly: [{\"channel\": \"/meta/connect\",
      // \"clientId\":\""+_clientId+"\","+"\"connectionType\": \"long-polling\", \"id\": \"1\"}]
      // Grizzly with id:
      // "{"+"\"channel\":\"/meta/connect\","+"\"clientId\":\""+_clientId+"\","+"\"connectionType\":\"long-polling\","+"\"id\":\""+getNextMsgId()+"\"}";
      try {
        customize(this);
        _client.send(this);
      } catch (IOException e) {
        Log.warn(e);
      }
    }
  /* ------------------------------------------------------------ */
  protected void doStop() throws Exception {
    try {
      close();
    } catch (IOException e) {
      Log.warn(e);
    }

    if (_threadPool == _server.getThreadPool()) _threadPool = null;
    else if (_threadPool instanceof LifeCycle) ((LifeCycle) _threadPool).stop();

    super.doStop();

    Thread[] acceptors = null;
    synchronized (this) {
      acceptors = _acceptorThread;
      _acceptorThread = null;
    }
    if (acceptors != null) {
      for (int i = 0; i < acceptors.length; i++) {
        Thread thread = acceptors[i];
        if (thread != null) thread.interrupt();
      }
    }
  }
  @Override
  // Read the page header
  // -1: EOF
  // 1 - outside the <page> tag
  // 2 - just passed the <page> tag but outside the <title>
  // 3 - just passed the <title> tag
  // 4 - just passed the </title> tag but outside the <namespace>
  // 5 - just passed the <namespace>
  // 6 - just passed the </namespace> but outside the <id>
  // 7 - just passed the (page's) <id>
  // 8 - just passed the </id> tag but outside the <revision>
  // 9 - (optionally) just passed the <redirect>
  // 10 - just passed the (next) <revision>
  protected Ack readToPageHeader(RevisionHeader meta) throws IOException {
    int i = 0;
    int flag = 2;
    boolean skipped = false;
    int revOrRedirect = -1;
    try (DataOutputBuffer pageTitle = new DataOutputBuffer();
        DataOutputBuffer nsBuf = new DataOutputBuffer();
        DataOutputBuffer keyBuf = new DataOutputBuffer()) {

      while (true) {
        if (!fetchMore()) return Ack.EOF;
        while (hasData()) {
          byte b = nextByte();

          // when passing the namespace and we realize that
          // this is not an article, and that the option of skipping
          // non-article pages is on, we simply skip everything until
          // the closing </page>
          if (skipped) {
            if (flag >= 6) {
              Log.warn("Peculiar read after skipping namespace");
              /*
              if (b == END_PAGE[i]) {
              	i++;
              } else i = 0;
              if (i >= END_PAGE.length) {
              	return Ack.SKIPPED;
              } */
              return Ack.FAILED;
            } else return Ack.SKIPPED;
          }

          if (flag == 2) {
            if (b == START_TITLE[i]) {
              i++;
            } else i = 0;
            if (i >= START_TITLE.length) {
              flag = 3;
              i = 0;
            }
          }

          // put everything between <title></title> block into title
          else if (flag == 3) {
            if (b == END_TITLE[i]) {
              i++;
            } else i = 0;
            pageTitle.write(b);
            if (i >= END_TITLE.length) {
              flag = 4;
              String title =
                  new String(pageTitle.getData(), 0, pageTitle.getLength() - END_TITLE.length);
              meta.setPageTitle(title);
              pageTitle.reset();
              i = 0;
            }
          } else if (flag == 4) {
            if (b == START_NAMESPACE[i]) {
              i++;
            } else i = 0;
            if (i >= START_NAMESPACE.length) {
              flag = 5;
              i = 0;
            }
          } else if (flag == 5) {
            if (b == END_NAMESPACE[i]) {
              i++;
            } else i = 0;
            nsBuf.write(b);
            if (i >= END_NAMESPACE.length) {
              flag = 6;
              String nsStr =
                  new String(nsBuf.getData(), 0, nsBuf.getLength() - END_NAMESPACE.length);
              int ns = Integer.parseInt(nsStr);
              nsBuf.reset();
              if (ns != 0) {
                if (skipNonArticles) {
                  skipped = true;
                  meta.clear();
                  return Ack.SKIPPED;
                }
              }
              meta.setNamespace(ns);
              i = 0;
            }
          } else if (flag == 6) {
            if (b == START_ID[i]) {
              i++;
            } else i = 0;
            if (i >= START_ID.length) {
              flag = 7;
              i = 0;
            }
          }

          // put everything in outer <id></id> block into keyBuf
          else if (flag == 7) {
            if (b == END_ID[i]) {
              i++;
            } else i = 0;
            keyBuf.write(b);
            if (i >= END_ID.length) {
              flag = 8;
              String idStr = new String(keyBuf.getData(), 0, keyBuf.getLength() - END_ID.length);
              long pageId = Long.parseLong(idStr);
              meta.setPageId(pageId);
              i = 0;
            }
          } else if (flag == 8) {
            int curMatch = 0;
            if ((i < START_REVISION.length && b == START_REVISION[i])
                && (i < START_REDIRECT.length && b == START_REDIRECT[i])

                // subtle bug here: some tag names can overlap
                // multiple times
                && (revOrRedirect == 3 || revOrRedirect == -1)) {
              curMatch = 3;
            } else if (i < START_REVISION.length && b == START_REVISION[i] && revOrRedirect != 2) {
              curMatch = 1;
            } else if (i < START_REDIRECT.length && b == START_REDIRECT[i] && revOrRedirect != 1) {
              curMatch = 2;
            } else {
              curMatch = 0;
            }
            if (curMatch > 0 && (i == 0 || revOrRedirect == 3 || curMatch == revOrRedirect)) {
              i++;
              revOrRedirect = curMatch;
            } else i = 0;
            if ((revOrRedirect == 2 || revOrRedirect == 3) && i >= START_REDIRECT.length) {
              if (skipRedirect) {
                skipped = true;
                meta.clear();
                return Ack.SKIPPED;
              }
              revOrRedirect = -1;
              flag = 9;
              i = 0;
            } else if ((revOrRedirect == 1 || revOrRedirect == 3) && i >= START_REVISION.length) {
              flag = 10;
              revOrRedirect = -1;
              return Ack.PASSED_TO_NEXT_TAG;
            }
          } else if (flag == 9 && !skipRedirect) {
            if (b == START_REVISION[i]) {
              i++;
            } else i = 0;
            if (i >= START_REVISION.length) {
              flag = 10;
              return Ack.PASSED_TO_NEXT_TAG;
            }
          }
        }
      }
    }
  }