Ejemplo n.º 1
0
  @Override
  protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters)
      throws Exception {
    URI url = new URI(uri);

    // must use copy as each endpoint can have different options
    MailConfiguration config = getConfiguration().copy();

    // only configure if we have a url with a known protocol
    config.configure(url);
    configureAdditionalJavaMailProperties(config, parameters);

    MailEndpoint endpoint = new MailEndpoint(uri, this, config);
    endpoint.setContentTypeResolver(contentTypeResolver);
    setProperties(endpoint.getConfiguration(), parameters);

    Map<String, Object> sstParams =
        IntrospectionSupport.extractProperties(parameters, "searchTerm.");
    if (!sstParams.isEmpty()) {
      // use SimpleSearchTerm as POJO to store the configuration and then convert that to the actual
      // SearchTerm
      SimpleSearchTerm sst = new SimpleSearchTerm();
      setProperties(sst, sstParams);
      SearchTerm st = MailConverters.toSearchTerm(sst, getCamelContext().getTypeConverter());
      endpoint.setSearchTerm(st);
    }

    // sanity check that we know the mail server
    ObjectHelper.notEmpty(config.getHost(), "host");
    ObjectHelper.notEmpty(config.getProtocol(), "protocol");

    return endpoint;
  }
Ejemplo n.º 2
0
  public void register() throws Exception {
    ObjectHelper.notEmpty(alias, "alias", this);
    ObjectHelper.notEmpty(servletName, "servletName", this);

    HttpContext actualHttpContext =
        (httpContext == null) ? httpService.createDefaultHttpContext() : httpContext;
    final Dictionary<String, String> initParams = new Hashtable<String, String>();
    initParams.put("matchOnUriPrefix", matchOnUriPrefix ? "true" : "false");
    initParams.put("servlet-name", servletName);
    httpService.registerServlet(alias, servlet, initParams, actualHttpContext);
    alreadyRegistered = true;
  }
Ejemplo n.º 3
0
  protected void createJmxConnector(String host) throws IOException {
    ObjectHelper.notEmpty(serviceUrlPath, "serviceUrlPath");
    ObjectHelper.notNull(registryPort, "registryPort");

    try {
      registry = LocateRegistry.createRegistry(registryPort);
      LOG.debug("Created JMXConnector RMI registry on port {}", registryPort);
    } catch (RemoteException ex) {
      // The registry may had been created, we could get the registry instead
    }

    // must start with leading slash
    String path = serviceUrlPath.startsWith("/") ? serviceUrlPath : "/" + serviceUrlPath;
    // Create an RMI connector and start it
    final JMXServiceURL url;
    if (connectorPort > 0) {
      url =
          new JMXServiceURL(
              "service:jmx:rmi://"
                  + host
                  + ":"
                  + connectorPort
                  + "/jndi/rmi://"
                  + host
                  + ":"
                  + registryPort
                  + path);
    } else {
      url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + host + ":" + registryPort + path);
    }

    cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, server);

    // use async thread for starting the JMX Connector
    // (no need to use a thread pool or enlist in JMX as this thread is terminated when the JMX
    // connector has been started)
    String threadName =
        camelContext.getExecutorServiceManager().resolveThreadName("JMXConnector: " + url);
    Thread thread =
        getCamelContext()
            .getExecutorServiceManager()
            .newThread(
                threadName,
                new Runnable() {
                  public void run() {
                    try {
                      LOG.debug("Staring JMX Connector thread to listen at: {}", url);
                      cs.start();
                      LOG.info("JMX Connector thread started and listening at: {}", url);
                    } catch (IOException ioe) {
                      LOG.warn(
                          "Could not start JMXConnector thread at: "
                              + url
                              + ". JMX Connector not in use.",
                          ioe);
                    }
                  }
                });
    thread.start();
  }
  /**
   * Is the given file a done file?
   *
   * <p>This method should only be invoked if a done filename property has been set on this
   * endpoint.
   *
   * @param fileName the file name
   * @return <tt>true</tt> if its a done file, <tt>false</tt> otherwise
   */
  protected boolean isDoneFile(String fileName) {
    String pattern = getDoneFileName();
    ObjectHelper.notEmpty(pattern, "doneFileName", pattern);

    if (!SimpleLanguage.hasStartToken(pattern)) {
      // no tokens, so just match names directly
      return pattern.equals(fileName);
    }

    // the static part of the pattern, is that a prefix or suffix?
    // its a prefix if ${ start token is not at the start of the pattern
    boolean prefix = pattern.indexOf("${") > 0;

    // remove dynamic parts of the pattern so we only got the static part left
    pattern = pattern.replaceFirst("\\$\\{file:name\\}", "");
    pattern = pattern.replaceFirst("\\$simple\\{file:name\\}", "");
    pattern = pattern.replaceFirst("\\$\\{file:name.noext\\}", "");
    pattern = pattern.replaceFirst("\\$simple\\{file:name.noext\\}", "");

    // must be able to resolve all placeholders supported
    if (SimpleLanguage.hasStartToken(pattern)) {
      throw new ExpressionIllegalSyntaxException(
          fileName + ". Cannot resolve reminder: " + pattern);
    }

    if (prefix) {
      return fileName.startsWith(pattern);
    } else {
      return fileName.endsWith(pattern);
    }
  }
  /**
   * Creates the associated name of the done file based on the given file name.
   *
   * <p>This method should only be invoked if a done filename property has been set on this
   * endpoint.
   *
   * @param fileName the file name
   * @return name of the associated done file name
   */
  protected String createDoneFileName(String fileName) {
    String pattern = getDoneFileName();
    ObjectHelper.notEmpty(pattern, "doneFileName", pattern);

    // we only support ${file:name} or ${file:name.noext} as dynamic placeholders for done files
    String path = FileUtil.onlyPath(fileName);
    String onlyName = FileUtil.stripPath(fileName);

    pattern = pattern.replaceFirst("\\$\\{file:name\\}", onlyName);
    pattern = pattern.replaceFirst("\\$simple\\{file:name\\}", onlyName);
    pattern = pattern.replaceFirst("\\$\\{file:name.noext\\}", FileUtil.stripExt(onlyName));
    pattern = pattern.replaceFirst("\\$simple\\{file:name.noext\\}", FileUtil.stripExt(onlyName));

    // must be able to resolve all placeholders supported
    if (SimpleLanguage.hasStartToken(pattern)) {
      throw new ExpressionIllegalSyntaxException(
          fileName + ". Cannot resolve reminder: " + pattern);
    }

    String answer = pattern;
    if (ObjectHelper.isNotEmpty(path) && ObjectHelper.isNotEmpty(pattern)) {
      // done file must always be in same directory as the real file name
      answer = path + File.separator + pattern;
    }

    if (getConfiguration().needToNormalize()) {
      // must normalize path to cater for Windows and other OS
      answer = FileUtil.normalizePath(answer);
    }

    return answer;
  }
Ejemplo n.º 6
0
  @Override
  protected void doStart() throws Exception {
    super.doStart();
    ObjectHelper.notEmpty(host, "host", this);

    this.repository = getCamelContext().getRegistry().lookupByNameAndType(host, Repository.class);
    if (repository == null) {
      throw new RuntimeCamelException("No JCR repository defined under '" + host + "'");
    }
    if (username != null && password != null) {
      this.credentials = new SimpleCredentials(username, password.toCharArray());
    }
  }
Ejemplo n.º 7
0
 /**
  * Validates this endpoint if its configured properly.
  *
  * @throws Exception is thrown if endpoint is invalid configured for its mandatory options
  */
 protected void afterPropertiesSet() throws Exception {
   RemoteFileConfiguration config = getConfiguration();
   ObjectHelper.notEmpty(config.getHost(), "host");
   ObjectHelper.notEmpty(config.getProtocol(), "protocol");
 }
Ejemplo n.º 8
0
 public static boolean setProperties(
     Object target, Map<String, Object> properties, String optionPrefix) throws Exception {
   ObjectHelper.notEmpty(optionPrefix, "optionPrefix");
   return setProperties(target, properties, optionPrefix, false);
 }
  /**
   * Perform the work to process the fileExchange
   *
   * @param exchange fileExchange
   * @param target the target filename
   * @throws Exception is thrown if some error
   */
  protected void processExchange(Exchange exchange, String target) throws Exception {
    log.trace("Processing file: {} for exchange: {}", target, exchange);

    try {
      preWriteCheck();

      // should we write to a temporary name and then afterwards rename to real target
      boolean writeAsTempAndRename = ObjectHelper.isNotEmpty(endpoint.getTempFileName());
      String tempTarget = null;
      // remember if target exists to avoid checking twice
      Boolean targetExists = null;
      if (writeAsTempAndRename) {
        // compute temporary name with the temp prefix
        tempTarget = createTempFileName(exchange, target);

        log.trace("Writing using tempNameFile: {}", tempTarget);

        // if we should eager delete target file before deploying temporary file
        if (endpoint.getFileExist() != GenericFileExist.TryRename
            && endpoint.isEagerDeleteTargetFile()) {

          // cater for file exists option on the real target as
          // the file operations code will work on the temp file

          // if an existing file already exists what should we do?
          targetExists = operations.existsFile(target);
          if (targetExists) {

            log.trace("EagerDeleteTargetFile, target exists");

            if (endpoint.getFileExist() == GenericFileExist.Ignore) {
              // ignore but indicate that the file was written
              log.trace(
                  "An existing file already exists: {}. Ignore and do not override it.", target);
              return;
            } else if (endpoint.getFileExist() == GenericFileExist.Fail) {
              throw new GenericFileOperationFailedException(
                  "File already exist: " + target + ". Cannot write new file.");
            } else if (endpoint.isEagerDeleteTargetFile()
                && endpoint.getFileExist() == GenericFileExist.Override) {
              // we override the target so we do this by deleting it so the temp file can be renamed
              // later
              // with success as the existing target file have been deleted
              log.trace("Eagerly deleting existing file: {}", target);
              if (!operations.deleteFile(target)) {
                throw new GenericFileOperationFailedException("Cannot delete file: " + target);
              }
            }
          }
        }

        // delete any pre existing temp file
        if (operations.existsFile(tempTarget)) {
          log.trace("Deleting existing temp file: {}", tempTarget);
          if (!operations.deleteFile(tempTarget)) {
            throw new GenericFileOperationFailedException("Cannot delete file: " + tempTarget);
          }
        }
      }

      // write/upload the file
      writeFile(exchange, tempTarget != null ? tempTarget : target);

      // if we did write to a temporary name then rename it to the real
      // name after we have written the file
      if (tempTarget != null) {
        // if we did not eager delete the target file
        if (endpoint.getFileExist() != GenericFileExist.TryRename
            && !endpoint.isEagerDeleteTargetFile()) {

          // if an existing file already exists what should we do?
          targetExists = operations.existsFile(target);
          if (targetExists) {

            log.trace("Not using EagerDeleteTargetFile, target exists");

            if (endpoint.getFileExist() == GenericFileExist.Ignore) {
              // ignore but indicate that the file was written
              log.trace(
                  "An existing file already exists: {}. Ignore and do not override it.", target);
              return;
            } else if (endpoint.getFileExist() == GenericFileExist.Fail) {
              throw new GenericFileOperationFailedException(
                  "File already exist: " + target + ". Cannot write new file.");
            } else if (endpoint.getFileExist() == GenericFileExist.Override) {
              // we override the target so we do this by deleting it so the temp file can be renamed
              // later
              // with success as the existing target file have been deleted
              log.trace("Deleting existing file: {}", target);
              if (!operations.deleteFile(target)) {
                throw new GenericFileOperationFailedException("Cannot delete file: " + target);
              }
            }
          }
        }

        // now we are ready to rename the temp file to the target file
        log.trace("Renaming file: [{}] to: [{}]", tempTarget, target);
        boolean renamed = operations.renameFile(tempTarget, target);
        if (!renamed) {
          throw new GenericFileOperationFailedException(
              "Cannot rename file from: " + tempTarget + " to: " + target);
        }
      }

      // any done file to write?
      if (endpoint.getDoneFileName() != null) {
        String doneFileName = endpoint.createDoneFileName(target);
        ObjectHelper.notEmpty(doneFileName, "doneFileName", endpoint);

        // create empty exchange with empty body to write as the done file
        Exchange empty = new DefaultExchange(exchange);
        empty.getIn().setBody("");

        log.trace("Writing done file: [{}]", doneFileName);
        // delete any existing done file
        if (operations.existsFile(doneFileName)) {
          if (!operations.deleteFile(doneFileName)) {
            throw new GenericFileOperationFailedException(
                "Cannot delete existing done file: " + doneFileName);
          }
        }
        writeFile(empty, doneFileName);
      }

      // let's store the name we really used in the header, so end-users
      // can retrieve it
      exchange.getIn().setHeader(Exchange.FILE_NAME_PRODUCED, target);
    } catch (Exception e) {
      handleFailedWrite(exchange, e);
    }

    postWriteCheck();
  }
Ejemplo n.º 10
0
  public void poll(
      long streamPosition, final String streamType, final int limit, final EventCallback callback)
      throws BoxServerException, AuthFatalFailureException, BoxRestException {

    // get BoxClient Event Manager
    final IBoxEventsManager eventsManager = cachedBoxClient.getBoxClient().getEventsManager();

    // get current stream position if requested
    if (BoxEventRequestObject.STREAM_POSITION_NOW == streamPosition) {
      streamPosition = getCurrentStreamPosition(eventsManager, streamPosition);
    }

    // validate parameters
    ObjectHelper.notNull(streamPosition, "streamPosition");
    ObjectHelper.notEmpty(streamType, "streamType");
    ObjectHelper.notNull(callback, "eventCallback");

    httpClient = new DefaultHttpClient(cachedBoxClient.getClientConnectionManager(), httpParams);

    // start polling thread
    LOG.info("Started event polling thread for " + cachedBoxClient);

    final long startStreamPosition = streamPosition;
    pollFuture =
        executorService.submit(
            new Runnable() {
              @Override
              public void run() {

                final ObjectMapper mapper = new ObjectMapper();

                long currentStreamPosition = startStreamPosition;
                BoxRealTimeServer realTimeServer = null;

                boolean retry = false;
                int retries = 0;
                int maxRetries = 1;

                while (!done) {
                  try {
                    // set to true if no exceptions thrown
                    retry = false;

                    if (realTimeServer == null) {

                      // get RTS URL
                      realTimeServer = getBoxRealTimeServer(currentStreamPosition, eventsManager);

                      // update HTTP timeout
                      final int requestTimeout =
                          Integer.parseInt(realTimeServer.getExtraData(RETRY_TIMEOUT).toString());
                      final HttpParams params = httpClient.getParams();
                      HttpConnectionParams.setSoTimeout(params, requestTimeout * 1000);

                      // update maxRetries
                      maxRetries =
                          Integer.parseInt(realTimeServer.getExtraData(MAX_RETRIES).toString());
                    }

                    // create HTTP request for RTS
                    httpGet = getPollRequest(realTimeServer.getUrl(), currentStreamPosition);

                    // execute RTS poll
                    HttpResponse httpResponse = null;
                    try {
                      httpResponse = httpClient.execute(httpGet, (HttpContext) null);
                    } catch (SocketTimeoutException e) {
                      LOG.debug("Poll timed out, retrying for " + cachedBoxClient);
                    }

                    if (httpResponse != null) {

                      // parse response
                      final StatusLine statusLine = httpResponse.getStatusLine();
                      if (statusLine != null && statusLine.getStatusCode() == HttpStatus.SC_OK) {
                        final HttpEntity entity = httpResponse.getEntity();
                        @SuppressWarnings("unchecked")
                        Map<String, String> rtsResponse =
                            mapper.readValue(entity.getContent(), Map.class);

                        final String message = rtsResponse.get(MESSAGE);
                        if (NEW_CHANGE.equals(message)) {

                          // get events
                          final BoxEventRequestObject requestObject =
                              BoxEventRequestObject.getEventsRequestObject(currentStreamPosition);
                          requestObject.setStreamType(streamType);
                          requestObject.setLimit(limit);
                          final BoxEventCollection events = eventsManager.getEvents(requestObject);

                          // notify callback
                          callback.onEvent(events);

                          // update stream position
                          currentStreamPosition = events.getNextStreamPosition();

                        } else if (RECONNECT.equals(message) || MAX_RETRIES.equals(message)) {
                          LOG.debug("Long poll reconnect for " + cachedBoxClient);
                          realTimeServer = null;
                        } else if (OUT_OF_DATE.equals(message)) {
                          // update currentStreamPosition
                          LOG.debug("Long poll out of date for " + cachedBoxClient);
                          currentStreamPosition =
                              getCurrentStreamPosition(
                                  eventsManager, BoxEventRequestObject.STREAM_POSITION_NOW);
                          realTimeServer = null;
                        } else {
                          throw new RuntimeCamelException("Unknown poll response " + message);
                        }
                      } else {
                        String msg = "Unknown error";
                        if (statusLine != null) {
                          msg =
                              String.format(
                                  "Error polling events for %s: code=%s, message=%s",
                                  cachedBoxClient,
                                  statusLine.getStatusCode(),
                                  statusLine.getReasonPhrase());
                        }
                        throw new RuntimeCamelException(msg);
                      }
                    }

                    // keep polling
                    retry = true;

                  } catch (InterruptedException e) {
                    LOG.debug(
                        "Interrupted event polling thread for {}, exiting...", cachedBoxClient);
                  } catch (BoxSDKException e) {
                    callback.onException(e);
                  } catch (RuntimeCamelException e) {
                    callback.onException(e);
                  } catch (SocketException e) {
                    // TODO handle connection aborts!!!
                    LOG.debug("Socket exception while event polling for {}", cachedBoxClient);
                    retry = true;
                    realTimeServer = null;
                  } catch (Exception e) {
                    callback.onException(
                        new RuntimeCamelException(
                            "Error while polling for " + cachedBoxClient + ": " + e.getMessage(),
                            e));
                  } finally {
                    // are we done yet?
                    if (!retry) {
                      done = true;
                    } else {
                      if (realTimeServer != null && (++retries > maxRetries)) {
                        // make another option call
                        realTimeServer = null;
                      }
                    }
                  }
                }
                LOG.info("Stopped event polling thread for " + cachedBoxClient);
              }
            });
  }